diff --git "a/data_all_eng_slimpj/shuffled/split2/finalzzsikl" "b/data_all_eng_slimpj/shuffled/split2/finalzzsikl" new file mode 100644--- /dev/null +++ "b/data_all_eng_slimpj/shuffled/split2/finalzzsikl" @@ -0,0 +1,5 @@ +{"text":"\n\nTHIS IS A BORZOI BOOK PUBLISHED BY ALFRED A. KNOPF\n\nCopyright \u00a9 2010 by Louise Yates \nAll rights reserved. Published in the United States by Alfred A. Knopf, an imprint of Random House Children's Books, a division of Random House, Inc., New York. \nOriginally published in 2010 in Great Britain by Jonathan Cape, an imprint of Random House Children's Books. \nKnopf, Borzoi Books, and the colophon are registered trademarks of Random House, Inc.\n\nVisit us on the Web\n\nEducators and librarians, for a variety of teaching tools, visit us at www.randomhouse.com\/teachers\n\n_Library of Congress Cataloging-in-Publication Data_ \nYates, Louise. \nDog loves books \/ Louise Yates. \u2014 1st American ed. \np. cm. \nOriginally published: Great Britain : Jonathan Cape, 2010. \nSummary: Dog loves books so much that he decides to open a book store. \neISBN: 978-0-375-98479-2 \n[1. Dogs\u2014Fiction. 2. Books and reading\u2014Fiction.] I. Title. \nPZ7.Y276Do 2010 \n[E]\u2014dc22 \n2009011097\n\nThe illustrations in this book were created using pencil and watercolor.\n\nRandom House Children's Books supports the First Amendment and celebrates the right to read.\n\nv3.1\n\n_For Eleanor and Cedric_\n\n# Contents\n\nCover\n\nTitle Page\n\nCopyright\n\nDedication\n\nFirst Page\n\nAbout the Author\n\nDog loved books.\n\nHe loved the smell of them,\n\nand he loved the feel of them.\n\nHe loved everything about them....\n\nDog loved books so much\n\nthat he decided to open his own bookstore.\n\nHe unwrapped,\n\nunpacked,\n\nand stacked the books,\n\nready for the Grand Opening.\n\nWhen the day of the Grand Opening finally came,\n\nDog had a bath,\n\ndried his fur,\n\nblew his nose,\n\nand threw open the door\n\nto greet his new customers.\n\nBut there was no one there.\n\nSo Dog tried to keep busy.\n\nAnd then...\n\na lady came into the store.\n\n\"I'll have a tea with milk and two sugars,\" \nshe said.\n\n\"I'm sorry,\" said Dog, \"But this is a bookstore. I only sell books.\"\n\nThe lady walked out.\n\nDog was alone.\n\nHe waited and waited.\n\nThen a man came into the store...\n\nto ask for directions.\n\nWhen he left, Dog was downhearted.\n\nBut not for long!\n\nHe wouldn't wait a moment more.\n\nDog fetched a book from the shelf \nand began to read.\n\nWhen he read, he forgot that he was waiting.\n\nWhen he read, he forgot that he was alone.\n\nWhen he read, he forgot that he \nwas in the bookstore.\n\nAnd when one adventure ended,\n\nDog simply took another book \ndown from the shelf and...\n\na new adventure began!\n\nSo Dog was somewhere else altogether when...\n\na customer came into the store to ask for a book.\n\nDog knew exactly which ones to recommend.\n\nbut most of all...\n\nhe loves to share them!\nLouise Yates began drawing pictures to go with the stories she wrote for school and, at a young age, began telling people that she wanted to be a children's book illustrator. \"One of the things I love most about picture books is the silences, the moments when the text shuts up and the pictures either tell you something that the text hasn't or something totally different,\" she writes.\n\nHer first picture book, _A Small Surprise_ , is an inspired example of those moments of silence when the pictures have their say. In its rave review of _A Small Surprise_ , _Kirkus Reviews_ predicted that it \"will be sure to have readers in stitches.... Yates's debut is one of those books that grows on readers with repetition. Small children who feel they aren't big enough to do anything will appreciate the message, while their adults might be inspired to look for the hidden talents.\"\n\nLouise Yates was born in England and lives in London.\n\n","meta":{"redpajama_set_name":"RedPajamaBook"}} +{"text":"\n\nCopyright \u00a9 2018 DC Comics.\n\nDC SUPER HERO GIRLS and all related characters and elements \u00a9 & TM DC Comics and Warner Bros. Entertainment Inc.\n\nWB SHIELD: TM & \u00a9 WBEI. (s18)\n\nRHUS 39186\n\nAll rights reserved. Published in the United States by Random House Children's Books, a division of Penguin Random House LLC, New York, and in Canada by Penguin Random House Canada Limited, Toronto. Random House and the colophon are registered trademarks of Penguin Random House LLC.\n\nVisit us on the Web!\n\nrhcbooks.com\n\ndcsuperherogirls.com\n\ndckids.com\n\nHardcover ISBN 9781524769239 \u2014 Ebook ISBN 9781524769253\n\nv5.1\n\na\nFor Rob, who makes me laugh\nContents\n\n_Cover_\n\n_Title Page_\n\n_Copyright_\n\n_Dedication_\n\nPrologue\n\nChapter 1\n\nChapter 2\n\nChapter 3\n\nChapter 4\n\nChapter 5\n\nChapter 6\n\nChapter 7\n\nChapter 8\n\nChapter 9\n\nChapter 10\n\nChapter 11\n\nChapter 12\n\nChapter 13\n\nChapter 14\n\nChapter 15\n\nChapter 16\n\nChapter 17\n\nChapter 18\n\nChapter 19\n\nChapter 20\n\nChapter 21\n\nChapter 22\n\nChapter 23\n\nChapter 24\n\nChapter 25\n\nChapter 26\n\nChapter 27\n\nChapter 28\n\nChapter 29\n\nChapter 30\n\nEpilogue\n\n_About the Author_\n\nThat the teenaged sword-wielding hero Katana had just been named Super Hero of the Month was no surprise. After all, she had solved the mystery surrounding the death of her grandmother, Onna-bugeisha Yamashiro\u2014the first female super hero samurai. Plus, she had set things right for the mysterious Ghost Crabs that had invaded Super Hero High _and_ saved the world from the evil villain Dragon King and his army of mutated reptilian warriors.\n\nSo what did all that mean for the students at Super Hero High?\n\nIt was time for cake!\n\nThere was always a celebration when Super Hero of the Month was announced, and Bumblebee had planned a little surprise for Katana.\n\n\"How did you know it would be me?\" Katana asked. Her straight black hair glistened and her big brown eyes were bright. There was a rosy flush to her pale complexion from all the attention.\n\nOther students, like the irrepressible jokester Harley Quinn, loved being in the spotlight, and even sought it out. But not Katana. To her it was just something to get used to, like fighting interplanetary villains or getting her homework in on time.\n\n\"Oh, I had a hunch,\" a tiny voice said from beneath the lemon butter cake that was flying across the room. The cake boasted a citrus sugar glaze and the words Congrats, Katana! written in royal red icing.\n\nFrom underneath the cake, Bumblebee grew from bee-sized to girl-sized as she set it down. Thick honey-colored streaks accentuated her rich brown curly hair, and even though her yellow insect wings may have looked delicate, they were anything but. Having delivered the cake, she treated herself to a small taste of the icing with her finger. She looked around the room as the party took shape.\n\nSupergirl had snuck in and decorated Katana's dorm room with colorful balloons and streamers, and Poison Ivy had filled it with Katana's favorite Japanese snowball flowers.\n\n\"Achoo! Achooo! Achooooo!\"\n\nNear Katana's display of swords someone was sneezing loudly. \"Achooooosie woozie!\" the girl in the blue shorts and mismatched tights said with gusto.\n\n\"Is the word _subtle_ in her vocabulary?\" Cheetah asked as she waited impatiently for the cake to be cut.\n\n\"Isn't anyone going to say gesundheit?\" the girl in the blue shorts asked.\n\n\"Gesundheit,\" said several voices around the room.\n\nThe black mask over her eyes could not hide her look of mischief. \" _YOWZERS!_ Those are some mighty flowers,\" she continued. \"They're killing my allergies. Killing 'em, I tell you.\" The girl was Harley Quinn. She might have seemed unfocused, but she was looking at one person in particular.\n\n\"Hey, over here! Katana, am I going to score this interview or am I going to score this interview?\" Harley quipped. She somersaulted through the partygoers. Her blond pigtails, streaked with red and blue, kept bouncing even when she stood still.\n\n\"I need to do this first,\" Katana said. She picked up the cake and threw it. Before it smashed into the ceiling, Katana unsheathed her sword, leapt, and in midair, expertly cut it into three dozen pieces. Each identically sized slice landed on one of the plates lined up in rows on the table.\n\n\"I love cake!\" Big Barda announced as she took the first piece. She removed her heavy gold-and-black helmet and set it aside. Cake was serious business.\n\nHarley gave Katana a big impatient smile. The young samurai knew that there was no stopping Harley when she wanted something. And right now Harley wanted one of her famous \"exclusively exclusive Harley Quinn's Harley's Quinntessentials scoops\"!\n\n\"Your fave hostess with the mostest, Harley Quinn, here,\" the Web star said, beaming into the camera.\n\nHarley took a large bite of cake, leaving some frosting on her nose. When Katana pointed this out, Harley thanked her, added more frosting, and waggled her eyebrows at her digital audience.\n\n\"Just clowning around,\" she told her viewers. \"But this is serious stuff now. Seriously awesome! I've got Katana in person to tell us how she felt when she heard she was Super Hero High's Super Hero of the Month.\"\n\nKatana blinked into the camera. Not everyone was as comfortable as Harley was at being broadcast to thousands of viewers. Harley's Web channel had been a hit since its debut. There was no telling how many viewers she could get.\n\n\"It feels pretty great,\" Katana said. \"But it was a team effort\u2014\"\n\n\"Aww, she's too modest!\" Harley interrupted, turning the camera on herself and reenacting Katana's martial arts moves. \"Boom! Boom! Blam! Blam! Slice and dice! You shoulda seen this girl wielding her sword. It was like she was holding a bolt of lightning! Speaking of lightning, let's chat with everyone's fav-o-rite weather-themed super hero sisters, Thunder and Lightning.\"\n\nBefore Thunder could answer, Harley dashed off into the crowd. Thunder stood confused, and tugged on the V-neck collar of her sleek black-and-electric-yellow costume. The yellow barrettes that held her bangs in place matched her boots. Her sister, Lightning, crouched down to tie her high-top sneakers. Her sporty clothes made her look like she was always ready for action.\n\n\"That was weird,\" Lightning said. \"Harley was just talking to us and now she's gone...again.\"\n\n\" _She's_ weird,\" Thunder said, quickly adding, \"But I mean that in the best way!\"\n\nJust then, everyone heard a familiar voice. Only it didn't sound normal.\n\n\"Help!\" Harley was crying. \"Someone help me!\"\n\n\"Harley's such a crack-up,\" Cheetah said, rolling her eyes. \"Class clowns are like that.\" Supergirl, hovering nearby, was carrying all the empty plates in two five-foot stacks. She frowned at her feline classmate.\n\n\"We should check this out,\" Wonder Woman announced, always attuned to possible trouble. She tossed her plate so it landed on Supergirl's stack, then adjusted the golden cuffs on her wrists. She motioned the others to follow her as she tracked the sound of Harley's voice.\n\n\"Help!\"\n\nEveryone could hear Harley still yelling. But as they turned the corner, Harley was nowhere to be seen. Instead, her ever-present video camera was on the floor.\n\nBumblebee ran to pick it up. She looked at the video screen. On it was Harley yelling \"Help! Someone help me!\" Then the screen went dark.\n\n\"This doesn't look good,\" Bumblebee said.\n\nBatgirl watched over Bumblebee's shoulder as Bumblebee replayed the video. \"Harley's in trouble!\" Batgirl said. \"She would never be without her camera.\"\n\nWonder Woman looked perplexed. \"I don't see anything,\" she said, staring at the blackness on the screen.\n\n\"Exactly,\" said Batgirl. \"But when I hit 'Playback,' you can hear her. Listen.\"\n\nSure enough, it was the first sound of Harley crying for help that they had all heard.\n\nInstantly, the Supers snapped into action.\n\n\"I'll check the school...,\" The Flash said, racing away at super-speed before he had even finished his sentence.\n\n\"I'll search the underground caverns,\" Katana volunteered.\n\n\"I'll inform Principal Waller,\" Hawkgirl announced.\n\n\"Wait!\" Batgirl called out.\n\nThose who remained crammed around the small video screen. They gasped when Harley's face appeared. She was laughing. \"Gotcha!\" Harley said. \"I'm okay, it was all just a joke! I'm fine. I...\"\n\nJust then, a menacing shadow came up behind her, and suddenly the screen went dark and silent.\n\nAs Supers fanned out over the school and across Metropolis to save their friend, Harley wasn't far from where she had disappeared. The truth was, she wasn't even in danger. Instead, Harley was laughing from the top of the school's iconic Crystal Tower.\n\n\"This is gonna make great entertainment!\" Harley said. She had a habit of talking to herself. That way, it always seemed like someone was with her. Having planned ahead, Harley had placed remote cameras around campus. \"Everyone's going to tune in!\" she told herself. \"And then when I reveal my hiding\u2014\"\n\n\"You are in so much trouble!\" a familiar voice growled. Harley looked up, surprised to find Cheetah glaring down at her with her hands on her hips. Cheetah's long brown hair whipped behind her.\n\n\"Harley, you forgot I have super-vision,\" Supergirl said, landing from above and making sure not to step on Cheetah's tail with her red high-top sneakers. \"I spotted you as soon as I flew above campus and looked back.\"\n\nSupergirl yelled down to Beast Boy, who was slithering around in the form of a green snake, checking out low, hard-to-get-to areas. \"Alert the Supers on the ground that Harley has been found and she's safe! I'll tell the ones in the sky,\" she said, leaping off the tower and flying away.\n\nBeast Boy turned back into his scruffy green teen self for a moment before changing into a small coqui frog. Despite his now-minuscule size, his voice could generate sounds as high as one hundred decibels\u2014as loud as a jackhammer. He croaked, \"Harley Quinn has been found. Harley Quinn is safe. Harley Quinn has been found. Harley Quinn is safe. Harley Quinn has been found....\"\n\nExcept for her light blue eyes narrowing with disapproval, Cheetah hadn't moved.\n\n\"What?\" Harley asked, feigning innocence. \"Would you like to say a few words to our Harley's Quinntessentials viewers?\"\n\n\"Put the camera down,\" Cheetah said. \"Everyone's looking for you. They think you're in danger.\"\n\n\"I was,\" Harley said, laughing. She loved to laugh. She laughed at everything really. \"I was in danger of not having enough viewers. But now, everyone will tune in to my new 'Find Harley' segment! I was secretly videoing your reactions, and they were priceless. Score one for Harley!\"\n\n\"Score zero,\" Cheetah said. \"I'm going to tell Principal Waller that it was all just a joke from our resident class clown. Then we'll see who's laughing.\"\n\n\"No one is laughing,\" Principal Waller was saying, her back to Harley Quinn. Harley could see in the reflection in the office window that the principal's normally stern face looked even more serious. Harley didn't even think that was possible. The Wall, as Principal Amanda Waller was often called\u2014though never to her face\u2014had a look that would make Ares, the god of war and Wonder Woman's half-brother, cry.\n\nHarley squirmed on the wooden chair across from Waller's desk. \"Put the ice blaster back,\" the principal ordered, without looking. \"I've asked you before not to touch things on my desk.\"\n\n\"Yes, Principal Waller,\" Harley said, quickly placing it back on top of the pile of confiscated weapons.\n\nAll weapons were supposed to be checked in and assigned tracking numbers, but students were always forgetting this formality. Well-meaning parents sent swords, chemicals, lasers, and other items that they thought their kids might find useful at school. And some students, like Poison Ivy and Cyborg, were always coming up with new ways to weaponize everyday objects for Lucius Fox's Weaponomics class. That was fine for class, but it wasn't something Waller could allow in the common areas.\n\n\"That little stunt you pulled, about going missing. What do you have to say for yourself?\" Principal Waller demanded.\n\n\"It was just for giggles...and a twenty-three percent increase in viewership,\" Harley answered innocently. \"And math! I'm using what I learned in class and applying it to my channel.\" She aimed her infectious grin at the principal. When Waller didn't respond, Harley ramped up her smile. After years heading up Super Hero High, the principal was immune to the charms of her students, even ones as lovable as Harley Quinn.\n\n\"I see,\" said Waller. \"How about this, then: zero new Harley's Quinntessentials videos plus detention. For two weeks.\" The Wall's eyes stayed locked with Harley's as she smiled warmly and added, \"Math.\"\n\nThat afternoon in the dining hall, no one would look at Harley. \"What did I do?\" she implored. \"What did I do?\"\n\n\"If you don't know, then maybe you should think about it,\" Wonder Woman said to be helpful.\n\nHarley set her tray down between Katana and Bumblebee. Both scooted over to give her room\u2014more room than usual.\n\n\"What did I do?\" she asked as Star Sapphire strolled past, giving her a chilly look.\n\n\"Think about it,\" Wonder Woman reminded Harley.\n\n\"Psst,\" Harley whispered to Bumblebee. \"Give me a hint.\"\n\nBumblebee was busy pouring honey over her spaghetti. She really liked honey. On everything.\n\n\"Harley,\" Katana said. \"People are mad at you for making them think you were in danger. That's not funny.\"\n\n\" _You_ were worried,\" Harley said, slumping in her chair so her head barely appeared above the table. \" _I'm_ worried! Waller banned any new Harley's Quinntessentials videos for two weeks! I'm in reruns. For seven days times two! She even confiscated my video cameras. I won't have any viewers left when I return with fresh stuff.\"\n\nKatana frowned. \"Is that what you're worried about?\" she said. \"How many viewers you have?\"\n\n\"Well, yes!\" Harley said. \"You got that right!\"\n\nKatana let go of a heavy sigh. \"There's more to life than viewers,\" she said.\n\nHarley topped her mountain of garlic mashed potatoes with a cherry. \"Not if you're Harley Quinn,\" she declared.\n\n\"Hiya, fellow detainees!\" Harley said as she cartwheeled into the after-school detention room. She waved to Frost and Lady Shiva. Both looked bored.\n\n\"Everyone take a seat, and no talking!\" Vice Principal Grodd grumbled. His red bow tie matched the hankie in his suit coat pocket. Grodd was very dapper for a gorilla.\n\nHarley let out an audible sigh and sat next to Poison Ivy. The flowers in her long red hair were wilting.\n\n\"Whatcha in for?\" Harley asked brightly. She wasn't about to let anyone know she was bummed. Even though Harley could make almost anything fun, there were dozens of places she'd rather be than detention.\n\nPoison Ivy shook her head. \"Chompy got out of hand again,\" she said.\n\nHarley nodded. Everyone knew Ivy's large and overactive pet plant. Whenever Chompy overgrew his latest pot and went wild, it took Parasite, the janitor, a full day to clean up the mess.\n\nOn Harley's other side, The Flash was leaning so far back in his chair that three of its legs were off the ground. Harley passed him a note. It read,\n\nWhat are you in for?\n\nHe waited until Grodd was fully engrossed in his _101 Banana Recipes_ book.\n\nThe Flash wrote back.\n\nBreaking the sound barrier-twice.\n\nSounds awesome!\n\nHarley wrote in her loopy scrawl. She drew a sad face.\n\nPoison Ivy cleared her throat. She pointed to Grodd, who had fallen asleep and was now snoring gruffly. \"Don't wake him,\" she whispered. \"We have to stay out of trouble!\"\n\nHarley attempted to look serious, but failed. \"Me, stay out of trouble?\" she said. \"Not possible!\"\n\nWithout Harley's Quinntessentials to keep her busy, Harley had a lot of free time\u2014not when she was in detention, of course, but all the hours she normally spent on her Web channel were now open.\n\n\"Two weeks! She might as well have said forever!\" Harley said, moaning in her booth at the Capes & Cowls Caf\u00e9.\n\n\"One extra-large sweet potato fries with four sides of ketchup!\" Steve Trevor announced, placing the order in front of her. He had just gotten a trim, and now his blond hair was a tad too short. \"Hey, Harley, with your channel in reruns, I don't know what's happening at Super Hero High. Um...how's Wonder Woman?\" He blushed. \"I'm asking for a friend.\"\n\nSteve's dad owned Capes & Cowls Caf\u00e9, and though he wasn't a super hero, Steve worked as hard as one. The restaurant was a mishmash of homey and trendy that the Super Hero High students loved.\n\nRegular teens and Supers alike\u2014and even some of the teachers\u2014went there. Steve always set aside a dozen apple cider doughnuts for Batgirl's father, Police Commissioner Gordon.\n\nHarley picked up a sweet potato fry and pointed it toward the door. \"There's Wonder Woman,\" she said. \"Let's ask her!\"\n\nBefore Steve could stop her, Harley shouted, \"Hey, Wonder Woman! Wonder Woman, over here!\" Harley waved, then pointed to Steve, who looked like he was trying to make himself invisible. \"Stevie here has been asking about you! Come talk to him!\"\n\nWonder Woman blushed as red as the star on her gold tiara. The only person who was a brighter red was Steve...and Red Tornado, the school's flight teacher, who had stopped in for a strawberry smoothie. But then, he was always that red.\n\n\"When is your channel going to be back up?\" Star Sapphire asked Harley from the next table. She played with the power ring on her finger.\n\nHarley could only stare at the purple glow coming from the ring. \"Pretty!\" she said, her attention shifted away from Wonder Woman and Steve.\n\n\"I have a scoop for you,\" Sapphire whispered. Frost, who was sitting next to her, raised her eyebrow inquiringly as she blew on her peppermint tea, turning it ice-cold.\n\n\"Whatcha got?\" Harley asked, snapping to attention. A scoop! Harley loved nothing more than getting news first. Her motto was _All the news, as it happens...and sometimes even before!_\n\n\"I heard from a little bird that we're finally getting a new music teacher,\" Sapphire said.\n\n\"It's about time!\" Harley whistled with approval. \"Can't wait to interview her. Or him. Do you know who it'll be?\"\n\nSapphire smoothed the front of her pink and purple dress. The insignia on her belt matched the one on her jeweled headband, which matched the color of her ring.\n\nHarley took note of her own clothes: a black, white, and red checkered shirt with short black sleeves, and blue jean shorts with a thin belt over colored tights\u2014black on one side, red on the other. All with comfortable chunky blue sneakers on her feet. Harley felt a little sad...for Star Sapphire. _If only everyone could have a costume as fun, fashionable, and functional as min_ e, she thought.\n\n\"I hear it's a he, and he's starting soon,\" said Sapphire, reminding Harley of what they were talking about. \"By the way, you will be featuring me on Harley's Quinntessentials when you're back on the air, right?\"\n\n\"You betcha!\" Harley assured her. Fashionistas always tuned in when Star Sapphire was on her show.\n\nAs Harley settled back to contemplate her happy return to the Internet, she noticed a familiar figure at the counter. She grabbed her plate and plopped down next to her. \"Heya, Lois! What's the new news?\"\n\nLois Lane pushed her glasses up and smiled. \"Hi, Harley. I heard about Harley's Quinntessentials going on hiatus.\"\n\n\"Yeah, well, Waller's trying to teach me a lesson,\" Harley said nonchalantly\u2014with a shrug that said, \"In the meantime, I guess that means you'll get all the scoops!\"\n\n\"We're not in competition,\" Lois said. \"I report the news, and you do news and entertainment.\"\n\nHarley glanced at the jukebox. Captain Cold from CAD Academy had it blasting a retro rock song. The music inspired Beast Boy to lead a bunch of kids in a dance in the middle of the caf\u00e9.\n\n\"Well, just news is boring,\" Harley mused as a conga line of teens weaved in and out of the caf\u00e9. \"Booor-ring! Oopsie, sorry\u2014you know what I mean,\" she said to the teen reporter.\n\n\"No need to apologize. It can be boring,\" Lois said, laughing. \"But straight-up news is what I'm interested in. What are you interested in?\"\n\nHarley tugged on a pigtail, watching it bounce when she let go. \"I'm interested in having the most viewers in Metropolis. No, wait\u2014in the world and beyond!\"\n\n\"You've always thought big,\" said Lois. \"Harley, you're a force to be reckoned with. Half of your audience tunes in to see the inside story on the Supers\u2014and you have all prime access to that\u2014and the other half tunes in to see you!\"\n\n\"Little ol' me?\" Harley said with a twinkle in her eye. She did a backflip onto a table. \"Why would anyone want to look at me?\" Harley said, her arms raised dramatically above her head as kids in the caf\u00e9 applauded.\n\n\"Um. Harley,\" Steve said, wiping his hand on a towel. \"Remember, we talked about no standing on tables.\"\n\nHarley giggled. \"Right-O, Steve-O,\" she said. \"My bad.\"\n\nAfter Lois left, Harley continued to peck at her fries, but she couldn't stop thinking about what the young reporter had said. She wondered what might happen if she did more than cover the falls, foibles, and fantastic happenings of her fellow Supers, like Star Sapphire's Fashion Fix It. What if she did specials like...\n\nIt was hard to concentrate. Steve had recently installed the retro jukebox. It was all bright lights and neon colors, and music, music, music. It seemed like half the restaurant was dancing to the music. Most of the kids were just goofing off, but a few were really talented.\n\nAs she watched, Harley's brain began to go into overdrive. She had so many ideas it was hard for her to keep up with herself. Finally, one thought hit Harley so hard that she yelled, \"OUCH!\"\n\nShe jumped up and dashed out the door.\n\n\"Hey, Lois!\" Harley called, running after her. By then Lois was in Centennial Park. \"Slow down! I have something to ask you.\"\n\nLois looked curious. \"Yes?\"\n\n\"Okay, okay. News, yes. News is news. But when it's not new anymore, it's not news, right?\" Harley reasoned.\n\n\"I...think so?\" Lois said slowly. \"What are you saying, Harley?\"\n\n\"I'm saying, what if I expanded Harley's Quinntessentials beyond Super Hero High? What if I took the news and turned it into entertainment?\" Harley looked right at Lois. \"What if I broadcast a dance contest? And what if it was live so everyone everywhere could tune in? That way we'd all know the winner at the same time! I'd be making the news instead of just reporting it! Isn't that a great idea? A totally _**WOWZA-YOWZA**_ of an idea! I'll have more viewers than I'll know what to do with! I'll have so many viewers that\u2014\"\n\n\"Whoa, whoa, slow down,\" Lois said. She waited patiently for Harley to stop with the somersaults. \"You do know that there's a difference between informing your viewers with the news and entertaining, right?\"\n\nWhen Harley gave her a blank stare, Lois tried again. \"The news is fact. We strive to tell our viewers the truth and inform them about what's happening in the world. Especially when the information may impact them.\"\n\n\"Yes!\" Harley agreed \"Impact them! That's what I plan to do. POW! I'm going to have reality shows on Harley's Quinntessentials! And the first show will be a dance competition called Harley's Dance-O-Rama! What do you think of that?\"\n\nLois gave Harley a weak smile. \"Um, okay,\" she said. \"But it sounds more like entertainment than\u2014\"\n\n\"It sounds like blockbuster ratings, that's what it sounds like!\" Harley assured her.\n\nThere were only two more days left in detention. Vice Principal Grodd had finished his banana recipe book and was now reading a cookbook called _Bamboo and You._ As he sat munching on a stalk, the Supers shifted in their seats. Blessed with powers like super-speed, super-strength, and enhanced mental abilities, they weren't good at staying still.\n\nIn the back corner, Poison Ivy kept sticking her head into her backpack and talking. When she saw Harley staring at her, she offered a sheepish grin. \"I'm comforting one of my baby daffodils,\" Ivy whispered apologetically. \"She's lonely.\" A petite yellow flower peered out from the backpack and then quickly retreated. Harley smiled. Poison Ivy was crazy about her plants, and they were crazy about her, too.\n\nOutside the window, Supergirl was zooming in and out of the clouds, playing bow-and-arrow boomerang. In the game, Arrowette, whose family's archery skills were legendary, would take her stance, draw her bow, aim into the sky, and release an arrow. As the arrow hurtled at almost four hundred feet per second, Supergirl would catch it and then throw it back. Their record was fifteen in fifteen seconds.\n\nHarley opened her notebook. There was a big HQ in blue and red on the cover. Inside, in her loopy handwriting, were her notes for the Dance-O-Rama. It was all coming together\u2014on paper, at least. Once her Web channel was back up and running, the real fun could start. But first Harley needed some help.\n\nThat night Harley stood at the front of the room and said, \"You're all probably wondering why I asked you here.\"\n\nBeast Boy had a giant red-pepper pizza in front of him. \"I thought we were in the dining hall for dinner,\" he said, folding the pizza in half and eating it like a taco.\n\n\"I want to know why we're here,\" Big Barda said. She had so many servings of mashed potatoes on her plate, it looked like the Swiss Alps had relocated.\n\nAs Harley told the Supers about her Dance-O-Rama, some ignored her, but others seemed interested. Hawkgirl raised her hand. \"So let me get this straight. Heroes and villains will be allowed to try out to be contestants?\"\n\n\"That's right!\" Harley said. \"And regular citizens, too. It's open to all.\"\n\n\"And you can have as many people on your team as you want?\" Supergirl asked.\n\n\"And as few,\" Hawkgirl added. She had been taking notes. \"You can be a soloist.\"\n\n\"I can be a soloist?\" Wonder Woman asked.\n\n\"Anyone can,\" said Harley.\n\n\"What are the rules?\" asked Hawkgirl.\n\n\"Who needs rules?\" said Harley.\n\n\"The contest does,\" Hawkgirl said. \"Otherwise it will be chaos.\"\n\n\"Would chaos be so bad?\" Harley asked.\n\n\"It could be,\" Supergirl said. \"Have you run this past Principal Waller yet?\"\n\nHarley suddenly got serious. _**YOWZA!**_ If anyone could stand in the way of this great idea, it would be the Wall.\n\n\"Let me understand this, Ms. Quinn,\" Principal Waller said. Already an imposing figure, she was wearing one of her severe dark gray suits. Waller had seven of them, one for every day of the week.\n\nBumblebee flew into and out of the office, delivering papers and passing along messages. When Bumblebee saw Harley, she offered her a warm smile. Harley smiled back. She appreciated Bumblebee's upbeat nature. _Too many Supers are stressed out and so serious_ , Harley lamented as a dozen other thoughts bounced around in her head.\n\n\"Dancing?\" Waller continued, making it sound like Harley had asked permission to hold a worm-eating contest. \"And you want to enlist some of my students to help you? And you want open auditions\u2014ones in which a contestant's past is not of consequence? And you want to broadcast the contest live from Super Hero High on your Web channel?\"\n\nHarley gulped. When Waller said it, hosting a Dance-O-Rama didn't sound so fun.\n\n\"Yes, ma'am,\" Harley mumbled.\n\n\"Well, Harley.\" Waller shuffled some papers on her desk. \"I think it's a great idea.\"\n\nHarley got up and made her way to the door. \"Yeah, yeah, got it. I hear ya, I hear ya. No dance contest. Anyway, thanks for listening.\"\n\nAs Harley dragged herself down the hall, the sound of buzzing got louder.\n\n\"Harley, wait. Waller sent me to talk to you,\" Bumblebee called after her.\n\nHarley stopped to pull up her socks. They were always falling. \"Am I in trouble again?\" she asked. Despite her best efforts, it seemed like Harley was always getting called out. Most people, she decided, did not have her refined sense of humor and penchant for fun. Harley held up her hands. \" _ **YOWZA.**_ I surrender already. Arrest me!\" she joked.\n\nBumblebee's laugh was light and warm, like honey. \"There's no need for that,\" she assured her. \"Waller thinks you didn't understand. Harley, she was giving you permission to go ahead and hold the dance contest!\"\n\n\"Wha-wha-what?\" Harley blabbered. Her jumbled thoughts were spinning.\n\nWhen Bumblebee nodded, Harley's whoop of joy could be heard all the way to the athletic field. \"Yes!\" she yelled. \"Get ready, world! Harley's Dance-O-Rama is going to be the biggest and best-est dance contest anyone has ever seen. Ratings are gonna go straight through the roof, pierce the clouds, and ricochet off the stars!\"\n\nBig Barda was tossing huge weights to Supergirl, who tossed them to Wonder Woman, who was stacking them up so the Supers would have something to knock down.\n\n\"Does this look crooked?\" Wonder Woman asked as she stepped back to appraise the pile.\n\nAcross the room, Miss Martian was nervously dangling several feet above the floor from a rope that was part of a training exercise.\n\n\"And...go!\" Coach Wildcat yelled as he lit the bottom of the frayed rope with a match. It looked like an upside-down Fourth of July sparkler. \"Miss Martian, you'd better start climbing the rope before the fire catches up to you!\"\n\nFrost stood by the sidelines and tried not to yawn. She was there to put out the fire if needed.\n\nAs the rope began to sizzle, Miss Martian scampered up. Her brown eyes were big with misgiving, and her long red hair covered her face. She had never gone so high or so fast before! Poison Ivy stood by and applauded.\n\n\"Good!\" Wildcat barked. \"El Diablo, you're up next! Replace that rope and then climb it, stat!\"\n\nIn another part of the gym, Katana was twirling swords so fast you could hear them slicing the air. Cyborg tried to do the same. However, the sound he made was the metal clang when he accidentally hit himself with the weapon time and time again. \"Pick it up and try again,\" Katana encouraged him. \"And don't worry about dents. You can get those fixed later.\"\n\n\" 'Scuse me, Coach Wildcat,\" Harley said, tapping him on the shoulder. It was as solid as cement. \"May I have a few minutes of your time?\"\n\nWildcat turned around, his face in a scowl. \"Is this important?\" he asked. \"I have super heroes to train.\"\n\n\"It's super-duper important, Coach!\" Harley assured him.\n\n\"You really think teaching dance during PE is a good idea?\" Wildcat asked as El Diablo accidentally lit the bleachers on fire. Frost put out the flames by sending a blast of ice over them. Wildcat jerked his head around as a blur burst past. \"Hey, Flash, speed it up!\" he yelled.\n\nWildcat looked serious as he turned back to Harley, who nodded eagerly.\n\n_Geez. There's so much seriousness around school,_ Harley thought in the face of Wildcat's unending scowl. _Good thing they have me._\n\n\"This is a physical education class,\" the coach reminded her. \"These Supers need to be agile and alert at all times. After all, they may be saving the world someday, and that someday could be sooner than anyone thinks. Harley,\" he said, \"give me three good reasons why I should even be listening to you talk about dancing.\"\n\nHarley had anticipated this. She turned to Batgirl and nodded. Clinging to the ceiling using one of her B.A.T. (Barbara-Assisted Technology) devices, Batgirl hit \"On\" and Harley's POWer (Project, Out-logic, and Wow) presentation appeared on the east wall.\n\n\"One,\" Harley began as a photo of exuberant octogenarians dancing appeared, \"dancing makes for strong bones. Two, it helps increase stamina. Three, it improves memory by making us recall steps and routines. Four, balance is called into play, strengthening our core muscles. Five\u2014\"\n\n\"Enough!\" Wildcat said, raising his paw. \"Enough already, Harley!\"\n\nShe paused and held her breath.\n\n\"I'll give you gym periods three and four. But if I don't see results and it's a bust,\" Coach Wildcat warned, \"then you'll be mopping the floors alongside Parasite until Doomsday. Got it?\"\n\n\"Got it, Mr. Coach Wildcat, sir,\" she promised. \"Harley Quinn won't let you down!\"\n\nThe next day, Harley's classes seemed _sooo looong_. She just couldn't sit still. In Crazy Quilt's Super Suits design class, Harley kept applauding and whistling, hoping to speed things up.\n\n\"Harley, Harley, Harley!\" Crazy Quilt said as he sauntered down the catwalk that split the room in half. \"Please hold your applause until the situation merits it.\" He stopped mid-runway and stuck a disco pose. When the class was silent, Crazy Quilt whispered to Harley, \"You can applaud now.\"\n\nAt last! The class she was waiting for. Harley was bouncing off the walls. Literally.\n\n\"Quiet!\" Wildcat blew his whistle and then waited for the Supers to be silent. These were the elite teens of the universe, the super heroes of tomorrow...but for now, they were typical energetic teenagers in PE class.\n\n\"CALM DOWN!\" Harley yelled. \"This is important.\" She looked at Wildcat and said reassuringly, \"Go ahead, Coach.\"\n\nWildcat scowled and continued. \"Yesterday we learned how to disable our detractors with head locks, hard punches, and elbows to the solar plexus. Today we're going to learn pivots, pirouettes, and a do-si-do or two, thanks to Harley Quinn's suggestion. That's right: we're all going to dance! And anyone who thinks they can't learn a thing or two from me about cha-cha-cha-ing is in for a surprise.\"\n\nHawkgirl frowned. Beast Boy grinned. Harley did an aerial, and when she nailed her landing she pointed to Wildcat and announced, \"Supers, you're looking at the Ranger Ridge State College dance champion! Give it up for Coach 'Crazy Legs' Wildcat!\"\n\n\"That's ancient history,\" he said with a modest grin. \"But think about it. The best battles are like choreographed dance routines. It's a give and take, and there's a rhythm to it.\"\n\n\"How about heating up this class with a little salsa dancing?\" said El Diablo.\n\n\"How about a little polka?\" Wildcat asked.\n\n\"How about a little _polka_ in the eye,\" Harley whispered to Bumblebee, then laughed at her own joke.\n\n\"Polka?\" El Diablo said. The black images of flames that adorned his arms rippled. \"That's so old-school.\"\n\nParasite, the school janitor, was sweeping up under the bleachers. \"Polka's not old-school,\" Harley heard him grumble. \"The easier it looks, the harder it is.\"\n\n\"Okay,\" Wildcat called out. \"Pick your partners.\"\n\n\"You heard him,\" Harley yelled. She began clapping. \"Let's go! Let's go! Let's go!\"\n\nWildcat looked at her sideways. Harley shrugged. \"I figured you need a dance assistant, and that person ought to be me.\"\n\nThere was a mad rush. Big Barda and Supergirl stood together. Green Lantern and Lady Shiva were happily chatting. Cheetah and Star Sapphire were conspiring. Everyone had a partner except one student, who stood on the sidelines.\n\n\"Miss Martian,\" Wildcat said. \"I'm sorry, but there's an odd number of dancers, so I'm afraid you'll just have to sit this one out.\"\n\n\"That's fine,\" Miss Martian said softly. She began to fade until no one could see her.\n\n\"Dancers,\" Wildcat bellowed. \"I want you to watch this video first, and then we polka!\"\n\nAt a school full of super heroes, everyone wanted to be the best, whether at battling intergalactic villains, outsmarting criminals, or doing a polka. They studied the video of big-skirted women and men in jaunty vests with a keen interest. Hawkgirl took notes. Bumblebee danced in place.\n\n\"Okay, ready?\" Wildcat asked. He didn't wait for an answer. \"And...go!\"\n\nAs the relentlessly upbeat strains of accordion and clarinet pumped through the gym, an imposing figure stepped into the room. Amanda Waller's face was unreadable as she watched her students galloping and gallumphing in pairs.\n\n\"Big step, small step! Small step!\" Wildcat was calling as he clapped his paws to the beat. \"That's right! Big step, half step, half step. Full, half, half...No, no, Wonder Woman and Supergirl, no flying. This is on the ground only. Flash, slow down. Barda, Katana, it's not all big steps!\"\n\n\"You heard him!\" Harley called out, bouncing up and down to the music. \"Big step, small step!\"\n\nThe Supers were bumping into each other, causing some to crash against the walls and\/or knock over the other dancers. They were all enjoying the confusion, especially Harley\u2014until she noticed Principal Waller staring at something at the far end of the gym.\n\n\" _ **WOWZA!**_ \" Harley said, pointing. \"Do you see what I see?\"\n\nSoon everyone was watching Parasite doing an incredible polka...alone. His eyes were closed as he deftly moved through the steps, lost in the music.\n\nThere was a collective gasp as his partner slowly appeared. Miss Martian was smiling as she polkaed around the gym with the janitor. As they continued to skip and spin, Waller nodded to Wildcat before leaving.\n\nWhen the music ended, the applause began. Parasite was a little out of breath. It took great control to dance and keep his powers in check\u2014he had the ability to drain Supers of their powers. But Miss Martian was beaming. \"Thank you,\" she said bashfully.\n\n\"Thank _you_ ,\" he said, giving her a small bow before he picked up his broom. He tried not to smile amid the calls of \"Great job!\" and \"Parasite, you're the polka king!\"\n\nWildcat looked at Miss Martian. \"Next time,\" he said, \"you will show these Supers how it's done.\"\n\n\"How would you describe yourself?\" Bumblebee asked the girls who were crowded around her locker. She was holding the \"What Super Are You?\" quiz in _Super Student, Super Star_ magazine.\n\nHarley didn't hesitate. \"I'm the frosting on the cake! The _zzazz_ in _pizzazz_! The ribbon on the present! The duper in super!\" she said, leaping up and then taking a bow.\n\nCheetah strolled past and commented, \"What you are is a class clown.\"\n\nFrost followed, laughing. \"Where's your red nose?\" she asked.\n\nHarley lit up. \"Thanks for the reminder!\" She pulled a red foam nose seemingly from out of nowhere and plopped it on her nose. Then Harley grabbed her book bag and headed to class, leaving a trail of giggles, guffaws, and shocked expressions in her wake as she made her way down the hall yelling, \"Clown comin' through!\"\n\nThe line into the gym snaked out of the building and wrapped around the base of Crystal Tower. Twice.\n\n\"Lookit!\" Harley cried. \"Look at the semifinalists! We're gonna have big fun!\"\n\nJust a few days earlier, Harley's Quinntessentials had gone back on the air with new segments. \"Hey, Harley fans,\" she had broadcast. \"Didja miss me? I sure missed you, and you're not gonna wanna miss this\u2014Harley's Dance-O-Rama!\"\n\nThe buzz for the Dance-O-Rama was so big that even Lois Lane reported on it. \"Word is that dancers from around the world and beyond are eager to show their moves,\" Lois had said.\n\n\"I'm glad I had everyone check in online before they showed up,\" Batgirl told Beast Boy as she consulted the mini-computer on her wrist. \"Each entry was given a number. We have one hundred eighty-seven dance groups and thirty-seven soloists for the semifinals. Good thing we had the groups send in tapes for us to cull through first. Otherwise we'd have more contestants than people in the entire city of Metropolis!\"\n\n\"Thirty-eight soloists,\" Beast Boy corrected her.\n\n\"No, thirty-seven,\" Batgirl said, triple-checking the list.\n\n\"A super-talented last-minute performer just showed up,\" Beast Boy told her. He began to moonwalk. \"We don't want to leave this one out. This will rock the ratings, believe me!\"\n\nHarley's eyes grew big. \"Who is it?\" she asked, scanning the crowd.\n\n\"Me!\" Beast Boy said, stopping and pointing to himself. \"Right here. Right now. With all the right moves.\"\n\nBatgirl shook her head. \"You were supposed to send in an audition tape like everyone else.\"\n\nBeast Boy turned into a dancing hippo and gracefully balanced on one foot. \"But I'm not like everyone else,\" he noted. \"I'm special.\"\n\nBumblebee flew up. As official troubleshooter, it was her job to take care of any unforeseen problems. \"There's no time for arguing, people,\" she reminded everyone.\n\n\"Then it's settled! Let's let him in,\" Harley proclaimed, adding, \"He'll be good for ratings!\"\n\nIt was an odd gathering as the contestants descended on Super Hero High. A whole contingent from the Planet XOXO were dressed as puffy Valentine hearts, a trio of break-dancers from CAD Academy had brought a crate of plates and coffee cups with them, and what looked like half of Korugar Academy was present. Plus, there were dance teams from almost every regular high school, villains who had come out of hiding to show off their samba skills, and even one hundred tap dancers from Tap Dance Town, that new senior citizen community for retired super hero sidekicks.\n\nIt was sure to be a spectacle, and Harley had placed cameras around the gym to capture every dance move.\n\n\"Three, two, one...and we're live!\" Harley turned to the camera as two Furies from Apokolips Magnet stormed the stage looking confident.\n\nBig Barda fiddled with the sound system, making sure it was working. Barda took her job as DJ seriously, and her status as a Super Hero High student even more seriously. Normally, Bumblebee would have DJ'ed, but as the show's troubleshooter, she was already swamped.\n\n\"Welcome to Harley's Quinntessentials,\" Harley said gleefully, \"or HQ, to my friends. Today we usher in a new show. Yes! It's time for the semifinals of our _**POW! BANG! WHAM! WOWZA!**_ of a spectacle, the Harley's Dance-O-Rama! And now let's get started! First up, the Furies!\"\n\nThe duo from the dark and desolate planet started off slowly, but with each powerful stomp, their hip-hop dance ramped up until the entire school was shaking. When the music stopped, Furies Stompa and Lashina looked triumphantly at the DJ standing behind the music console.\n\n\"Hey, Barda, see what you're missing?\" Lashina snarled, tossing her black-and-blue ponytail over her shoulder.\n\nStompa took a bow. \"You should never have left Apokolips,\" she said when they walked past their former schoolmate. Her heavy boots made the gym tremble beneath Big Barda's feet.\n\n\"It's okay, Barda,\" Supergirl said, quickly flying over. \"You're one of us now. Those bad days at Apokolips are\u2014\"\n\nHarley interrupted. \"C'mon, c'mon, we got a show to put on!\" she reminded them with a circular motion of her arm that said \"Let's keep the ball rolling.\"\n\nHawkgirl consulted her watch. Harley had named her stage manager, and as with all her assignments, she wanted to make sure everything was perfect.\n\n\"Katana, we're ready for the next group,\" Hawkgirl said into her headset. \"Send in the clowns.\"\n\nHowls of laugher rippled through the stands as the clowns pushed and pulled and tumbled over each other to get to the stage.\n\n\"Wait for me!\" Harley cried, joining them.\n\n\"Oh, look! It's our very own class clown, doing her thing,\" Cheetah said as Harley rolled past her.\n\n\"It's going to be just as hard to corral Harley as the contestants!\" Batgirl shouted to Big Barda, who cued up the circus music.\n\nThe Comic Conga Clowns soon had everyone in the stands dancing in one long line around the gym and out the building. When the first clown in front leaned back, so did everyone else. And when she sat down, it caused a chain reaction of everyone falling into the lap of the person behind them.\n\nHarley could not stop laughing, nor could anyone watching. Though the semifinals had just begun, she was having a great time, and the dancers kept coming: samba, tango, foxtrot. Polka. Belly dancing. Ballet. Every kind of dance imaginable was being demonstrated.\n\n\"And now, another group from my own Super Hero High!\" Harley said into the camera. \"Here are Green Lantern, Raven, Catwoman, and Starfire doing their rendition of swing dancing!\"\n\nBatgirl was monitoring the online viewership. There were hundreds of thousands of viewers from every corner of the universe. She even detected some views from another galaxy. The show was breaking records. Batgirl had to admit: Harley knew how to entertain a crowd.\n\n\"And that's all for today!\" Harley announced. \"Tomorrow, we will resume our semifinals! So, until then, keep watching and keep laughing,\" she said as her channel started replaying the day's events.\n\nIf Harley Quinn had her way, Harley's Quinntessentials would be live 24\/7. But Waller had put limitations on how much time she could broadcast. There was, after all, something called \"school.\"\n\n\"That was exhausting,\" Batgirl said as they crowded into Harley's dorm.\n\n\"Everyone, thank you for all your help in making the Dance-O-Rama a hit!\" Harley enthused. \"Just wait until tomorrow, when we name the finalists. That's gonna be big!\"\n\n\"I'll bet you're going to get zillions of messages telling you how great you are,\" Miss Martian noted, looking at Harley with admiration. \"I wonder what that's like?\"\n\n\"What what's like?\" asked Harley.\n\n\"To be you,\" said Miss Martian. \"To have so many fans, and to get fan mail.\"\n\n\"It's the best!\" Harley exclaimed. \"Fans make you feel good, and fan mail can make you feel even better.\"\n\nThis Harley knew to be true. After all, she kept all her fan mail, and had a special file for her favorites to reread during those days when life wasn't as funny as it should be.\n\nOnline\u2014and in just about every other form of mass communication\u2014there was a lot of grumbling, with complaints of fixed votes and bribes and heavy hints of favoritism. Harley could not believe the response. She was in heaven!\n\nAfter a seemingly endless second day of semifinals, the finalists had been chosen via a panel of secret judges, votes from the Internet audience, and, of course, Harley. Now it was time to drop in on the tech behind her success\u2014the one and only...\n\n\"Hi, Batgirl!\" Harley shouted as she entered the Bat-Bunker. \"Any press is good press, don't you think?\" she said, tossing her mallet in the air. Just as Harley was about to grab it, a net dropped from the ceiling and caught it. \"Hey, that's mine!\" she complained.\n\n\"It's mine now,\" Batgirl said good-naturedly. \"You know that no one's supposed to play with their weapons in here. I have too much high-tech equipment and can't afford for anything to break. I'll give it back to you when you leave.\"\n\nHarley wandered around the Bat-Bunker, the dorm room that doubled as Batgirl's computer control center. The screens glowed blue in the purple room.\n\n\"So, what are my numbers?\" Harley asked, pressing some buttons randomly.\n\nBatgirl removed Harley's hand from her keyboard and reset the computers back to the way they were. Then she flexed her fingers and addressed the computer keyboard like a pianist. Instantly, a detailed map of Metropolis appeared with numbers running across it. Overlaid on top of that, a map of the United States appeared, then a map of the world, then the key locations around the greater galaxy covered the screen. \"Take a look for yourself,\" Batgirl said, scooting over.\n\nHarley leaned in. The number was getting bigger and bigger. \" _ **WOWZA!**_ \" she proclaimed. \"I'm a huge hit!\"\n\n\"Yes, but not everyone is a fan,\" Supergirl pointed out. Harley had been so focused on the numbers, she hadn't noticed Supergirl eating cookies in the corner. \"Look at your message board.\"\n\nOn another screen were comments from viewers. Most were like this:\n\nThe BEST show ever. I love HQ's Dance-O-Rama!\n\n\u2014Dance-O-Rama Fan Family\n\nHarley Quinn deserves the awesomeness award!\"\n\n\u2014MH234\n\nCan't wait to see the finals. I just know Beast Boy is going to win!!!\n\n\u2014Beast Boy\n\nBut some said:\n\nKiller Croc should have been a finalist. So what if he's a criminal?\n\n\u2014KC Fan Club and Employees\n\nThe votes were rigged!\n\n\u2014CAD Academy Parents Association\n\nWatch out, Harley Quinn, you picked the wrong dancers!!!\n\n\u2014Anonymous\n\nSupergirl wrinkled her brow. \"Do those bother you?\" she asked.\n\n\"Aw, shucks!\" Harley said after reading the angry comments. \"I'm not afraid of anyone! So what if I lose a couple of viewers? I've got plenty more where they came from!\"\n\nWith the finals less than a week away, the dance competition was all anyone could talk about. \"It's too bad you and Parasite didn't try out,\" Katana said to Miss Martian.\n\nMiss Martian blushed. \"Dancing's not my thing.\"\n\n\"Well, it's _my_ thing,\" Star Sapphire said. She pirouetted around the tables in the dining hall, hitting several students with her deep purple hair as she whirled around. \"I've already started planning my victory party.\"\n\n\"Nothing like a little self-doubt,\" The Flash said to himself as he passed by holding a tray piled high with cheeseburgers.\n\nSapphire straightened her tiara. \"I'm having couture costumes made for me and my corps de ballet. Now all I need is a dance partner.\" She looked around. \"Oh, Flash,\" she said as she adjusted the glowing ring on her finger. \"May I have a word with you?\"\n\nSince the dozen finalists included entries from Super Hero High, Wildcat left the gym open for the groups to practice. \"Nothing wrong with home court advantage,\" he said when Hawkgirl asked if this was fair.\n\n\"Let's triple-check this,\" Hawkgirl said to Batgirl.\n\n\"I'm all for that,\" Batgirl said, consulting her computer. \"My list includes the following: one hundred Tappers from Tap Dance Town; The CAD Academy Break-Dancers; the Belle Reve Penitentiary Guard Cha-Cha-Chas; Little Beth from Miss Toddler Tot's School for the Tiny and Talented; the Jigs Up, a group of former bank robbers from Limerick, Ireland; the Doomsday Divas, a group of reformed villains; a trio of dancers from Intensity Institute; our own Super Hero High entries; and the mystery dancer.\"\n\n\"Who's the mystery dancer?\" Hawkgirl asked. \"I don't like not knowing.\"\n\n\"Harley, who's the mystery dancer?\" Batgirl asked.\n\n\"Don't know,\" Harley said. \"It's a mystery!\"\n\n\"There's no way we can fit the hundred tap dancers in the gym\u2014and it's a direct violation of the fire code,\" Hawkgirl noted, shaking her head. \"Last time we had them dance in the parking lot. But that's going to be full of vehicles since the competition is a hot ticket.\"\n\nBatgirl agreed. \"What do you want to do about that?\"\n\n\"I don't know,\" said Harley. She was editing a commercial featuring the finalists and trying to mimic their moves. \"You guys figure out the details. I'm more of a big-picture person.\"\n\n\"Outside,\" Batgirl said. \"They'll have to dance outside on the sports field. I can get Supergirl and some of the others to construct a dance floor\u2014\"\n\n\"Heard you, and we're already on it!\" Supergirl said over Batgirl's comm bracelet. \"Look out the window.\"\n\nHarley could see Supergirl and Wonder Woman carrying twenty-foot stacks of wood planks and handing them off to The Flash, who was building a dance floor at super-speed on the sports field as Bumblebee directed him.\n\n\" _ **WOWZA!**_ We've thought of everything,\" Harley enthused. \"What could possibly go wrong?\"\n\nSaturday morning rolled around sooner than anyone expected. Wonder Woman enjoyed several bowls of colorful sugary cereals\u2014it was her one weakness. Bumblebee fortified her steel-cut oatmeal with extra honey. Batgirl had gotten up early, had fruit, granola, and yogurt, and was already at work in the gym where the show was taking place. A stickler for details, she wanted to triple-check the equipment.\n\n\"Can you go faster?\" Harley asked. She was so excited that she had eaten breakfast three times. Two on purpose, one by accident.\n\n\"I could if you would please move aside,\" Batgirl said. She was staring into Cyborg's eyes as he stared back at her. \"Harley, can you see what he sees?\" she asked.\n\nHarley checked her computer. \"Yep!\" she said gleefully. \"What an awesome, incredible idea, to have extra cameras! Who was the genius who thought of that?\"\n\n\"You,\" Batgirl said, rolling her eyes.\n\nHarley blushed and fanned her face with her hands. \"Aww, you are too kind!\"\n\n\"How do I turn this off?\" Cyborg asked. \"I don't want everyone to know what I see all the time!\"\n\n\"Just blink quickly three times to turn it off, four to turn it on,\" Batgirl told him.\n\nHarley batted her eyes at him. \"Thanks, Cyborg! Be sure to get the crowd shots. The ones of them cheering and yelling. Oh, and lots of shots of the host, too.\"\n\n\"That's you, Harley,\" he said, imitating Batgirl good-naturedly.\n\nHarley tapped the side of his metal head. \"Nothing gets past you, does it?\" she joked.\n\n\"Bumblebee, just in time. You're next,\" Batgirl said as her friend arrived and shrank down to be outfitted with a micro-camera. That way, she could fly right into the middle of the dancers and broadcast live.\n\nAs Harley tested the camera, Batgirl blurted out, \"Macro micro mini drone!\"\n\n\"Whatzat?\" asked Harley.\n\nBatgirl shook her head. \"Oh, just an idea,\" she said. \"I'll tell you later. You've got a show to put on. Plus, you've got to coordinate with all the judges.\"\n\n\"The judges?\" Harley asked.\n\n\"I know you had help selecting the semifinalists, so I assumed you'd have judges for the finals,\" Batgirl said.\n\nHarley's brain was racing. She knew there was something she'd forgotten. \"Snap!\" she finally said. \"Here's a news flash: no finalist judges. I've got something a billion times better!\"\n\n\"What?\" Batgirl asked.\n\n\"Me!\" said Harley, nodding happily. \"I can't wait to name the winner! Excuse us\u2014the judges have some decisions to make.\"\n\nAfter conferring with herself, Harley decided that she alone would determine who the winner was. After all, this was her Web channel, and this was her show.\n\nThe dance-off started smoothly. Star Sapphire and her corps de ballet were marvelous. After Barda made sure all the loudspeakers were working, she played the music from Tchaikovsky's _Swan Lake_. The ballerinas' costumes sparkled whenever they pirouetted, which was often. Then, when The Flash lifted Sapphire, he paused so the audience could take in the beauty of his partner\u2014that was her idea.\n\n\"Spin!\" Star Sapphire whispered. \"Like we practiced.\"\n\nThe Flash nodded, started off slowly, and then spun so fast the two of them rose in the air, to the delight of the audience. Then, as they floated above, purple glitter showered down on the crowd. Never had there been louder cheering, or more sparkles, for Swan Lake.\n\nAs if to balance the beauty and grace of Sapphire's dance team, CAD Academy went next. Captain Cold was in charge, as usual. He swaggered up onstage, followed by his crew: Ratcatcher and Magpie. While Barda manned the DJ booth and played the hard-driving beat, Captain Cold and company jerked around in an odd but mesmerizing rhythm.\n\n\"Cap'n Cold and His Break-Dancers are in the house!\" Barda yelled as Captain Cold pulled a plate out of his jacket and hurled it at the audience.\n\nA roar of approval went up as the CAD Academy dancers broke dozens of dishes\u2014smashing them on the ground, and throwing them into the audience and at each other.\n\nAt the far end of the gym, Parasite looked on and shook his head. He knew who would be cleaning up the mess.\n\n\"They crack me up,\" Harley said with a laugh as she took center stage while the CAD Academy students took their bows.\n\nThe show continued at whiplash pace, with Harley at the helm and Cyborg and Bumblebee displaying stellar camera work. \"Next,\" Harley announced, \"we go outside for the One Hundred Tappers, and not one of them is under one hundred years old! You know what that means, right? One hundred times one hundred equals awesome!\"\n\nThe special dance floor that Supergirl and the others had installed worked perfectly. The sound of two hundred feet tapping in unison was so loud it could be heard in Metropolis and beyond. The crowd was so jazzed by the tapping tones of the 100 Tappers that they stood up and began tapping along. When the Super Hero High buildings began to shake off their foundations, Harley was forced to cut their dance short. Even she was worried that they might cause an earthquake.\n\n\" _ **WHOA**_ and _**WOWZA!**_ That's going to be a hard act to beat,\" Harley said as she led the audience back inside. \"But now we have a team who teaches by day and dances by night\u2014our very own Super Hero High teachers!\"\n\nThe audience oohed as the lights dimmed and a disco ball lowered from the ceiling. When Supergirl's laser gaze hit the mirrored ball, it lit up and showered the gym with hundreds of thousands of reflective sparkles. When Barda dropped the needle on a disco classic, Crazy Quilt struck a pose, looking resplendent in his all-white three-piece suit with flared pants and oversized purple glasses. His body moved in a combination of quick jerks and fluid spins. He did the splits\u2014 _literally\u2014_ and leapt up, not letting the rip in his pants stop him. When Vice Principal Grodd appeared behind Crazy Quilt along with June Moone, the music veered as the two did a graceful modern dance depicting the beauty of the change of seasons.\n\n\" _ **YOWZA,**_ will ya look at that!\" Harley exclaimed.\n\nNow the trio locked arms and were doing a high kick ending with a three-person backflip. The audience was on their feet cheering as the teachers left the stage.\n\n\"A-plus!\" shouted Harley.\n\nSomeone was pacing behind Barda. When Harley called him onto the stage, she was surprised to hear him say into the mic, \"Golly gosh, I'm so nervous.\" He was green, but then, he always was. \"I don't think I can do this!\"\n\nBeast Boy looked like he was on the verge of tears. The audience sat silent. A few even sobbed along with him as the green teen buried his face in his hands and wept. He started to walk off stage, defeated before he had even begun.\n\n\"Aww, Beasty, you're gonna be great,\" Harley assured him.\n\n\"You know what?\" Beast Boy looked around at the crowd. \"You're right!\" He gave one of his impish grins, pointed to Big Barda, and yelled, \"Hit it, BB!\"\n\nAs the music pulsated, Beast Boy morphed into an astonishing menagerie of animals. A hip-hop hippo, a graceful gazelle, a belly-dancing anaconda, and a twisting, turning otter. He had morphed through thirty-seven different animals by the time he was done. It took both Supergirl and Katana to get Beast Boy off the stage. As he took his umpteenth bow, Harley leapt over him to the center of the stage.\n\n\"And now for our mystery group,\" she announced. Harley paused for drama. She was all about the drama. \"This last-minute addition has been together since they met at Pedigree Prep Hall in kindergarten. Having just graduated from high school, they are looking for their next adventure. Perhaps it will be as professional dancers? You tell me! Put your hands together for a group you're going to be hearing a lot from...the Green Team!\"\n\nThe gym went dark. Slowly the lights went back on and, through a haze of smoke, the Green Team seized the stage. The young men and women were dressed in chic matching designer suits.\n\n\"They're wearing Calder Melino shoes!\" Sapphire whispered appreciatively to Lady Shiva as she took a picture of them and instantly posted it on #FashionistaFotos.\n\nWith precision so sharp that the entire audience gasped as if on cue, the Green Team snapped into three rows of four. They bowed and began to dance to the sounds of Celtic fusion funk. Acting as one instead of twelve, the Green Team incorporated all the styles of dance that been displayed in the contest thus far into their own performance.\n\n\"This is truly amazing,\" Harley said breathlessly. \"We are seeing the future of dance! Green Team, we're expecting to see a lot of you in the future!\"\n\nThe audience was on their feet roaring their approval.\n\n\"Next up, we name the winners,\" Harley announced. \"But first, a short break!\"\n\n\"I dunno, I dunno,\" Harley wailed as she nervously yanked on her own bouncy blond pigtails.\n\n\"You dunno what?\" Barda asked.\n\n\"I dunno who the winner is,\" Harley said to herself. \"They are all _sooo_ good!\"\n\n\"True,\" Batgirl agreed. \"But you have to pick one. Remember, instead of audience votes or a secret ballot, you said you were going to be the sole judge.\"\n\n\"Is it too late to do an online audience vote?\" Harley asked, biting her fingernails.\n\nBatgirl nodded. \"You have to go out there now and announce the winner. This show is streaming live. Your audience is waiting.\"\n\nHarley grimaced and pulled on her pigtails even harder.\n\n\"Quiet, everyone!\" Harley yelled.\n\nOutside, one hundred tap dancers stood at attention. Cyborg aimed his camera on them in case they were the winners. Inside, Grodd, Crazy Quilt, and June Moone held hands, waiting to hear their names. The CAD Academy break dancers were already congratulating themselves, and Sapphire had changed into her new celebration party dress as The Flash tried in vain to remove the purple glitter from his costume.\n\n\"This is a first!\" Harley said, her excitement bubbling up as she thought out loud. \"Never before in the entire history of dance contests has something like this ever happened!\"\n\nThe Green Team looked at each other and tried not to smile. Little dancing toddlers from Miss Toddler's Tots School for the Talented and Tiny squirmed in their mothers' arms. The Wally Waltzers from Vienna held their collective breath.\n\n\"The winner is...EVERYONE!\" Harley cried. \"It's a twelve-way tie!\"\n\nThe audience was silent. Stunned. Then the noise began. It was unclear whether people were cheering or booing, but either way, Harley was happy.\n\n\"And that's it for the first-ever Harley's Dance-O-Rama. Tune in for my next totally live, totally unexpected contest. Until then, keep watching. I know I will be!\"\n\nThe cameras shut off, but the crowd remained. Some were applauding the audacity of it all. Others were grumbling. And others were getting louder as they expressed their displeasure, since they were certain their team or their favorite should have been the one and only winner.\n\n\"I won?\" Beast Boy asked, looking confused. \"But so did they?\" he pointed to the trio from CAD Academy. They looked more intimidating than usual, if that was possible.\n\n\"We should have been the sole winners.\" Captain Cold's voice was as chilly as ice. He started to freeze Harley, but Wonder Woman stopped him with her lasso.\n\n\"This is a travesty,\" Sapphire said, staring down Harley. \"I should have won! I've already paid for the party!\"\n\n\"But you did win,\" Harley sputtered, unsure of why some people were mad at her. \"Everyone won.\"\n\n\"It's not winning if there are others on the winner's stand,\" Sapphire lectured Harley. \"If this is your idea of a joke, it isn't funny!\"\n\nWhen Harley started to protest, Cheetah commented, \"Looks like the class clown has really flubbed this one.\"\n\nDespite the mixed reactions to Harley's announcement, or maybe because of it, her viewership soared. Not only did a record number of people tune in, but they watched the Dance-O-Rama over and over again. Harley was getting hundreds of messages at a time. She was loving it.\n\n\" _Unexpected_ was the word for Harley Quinn's first-ever dance contest,\" Lois Lane reported. \"The chatter is burning up the Internet. Some are thrilled with the judicious twelve-way tie. Others are incensed, saying that Harley copped out by refusing to name one winner. There have even been threats lobbed at her. Harley, what do you have to say about all this?\"\n\nHarley smiled at the camera. \"I say let's do it again. But first, I've got something even bigger planned. You'll be the third to know, Lois. First me, when I think of it. Second will be my loyal and loving Harley's Quinntessentials audience!\"\n\n\"Harley, are you worried about the angry comments?\" Lois asked. \"Some dance fans can get pretty serious.\"\n\n\"Nah,\" she said, sounding cavalier. \"I can handle anything. I'm Harley Quinn!\"\n\nAt the weekly assembly, Supers were flying and tumbling and climbing the walls. That is, until Principal Waller took the stage and cleared her throat. Instantly, everyone was seated and the room was so silent you could hear Vice Principal Grodd crack his knuckles. Repeatedly.\n\nAs Waller congratulated the Dance-O-Rama competitors from Super Hero High, the dancers stood to be acknowledged. The reception was thunderous. After all, the Supers were always ready to support each other. Star Sapphire and her corp, including The Flash, stood and twirled before taking a bow. Beast Boy turned into a parrot and flew overhead squawking, \"Thank you! Thank you! Thank you!\" And the teachers waved politely, as if they were in a parade.\n\n\"Disco! Disco! Disco!\" the Supers chanted. It didn't take much for Crazy Quilt to stand and strike a disco pose.\n\n\"You do the disco pose!\" a Super yelled to Principal Waller. Harley looked around to see who would be so brave.\n\nNo one was taking credit.\n\n\"Never going to happen,\" Principal Waller said, trying to hide her amusement. \"Now, let's talk about why you are all here and the responsibilities you shoulder.\"\n\nBig Barda had a piece of lemon cake in front of her, but she was ignoring it.\n\n\"You gonna eat that?\" Harley asked. She loved cake. Birthday cakes. Pound cakes. Funnel cakes. Ice cream cakes. All cakes\u2014especially cakes right in front of her!\n\n\"Not hungry. You can have it,\" Barda said, handing it over.\n\nAs Harley dug in, Supergirl put her arm around Barda's shoulder. \"Are you all right? You look worried.\"\n\n\"I think Principal Waller was talking about me,\" Barda said, staring down at her lap.\n\n\"What do you mean?\" Bumblebee asked. She was working on her second slice of honey bread.\n\n\"I think that when she was talking about responsibility, she was telling me that I'm responsible for Granny Goodness and the Female Furies when they came through the Boom Tubes and tried to take over the school,\" Big Barda said in a rush.\n\n\"Well, you were one of them then,\" Harley said, trying to be helpful.\n\nSupergirl, Bumblebee, Thunder, and Lightning glared at her.\n\n\"Wha?\" Harley said through a mouthful of cake. \"It's true!\"\n\nSupergirl turned back to Barda. \"That was then. You've changed and helped the fight against evil and are partly responsible for our victories!\"\n\n\"That's right,\" Lightning chimed in. \"Remember what Principal Waller keeps telling us?\n\n\" 'We are here because of who we can become tomorrow,' \" her sister said.\n\nSupergirl nodded. \"I didn't ask for my powers of strength and flight and heat vision. But now that I have them, I have a responsibility to make sure I use them to my best ability, and to help others in the process. Harley,\" she said, \"what's your take on responsibility?\"\n\nHarley polished off the last morsel of cake and the colorful crumbs left on the plate. \"I've been giving this lots and lots of thought,\" she told the group. \"So many thoughts, my noggin' is a-swimming. Ha! Can you just picture a head swimming?\"\n\nEveryone waited for Harley to sit down and stop pretending that her head had come free and was bobbing up and down on an imaginary ocean.\n\n\"Anyway,\" she continued. \"I was thinking about the Dance-O-Rama and how great it was, and even now the replays of the Web special are getting more and more views. Plus, I got a record number of comments after\u2014\"\n\nMiss Martian leaned over and whispered reverently to Ivy, \"She gets tons of fan mail! I know. I've seen it.\"\n\n\"\u2014so when I think about responsibility, I think that it is my responsibility to...Are you ready? This is big!\" Everyone nodded as Harley stood on her chair and shouted, \"It is my responsibility to announce that the next Harley's Quinntessentials will feature...a Battle of the Bands!\"\n\n\"Who can tell us why your weapons are important?\" Mr. Fox asked. He strolled purposefully up and down the rows of desks with his hands laced behind his back. His thick black glasses made him look serious, but his orange sweater and magenta tie said otherwise.\n\nWonder Woman raised her hand.\n\n\"Yes, Wonder Woman?\" the Weapononics teacher said.\n\n\"Our weapons are to protect and defend,\" she began. \"However, in the wrong hands they could be used to destroy. It is our responsibility to use them wisely.\"\n\n\"Excellent!\" said Mr. Fox, beaming. \"Anyone else? Harley, what about your mallet?\"\n\nHarley had been daydreaming about the Battle of the Bands. In her imagination, after the winner was announced, she would start a record label called Mallet Music, and it would be an instant hit\u2014\n\n\"Harley?\" Mr. Fox said, snapping her out of her daydream.\n\n\"Huh? Harley? That's my name, don't wear it out!\" Harley quipped.\n\nAs the class laughed, Mr. Fox shook his head. Harley smiled sheepishly and shrugged.\n\nUnfortunately, this was not the last time she'd be caught daydreaming.\n\nIn history class, their teacher Liberty Belle talked about the great battles of the last century\u2014including recent ones with the Supers, led by Katana, battling Dragon King, and Supergirl leading the charge against Granny Goodness, and Batgirl versus the Calculator.\n\n\"I seek to honor the legacy of my grandmother,\" Katana said. \"She fought hard against evil, and passed down her beliefs to me. I feel that in my heart.\"\n\n\"Thank you,\" Liberty Belle said. \"Harley, you look like you want to say something. What can you add to this conversation?\"\n\nHarley had been poking the girl in front of her, who was doing an excellent job of ignoring her. She was hoping Hawkgirl would agree to be stage manager for the Battle of the Bands.\n\n\"Harley...?\" Liberty Belle said, waiting for an answer.\n\n\" _ **WOWZA,**_ Teach!\" Harley said, glancing around the room. \"Um, er...well, yes.\" She wished she knew what the question was. That would make things so much easier!\n\nEveryone was staring at her. Cheetah smiled and whispered, \"We were talking about our favorite foods.\"\n\nHarley winked a \"thank you\" and said with gusto, \"Fried pickles and triple-chocolate swirly ice cream loaded with sprinkles!\"\n\nHarley had one last class that day. An elective. Music. Super Hero High had been missing a music teacher ever since the last one fled during Thunder and Lightning's Dueling Duets demonstration. Thunder had created powerful shock waves that hit all the acoustic instruments, causing them to reverberate cacophanously. Then Lightning countered by trying to commandeer the electronic synthesizers and drum machines with her electrical powers and overloading them. The equipment began to malfunction and sparks flew\u2014musically and literally.\n\n\"I can't wait to meet the new teacher,\" Harley was saying as she bounced down the hallway.\n\n\"Me too!\" said Raven as she rushed past, her dark cloak fluttering behind her.\n\nThe music room was full. Some students were carrying their instruments\u2014violins, guitars, a piano. Big Barda had an accordion, and Green Lantern was polishing his tuba.\n\nThe man in the front of the classroom was bent over, digging through a briefcase. \"Ah! Here it is,\" the new teacher said, pulling out a silver flute. His green cape covered his face, but when he pulled it off, he had a brilliant smile. \"I am your new music teacher, Pied Piper!\"\n\n\"Mr. Pied Piper,\" Beast Boy called out, \"what kind of music will you be teaching?\"\n\n\"What kind would you like?\" he asked, waving his flute like a conductor's baton.\n\nAs they called out \"Classical!\" \"Hip-hop!\" \"Retro rock!\" \"Jazz!\" \"New wave!\" and \"Electrolite!\" the Pied Piper nodded.\n\n\"We will do all that and more. But first, I've heard a musical rumor. Harley Quinn!\" he called out. \"Is it true you're putting on a Battle of the Bands? If so, I'd like to offer my services to coach any Super Hero High musicians who might be competing. Is that okay with you?\"\n\nHarley grabbed one side of Big Barda's accordion. \"Hold on!\" she instructed Barda as she ran across the room, stretching out the bellows. \"Here's my answer, Mr. Pied Piper, sir!\"\n\nShe let go and the accordion folded back toward Barda, making a _wooom_ sound. \"That's music for yes,\" Harley said, letting go of a big laugh. \"This 'battle' is gonna be epic!\"\n\nBatgirl was buried. There were so many audition videos and Web links of bands that it was almost a full-time job logging them all in\u2014and it had only been a couple of days since Harley's announcement.\n\n\"It's gonna be the biggest and baddest and best-est Battle of the Bands this world has ever seen!\" Harley proclaimed to her Web fans. \"Everyone is welcome to enter. Just send in a short audition tape, and if you're one of the lucky finalists, you will perform LIVE on the Internet for an audience of a zillion-ish viewers!\"\n\n\"What can we do to help?\" the ever-efficient Hawkgirl asked.\n\n\"You can help me log these in,\" Batgirl said, pushing a pile of old-school tapes and discs toward her.\n\n\"Is this why you called a meeting of the Junior Detective Society?\" Bumblebee asked. \"For our help in sorting this all out?\"\n\nThe Junior Detective Society was a school club mostly comprised of Batgirl, Hawkgirl, The Flash, and Bumblebee\u2014though other Supers helped them with cases or came to them for help. The Junior Detectives loved a mystery.\n\n\"Yep,\" Batgirl confirmed. \"It's a mystery how we can get through the auditions. We need a system to sort and view everything. Harley's putting together a group of Supers and citizens to help listen, right?\"\n\nHarley nodded, then went back to watching a commercial of herself advertising the Battle of the Bands on one of Batgirl's computer screens.\n\n\"We're on it,\" Hawkgirl said. She was already drawing a diagram of a sorting system, while The Flash in a nanosecond\u2014or two\u2014had logged in the videos. Meanwhile, Bumblebee was online, scanning the emails with musical Web links.\n\n\"It's like anyone who's ever picked up a musical instrument is vying to get on the show!\" The Flash exclaimed.\n\nSure enough, it was a who's who of super heroes, super villains, and citizens. \"Look!\" Bumblebee called out excitedly. \"Mandy Bowin is auditioning!\"\n\nMandy had been a student at Super Hero High, but left to pursue her music. Also on the list was the Korugar Academy Marching Band, plus Black Canary and the Birds of Prey, and the Bad Banshees featuring Silver Banshee on vocals, Gizmo on drums, and Jinx at the keyboard.\n\n\"There are lots of Supers from Super Hero High trying out, too!\" Hawkgirl noted.\n\nA knock on the Bat-Bunker door interrupted them. Batgirl buzzed Wonder Woman in. \"Dinnertime!\" said Wonder Woman.\n\n\"You guys go ahead,\" Batgirl said to her friends. \"I want to finish this up, then send it out to the preliminary screeners and the judges.\"\n\nAt last the room was quiet, and Batgirl exhaled. \"So nice to be alone sometimes!\" she said after a few minutes of silence.\n\n\"So then,\" a voice said, \"do you think I'll break the number for the most viewers with BOB? That's what I've nicknamed Battle of the Bands. BOB, get it?\"\n\n\"Harley, you startled me!\" Batgirl said, laughing. \"I thought you had left with the others.\"\n\nHarley began randomly touching all the buttons and keys on Batgirl's computer console. \"I've asked you not to do that,\" Batgirl said, moving her friend's hands away. \"Was there something you wanted to talk about? Is this about Battle...er, BOB?\"\n\n\"Maybe, maybe not,\" said Harley. She was now fiddling with Batgirl's Batarang and accidentally dislodged it.\n\nBatgirl ducked, then caught it with one hand while still typing with the other. \"What is it?\" she asked.\n\n\"Aww, nothing!\" Harley said, putting on a smile to mask her frown. \"I was just scared for half a second. But it's dumb, and I'm fine. Not to worry. I'm not worried. Who's worried? Not me! Is it you? What are you worried about, Batgirl? Do you wanna talk?\"\n\n\"Harley, stop jumping on my bed and tell me what's going on,\" Batgirl said, patiently.\n\nHarley sat cross-legged on the floor and Batgirl joined her.\n\n\"What if I mess up?\" Harley said, so softly that Batgirl had to strain to hear. \"What if the Battle of the Bands isn't a huge hit? Some people are already mad at me because I named everyone a winner at the Dance-O-Rama.\"\n\n\"I thought this sort of thing didn't bother you,\" Batgirl said.\n\n\"It doesn't!\" Harley said a little too loudly.\n\nBatgirl didn't respond.\n\n\"Okay, okay, it does bother me a little. But don't tell anyone. I have a reputation to uphold!\"\n\n\"Everyone likes you,\" Batgirl assured her.\n\n\"Not everyone,\" Harley said. \"Some people think I'm just a class clown. But I'm more than that, aren't I?\"\n\nBatgirl reached over and gave her a hug. \"You're fun and funny, and a super friend. You've proven yourself to be a hero again and again. Harley Quinn, you're one of a kind!\"\n\nHarley gave her friend an \"aww, shucks\" grin as Batgirl turned back to the task at hand.\n\nThe Internet was lit up, and rumors were flying so fast about who would make it to the finals that everyone was dizzy. Some of the musicians were even sending promotional items like T-shirts emblazoned with their band's logo on them in the hopes of currying favor with the judges.\n\n\"Look! I got this in the mail,\" Miss Martian said. She was so excited she kept shifting from foot to foot.\n\nMiss Martian unfurled a poster of the Green Team. Inexplicably, they were standing on a white sand beach, each gazing in a different direction, as the orange sun melted into the azure sea. The headline read\n\n> _**FOR YOUR BATTLE OF THE BANDS CONSIDERATION: THE GREEN TEAM!**_\n\nClipped to the top of the poster was a twenty-dollar bill.\n\n\"That,\" said Hawkgirl, frowning, \"is an infringement upon the rules. No bribes! The Green Team just disqualified themselves.\"\n\n\"Yeah,\" Harley had to admit. \"They're out. That's a shame. Since the Dance-O-Rama they've earned a huge following.\"\n\nMiss Martian stared dreamily at the Green Team and asked, \"Can I keep the poster?\"\n\n\"We cannot, cannot, cannot have the same mess we had with the twelve-way tie for the Dance-O-Rama,\" Harley told Batgirl.\n\n\"But, Harley, you were the one\u2014\" Hawkgirl started to say, but Harley put her fingers in her ears.\n\n\"I can't hear you,\" Harley said. \"Lalalalala, I can't hear you!\"\n\n\"I can program the site so that no one can vote more than once,\" Batgirl was saying. \"I'm installing a pupil recognition device to ensure one person, one vote.\"\n\n\"Well, since you have this under control, I'm off to the Battle of the Bands location,\" Harley informed them. She was now pacing the room, adding a few flips here and there. \"It's spectacular!\"\n\nBatgirl looked up. \"Where is it?\"\n\n\"Not sure yet,\" Harley admitted. \"But when I find it, I'll let ya know!\"\n\nAs Harley and Katana flew in the Invisible Jet with their pilot, Wonder Woman, they looked for a venue that would be inviting, could hold lots of people, and had great acoustics.\n\nThe trio was getting weary. Flying around the world was exhausting. So many places to go. So much to see. So little time. They flew over Diamond Head in Hawaii, but there was no guarantee that the volcano wouldn't erupt mid-BOB. The Colosseum in Rome was \"too old and musty-dusty,\" according to Harley, and the Sydney Opera House in Australia was already booked.\n\n\"What about the Grand Canyon?\" Wonder Woman suggested. She shifted gears and turned her jet ninety-seven degrees to the left. \"The acoustics would be amazing!\"\n\nSoon they were flying above the South Rim. Red rocks and mile-deep canyons revealed the millions and millions of years of geological history.\n\n\"This looks like the perfect place for BOB!\" Harley enthused.\n\nAs they landed and scrambled out of the jet, Katana looked down into a ravine. \"Hello!\" she yelled.\n\n\"Hello! Hello! Hello!\" it answered.\n\n\"Too much echo,\" Katana said, shaking her head.\n\n\"Knock, knock!\" Wonder Woman said, giving it a try.\n\n\"Knock, knock, knock, knock,\" the Grand Canyon replied, and then added, \"Who's there?\"\n\n\"Huh!\" Wonder Woman shouted. \"Did you hear that?\"\n\nHarley couldn't stop laughing. \"That was me! Okay, where to next?\"\n\n\"Food?\" said Wonder Woman. \"I'm hungry.\"\n\n\"Me too,\" Katana said.\n\n\"Me three,\" Harley agreed.\n\nWonder Woman shifted into autopilot. After landing near Metropolis's Centennial Park, the girls were on foot when Katana stopped abruptly, causing Harley to bump into her. \"Do you hear that?\" Katana asked.\n\n\"Hear what?\" asked Harley. \"The laughter of little children at play? The melodic tunes of the birds singing? The plaintive meow of Rainbow the cat up the tree?\"\n\n\"No,\" Katana said, pivoting around. \"That!\"\n\nWonder Woman was already on the move. Three burly truck drivers were yelling.\n\n\"Help!\" the biggest one cried. \"Our trucks were stolen and they're full of medical equipment for the Metropolis Hospital!\"\n\n\"We've got this covered!\" Harley assured him.\n\nWith Wonder Woman in the air and Harley and Katana on the ground, they caught up to the wayward trucks in no time. Blocking the vehicles, the Supers stood with their hands on their hips as the trucks screeched to a halt only inches away from them.\n\nFor a brief second, the smile slid off Harley's face. \"Uh-oh,\" she said.\n\n\"Not good,\" Katana agreed.\n\n\"Not good for them,\" Wonder Woman added.\n\n\"Well, hello, hello, girlies,\" said the criminal, who looked like a cross between a pterodactyl and a man. He flapped his powerful wings, causing the leaves to blow off the trees.\n\nWonder Woman's eyes narrowed. \"Hello, Airstryke.\"\n\n\"How's Queen Hippolyta?\" the baddie Airstryke asked as he rose above the ground. \"I haven't seen you or your mother since she threw me in prison.\"\n\nWonder Woman flew up so they were face to face, one hundred feet in the air.\n\nHarley stood her ground, twirling her mallet, ready for action. Katana was poised to unsheathe her sword.\n\n\"Mom's fine, thanks for asking,\" said Wonder Woman as Airstryke flew at her with his sharp teeth bared. \"You should brush more often,\" she added.\n\nKatana and Harley were about to throw their weapons at him, when the doors of the other trucks flew open. A muscled man who had a skull instead of a face stepped out of one, and a man dressed in red with yellow boots and cape leapt out of the other.\n\n\"Aerialist and Atomic Skull,\" Katana said to Harley. \"Liberty Belle told us about them, remember?\"\n\nHarley nodded in the affirmative, but in reality she wished she had paid more attention in class.\n\n\"I got the leaping guy,\" Harley called out as Aerialist jumped backward on top of a truck. She tossed her camera up against a nearby building so that it hit the wall...and stuck.\n\nKatana crouched down. \"Atomic Skull's mine,\" she said.\n\nAs the battle ensued in the air, on the ground, and along the desolate road, Harley was laser-focused on Aerialist.\n\n\"You used to be a stuntman?\" she asked as he hurled himself toward her.\n\nHarley cartwheeled at him so fast that she was nothing more than a blur of a ball. Midair, she hit him with her mallet. \"How's that for a stunt?\" she asked. He slammed against a nearby building and then fell to the ground, completely stunned.\n\nAbove, Wonder Woman was in fast pursuit of Airstryke, who did a one-hundred-eighty-degree turn in midair and started chasing her. \"Wonder Woman, look at you,\" he said. \"I remember when you were just an itty-bitty little thing trailing along in your mother's shadow!\"\n\n\"Well, Airstryke, I'm not a little girl anymore!\" Wonder Woman adjusted the golden cuffs her mother had given her. She lifted her Lasso of Truth and began to twirl it. As it sliced through the air, it was Airstryke's turn to flee.\n\nAs Airstryke tried to get away, she lassoed his foot, and with a mighty pull, sent him hurtling toward the ground.\n\nMeanwhile, Atomic Skull began to glow. He was emitting a radioactive field as Katana circled him, sword in hand. \"What do you want with the medical equipment?\" the villain asked.\n\n\"I want to help the children at the hospital,\" she said.\n\n\"Your heart is too soft.\" He laughed and shook his head.\n\n\"Maybe,\" Katana said, tightening her grip. \"But my sword is not!\"\n\nA few yards away, Harley bowled the Aerialist over with a swing of her mallet as he leaped toward her. He went soaring when the mallet made contract. Midair, he crashed into Airstryke, and the two villains tumbled onto the asphalt in a heap.\n\n\"Now, that's what I call an air strike,\" Harley said with a laugh.\n\nFlying around the defeated villains at super-speed, Wonder Woman tied them up with the Lasso of Truth. Then she and Harley joined Katana.\n\n\"Something's wrong with your noggin!\" Harley quipped as Atomic Skull began generating more and more energy. The heat force around him expanded. \"You're getting all full of yourself.\"\n\nAtomic Skull laughed. \"Goodbye, super heroes,\" he said. \"Nice knowing you!\"\n\nBut before he could activate his lethal blast projection, Harley distracted him with a series of cartwheels. Simultaneously, Katana caught his attention as she neared him with her sword. Atomic Skull didn't see Wonder Woman. The Amazon had picked up a large moving van and scooped him up into the back. The villain was jostled as he banged around inside the truck.\n\nHarley slammed the doors of the van as Wonder Woman set it down. Katana put her sword through the handles to make sure Atomic Skull couldn't get out until the authorities arrived.\n\n\"Case closed!\" Harley cheered.\n\nBy the time Harley and her friends made it to Capes & Cowls, Steve Trevor had a table reserved for them.\n\n\"Some truck drivers called and bought these for you,\" he said. His wide smile revealed his braces as he served the heroes their favorite smoothies.\n\n\"Hi, Steve!\" Wonder Woman said brightly.\n\n\"Hi, Wonder Woman! Um, I have to take some orders, but I'll be back to check on you,\" he said, backing away and bumping into the table behind him.\n\n\"Watch where you're going!\" sneered Captain Cold.\n\n\"Sorry, sorry,\" Steve apologized.\n\nHarley was calling Batgirl on her phone. \"Would you mind uploading the video I just sent you?\" she asked. \"It's a Save the Day that just happened.\"\n\n\"Sure thing,\" Batgirl said from the Bat-Bunker. \"I'll also set you up so you'll be able to do it yourself. In the meantime, have you found a venue yet?\"\n\n\"Still looking,\" Harley reported. She watched Steve set a huge pizza on the table. One side had ham and pineapple on it, and the other had mushrooms. Harley took two slices of ham and pineapple, put a slice of mushroom between them to make a pizza sandwich, and bit into it.\n\n\"We're using the land behind the caf\u00e9 as a temporary animal preserve while the zoo gets ready for its new wildlife sanctuary,\" Steve was telling Katana and Wonder Woman.\n\n\"That's nice of you,\" said Wonder Woman.\n\n\"That explains the smell,\" Harley said, pinching her nose.\n\n\"It's no big deal,\" said Steve. \"Anything for the animals. Some have been injured or orphaned, or are old and wouldn't last in the wilderness. If they become strong and independent enough, they're returned to the wild. They'll be out of here and at the sanctuary in a couple days.\"\n\nKatana looked out the window. She could see the animals milling about. \"They've been through a lot. As far as I'm concerned, they can make all the smell and noise they want!\"\n\nThe table was quiet for a moment as they listened to the animals. It sounded like they were in the same room.\n\n\"Hey, Stink-o Steve-o,\" Ratcatcher called out. \"More french fries over here, and make it snappy!\" He threw several rat traps on the ground and Steve had to leap over them to avoid getting caught. Snap, snap, snap!\n\nBut all Harley could hear was the sounds of the animals.\n\n\"Good food. Lots of space. Great acoustics.\" Harley began. She looked up at the ceiling as she kept repeating herself. \"Good food. Lots of space. Great acoustics. Good food. Lots of space. Great acoustics.\" Suddenly, Harley leapt to her feet. \"I got it! I know where we should hold the Battle of the Bands!\"\n\nSteve tiptoed around the rat traps and brought the teens another pie. But instead of a pizza pie, it was an apple pie. \"It's made from locally grown apples from Poison Ivy's garden,\" he said. \"Dig in, it's fresh out of the oven.\"\n\nSteve noticed Harley staring at him...very intently.\n\n\"Um, is there anything else I can do for you?\" he asked.\n\n\"You betcha!\" Harley said. \"You can host my Battle of the Bands here!\"\n\n\"I don't understand,\" Steve said. \"Here?\"\n\n\"Here!\" said Harley. \"You have good food. Lots of space. It's perfect!\"\n\n\"It is perfect,\" Wonder Woman chimed in. \"We can transform your parking lot and that area where the animals are into an arena....\"\n\n\"And the caf\u00e9 can provide food stands,\" Katana explained, \"and the Supers will help man them. But you can be in charge of the menu, Steve!\"\n\n\"And your acoustics are awesome,\" Harley said. She raised her hand and yelled, \"Shhh! Everyone be quiet!\"\n\nAll were silent as they listened to the sound of a green hippopotamus mumbling about needing ice cream.\n\n\"What's going on here?\" the green hippo said.\n\n\"Beast Boy,\" Harley enthused. \"Tell Steve here that Capes and Cowls would be the perfect venue for BOB.\"\n\n\"What she said,\" Beast Boy said, turning back into a boy.\n\n\"Think of the publicity!\" Harley added.\n\n\"I don't know,\" Steve said, rubbing his chin thoughtfully. \"It's a pretty big deal, the Battle of the Bands. Everyone will be watching.\"\n\n\"Exactly!\" Harley said, nodding.\n\nThe girls agreed: The caf\u00e9 would be just the place. It was centrally located and had everything they were looking for. Plus, the BOB wasn't until after the animals were to be relocated to the zoo's wildlife area.\n\nJust then, the bell on the door signaled another customer. \"It's Pied Piper!\" Katana said. \"Hello!\"\n\nThe music teacher had been working with the Supers and teachers who had entered the contest, and everyone couldn't help but adore him. Walk past his music room at any hour of the day and you could hear The Flash breaking up more sets of bongos than he was willing to admit, and the retro-rock sounds of Teacher Teacher with Liberty Belle singing lead and backed up by Doc Magnus on the synthesizer and Red Tornado on the electric guitar. And no one could ignore\u2014or stand\u2014the vivacious vocal stylings of Beast Boy.\n\n\"Pied Piper is the best!\" Harley was saying as she watched him nodding his head to the music playing on the jukebox.\n\n\"Yes, and he's deaf and uses that to his advantage,\" Katana added.\n\nHarley raised her eyebrows.\n\nPied Piper waved at the girls as he picked up his to-go order and left.\n\n\"Deaf? No way!\" Harley insisted. \"But he's the music teacher!\"\n\n\"And an incredible one,\" Katana added. \"Pied Piper can feel the music in a much more powerful way than the rest of us. Plus, the rumor is that he can read lips so well the government has used him as a spy since he also understands several languages!\"\n\n\"How did I miss that?\" Harley asked.\n\n\"You've been busy,\" Katana said. \"Harley, sometimes you're so busy you don't notice what's happening around you, or even have time to spend with your friends.\"\n\nWonder Woman nodded. \"It's true!\"\n\nHarley wondered if her friends were trying to tell her something. She made a note to talk to them about it, when she had more time. Then she burst out laughing. _Like, when am I ever going to have more time?_ she asked herself.\n\nThere were so many students clogging the corridors that Principal Waller asked the head hall monitor to add extra hours.\n\n\"Keep it moving,\" Hawkgirl said as she flew up and down the flight lanes that flanked the walkways. \"Nothing to see here!\"\n\n\"But everything to listen to,\" quipped Harley as she stood outside the music room. \"It's sounding great in there.\"\n\nShe was right. Pied Piper had helped whip the musical acts into shape. Many of them had been good, but under his direction, now they were great.\n\n\"Less feedback on the keyboard amp!\"\n\n\"Your falsetto is sounding false!\"\n\n\"Love the harmony, keep it up!\"\n\n\"Dueling pianos, I want more ritardando!\"\n\nThe only time the competitors weren't listening to him was when they were arguing among themselves.\n\n\"As lead singer, I should be able to pick the song,\" Liberty Belle was saying to Red Tornado.\n\n\"Well, it better have a great acoustic guitar solo,\" he countered.\n\n\"Cheetah, could you do your warm-ups over there?\" The Flash asked as he broke another pair of bongos. \"You're distracting me.\"\n\n\"No, you move,\" she said, raising her voice.\n\n\"Miss Martian? Miss Martian, are you with us?\" asked Poison Ivy.\n\n\"I'm here,\" the shy invisible alien said quietly as a cello made its way across the room.\n\n\"I could stand here listening all day,\" said Harley as she looked in from the doorway and waved to her friends.\n\n\"And I could write you up,\" Hawkgirl said good-naturedly. \"Anyway, shouldn't you be working on that assignment for Fox's class? It's due tomorrow.\"\n\nHarley tried to hide her surprise. \"Oh! It's due tomorrow? Good thing I'm almost done. Um. Could you remind me just what we're supposed to do?\"\n\nThe truth was, Harley was so busy with Battle of the Bands that her schoolwork had begun to slip. And so had her time with her friends, and most everything else. On the plus side, her viewership was rising at a rocket's pace. BOB updates were rotated at regular intervals, and then viewers stayed for Harley's exclusive Super Hero High gossip clips and laughed along to reruns of \"Super Heroes' Super Blunders.\"\n\nLuckily, Harley's team of BOB volunteer judges had winnowed the thousands of auditions down to the final fifty. Harley herself would pick the top ten, but she was having trouble deciding. Every audition sounded like a winner, and she had difficulty rejecting anyone because that might make them sad.\n\n\"Please pass your assignments to the front of the class,\" Mr. Fox said. \"I am looking forward to reading these. As a preview, we will go around the room and each of you will provide a one-sentence summary of your report. Ms. Quinn, we'll start with you.\"\n\nHarley gulped and looked desperately at Miss Martian, trying to get her attention. _Read my mind, Miss Martian! Read my mind, and tell me what to say!_ Harley had her eyes screwed shut and was thinking hard. _Whisper what the assignment was and what I should say!_\n\n\"Harley, are you okay?\" Mr. Fox's brows were knit together as he scrutinized her face.\n\nHarley unscrewed her eyes. She looked at Miss Martian, who refused to meet her gaze. \"Yes, sir, Mr. Fox, sir!\" Harley said.\n\n\"And your sentence would be...?\" he prodded.\n\n\"Well, my report is about all that stuff that is so important and that we need to know about and that we were supposed to write about. And that's what my report is about!\" she said.\n\n\"Please stay after class, Ms. Quinn,\" Lucius Fox said. \"Now, Wonder Woman, please put your hand down. Yes, you can go next.\"\n\n\"So then he tells me that not only do I have to make up my missing assignment, but I need to write an additional paper on the Power of Powers,\" Harley said, moaning.\n\n\"I can help you with your homework,\" Supergirl volunteered. A group of girls was hanging out in Harley's room.\n\n\"Would you?\" Harley said, sitting on the clothes on top of the books on top of her bed. It was hard to tell where the pile ended and the bed began, but that never seemed to bother Harley. \"That would be swell! Could you have it done by Tuesday?\"\n\n\"I said I would help, not do it for you,\" Supergirl said, sounding friendly but firm.\n\n\"But I'm sooo busy with the Battle of the Bands,\" Harley explained. \"We have less than a week to go!\"\n\n\"Don't I know it?\" Supergirl said. She was on Harley's amphitheater committee along with Wonder Woman and The Flash. They were charged with creating a band shell now that the temporary wildlife sanctuary had been moved out.\n\n\"Pleeeeease,\" Harley begged.\n\n\"No!\" Supergirl replied.\n\nHarley looked exasperated and blew a wisp of hair out of her eyes. \"Fine. Homework. Check. Moving on. What's everyone else up to?\"\n\nThe food committee was headed up by Steve Trevor. Wonder Woman had volunteered to be on that committee, too, as well as on the parking lot committee and the crowd control committee. With Hawkgirl as stage manager, Batgirl was assigned to check in the contestants. Big Barda was in charge of the sound system. And Bumblebee was talent wrangler. The entire Capes & Cowls Caf\u00e9 was the designated greenroom. With the waiting area sure to be packed, Bumblebee's ability to shrink made her the ideal candidate to weave in and out of the crowd of hopefuls.\n\n\"A greenroom is just what they call where the talent hangs out before they go onstage,\" Batgirl explained. She knew this, having been a contestant on TechTalk TV.\n\n\"But it's not green,\" Poison Ivy pointed out. \"Though I could fix that.\"\n\nSuddenly Harley leapt up and began jumping on her bed, holding her hands up so she wouldn't hit her head on the ceiling. \"It's time! It's time!\"\n\n\"What's time?\" Ivy asked.\n\n\"I'm going live in ten minutes to name the finalists,\" Harley blurted out. \"This is gonna be big! Maybe the biggest thing ever!\"\n\nAs Harley turned on her video equipment, Big Barda stopped in. \"Hey, Harley, me and some of the others are starting a glee club. I'm thinking of calling it Mighty Melody Makers. Wanna join us? It'll be fun!\"\n\n\"Fun! Who has time for fun?\" Harley said, looking serious, then grinning ear to ear. \"I'm about the make the big announcement and I barely have time to eat and sleep. There's no time for glee!\"\n\nAdam Strange and Arrowette were hard at work in Centennial Park. Since Harley anticipated overflow crowds, video screens were sent for. That way, spectators could watch off-site and still be a part of the festive atmosphere.\n\nAdam was in the air, hovering with the power of his jet pack. \"Is it straight?\" he asked, holding up the last giant screen that needed to be placed.\n\n\"A little to your left,\" Arrowette said. She pulled three arrows from her quiver in quick succession, took aim, and shot. Each arrow made a satisfying twang when she let go. They stopped an inch from Adam's hand and secured the screen to the wooden post.\n\n\"Hey, you almost hit me,\" he called out.\n\nArrowette reached over her shoulder for another arrow from her quiver. \"If I wanted to hit you, I would have,\" she said with a wink.\n\nHarley couldn't stop moving or talking. \"Thisis\u00adgonnabesobig! Iwouldn'tbesurprise\u00addifIbusted\u00adthe\u00adInternet\u00adwithsomany viewers!\" she said as she cartwheeled backstage.\n\n\"You're going to have to slow down if you want to be understood,\" Hawkgirl barked. The amphitheater was still under construction, but it was taking the shape of a giant open oyster shell. Katana had painted the impressive red-and-gold Battle of the Bands sign that hung overhead. Harley had asked her to add her HQ logo, and with the help of art teacher June Moone, Katana created one in neon lights.\n\nFor the stage itself, Poison Ivy had suggested that they reuse the dance floor. However, Hawkgirl pointed out that it was pocked and damaged due to one hundred tap dancers and various others.\n\n\"Besides,\" Harley was quick to remind everyone, \"this is gonna be BIGGER than the last special, and _**YOWZA!**_ We need lots and lots and lots of room for the live audience!\"\n\nPoison Ivy gave this some thought and absentmindedly began braiding her long red hair before proclaiming, \"I've got it! Let's use recycled wood from the old Schumacher Shoelace factory that was recently torn down!\"\n\nShe had barely finished her sentence when Wonder Woman and Supergirl were on the job. Not only did they think this was a great idea, but later they even stacked boulders they had recently cleared from an avalanche in Denver to flank the sides. For extra oomph, Poison Ivy created a cascade of fragrant flowers and then a huge canopy of tulip trees, saucer magnolias, and ropey vines to shade the audience. The result was spectacular, like nature herself was the architect.\n\nSteve Trevor had several Capes & Cowls Caf\u00e9 booths set up around the perimeter. Some sold tropical fruit and berry smoothies, others featured freshly baked cookie crisps in the shapes of musical instruments, and still others sold pizza, veggie burgers, and sweet potato fries. Each booth was manned by volunteers from the zoo and students from Super Hero High. Since the proceeds were going to the wildlife sanctuary, Principal Waller had offered community service points to those who helped out.\n\n\"The contestants are starting to arrive,\" Bumblebee reported from the greenroom. \"Ukulele United from the island of Kauai is here and they're passing out fresh orchid leis to everyone. They smell lovely.\"\n\n\"Got it!\" Hawkgirl said into her headset. She turned to Harley. \"One hour to showtime!\"\n\nThe Capes & Cowls Caf\u00e9 greenroom looked the same as the restaurant always did: cozy and comfortable, yet with a trendy edge to it. The only difference was that Katana had created several posters, one for each of the finalists, with their names and Welcome! on them.\n\n\"We're better-looking than that,\" Captain Cold said, sending a chill around the room. \"Well, I am. Not so sure about them.\" He laughed as other members of CAD Academy's heavy-metal band hauled in their instruments.\n\nMagpie, the drummer, was dressed in a tattered black dress anchored with steel-tipped boots. Ratcatcher had spiked his hair so that it stood up in every direction and could have doubled as a weapon. Captain Cold wore ice-blue mirrored sunglasses and a distressed leather bomber jacket with CC on the back.\n\n\"Hey!\" Harley yelled at Ratcatcher. Big Barda stood behind her and crossed her arms. \"Stop tearing the other groups' posters down or ya get disqualified.\" She turned to the camera and when the red light went on, Harley began, \"In a short while we'll go behind the scenes of HQ's first-ever Battle of the Bands. And at the top of the hour, stay tuned for the live competition where you, the Internet viewers, have a front-row seat!\"\n\nShe was grateful that Batgirl had created a portable video control console so that she could record, broadcast, and even edit her shows from anywhere. And the best part was that the whole thing could fit in her pocket!\n\nAs the other musicians entered, Beast Boy, whom Harley had designated as the official greeter, welcomed everyone with a \"Hello! Hello! Congratulations on making it to the finals!\" Then, with her trademark efficiency, Batgirl logged them in. Finalists included Female Furies' Apokopella group with Mad Harriett as the lead, a marching band from Korugar Academy, and Black Canary and the Birds of Prey. Soloists included former Super Hero High student Mandy Bowin on violin, and current Super Hero High student Cheetah, who, in an uncharacter\u00adistically low-key move, had not made a big deal about her singing.\n\n\"I'm going to catch everyone off-guard,\" she confided to Sapphire, who nodded her approval, \"and knock 'em over when they hear me sing.\"\n\nThe contestants eyed each other. Some looked nervous, like Mandy, but most were supremely confident, bordering on belligerent.\n\n\"Oops!\" said Mad Harriett as she pushed her unruly green hair off her orange face and \"by accident\" spilled apple juice onto Silver Banshee. \"Sorry about that.\"\n\nSilver Banshee grabbed a napkin and wiped the fruit juice off her costume. Her fluorescent blue pupils began to glow, and her skin flushed briefly before turning pale white again.\n\n\"Tell me it was an accident,\" Silver Banshee said. Her bandmates stood behind her, frowning.\n\nFemale Furies Stompa and Speed Queen stood behind Mad Harriett. All grinned menacingly.\n\nBig Barda, who had once been a Fury, stepped between the feuding bands. \"No fighting, please.\"\n\n\"Did someone say fighting?\" Captain Cold asked. He whipped out his ice blaster and covered the whole caf\u00e9 with icicles.\n\n\"That's cold,\" Cheetah said, racing around and breaking the icicles as members of Korugar Academy's band marched over them, making crunching noises.\n\n\"Ouch! Hey, watch it!\" Ratcatcher squealed when he was accidentally stomped on.\n\nSoon mayhem broke loose as musical instruments flew. When Mandy Bowin retreated to a corner booth, Barda hurried to protect her. \"I'll keep you safe,\" she promised. \"By the way, I'm a big fan. Your music has meant so much to me. It's beautiful and soothing and happy.\"\n\n\"Thank you,\" Mandy said, cradling her violin and ducking nanoseconds before a pizza would have hit her head.\n\n\"Contestants! Please cease!\" Silver Banshee said. When everyone ignored her, she raised her voice to supersonic levels. \"STOP. NOW.\"\n\nThe whole room rattled. Everyone looked startled and covered their ears.\n\nThe room went quiet.\n\n\"Thank you,\" Silver Banshee said. A sly smile crossed her face. \"We'll fight it out on the stage.\"\n\nHarley basked in the applause. As it washed over her, she felt like she was home. \"Harley! Harley! Harley!\" the audience chanted. Each time the curtains of flowers behind her billowed, it sent out a fragrant scent so lovely, no one would have known that just days before, wild animals had congregated there.\n\n\"Aww, you guys!\" Harley said, looking out over the massive crowd. \"I CAN'T HEAR YOU!\" She cupped her ears. \"And what about y'all watching from Centennial Park? I can't hear you either!\"\n\nAs the roars from the two crowds meshed, creating a tsunami of sound, Hawkgirl said into the headset, \"Harley, we're ready to go. Announce the first contestant.\"\n\nHarley cleared her throat. This was her moment. A chance to redeem herself from those who were mad at her for the twelve-way tie at the Dance-O-Rama. A chance to become a force to be reckoned with in the entertainment industry. A chance to become the most watched Internet star ever. She was ready.\n\n\"Good afternoon, everyone!\" Harley shouted. \"Aww, look at all of you. Sit down, sit down. Now stand up, now sit down.\" Everyone followed along, laughing. \"Thank you for coming to Harley's Quinntessentials Battle of the Bands! Our first contestants hail from CAD Academy. Give it up for the heavy metal sounds of Cap'n Cold and Crew!\"\n\nAs Captain Cold smirked his way onstage, the audience cheered. Heavy metal had never sounded so fresh, so cool, so crisp, so...heavy. Even traditionalists like Crazy Quilt were jumping up and down in the aisles. The band finished to uproarious applause.\n\n\"Remember Cap'n Cold and Crew when you vote after the show,\" Harley said. \"And remember, you only get one vote, so make it count.\"\n\nEveryone cheered again. Harley beamed. She wondered if her parents were watching.\n\n\"And now we're going to take it down a notch, or two, or three. Just listen to the violin serenade of Mandy Bowin\u2014or as some call her, Virtuoso!\"\n\nMandy looked small. She wore a simple peach-colored dress with a Peter Pan collar and pink ballet slippers. Her brown hair was held in place by a light blue headband. The audience stirred nervously. How could this girl, a mere mortal, even begin to compete with all the heavy metal that had just exited the stage?\n\nWith her eyes closed, Mandy lifted her violin and tucked it snugly under her chin, then gracefully lifted the bow in the air. No one was prepared for what happened next.\n\nIt was as if a soothing breeze blew across the amphitheater, sailed over the crowd watching in Centennial Park, and then swept into the new wildlife sanctuary at the zoo. As the musical notes from Mandy Bowin's violin alighted over the audiences and animals, all agreed they had never heard music this beautiful.\n\n\"I'm not crying, you're crying,\" Beast Boy said to Cyborg.\n\n\"I'm not crying, she's crying,\" Cyborg said.\n\n\"I'm not crying, he's crying,\" Frost said, pointing to Vice Principal Grodd as she whisked icicles from her face.\n\nHarley captured it all on camera. She knew that tears and fears were two things that audiences loved, and the tears were flowing.\n\nThe smile on Mandy's face was as serene as her music. Suddenly it didn't matter that she wasn't a super hero. When Mandy Bowin played her last note, the audience sat enraptured. It was Beast Boy who leapt to his feet first, followed by thousands of others. The cheering more than doubled the decibels of the heavy metal band. Even Ratcatcher was on his feet cheering, until Captain Cold hit him with a chilly blast.\n\nAfter several bows, Mandy sheepishly walked off the stage. She grinned at Wonder Woman, who had been standing in the wings. \"Virtuoso,\" Wonder Woman whispered.\n\nAs the camera lingered on the two, Harley informed her audience, \"Mandy was once a student at Super Hero High, but left to pursue her dream to become a musician. At the same time, Wonder Woman left Paradise Island to pursue her dream to become the best super hero she could be. Talk about amazing second acts! And now we pause for this important message.\"\n\nWhile Steve Trevor explained that all the profits from the food venues would go to the zoo's new wildlife sanctuary, Harley readied for the next group.\n\n\"This is going great, isn't it?\" she said to her crew.\n\nBatgirl, Hawkgirl, and Barda all nodded. It was going well. Smoother than anyone could have imagined.\n\nWhen Steve was done, there was a polite round of applause led by Wonder Woman. Then Harley cartwheeled back onstage. \"Is this on?\" she said, playfully tapping the microphone. \"Next up, it's a little bit of rock, a little bit of folk, a little bit of rap\u2014and it's all amazing music. Let's say aloha to Ukulele United, the all-ukulele band from the island of Kauai!\"\n\nCheers rose and hands went up in the air as the group from Hawaii hula-danced onto the stage, throwing lush leis of orchids into the crowd. Then, with a single string from a single ukulele, the music began. One at a time, the others joined in, until, united in music, the lead singer launched into a heartwarming ballad about the Hawaiian islands.\n\nJust as Ukulele United were rising to the crescendo, Bumblebee flew onstage, grew full-sized, and took the microphone.\n\n\"What are you doing?\" Harley yelled. \"We're live!\"\n\n\"Sorry,\" Bumblebee said to Ukulele United, \"but I have to do this.\" She faced the audience. \"This is an emergency. Audience members, we're going to need you to get to a safe place. All Supers in the vicinity, we have to Save the Day! Animals from the zoo and wildlife sanctuary are on the loose and on a rampage!\"\n\nThe crowd began to panic. Supergirl, Cheetah, and the others tried to calm nerves as they led the crowd to safety, which was quite an effort, considering the thousands of panicked people there.\n\nHarley turned to the camera and reported, \"We interrupt this incredible and popular Harley's Quinntessentials Battle of the Bands with this important announcement. There's chaos at the Metropolis Zoo\u2014and so we super heroes gotta go Save the Day!\"\n\n\"What's the scoop?\" Harley asked as she arrived on the scene. Lois Lane was stationed next to an open cage.\n\n\"The villain Lion-Mane has released all the animals. They're running wild,\" Lois informed her.\n\n\"Who's running wild, the people or the animals?\" Harley asked.\n\n\"Both!\" said Lois. \"Everyone's in a panic!\"\n\n\"That's not like them,\" said Beast Boy.\n\n\"The animals are normally well taken care of,\" Poison Ivy chimed in.\n\n\"We'll get to the bottom of this,\" said Wonder Woman, who was flying overhead. \"But first, let's make sure everyone is safe!\"\n\nAs animals and people ran past, Bumblebee buzzed in and said, \"I've got a lock on Lion-Mane. He's headed toward the Metropolis Museum of Art.\"\n\n\"Of course!\" Batgirl said, looking at her wrist computer. \"A new exhibit is going to open tomorrow featuring a priceless jeweled lion statue. It's worth millions!\"\n\n\"The animals on the loose are a decoy\u2014and they're also meant to be a distraction,\" Hawkgirl deduced.\n\n\"Precisely,\" added The Flash.\n\n\"Camera off,\" Batgirl said to Harley.\n\n\"Aww,\" Harley moaned. \"Think of the viewers!\"\n\n\"I'm thinking of how to sneak up on Lion-Mane,\" said Batgirl. \"And sneak means he can't know that we know. C'mon, we have a lion to tame!\"\n\nWhile Harley and the others rushed to the museum, the other Supers, led by Beast Boy, rounded up the animals and made sure that frightened citizens were safe.\n\nBatgirl checked in with Supergirl, who informed her, \"Beast Boy says that Lion-Mane told the animals that they were all going to be shipped away to desolate desert islands. That unless they ran away, they would no longer be cared for. They panicked.\"\n\n\"That makes sense,\" said Bumblebee. \"The animals are usually so kind and loving. And the zookeepers treat them like family, and vice versa.\"\n\n\"Well, this family is outta control,\" said Hawkgirl. \"The wrong information can do that.\"\n\nWith super-speed and stealth, Harley and the Junior Detectives approached the museum. The guards were nowhere to be seen. The museum stood eerily empty.\n\nBatgirl consulted her holographic museum map. It glowed green in the air in front of her. \"He's there,\" she said, pointing. \"Where the red light is glowing. It senses body heat. Several people are locked in what looks like a storage room. They must be the missing guards.\"\n\n\"They'll be safer there,\" Hawkgirl noted. \"I'll take the north hallway. The rest of you take the stairs and employee elevators. We need to sneak up on Lion-Mane.\"\n\n\"I'll go with you!\" Harley said, turning on her camera.\n\nThe Flash gave her a stern look. \"If your viewers can see what we're up to, so can Lion-Mane. You can't have that on.\"\n\n\"Aww, you're no fun,\" Harley chided him. But she turned off the camera.\n\nAs Harley powered down her camera, the other Supers shifted into stealth mode and scattered in search of Lion-Mane. Harley had just looked up when she saw Beast Boy's shadow. \"Smart move!\" she said, nodding appreciatively. \"You're looking like a lion. He's a lion. Lion versus lion.\" For good measure, she added, \"ROAR!\"\n\n\"ROAR!\" came back at her. Only this one shook the walls.\n\n\"Beast Boy?\" Harley asked as someone else stepped out of the shadows.\n\nIt was Lion-Mane, and he was carrying the famous, fabulous, bejeweled lion sculpture. \" _ **YOWZA,**_ you got a mighty roar, Mr. Mane,\" she said, reaching for her mallet. \"Have you ever thought about auditioning for the Battle of the Bands as a singer?\"\n\n\"You better get out of my w\u2014 Uh, do you really think I have a great roar?\" Lion-Mane asked as he loosened his grip on the statue. He was distracted by her compliment and the thought of performing. \"Really? Be honest.\"\n\n\"Oh, sure,\" Harley said, taking a step back. \"But first, you gotta think about this.\"\n\nWith that, she lifted her mallet high and, with all her might, brought it down on his foot. Surprised, Lion-Mane dropped the statue and roared so loud the building rocked, alerting all the Supers.\n\nAfter Lion-Mane's capture, rain had put a damper on the contest. And with the amphitheater being outdoors, even good intentions couldn't stop the storms.\n\n\"We'll reschedule!\" Harley proclaimed as the rain threatened to wash her away. But several contestants couldn't make it back the following week, so Harley was forced to scrap the show.\n\n\"The good news is that even though the Battle of the Bands was canceled, we still made money for the wildlife sanctuary,\" Steve Trevor said as he gingerly picked up some wayward rat traps left behind by CAD Academy. It didn't look good for a caf\u00e9 to have those lying around.\n\n\"That is good news,\" Harley agreed while she checked her messages. She had gotten several comments about how the BOB had ended. Many said the show should have gone on. However, MH234 wrote: \"The best Battle of the Bands in history! Love how it didn't end so that we have something to look forward to on your channel!\"\n\nHarley knew she could always count on MH234 to cheer her up.\n\nAs the Supers headed back to campus, the rain stopped. \"Look!\" Katana said, pointing.\n\nThey all tilted their heads back. \"What is that?\" Harley turned on her camera. Bubbles the size of baseballs were floating down from the sky. When the sun's rays hit them, they looked like round rainbows. Supergirl popped one, and a flyer fell to the ground.\n\nKatana read, \" 'In town for only twenty-four hours: the Krazy Karnival! You have only one day to experience the chills, thrills, and delights of the world's greatest and grandest amusement park!' \"\n\nAs the Supers gathered the wayward flyers that littered the ground, a holographic billboard lit up the sky. A jolly man wearing a colorful hat trumpeted, \"Come one, come all, to the new and improved Krazy Karnival! I'm J.J. Tetch, the new owner, and you're in for big surprises!\"\n\n\"Surprises?\" Harley said as her eyes twinkled. \"No one loves surprises more than me!\"\n\nShe immediately began broadcasting. \"The world-famous Krazy Karnival is coming to Metropolis, and even if you can't be there...you can! That's because I'll be recording all the fun and all the _**KRAZINESS**_ live on this channel!\"\n\n\"It does sound like fun,\" Miss Martian said. Harley didn't even know she was there. \"I wish I could go.\"\n\n\"Why can't you?\" Harley asked.\n\n\"Crowds make me nervous,\" said Miss Martian. \"I have trouble maneuvering through them.\"\n\n\"Stick with me,\" Harley generously offered. \"I'm great at maneuvering. Plus, this is my chance to log the most viewers ever. I couldn't video the Junior Detectives sneaking up on Lion-Mane after I hit his foot. Or the great catch I made when he dropped the statue. Oh, sure, once he was in custody, I got it all on camera. But then, so did Lois Lane, who also had footage of the Supers leading the animals back. And that scene of a green monkey\u2014Beast Boy\u2014cradling a scared baby capuchin monkey and reuniting her with her mother. That was ratings gold for Lois!\"\n\n\"It's not all about ratings, is it?\" asked Miss Martian meekly.\n\n\"There's nothing wrong with big ratings,\" Harley said as she burst a bubble. \"In fact, that's my goal: to have the most viewers in the world!\"\n\nPied Piper was at the piano. He nodded to Cheetah, who was staring at the ground. As the teacher's fingers nimbly hit the piano keys, Cheetah raised her head. Harley watched her face transform. It was confident, yet vulnerable at the same time. Then that smile appeared. The famous Cheetah smile, as if she knew something you did not.\n\nCheetah winked at Harley and began to sing. It was a torch song\u2014the heartfelt lyrics were about love and loss. As the last note hung in the air, the room was silent. Pied Piper leapt up. \"Bravo, bravo!\" he shouted. \"I could feel that emotion. Beautiful. Seriously, beautiful. Thank you.\"\n\nCheetah took a bow, and when she swept past Harley, she said, \"I would have won the Battle of the Bands. You should have a rematch.\"\n\nIn the front of the room, Cyborg had turned himself into a one-man band\u2014a synthesizer with an electronic keyboard, and speakers coming out of his boots. As the rest of the class rocked to the beat, Harley kept thinking about her show. What could she do next to top it? Surely her viewers were expecting something spectacular. Was it enough to just live stream the Krazy Karnival?\n\n\"Harley?\" Pied Piper called out. \"You're up!\"\n\nEach student had been charged with doing a two-minute performance piece, whether it was singing solo or in a group, playing an instrument, or even karaoke.\n\n\"OH!\" Harley cried. She hadn't prepared. \"For my piece, I'm going to...to...\" She looked around, desperate for inspiration. Suddenly, she saw it: Green Lantern was holding his tuba. \"We're doing a duet!\" she announced. As Harley dragged him to the front of the room, she whispered, \"Just go along with me.\"\n\n\"What? No,\" Green Lantern protested, running his hand through his thick brown hair. \"I'm doing a tuba solo\u2014\"\n\n\" _So low_?\" Harley quipped, grabbing the tuba. \"And how's about holding it _high_ for a hat?\"\n\nWhen she placed the mouth of the tuba over her head, the class howled with laugher.\n\n\"Harley, please stop. Instruments are not toys,\" Pied Piper cautioned.\n\nBut Harley couldn't hear him from inside the tuba. \"It's dark in here!\" she cried out comically, getting more laughs from the classroom.\n\n\"Give that back to me,\" Green Lantern insisted. When he tried to wrench the tuba off Harley's head, it was stuck.\n\nIn a panic to un-tuba herself, Harley began running around the room, knocking over instruments and students. Green Lantern was in pursuit, causing even more calamity and chaos. Soon, Supers had taken sides, yelling, \"Go, Harley!\" and \"Return the tuba!\"\n\n\"Come back!\" Green Lantern called out.\n\n\"This is epic!\" Beast Boy cheered. \"Harley, you're such a crack-up!\"\n\n\"The class clown does it again,\" Cheetah said, yawning. \"This is pathetic. She'll do anything for a laugh.\"\n\n\"Hello, Harley!\" Dr. Arkham was studying his desk through a magnifying glass. When he sat up, he was still holding it in front of his face. It made his left eye look huge. \"I lost something,\" the school counselor explained. \"But now I can't remember what it was.\"\n\n\"Was it this?\" Harley asked, looking around. She grabbed a globe of Mars.\n\n\"Aha!\" Arkham took the red planet from her. \"Nope,\" he said, putting it down next to a tall stack of books, all written by him. \"But I'll leave that here, in case I need to find it sometime.\"\n\nHarley settled into her favorite chair. Arkham's office was dark and crowded with important-looking books, piles of paper, and an impressive stack of unopened mail. It smelled like the forest after the rain. Harley liked it in here. It was quiet\u2014somber, even. She didn't feel the need to entertain when she was with Dr. Arkham.\n\n\"What's on your mind?\" he asked. \"Are you still feeling lonely and blue?\"\n\n\"Blue, green, whatevs,\" Harley quipped. \"What's not on my mind? You know me. Always thinking, thinking, thinking. Who knows what goes on in my noggin? It's so busy up there that sometimes I can't sleep.\" Harley paused. \"Hey, doc, is it possible to think too much?\"\n\nAs Arkham stroked his beard, she wondered why his head was bald when he had so much hair on his face.\n\n\"Hmm. Um. Yes. Sometimes we do tend to overthink,\" he said. \"Tell me, what would you like to talk about today?\"\n\n\"Aww, nothing,\" Harley said, jumping up and looking out the window. It was a sunny day and she could see Wonder Woman and Supergirl playing catch with a teacher's car. Harley turned back to the counselor. \"It's just that some of my friends are pressuring me to spend more time with them.\"\n\n\"Go on,\" Arkham said.\n\n\"I would, but I'm busy, busy, busy. I've got my Harley's Quinntessentials to run, you know. It's a lot of work making people happy! Serious business, I tell ya. And it's not just on my Web channel. In person, too, I have to think of jokes and say funny stuff, and get all, you know...Harley-esque!\"\n\n\"Go on,\" Arkham said.\n\n\"Whenever I see someone looking stressed, I want to cheer them up. So I'll tell a joke, or do a super-duper gymnastics move, or whatevs, even if I'm not feeling so great myself.\"\n\n\"Go on,\" Arkham said.\n\n\"I dunno,\" Harley said, slumping back into her chair. \"Lots of kids call me the class clown, like that's a bad thing. And it makes me feel funny. Not ha-ha funny, but weird funny.\"\n\nArkham looked like he was asleep. But then he blinked his eyes open. \"Harley,\" he said. \"People underestimate the benefits of being happy. Laughter can make people feel better. You get that. Most don't.\"\n\n\"But what about hanging out with my friends? I would, but there's no time! Oh, wait,\" Harley said, interrupting herself. \"I gotta cut today's session short. I'm busier than a bumblebee. There's someplace I gotta be.\"\n\n\"Harley!\" Dr. Arkham called after her. \"I need to ask you something.\"\n\n\"Yeah?\"\n\nHe waved his magnifying glass in the air. \"Why am I holding this?\"\n\nThat afternoon in detention, Green Lantern refused even to look at Harley. \"You could at least have warned me,\" Green Lantern griped. \"We could have rehearsed.\"\n\n\"I didn't know until I saw the tuba,\" Harley admitted. \"It was so big and shiny!\"\n\n\"No talking!\" Lucius Fox called out. Unlike Grodd, he did not appreciate detention duty.\n\n\"You have to admit, we had fun, right?\" Harley whispered to Green Lantern. \"Everyone was laughing.\"\n\n\"Shhh,\" Big Barda said.\n\nGreen Lantern gave Harley's question some thought. \"Maybe a little, but it's not worth getting in trouble for.\"\n\n\"I dunno,\" Harley mused. \"I kinda thought it was totally worth it. It sure cheered up the room!\"\n\nWhen Harley plopped her tray down on the table, Katana turned to her and said, \"We were just talking about fan mail.\"\n\n\"I never get any,\" said Miss Martian, \"unless you count the letters from my mom. She sends tons of them.\"\n\nKatana sliced her veggie lasagna into perfectly square bite-sized pieces. \"My parents email me twice a week,\" she noted. \"Although I wouldn't call it fan mail. It's more like how-did-you-do-on-that-test mail.\"\n\n\"I hear from my grandmother all the time,\" Hawkgirl said. She was eating another helping of mac 'n' cheese 'n' mushrooms. \"Half of it's fan mail, the other half is her worrying if I'm eating enough. Will someone take a photo of me with this?\" She held up her plate and smiled at Batgirl.\n\nBatgirl handed Hawkgirl's phone back and said, \"I hear from my dad constantly!\" As if on cue, Commissioner Gordon waved to his daughter, then sat down at the faculty table. \"Harley,\" Batgirl asked, \"do your parents write to you?\"\n\nHarley poked holes in her chicken potpie. \"Oh, they're so busy with their world travel, they don't have time to write,\" she said.\n\n\"What do they do?\" asked Big Barda.\n\n\"Tightrope walkers,\" Harley said quickly. \"All around the world, everywhere there are tightropes.\"\n\nHawkgirl sent the photo Batgirl had taken of her to her grandmother, then said, \"Harley, I thought you told me your parents were accountants.\"\n\n\"Did I say that?\" Harley asked. \"Well, they used to be. Now they're librarians.\"\n\nBatgirl perked up. \"I didn't know that!\"\n\n\"Oh, sure, they have a library in their motor home, and they only have cookbooks, because they used to be professional chefs.\"\n\n\"So they're tightrope-walking accountant librarian chefs?\" asked Barda.\n\n\"They were chefs and accountants, but that was after they sold spaceship insurance,\" Harley said, not meeting anyone's gaze.\n\n\"Wait!\" Beast Boy leaned over from the next table. \"You told me you were raised by raccoons!\"\n\nHarley laughed. \"Did I say that? My bad. I meant coyotes.\"\n\n\"You must get tons of fan mail because of your Web channel,\" Miss Martian said. \"Tell us about it!\"\n\nHarley was glad to change the subject. She tried to look modest. It was true. She probably got more fan mail than the others did. In fact, she was always telling her viewers to \"Let me know!\" And they did.\n\n\"I answer all my fan mail right away,\" Wonder Woman was saying.\n\n\"I save them up and answer once a week,\" Supergirl said. \"I noticed I get more emails after a battle or Save the Day.\"\n\n\"I don't get as much as the two of you,\" Bumblebee offered. \"But I love it when fans send me honey. There's this group who calls themselves the Bumblebee Honeys, and they're my unofficial fan club. I always send them a handwritten thank-you note when they send honey. Anyone get anything interesting recently?\"\n\n\"I just got this,\" Harley said, pulling a mirror out of her pocket.\n\nThe girls gathered around. A round of \"oohs\" went up in the air as they admired the gorgeous hand mirror.\n\n\"That's carved from teak,\" Katana said, inspecting the craftsmanship. \"Look at the inlaid pearl.\"\n\n\"It looks old,\" noted Supergirl. \"Like a family heirloom.\"\n\nBumblebee held it up to the light. \"Wow, my reflection looks like I'm actually in the mirror, like it's three-D.\"\n\nHarley took it back and peered at herself. She wiggled her ears. \" _ **WOWZA!**_ \" she exclaimed. \"You're right. I look more real in the mirror than I do right here!\"\n\n\"Who sent it?\" Supergirl asked.\n\nHarley shrugged. \"Don't know.\"\n\nNo one was surprised by this. School packages were often delivered by drones or birds, or on the backs of rockets.\n\n\"There was no name or return address on it,\" Harley continued. \"But the note said: 'To Harley Quinn, from your biggest fan.' \"\n\nFor the next few days, Harley was never without the mirror. She used it when she needed to fix her hair, or after eating. \"No one wants to see a close-up of a Super with food in their teeth, am I right?\" she asked. Harley even used it to practice her lines for her Web channel.\n\n\"Harley, please put your mirror away,\" Pied Piper said. \"I'd like you to focus on what I'm about to show you.\" He began playing a video of singers from around the world doing their interpretation of the same song. \"Focus, Harley. Focus.\"\n\nEasy for him to say, she thought as she tucked the mirror back in her pocket. She looked up. Now, what was that she was supposed to do?\n\nBack in her room, Harley took the hand mirror out again. \"Hello, HQ fans,\" she said as she watched herself. \"Harley here, asking, How would you like a super-duper exclusive behind-the-scenes Harley-riffic special at Krazy Karnival?\"\n\nShe was pleased with her idea. It was sure to attract attention. After all, everyone had heard of Krazy Karnival. So why not turn the amusement park's twenty-four hours in Metropolis into a mega-special, Harley-style?\n\n\"Let me know,\" Harley practiced saying. \"Send me a message!\" She was about to put the mirror down, but stopped and gasped.\n\nIt looked like the Harley in the mirror winked at her.\n\nIt was impossible to get hold of Jervis \"J.J.\" Tetch, the Krazy Karnival's new owner. Not even Batgirl could find him, and if she couldn't, then no one could.\n\n\"He's elusive, that's for sure,\" Batgirl said as Harley leaned over her shoulder and tapped the computer screen. \"Um, Harley, personal space, remember?\"\n\nHarley stepped back.\n\nFrom what Lois reported, Harley knew that J.J. had recently taken over the amusement park, but he was something of a mystery man.\n\n\"Maybe I should do this later,\" Batgirl said as Harley did a tumbling routine and nailed her landing a few inches from Batgirl's workshop area.\n\nThere were lots of sharp tools and confusing gadgets and wires and whatnots. Harley opened a black velvet box and examined a teeny-tiny silver pellet nestled beside a ring.\n\n\"No, no, no! Search for Tetch now. I'll be quiet,\" promised Harley as she held the pellet to the light.\n\nBatgirl let out a huge sigh. She sighed a lot around Harley. \"Careful with that. Remember when you put a micro-camera on Bumblebee?\" Harley nodded. \"Well, that gave me an idea, and you're holding it.\"\n\n\"What is it?\" Harley asked, squinting at the object.\n\n\"I've been toying with the prototype of a micro ring-activated drone camera,\" Batgirl said, taking the pellet from Harley. \"I'm calling it the QuinnCam.\"\n\nHarley beamed. It was named after her! She slipped her mirror out of her pocket and said into her reflection, \"Harley Quinn here, reporting live via the QuinnCam!\"\n\nThe bubbles started slowly, drifting down from the clouds like a summer's rain. Only instead of showers, it felt like happiness blanketing Metropolis. Supergirl spotted them first as she flew back to school, having spent the night at her Aunt Martha and Uncle Jonathan's farm.\n\n\"The Krazy Karnival has arrived!\" Supergirl announced as she flew around the dorm, throwing cookies to everyone she passed. Aunt Martha always made enough for the entire school.\n\nHarley reached for her mallet and camera. As an afterthought, she tucked the velvet box from Batgirl's workshop into her pocket, just in case. \"It's showtime!\" she announced, looking in her hand mirror. \"Miss Martian, let's go!\"\n\nFor days Harley had been publicizing it: \"Coming soon, the Krazy Karnival on Harley's Quinntessentials, streaming live!\" And in what she claimed was a spur-of-the-moment genius idea, she promised, \"Music fans, get this! We're gonna have a rematch of the HQ Battle of the Bands at the Krazy Karnival! So tune in to see who the winner will be!\"\n\nShe hoped J.J. Tetch would be as enthusiastic as she was. Should she have gotten his permission first? Harley brushed away her doubts. Better to do first and ask later, she reminded herself. \"Right, Miss Martian?\" she said as she pushed past the crowds toward the sights and sounds of the Krazy Karnival.\n\n\"Huh?\" the mind reader asked.\n\n\"Are you reading my mind now?\" Harley said.\n\n\"Um, no,\" Miss Martian protested. \"Mind-reading is my superpower. I only use it when I have to, for the good of the world or to save lives.\"\n\nHarley laughed. \"There's so much going on in my mind, I doubt you could read it anyway. Try!\"\n\n\"I don't think so,\" Miss Martian demurred.\n\n\"No, go ahead,\" Harley insisted. \"You have my permission.\"\n\n\"Okay,\" Miss Martian said, closing her eyes. After a couple of seconds, she said, \"It's confusing, that's for sure!\"\n\nHarley grinned proudly.\n\nNear the entrance was a long line. It looked like the entire population of Metropolis was in attendance, in addition to most of nearby Gotham City, and every place in between. Schools from every country and galaxy were represented, since students got in free. And, of course, everyone from Super Hero High was there, except for the teachers and Principal Waller, who were at an Excellence in Education Conference on Upsilon Andromedae B\u2014the planet, not the band.\n\nHarley was in heaven.\n\n\"We are going to have the best day ever!\" she enthused.\n\n\"I'm not sure,\" Miss Martian said, looking at the crowds. She started to fade. \"There are so many people here.\"\n\n\"Exactly!\" said Harley. \"You read my mind! The more the merrier, and the merrier the more viewers, and the more viewers the more popular Harley's Quinntessentials! What are we waiting for? Let the adventure begin!\"\n\n\"Excuse me, pardon me, excuse me, Harley Quinn here, and I need to be there!\" she said, pointing.\n\nThe giant bubble machine rose from the center of the carnival looking like a colossal jukebox with a rainbow of bubbles shooting out as music played. As Harley made her way past the crowd of excited guests, Miss Martian trailed along, looking at the video screens that were everywhere. On them, J.J. Tetch was touting, \"You're in for the time of your life!\"\n\n\"Hurry!\" Harley called out. She wasn't sure if her friend was way behind or had turned invisible again. \"Stick with me, Miss Martian, and you'll have a day you'll never forget,\" Harley promised. \"You can help me put up my cameras all over the place. The more the better!\"\n\n\"Maybe I'll just go back to school,\" Miss Martian said, out of breath. \"I have a good book I'm in the middle of. It's called _The Shout of the Clam_.\"\n\n\"Look! It's the Green Team! Helloooo, Green Team,\" Harley said, waving. The teens shouted and waved back.\n\n\"Did you get permission yet?\" Miss Martian asked as Harley hurried her along, placing cameras along the way. \"To do a behind-the-scenes here and to host the Battle of the Bands?\" She saw band members lugging their instruments.\n\nHarley snorted. \"You sound like Hawkgirl.\"\n\nMiss Martian smiled shyly. \"Thank you.\"\n\n\"Not yet. Let's find the owner of the Karnival. He's gotta say yes to an interview! He'd be crazy not to. And as for the Battle of the Bands, I think it's totally necessary, don't you?\"\n\n\"But where will it be? When will it be? You just told the bands to show up, and...and\u2014\"\n\nHarley stopped and shook her head. \"Miss Martian, there's nothin' to worry about. We'll figure it out when we get there! That's the Harley way.\"\n\nMiss Martian's eyes widened with concern, but she clamped her mouth shut.\n\nAt the gates, cheerful carnival workers decked out in colorful light-up costumes handed out treats, like Raspberry Sugar Bombs that made hilarious exploding noises when you bit down and Cotton Candy Clouds so light that if you didn't eat them immediately, they floated away. Some students from Metropolis Elementary were carrying deep-fried hot dogs on sticks, while others ate gooey slices of pizza. Busloads of kids were screaming and laughing. Though they had just arrived, their chaperones already looked exhausted as they grabbed for the free light-up necklaces and \"Krazy\" hats as fast as the carnival workers could pass them out.\n\nBumblebee flew up to Harley and Miss Martian. \"Isn't this great?\" she asked. \"I'm going to get one of those hats with lace and sparkles. What about you two?\"\n\n\"No time for hats,\" Harley said. \"We can't wait to get to the fun, isn't that right, Miss Martian?\"\n\n\"Oh, well, a hat might be nice,\" Miss Martian said softly. Just then, a carnival worker with white wings and silver hair plopped a flowerpot hat on Miss Martian's head, much to her delight.\n\n\"It looks lovely on you!\" the worker said. \"I'm Silver Swan, and I must say, the peach and yellow flatter your green skin.\"\n\nMiss Martian blushed again.\n\n\"Here's one for you,\" a muscled man in yellow said to Harley. He was holding a jester's hat. Four colorful padded points that resembled donkey ears in red, green, purple, and yellow flopped merrily. Their tips were weighed down with jingly bells. But before he could put it on her, Harley started running.\n\n\"Look!\" she cried, dragging Bumblebee as Miss Martian hurried to keep up. \"Over there!\"\n\nBumblebee rode the Honeycomb Hideaway ride again and again. It was a delight to sit in the golden honeycomb cups as they sailed in and out of honeycomb-land, bees buzzing around in sweet harmony. The attraction's song was the kind that played over and over in your head, long after the ride was over. \"Bees, bees, a world of bees...\"\n\nMeanwhile, Harley and Miss Martian were mesmerized by the wonderland of lights and sounds and tech. Everything was so retro that it was daringly modern. Old carnival attractions had been expanded and improved and were awash in neon colors. Everywhere you looked there were digital displays controlling the overhead aerial holograms of jolly J.J. reminding everyone, \"As my guest at Krazy Karnival, it's your job to have fun!\"\n\nHarley entered the Game Zone. Her heart was racing. So much to see and do!\n\n\"Step right up! Test your strength! Who will show 'em how it's done?\" The burly carnival worker wearing a teeny top hat was holding up a sledgehammer. \"Ring the bell and win a prize! Who will be next? How about you, girlie? Think you're strong enough to ring the bell?\"\n\nHarley looked at the shiny bell at the top of the Strength Test. \"Hit this target down here,\" the carnival worker explained. \"And the puck goes up. If you're strong enough and it goes high enough, it hits the bell and you win a prize!\"\n\nThat was all that Harley had to hear. \"I'm game!\" she shouted, twirling her mallet in one hand. \"And I don't need your sledgehammer. I brought something of my own.\"\n\nSetting up her camera to make sure this was streaming live, Harley got in position. She gripped her mallet tight and focused on the target. Then, with all her might, she brought her mallet down hard.\n\nCheers rose all around. The worker's jaw hung open. Harley had hit the target so hard that the puck broke through the Strength Test game and sent the bell sailing into the air.\n\n\"There's my prize!\" Harley announced, catching the solid metal bell before it hit the ground. \"I'm keeping this!\"\n\nHarley bowed to the cheering crowd as she walked on. She could not believe how much fun everyone was having. It was as if they were in a haze of happiness. She hooted to Cheetah and Star Sapphire, who were wearing fetching hats (a beret for Cheetah, a crown for Sapphire) and taking selfies. Both smiled warmly at Harley and hooted back.\n\n\"I'm getting a headache,\" Miss Martian said softly. She adjusted her flowerpot hat.\n\nBy then, Bumblebee had left them to join Katana and Big Barda on the Rock 'n' Roller Coaster\u2014where you sat in faux boulders as they plummeted down a mountain. Also on the ride were several members of the Korugar Academy marching band. Every time the roller coaster went around a bend or dove down, instead of screaming they played their instruments as loudly as possible.\n\n\"This isn't helping my headache,\" Miss Martian whimpered.\n\n\"Too much fun can do that to you, if you're not used to it,\" Harley explained. \"I never get headaches.\"\n\n\"I think I need to sit down,\" Miss Martian said. She looked wobbly. \"You go ahead. I'll catch up later.\"\n\nThe Green Team made their way past, all holding up ice cream cones as if they were Olympic torches.\n\n\"Okay,\" Harley said to Miss Martian. \"See you in a bit. I'm off to find J.J.\"\n\nHe had to be somewhere, right? After all, this was his carnival. Harley knew what he looked like. The roundish face. The wide smile. The twinkling eyes. And that hat! That outlandish top hat with sparkles and lights on it. How could you miss someone who looks like that?\n\nAs Harley made her way past Katana and Frost holding hands and running under a shower of flower petals in the Orchid Zone, she paused. It was so cool that Supers who normally didn't hang out together were having fun here.\n\nThat was when she saw him. The elusive Jervis \"J.J.\" Tetch. Only, someone else was about to interview him first!\n\nThe reporter was just getting into position. She had checked her notes and made sure the microphone was on. But before she could say, \"Lois Lane here with Jervis 'J.J.'\u2014\" she was blindsided by a flurry of red and blue and black and white hurdling toward her.\n\n\"Harley?\" Lois said, just before she ducked.\n\nHarley had leapt over her and was now standing right next to the new owner of Krazy Karnival. With her back to Lois, Harley launched right into her interview.\n\n\"Hi, J.J. Tetch. You don't mind if I call you J.J., do you, J.J.?\" Harley asked. \"I'm\u2014\"\n\n\"Everyone knows who you are,\" said J.J. He was all smiles. \"You're Harley Quinn of Harley's Quinntessentials. I'm your biggest fan!\"\n\n\"I am? Um...you are?\" she asked. \"So nice of you! Hey, how about an exclusive interview? My fans wanna hear all about this Krazy Karnival of yours!\"\n\nHe looked over at Lois, who shrugged as if to say, \"Go ahead.\"\n\n\"Well, all right,\" J.J. said, handing Harley a jumbo whirly-swirly rainbow lollipop. \"Anything for you, Miss Quinn.\"\n\nHarley was beaming. This J.J. fellow was the nicest, smartest person in the world, she decided. \"So, J.J.,\" she began, \"can you tell my maybe millions and zillions of viewers why you bought this famous amusement park?\"\n\nHe straightened his massive hat, which had a habit of tilting to the right. \"My goal is to bring happiness and fun to the world,\" he said. Harley nodded so much holding her camera that it looked like he was jumping up and down. \"The Krazy Karnival was up for sale\u2014the last owner, who ran it for fifty years, decided to retire. So I bought it!\"\n\nThere was a crowd gathered behind them, waving to the camera.\n\n\"Tell us more,\" Harley urged.\n\n\"Well, this is the best Krazy Karnival ever,\" J.J. boasted with a sweep of his hand. His cheeks flushed red with delight. \"It's got new rides as well as hip and healthy new foods, with some new twists on old favorites,\" he added, \"like corn on the cob that pops into popcorn, and funny funnel cakes!\"\n\n\"Funny funnel cakes?\" Harley enthused as they started walking. \"I love funny, and I love funnel cakes!\"\n\nJust then a group of teens wandered past. \"Hey! Hey!\" J.J. called out. \"It's the famous Green Team, thrill-seekers and adventurers. I was hoping you'd be here. We made special hats just for you,\" he said cheerfully. He motioned to some of his workers, who promptly hauled a box of hats over to the carnival owner. \"Try them on for size!\"\n\nAs the Green Team put on their green-and-black bowler hats, Harley whispered to the camera, \"So far it's been all talk, but now\u2014fingers crossed\u2014maybe J.J. will give us a behind-the-scenes tour....\"\n\n\"Have fun, Green Team,\" J.J. was saying as he waved goodbye to them. He turned to Harley. \"How about a tour?\"\n\nHarley winked at the camera. \"It's like he was reading my mind!\" she exclaimed.\n\nJust as J.J. took the lead, he stopped to adjust Captain Cold's pirate hat. \"That's better. This really suits you.\"\n\n\"Thanks,\" Captain Cold said, offering him a smile that was uncharacter\u00adistically warm and pleasant. The rest of his Cap'n Cold and Crew heavy metal band giggled. \"Nice amusement park you have here, Mr. Tetch, sir,\" Captain Cold continued. \"I love it! And, Harley, we adore your Web channel! Can't wait for the Battle of the Bands. Krazy Karnival is the perfect place for it. I want to wish everyone good luck!\"\n\n\"You heard that right here,\" Harley said to the camera. \"Even Captain Cold loves Harley's Quinntessentials, and he's not the easiest person on the planet to please!\"\n\n\"You're hosting a Battle of the Bands here?\" J.J. asked, looking pleased. \"At my modest little amusement park? I'm honored!\"\n\n\" _ **WOWZA, YOWZA,**_ I thought you'd like that,\" Harley said to J.J. She watched as the gang from CAD Academy went their way, whistling and waving to those they passed, then noted: \"Captain Cold sure is in a good mood. I've never seen him like that before.\"\n\n\"Oh, Harley, my dear,\" J.J. said. His eyes were moist. \"You don't get it, do you?\"\n\n\"Get what?\" They passed another towering Sweet Treats stand, and he handed her an edible candy cup filled with the most delicious double-dipped chocolate berries she had ever tasted.\n\n\"It's you who people love. He was responding to your effervescence. It's why the masses tune in to your Web channel. To see you, Miss Quinn. They love you!\"\n\nHarley felt her face flush. She wondered if he was right. Was everyone watching her? Everyone at home? Everyone at school? A lot of times she'd have a really awesome segment, but Wonder Woman or some of the others would miss it.\n\n\"Sorry, Harley, I was doing homework,\" Batgirl would say.\n\n\"Did I miss a segment?\" Poison Ivy would ask. \"Chompy needed attention.\"\n\n\"Harley, you're always on, and I got stuff I gotta do,\" Beast Boy would tell her. \"But I'll try to catch up.\"\n\n\"They love me?\" Harley repeated. \"Aww, J.J., you're such a joker. But if you want to say it again, Harley's not gonna stop you!\"\n\nHe laughed good-naturedly. \"Harley, I've got a great idea that could benefit us both! But first, I have some business to attend to. I'll give you an exclusive interview shortly, but in the meantime, why don't we get you one of my famous Krazy Karnival hats?\" He looked around. His carnival workers were everywhere. Harley thought some of them looked familiar. \"M.M.!\" he called. \"A hat for Ms. Quinn. You must have missed her when she came in!\"\n\n\"So sorry, sir!\" the muscled man in the yellow costume with a green mask said. \"I'll make sure Harley Quinn gets a hat!\"\n\nAs he hurried away, J.J. ran after him. \"Wait up!\" he cried. \"Not just any hat. I want to make sure Ms. Quinn gets one of our super-special ones!\"\n\nHarley beamed. This was fun, fun, fun!\n\nAs fun as it would be to have her own super-special hat, Harley didn't have the patience to wait around. There were rides to go on, and games to play, and treats to eat, and...and...As she raced past the Ukulele United band cheering each other on at the Wheeeee Skeeeeeball game, Harley pivoted and doubled back. Something green had caught her eye.\n\n\"Why are you just sitting there?\" she asked a glum Miss Martian.\n\nNearby, Batgirl was at the Magic Donut Maker, watching eagerly as it shot free fresh hot mini-doughnuts into the crowd. \"Me next! Me next!\" Batgirl called out, jumping up and down, waving both hands.\n\nMiss Martian closed her eyes and brought her fingertips to her temple. \"My headache is getting worse,\" she said. One of the flowers on her hat was drooping over the front of her face. \"Maybe I should just go back to the dorm and take a nap.\"\n\n\"And miss all the fun?\" Harley asked. \"You don't want to do that.\"\n\nMiss Martian shook her head. \"I do want to stay, but this headache is crushing me.\"\n\n\"Maybe you should look for Poison Ivy,\" Harley suggested. \"She always knows what to do when someone is feeling a little blue. And your face is all blue right now. Here, look.\" She held out her hand mirror.\n\n\"Can you stay with me?\" Miss Martian asked. She didn't like what she saw in the mirror. \"I don't feel like being alone right now. This place is too crowded.\"\n\n\"But if it's crowded, you aren't alone,\" Harley reasoned.\n\n\"Never mind,\" Miss Martian said. Harley could see her disappearing as she began to walk away.\n\n\"Miss Martian, wait!\" Harley called after her. Even though she didn't want to miss a minute of fun, her friend needed her. \"Let's look for Ivy together.\"\n\n\"Have you seen Poison Ivy?\" Harley asked Bumblebee. She paused. \"You and Miss Martian are supposed to be having a great time like everyone else, but instead you're acting like worrywarts!\"\n\n\"I'm getting a strange feeling about this place,\" Bumblebee said. All the flowers on Miss Martian's hat wilted, making it look like it was melting. \"Um, maybe you should ditch the hat,\" she suggested.\n\nMiss Martian reached up. \"But I love this hat. It was a gift.\"\n\nHarley studied the hat. \"It's looking goopy, which is kinda Krazy-awesome!\"\n\nReluctantly, Miss Martian took off her hat. She took a deep cleansing breath. \"I'm starting to feel better already,\" she said, surprised.\n\nBumblebee lowered her voice. \"Have you two noticed how weird everyone is acting?\"\n\n\"Weird? No,\" said Harley. \"It's Krazy Karnival time, and everyone's in a great mood.\"\n\n\"Yeah, and what about those kids from CAD Academy?\" Bumblebee said.\n\n\"What about them? Captain Cold's been really nice,\" Harley pointed out.\n\n\"Exactly!\" said Bumblebee. \"When have you ever known him to be nice?\"\n\nHarley hesitated. \"Uh, never?\" Then she lit up. \"That's the power of the Krazy Karnival!\"\n\nJust then a familiar group of teens brushed past. \"Hey, Green Team?\" Harley yelled. \"Where are you going? You're heading the wrong way. That's the exit!\"\n\nThey all stared straight ahead as they kept walking. Lois Lane raced after them as they left the amusement park. \"How about an interview?\" she asked.\n\n\"Um, Harley?\" Miss Martian said, tapping her on the shoulder. \"Harley? Um, Harley, look!\"\n\nHarley followed Miss Martian's gaze. Bumblebee was staring at the same thing. Harley whipped out her camera. \"It's a Harley's Quinntessentials exclusive!\" she cried. She aimed the camera toward the sky, unable to believe what was happening.\n\nEveryone was gawking with their heads tilted up. Everyone but Bumblebee, who was now flying around warning people: \"Something is wrong, something is very wrong!\"\n\n\"Nothing's wrong,\" Beast Boy said, smiling. \"Everything's great!\"\n\n\"Yes, everything is lovely,\" Cheetah insisted as she adjusted her beret.\n\n\"She's right,\" said Katana. \"Cheetah's right again!\"\n\n\"Look!\" Bumblebee cried, pointing at the Bubble Machine.\n\n\"Whatever is happening, you're seeing it here first!\" Harley told her viewers. \"And so is the rest of the world, because we're broadcasting live on Harley's Quinntessentials!\"\n\n\"This is not good,\" Miss Martian warned.\n\n\"It's not good, it's _great_!\" said The Flash.\n\nThe others agreed. All around, Krazy Karnival guests were watching the High-Tetch Bubble Machine. Small bubbles had given way to one gigantic bubble...and it kept getting bigger and bigger.\n\n\"So pretty,\" said Frost, sighing.\n\nRatcatcher was crying and didn't care who saw him. \"The beauty of it!\" he said as Captain Cold nodded in agreement.\n\nBumblebee and Miss Martian glanced at each other as Harley kept her camera on. \"Viewers, I'm not sure what we're seeing here at Krazy Karnival,\" she reported, \"but it's crazy, all right, and I'm certain the carnival's breaking a new world record for the biggest bubble.\"\n\nBy now it was covering the entire Krazy Karnival, and closing up to encase it\u2014making it look like everyone was inside a giant dome. The bigger it got, the happier everyone was. When it sealed shut, all the guests started cheering and clapping.\n\n\"No, no!\" Bumblebee shouted. \"Don't you see? We're trapped in here!\"\n\n\"I've got the exclusive,\" Harley proclaimed. \"That's right, world, something weird is going on at Krazy Karnival, and to find out what it is, stay tuned right here on Harley's Quinntessentials!\"\n\nMiss Martian shook her head. \"This is bad. Really bad,\" she said before turning invisible.\n\n\"No!\" Bumblebee shouted. But no one paid attention to her. \"No, something's wrong.\"\n\nAmused, Harley recorded her using her blasters to try to penetrate the bubble. \"We're trapped!\" Bumblebee cried. \"The bubble has created a barrier to the outside world.\"\n\nHarley tossed her mallet up high into the air. It made a _klunk_ when it hit the bubble. \"It's totally solid!\" she said admiringly.\n\n\"It's not right,\" Miss Martian said, barely audible. Harley could hardly see her. \"And neither is anyone here. They're not themselves!\"\n\n\"We're happy here!\" said Hawkgirl as she twirled past them with her arms out to her sides. She was wearing a colorful Viking helmet. \"Why break the bubble when we can stay and have fun?\"\n\n\"That's right,\" Thunder and Lightning chimed in as they executed silly synchronized-swim moves to imaginary music. Their fluffy cloud-shaped hats looked the same, but on closer inspection, one was cirrus and one was cumulus. \"There's no better place to be than at Krazy Karnival right now,\" the sisters said in unison.\n\n\"I totally agree with that,\" Batgirl said, adjusting the rainbow-colored mortarboard on her head.\n\n\"Hey, can you guys help me try to break this bubble?\" Bumblebee asked.\n\n\"Whatever for?\" said Wonder Woman. She was wearing an oversized bonnet festooned with feathers. \"It looks so cool!\"\n\n\" 'Cause it will be fun to try?\" Bumblebee said.\n\n\"Fun!\" shouted Wonder Woman. \"I'm up for that. I love fun!\"\n\nBut when Wonder Woman tried to break the bubble, she couldn't. Nor could Supergirl, or Cyborg, or anyone else\u2014though it didn't look like they were trying very hard. In fact, it looked like they were goofing off.\n\n\"It's totally solid!\" Harley reported. \"I guess we'll just have to stay and have fun!\" Adding, \"Reporting live from inside the bubble.\"\n\n\"I've got a bad feeling about this,\" Bumblebee kept saying.\n\nMiss Martian, barely visible, nodded. The carnival workers were now leaving their posts. Rides went unattended. Some attractions, like the Tilt-a-Whirl, were spinning faster and faster, to the delight of the riders. Guests helped themselves to the food carts, and others were grabbing armfuls of prizes in the Game Zone.\n\n\"Excuse me. Um, excuse me?\" Miss Martian said to Silver Swan. \"Should you really be leaving the Tunnel of Love when there are still people inside? You work there, right?\"\n\nSilver Swan adjusted the feathered crown on her head and flapped her wings. \"I'm on my break,\" she replied. \"No one tells me what to do. Well, almost no one...\"\n\n\"But it's dark in the Tunnel of Love and it might not be safe. What if the ride goes off the rails?\" Miss Martian asked.\n\n\"We'll have to deal with that when it happens, then, won't we?\" Silver Swan winked at her before flying off to join Cupid, who was abandoning her post at the Slings and Arrows game.\n\nMiss Martian was speechless as chaos began to consume the amusement park.\n\n\"This is so exciting,\" Harley said, swinging her camera left and right, up and down, to get all the angles. She was glad they had placed cameras everywhere, and cut to other scenes using her remote video control board.\n\n\"Slow down. I'm trying to\u2014\" Miss Martian pleaded. \"I can't read anyone's mind. Please slow down!\"\n\nHarley stopped. \"Wait,\" she said, as if hit by a wayward thought. \"I thought you only read minds if you thought lives might be in danger.\"\n\n\"I don't know what's happening,\" Miss Martian said. \"But whatever it is, it's not normal. Look!\"\n\nHarley swung around to see Cyborg and Big Barda scrambling up the side of the Ferris wheel while it was still moving. The massive steel structure was several stories high and circling nonstop.\n\n\"Look at me!\" Cyborg yelled as he hung off one of the passenger cars hundreds of feet in the air.\n\n\"That looks like fun!\" Barda shouted. \"Wait for me!\"\n\nHarley gasped as Barda leapt from one of the moving passenger cars to another. \"We're loopy!\" she shouted as the Ferris wheel continued to spin.\n\n\"Faster, faster!\" Cyborg urged Supergirl, who was in the air twirling the ride as if it were a pinwheel.\n\nThe kids in the passenger cars were squealing with joy.\n\nSuddenly, something cold hit Harley in the head. \"Hey!\" she yelled, expecting to see Captain Cold or Frost. Instead, Mandy Bowin was standing behind her holding an empty ice cream cone.\n\n\"Oops!\" Mandy said, giggling. \"Sorry!\" she yelled as she ran away and joined Hawkgirl, who handed her another cone and said, \"Okay, now this time hit Cheetah!\"\n\nHarley laughed as she followed them toward an unsuspecting Cheetah. This was sure to be a classic for her \"Super Hero Goofs and Giggles\" segment. On her way, Harley passed Batgirl stuffing her face with fried candy bars. Batgirl had even stockpiled a bunch of them on top of her hat and was balancing them as she strode purposefully back toward the Magic Donut Maker.\n\n\"Hey, Batgirl,\" Harley called out. \"How many viewers are watching right now?\"\n\nBatgirl wobbled as she came to a stop, continuing to balance her sugary load. \"Wait, look at this!\" she said. Her hat almost fell off, but she pulled it on tighter. Everyone gathered around as Batgirl projected the screen into the air from her Bat-phone.\n\n\"This is Lois Lane reporting live from downtown Metropolis,\" she was saying. \"Multiple robberies are happening all over the city. There would probably be even more if there weren't so many citizens at the Krazy Karnival. As for the perpetrators, all evidence points to the Green Team, a group of teens wearing green bowler hats. No one is safe with them on the loose,\" Lois continued. \"Commissioner Gordon and his police have been called in and are doing all they can. However, they could really use the help of the super heroes from Super Hero High!\"\n\n\"We're trapped!\" shouted Miss Martian from inside the bubble. \"We're trapped!\"\n\n\"It's weird, but the only signal that can get out of the bubble is your show, Harley,\" Batgirl said, trying to stifle a giggle. \"No phones, no messages. Nothing.\" Harley gave her a sideways look. Batgirl was not known to be a giggler. Something strange was definitely going on. \"And the only information that can come in to us is Lois Lane's Web channel!\" Batgirl said before laughing so hard she was in tears.\n\nLois was still talking. \"It appears the super heroes are all in attendance at the Krazy Karnival. Wait, what's that?\" Lois's voice remained calm, but her eyes widened. \"I can't believe what I'm seeing. It looks like the Green Team is...Can it be? The Green Team is multiplying!\"\n\n\"The Green Team's doing math?\" Harley quipped.\n\n\"There are reports that though they started out as a dozen, there are now one hundred members fanning out into every corner of Metropolis!\" said Lois.\n\n\" _ **WOWZA!**_ They're multiplying themselves! _**DOUBLE WOWZA!**_ Triple, even!\" Harley cried as the magnitude of what was happening finally hit her.\n\n\"It's worse than you think,\" Batgirl said, doubling over with laughter. \"The joke's on you!\"\n\nHarley could not believe her eyes. Or her ears. Batgirl had reprogrammed the video screens that were dotted around the amusement park. Now, instead of J.J. reminding everyone to have a great day, it was broadcasting Harley's Quinntessentials, where \"Harley\" was reporting from the Krazy Karnival.\n\n\"Lalala...The Supers of Super Hero High don't care about what's happening in Metropolis!\" a fake video Harley said. \"We just want to have fun!\"\n\n\"What's that?\" Bumblebee said, flying over to Batgirl.\n\n\"THAT'S NOT ME!\" Harley shouted. She could not take her eyes off her image on the screen. \"I'm standing right here!\"\n\nBut it sure did look like her. \"It's showtime!\" the Harley look-alike said. \"Sure, the Green Team may be taking over Metropolis, but we have more important stuff to do, like go on rides and play games!\"\n\nBatgirl switched back to Lois Lane's Web channel. \"Has Harley Quinn gone crazy?\" Lois was asking. \"What's up with our beloved super heroes when we need them most?\"\n\nBatgirl punched in some numbers. \"No one is paying attention to Lois, or any other channel, Harley. They're all tuned in to you. Yay! You rule!\"\n\n\"THAT'S NOT ME!\" Harley shouted.\n\n\"It sure looks like you,\" noted Bumblebee. \"Look, that Harley even has the same little freckles you have.\"\n\nHarley pulled out her hand mirror and did a freckle check. They were still there. \"I need to get on the air right now and fix this,\" she said as she squinted at her fake self.\n\n\"Hello, Harley Quinn here,\" Harley said to the camera. \"I'm here to tell you that there's a fake Harley out there\u2014\"\n\nHer broadcast was interrupted by the Fake Harley. \"And I'm here to tell you that it's me, Harley, who's being fake and funny!\"\n\n\"No, that's not me,\" Real Harley insisted before being interrupted again. The video screens jumped back and forth between Harleys.\n\n\"Loyal viewers, come along for the ride as we watch the Supers act really strange!\" Fake Harley said. \"What will happen? Stay tuned to find out.\"\n\nSuddenly footage of more Supers acting out in general mayhem and chaos and of rides going haywire were blasting on the screen.\n\n\"I\u2014I don't know what's happening,\" Harley sputtered. \"I'm not in control here!\"\n\n\"Then who is?\" Batgirl asked seriously, and burst out laughing.\n\nThe real Harley was running in circles to calm herself. Miss Martian made sure to be very, very still so as not to get caught in her whirlwind. Meanwhile, Bumblebee was buzzing around the amusement park, getting a fix on what was happening.\n\n\"Wow, she's not herself,\" Bumblebee whispered to Miss Martian as they watched Batgirl reprogram the Magic Donut Maker. It began to pump out so many doughnuts that they seemed to be raining down over everyone in the vicinity.\n\n\"No one is,\" noted Miss Martian. \"Well, you, me, and Harley, but it's like everyone else here is acting like someone other than themselves.\"\n\n\"Yeah, it's like something's happened to everyone,\" said Bumblebee. \"But what?\"\n\n\"I had a huge headache when I first got here,\" Miss Martian said. \"It hurt so much, and it wasn't until I took off my...hat. Hat! It's the hats!\"\n\n\"Ooookay...,\" Bumblebee said slowly. \"Now _you're_ acting weird.\"\n\n\"No! It is the hats,\" Miss Martian insisted. \"They are affecting everyone's minds. You, me, and Harley...no hats. Batgirl, Supergirl, Cheetah? The Green Team? They are all wearing the hats.\"\n\nBumblebee looked around. Batgirl was now doing a doughnut dance she had just invented, and Cheetah was wandering around passing out compliments to everyone she came across.\n\n\"You're right,\" Bumblebee said. \"They're all wearing hats and not acting like themselves.\"\n\nHarley sat on the ground and moaned. \"And the person who is most not like herself is ME. With THAT one on the air.\" She pointed to a video screen where the fake Harley was telling everyone to \"get reckless and wild!\"\n\n\"It is the hats,\" Miss Martian repeated. \"We have to get them.\"\n\nHarley nodded slowly. \"Okay.\" She pointed to Batgirl. \"Let's start with hers.\"\n\nBatgirl was sitting on the ground stuffing more doughnuts into her mouth when Bumblebee shouted, \"Three, two, one...go!\"\n\nThe three rushed Batgirl. \"Hey!\" she cried. \"What's going on?\"\n\n\"Give us your hat!\" Harley yelled.\n\n\"No way!\" Batgirl said, pulling it tighter on her head.\n\n\"Please,\" said Miss Martian. \"It is harming you.\"\n\n\"Is not!\" said Batgirl. She scaled up the tall skywalk that circled the Krazy Karnival and was now hanging upside-down with her legs bent over a rail. She held her hat on her head with one hand and finished a doughnut with the other.\n\nBumblebee flew up to her. \"I'll explain later,\" she said, attempting a fly-by to snatch the hat from Batgirl's head.\n\nImmediately, Batgirl reached for her Batarang and flung it at Bumblebee, who ducked out of the way.\n\n\"Hey!\" yelled Bumblebee. \"You almost hit me!\"\n\n\"No one touches my hat!\" Batgirl grumbled.\n\n\"She's not herself,\" Miss Martian reminded Bumblebee. \"We need to get her hat and destroy it to be sure she won't put it back on!\"\n\nHarley leapt onto the nearby Gravitron ride. She used its spinning centrifugal force to propel her up and landed atop the metal mesh roof of the skywalk. From there, Harley looked down at Batgirl, who was still hanging upside down, enjoying the view and the snacks.\n\nIn one move, Harley grabbed Batgirl's hat and tossed it up toward Bumblebee, who hit it with her blasters. But in her hurry, Harley lost her grip. She began to free-fall toward the ground.\n\n\"HELP!\" Harley yelled, flailing her arms and kicking. \"Someone catch me!\"\n\nBefore Bumblebee could get to her, Batgirl swooped in on a thin wire and grabbed Harley. They both landed lightly on the ground.\n\n\"Thanks, Batgirl,\" Harley said as she smoothed out her shirt.\n\n\"What just happened?\" Batgirl asked. \"I feel sort of weird.\"\n\n\"Too many doughnuts,\" Harley quipped. \"Come on, we'll explain. But first we have to make a plan.\"\n\n\"It's fun and chaos here inside the bubble,\" Fake Harley was reporting. On the screen was video of the Supers trying to tear the hats off the heads of the others. \"Like a game of capture the flag, my fellow super heroes are playing Grab the Hat. Never before have more people been more in love with their hats,\" she said, laughing. \"What's more important than hats? Nothing!\"\n\nThe footage was strangely compelling. Viewers had never seen anything like it. Some Supers, like The Flash, were too fast for just one super hero to catch. Katana and Big Barda were fighting over Barda's purple hat with red feathers, even though Katana had a jaunty green Robin Hood\u2014style hat of her own. \"Mine!\" Barda shouted. Everyone, friends and enemies, was engaged in fights over hats. As the mess grew, so did the number of viewers of Harley's Quinntessentials.\n\n\"Every news channel in the world has locked into HQ, but it looks like Fake Harley is still overriding your real reports,\" Batgirl said as she looked at her chart. She was keeping track of which Supers had had their hats confiscated and which ones were still wearing theirs.\n\n\"What about Lois Lane's reports?\" Harley asked.\n\nBatgirl shook her head. \"No one's watching that, even with Metropolis under siege. They'd rather watch you.\"\n\nSeparating super heroes from their hats proved difficult.\n\n\"No one's getting this hat!\" Supergirl yelled as she flew toward the top of the bubble. Wonder Woman, Hawkgirl, and Bumblebee were in pursuit.\n\n\"It's controlling you!\" Bumblebee said.\n\n\"It is not, and you are starting to bug me!\" Supergirl called out as she hovered out of reach. \"I love my hat! It makes me happy! Plus, it's _so_ cute.\"\n\n\"It _is_ cute,\" Wonder Woman said as she flung herself against the thick wall of the bubble. \"But there's nothing cute about mind control, and that bonnet you're wearing is making you all wonky. I wasn't myself until Batgirl Bataranged mine off my head!\"\n\n\"Wonky?\" Supergirl said. \"Who are you calling wonky?\" For a moment, Bumblebee distracted her with a sonic blast. In that second, Wonder Woman swooped in and got the hat, tossing it to Catwoman, who used her whip to destroy it.\n\nBumblebee gave her a thumbs-up. One more hat destroyed, one more Super to help get rid of the hats. What started out difficult was getting easier. Or was it? Harley wasn't sure. There were still hundreds and hundreds of guests to contend with, and they were totally out of control. So much was happening, Harley didn't know what to aim her camera at next.\n\n\"Video off,\" Batgirl ordered Harley.\n\n\"This could be important information\u2014think of the viewers!\" Harley protested. Batgirl didn't flinch. She wasn't as fun without the hat, Harley noted as she shut off her camera.\n\n\"Miss Martian, tell everyone what you know,\" Batgirl said.\n\nMiss Martian willed herself to be seen, and several Supers gathered around her. \"The hats are controlling\u2014or at least influencing\u2014everyone. But not in the same way. Some people are happy, others are belligerent, and still others are just flat-out wacky. It's as if someone wants everyone to act crazy.\"\n\n\"Well, it is the KRAZY Karnival,\" Harley joked.\n\nNo one laughed.\n\n\"So, what's our plan?\" asked Miss Martian. \"We have a plan, right?\"\n\n\"We confiscate all remaining hats,\" said Batgirl. \"Supers first.\"\n\n\"But we have to break the bubble that's trapping us in here,\" Wonder Woman noted. \"Lois Lane is reporting that the Green Team is robbing every house and business in Metropolis.\"\n\n\"Yes, but with all of us Supers working together, it will be easier to break it,\" Poison Ivy said.\n\n\"Someone plotted to have us trapped in here,\" Hawkgirl chimed in. \"But who?\"\n\n\"The Junior Detective Society will figure out who and why,\" said Batgirl.\n\n\"But first, this,\" Harley interrupted. She turned the camera on. \"This is the REAL Harley Quinn here, assuring you that the super heroes of Super Hero High will be in Metropolis soon to help save the day from the Green Team, who's\u2014\"\n\nThe screen sizzled with static. Fake Harley suddenly appeared. \"To save the day, we have the Green Team, a group of talented teens. And back in the bubble, let's watch the Krazy Karnival! I guarantee, you've never seen anything like it before!\"\n\n\"Why did you just say that?\" Beast Boy asked Harley. \"That was totally not the right thing to say!\"\n\n\"It wasn't me!\" Harley yelled, leaning in toward Beast Boy's face. \"I wouldn't do that!\"\n\n\"You just did!\" he yelled back.\n\n\"We can discuss this later,\" said Wonder Woman, breaking the two up. \"Right now we have work to do. Let's go get all those hats!\"\n\n\"Some of us should stay back and try to figure out who's behind this,\" Bumblebee said.\n\n\"Great idea,\" said Hawkgirl. \"Miss Martian, we'll need you here with us. Harley, stay in contact. I'd say that someone's out to get you. The fake Harley is proof of that.\"\n\n\"Proof, schmoof.\" Harley gripped her mallet. \"Let them try,\" she said. \"I'll show 'em why it's not smart to mess with Harley Quinn!\"\n\nAs the hat-free Supers zeroed in on their classmates still wearing hats, Beast Boy spotted Cheetah.\n\n\"Hey there, Cheetah, you sure look nice today,\" he said.\n\nCheetah absentmindedly touched her beret. \"Why, thank you, Beast Boy, and so do...\"\n\nBut before she could finish her sentence, Beast Boy had transformed into an eagle, snatched Cheetah's hat with his beak, and was flying circles above her.\n\n\"You\u2014you stole my hat, you green pest,\" Cheetah said accusingly.\n\n\"You're welcome,\" Beast Boy replied as he handed the hat off mid-flight to Adam Strange, who then tossed it to Starfire, who dropped it toward Katana, who sliced it in half before it touched the ground.\n\n\"Cheetah,\" Harley said, lowering her voice. \"You were being nice...to everyone.\"\n\nCheetah looked startled, and then she scowled like she had just sucked on a lemon.\n\nWith each hat confiscated and destroyed, the Supers gained momentum and Batgirl crossed another name off the list. Working together, they found gathering the hats from the Krazy Karnival guests was easy...almost. Captain Cold was particularly hard to separate from his pirate hat. But once hatless, he was back to his ornery self.\n\n\"Someone was trying to control my mind?\" he said, seething. \"That's not cool!\"\n\n\"The hat was controlling my mind?\" Lady Shiva repeated as she stared at the smoldering pile of felt and electronics at her feet. El Diablo and Sapphire had confiscated her hat; then El Diablo had hit it with flames. One by one, as each Super's head cleared, they began to understand what had happened.\n\nMeanwhile, when it finally dawned on guests that they had been under some sort of mind control, panic began to spread. Confusion built to epic proportions, especially when they tried to escape from the Krazy Karnival and learned that there was no way out of the bubble.\n\n\"Nothing good can come of this,\" Fake Harley reported. \"I love it!\"\n\n\"That's not me!\" Real Harley said, interrupting Fake Harley's feed. Suddenly the video cut to one of the remote cameras that Harley had put up earlier.\n\nOn the screen, Wonder Woman was swooping toward the Tunnel of Love, where she was met in the sky by Silver Swan. Each hovered in the air, neither speaking. Silver Swan did a pirouette so fast she had to hold on to her hat, to keep it from flying off. When she stopped, she glared at Wonder Woman, who returned her unblinking stare.\n\n\"Please give me your hat,\" Wonder Woman said evenly.\n\nOn the ground below them, The Flash, the last Super Hero High student with a hat still on his head, was being chased by several Supers.\n\n\"Why would I want to do that?\" Silver Swan scoffed.\n\n\"Because it's controlling your mind,\" Wonder Woman explained.\n\n\"No one controls Silver Swan,\" she said. \"If you want my hat, you're going to have to take it from me.\"\n\n\"Oh, you don't want that,\" Wonder Woman warned.\n\n\"Try me,\" Silver Swan dared her.\n\nWonder Woman flung her lasso at Silver Swan. But before it reached her, Silver Swan began to hum, slowing the lasso's projection. Then she let out a powerful sound wave that made the lasso snap back toward Wonder Woman.\n\n\"Oops!\" said Silver Swan. \"Maybe you aren't as invincible as they say you are.\"\n\nWonder Woman brushed off the comment and tightened her grip on the Lasso of Truth. \"I guess we're going to have to find out,\" she said, flying full force at her nemesis.\n\nSilver Swan pirouetted once more then retreated into the Tunnel of Love with Wonder Woman in pursuit.\n\n\"We can't see what's going on inside,\" Harley said over the video as the scene projected onto the screens all across the carnival. \"But something's sure happening!\"\n\nOnly the sounds of battle could be heard. Smashes and crashes abounded. At times, swan boats flew out of the entrance and exit, barely missing bystanders. Every now and then, Silver Swan flew out of the tunnel, followed closely by Wonder Woman...or Wonder Woman flew out with Silver Swan in pursuit, and then they both disappeared back into the tunnel. Things were happening so fast, no one could keep up with either combatant.\n\nSuddenly, there was quiet.\n\nNo one moved. All over the amusement park and beyond, viewers were riveted to the screens.\n\nWhere was Silver Swan? And more importantly, where was Wonder Woman?\n\nThey couldn't see anything, but they could hear a beautiful low hum coming from the tunnel. It was Silver Swan. Harley stared at the video monitor. There was a murmur from the crowd outside of what was left of the Tunnel of Love. Where was Wonder Woman?\n\nA rustle of wings signaled Silver Swan, who emerged smiling. Hawkgirl and Poison Ivy gasped.\n\nIt was Batgirl who began cheering first. \"There she is, right behind Silver Swan,\" she said, pointing at the screen. \"Wonder Woman's got the Lasso of Truth around Silver Swan!\"\n\n\"Look what's in her other hand!\" shouted Hawkgirl.\n\nSure enough, Wonder Woman was holding a hat.\n\n\"I wasn't keen on wearing it,\" Silver Swan was saying as she rubbed her forehead. \"But he insisted. He said everyone at the carnival had to wear the hats.\"\n\nThe video was suddenly fuzzy as Fake Harley took control. \"You saw it here first,\" she said, winking. \"Silver Swan was unemployed until J.J. Tetch, the kind owner of Krazy Karnival, gave her a job. But the real story is that those teens from Super Hero High will soon be out of work. They're stealing hats, of all things!\" Fake Harley looked straight into the camera and confided, \"I never did like any of my schoolmates. They're a sneaky bunch!\"\n\n\"Harley!\" said Poison Ivy, looking aghast. \"How can you say that?\"\n\n\"It's not me!\" Harley reminded her. \"It's the FAKE me.\"\n\n\"Oops, sorry,\" Poison Ivy said sheepishly.\n\n\"So it's J.J. Tetch behind all this,\" The Flash noted, still befuddled from the chase and having his hat removed.\n\n\"I think we all suspected that,\" Batgirl said.\n\n\"But the real question is why,\" Hawkgirl added.\n\n\"And what does he have against me?\" lamented Harley. \"He was so nice!\"\n\n\"I'm sure it has something to do with the Green Team,\" Batgirl deduced. \"Lois is saying that their looting is getting worse, and their team is multiplying.\"\n\n\"Why would anyone want to do math at a time like this?\" Harley quipped. Most of the heroes rolled their eyes while she snickered at her own joke.\n\n\"Harley, plug me in to the cameras you have all over the carnival. I want to see what's going on,\" Batgirl said.\n\nHarley and Batgirl sat side by side, Batgirl with her computer, Harley with her video control panel. The others looked over their shoulders.\n\n\"I think all hats are accounted for, except for the ones from the carnival workers,\" Supergirl said to Big Barda. \"The civilians are still calming down, and the super heroes from the other schools are all on board with helping us. Together we'll get the hats from the workers. So far they've refused to give them up of their own accord. It appears that J.J. hired a bunch of thugs and villains.\"\n\nHarley hit the \"On\" button on her camera and was about to broadcast, but someone beat her to it. \"Oh, my! What if there's a surprise in store for those super heroes? Like maybe a battle in the bubble!\" Fake Harley said gleefully. \"Whatever's up next is sure to be epic! Tell everyone to tune in.\"\n\n\"Hey!\" Real Harley cried. \"That's what I was going to say!\"\n\nHawkgirl said, \"You know things are totally crazy when Fake Harley and Real Harley are saying the same thing.\"\n\n\"Let's give it another try,\" suggested Wonder Woman as the Supers rallied. \"We've moved mountains, we've fought epic battles, we've conquered evil. Breaking a bubble shouldn't be all that hard.\"\n\nOthers followed her lead as she hurled her shield against the bubble. Bumblebee used her blasters, Supergirl used her heat vision, and Big Barda threw her mega-rod with all her might. But the bubble didn't even budge.\n\n\"Okay,\" Harley said. She was hopping up and down with an excess of energy. \"Plan B. We fan out and track down J.J. Once we get him, we find out what his motives are and how to get out of here. Everyone, pair up!\"\n\nThe carousel riders were relieved when Batgirl fixed the mechanics and slowed it down. Harley and Batgirl then bypassed the Rock 'n' Roller Coaster when they saw that Hawkgirl and Ivy had it under control.\n\n\"How's about going in there?\" Harley said, pointing to the House of Mirrors. She didn't wait for Batgirl's answer. It was as if it was calling to her. _Harley..._\n\nIt was cool in the darkness. Before Batgirl could activate her flashlight, the room was flooded with light so bright that both girls had to shield their eyes.\n\nHarley peeked through her fingers. \"Whoa!\"\n\nBatgirl squinted. \"Ditto!\" she said as she took in the hundreds of reflections. \"Are you seeing what I'm seeing?\"\n\n\"A whole lot of Harleys?\" Harley said.\n\n\"Yes, but only one of me,\" Batgirl noted. \"The mirrors are only showing _your_ reflection.\"\n\nHarley looked around. Sure enough, there were Harleys everywhere, but no Batgirls, other than the one standing next to her.\n\nHarley turned on her shoulder cam. \"I think I'm gonna want footage of this,\" she said as the red light blinked.\n\n\"It's like a Harley Quinn convention!\" Batgirl exclaimed.\n\n\"I'd go to that,\" Harley said. She stopped again to look at herself in the mirror. \"Uh, Batgirl?\"\n\n\"Yes?\" said Batgirl, who was taking a moment for reports from Metropolis. The city was now on lockdown.\n\n\"I think I just winked at myself,\" Harley said.\n\n\"Oh...kay?\" Batgirl said then returned her attention to their immediate situation. \"Let's keep an eye out for strange happenings.\"\n\n\"The wink was a strange happening,\" said Harley. \"Because my image winked at me, but I didn't do any winking.\" She started making faces and then began a series of somersaults and flips, watching herself in the mirror.\n\n\"What are you doing?\" Batgirl asked, perplexed. \"This is not the time to create new gymnastics routines.\"\n\nHarley did a complicated triple flip, but at the last second, reversed it, and yelled, \"Can you do that?\"\n\nThe Harley in the mirror just smiled and stood still.\n\nAt the same time, Batgirl and Harley shouted, \"FAKE HARLEY!\"\n\nHarley began smashing the mirrors with her mallet. As each mirror shattered, the Harley reflected there disappeared.\n\n\"One of the mirrors isn't really a mirror. That fake is in the room with us,\" Harley cried. \"I'm going to find this pretender. There's only one Harley Quinn!\"\n\n\"That's for sure,\" Batgirl said as she removed a Batarang from her utility belt and tossed it, causing mirrors to fall onto each other and break.\n\nThere was glass everywhere, but it seemed that for every mirror that broke, there was another to take its place. During it all, Fake Harley began taunting them, saying, \"Catch me if you can!\"\n\n\"Fake!\" Harley cried in frustration. She swung her mallet hard and shattered another mirror into hundreds of tiny shards of glass. Then she froze. \"Um, Batgirl?\" she called. \"Can you come here, please? I think you're gonna want to see this.\"\n\n\"Your hat, miss,\" the man said, smiling. He held out a jester's hat of many colors with a golden bell on the top. \"A gift from J.J.\"\n\nHarley's eyes locked on the equalizer in the man's other hand. It had mirrors on the end of it, and reminded of her of the trifold mirrors in a department-store dressing room.\n\n\"No, thank you,\" Harley said. \"I don't wanna muss up my hair.\" She poufed up one of her pigtails.\n\n\"I see you brought a friend to the party,\" he said, bowing slightly. \"How do you do? I'm Mirror Master.\" Though he had on a green hood and cowl, a white sailor hat with a first-mate insignia sat snug on his head, looking out of place.\n\n\"I know who you are,\" Batgirl answered. \"You use ultra-advanced mirror technology to create holograms, like the one you made of Fake Harley. But what I don't understand is how you were able to make it so convincing.\"\n\n\"Yeah, confess\u2014or say hello to this,\" Harley said, raising her mallet in the air.\n\n\"Well, you liked the mirror I sent you, right?\" he asked. He was taller than both girls by almost two feet, and muscular.\n\n\"What mirror?\" Harley asked. Her eyes flickered with recognition. She touched her pocket. \"Oh, that mirror!\"\n\n\"Yes, the hand mirror was from me,\" he said, smugly. \"Thought you'd like it. Who doesn't like to look at themselves? I know I do.\" He glanced at a mirror and admired himself.\n\n\"I get it now,\" Batgirl said, nodding. \"Harley, every time you looked in the mirror he was image-mapping you. Your looks, your movement, your quirks. Plus, he was collecting everything you've ever said so Fake Harley could have a speech bank to draw from.\"\n\nHarley gulped. \"Ya mean ya heard what I was saying when I was alone?\"\n\nMirror Master smiled. \"That I did, Harley! That I did.\"\n\n\"How unoriginal,\" Batgirl said. \"You're just a copycat.\"\n\n\"Oh, dear. Are you trying to hurt my feelings?\" Mirror Master said, feigning sadness. \"I'm more than a copycat. And to prove it, maybe I'll create an army of Batgirls next.\"\n\nHarley gasped. \"The Green Team! That's why there are so many of them. You did that!\"\n\n\"She's catching on,\" Mirror Master said. \"Good for you, Harley.\" He tapped his equalizer. \"I can control reflections and mirror images from here.\n\n\"What is it that you want?\" Harley asked.\n\n\"I want a good job review,\" Mirror Master said. \"I want to make the boss happy. Fake Harley was my idea,\" he boasted. \"He loved that!\"\n\n\"Please tell us more,\" Batgirl said, flattering him.\n\n\"Well, remember when you two created those HarleyGrams?\" Both nodded. Batgirl had helped Harley make small holographic images of herself to help promote Harley's Quinntessentials. \"I thought, I can do better than that! So I created a walking, talking reflection of Harley. One that can be programmed by me. At the same time, I can use my mirror skills to make it look like the Green Team is multiplying and cause confusion and panic everywhere.\"\n\n\"He's a genius,\" Fake Harley said.\n\n\"Harley, meet Harley,\" Mirror Master said smugly. \"Now, who's ready for some fun?\"\n\nHarley raised her mallet in the air at the same time Fake Harley did. As Mirror Master laughed, he didn't see Batgirl slip away. Real Harley and Fake Harley were swinging their mallets so fast and doing such astonishing gymnastics moves that it was impossible to tell which one was real.\n\n\"Get her!\" Mirror Master ordered Fake Harley. \"Use Harley's own techniques of speed, strength, and gymnastics on her. My Harley can do everything you can do,\" he boasted to the real Harley. \"Only, here, my Harley has the advantage.\"\n\nIt was true. With her reflection everywhere, Harley couldn't tell just who she was fighting. She was swinging madly, hitting every image of herself.\n\n\"Not even you can tell the difference between yourself and a fake,\" Mirror Master bragged.\n\nHarley paused. \"You are so right. Thank you for the tip!\"\n\nAs she ran around the room doing backflips and cartwheels, Fake Harley did the same. They moved so fast they blurred together. When they stopped, both faced Mirror Master.\n\n\"Stop playing around,\" he ordered. \"Get her!\"\n\n\"Get her!\" both Harleys yelled. \"Get Harley!\"\n\nHarley starting mimicking the fake version of herself. If she couldn't tell the difference, there was no way Mirror Master could either.\n\nStep by step, backflip by backflip, triple sidewinder by triple sidewinder, the Harleys did the same thing. They were mirror images of each other\u2014and their reflections filled the House of Mirrors.\n\n\"I see what you're doing,\" he said. \"You can't fool me.\"\n\nWhat he didn't see was that Batgirl had returned, and she had someone with her.\n\nHarley spied Batgirl and The Flash sneaking behind the mirrors. She wanted to call out to them, but if she did, Mirror Master would also know where she was.\n\nBatgirl kept staring down at something small in her hand: her B.A.T. heat-seeking device. There was only one Harley in the room who had a temperature and a heartbeat.\n\nMirror Master punched some buttons on the side of his equalizer. Instantly, Fake Harley started saying, \"It's me, Harley Quinn, and you're watching the all-Harley all-the-time Harley's Quinntessentials! I'm the real deal!\"\n\nAs the fake kept repeating this, so did the real Harley. She knew that confusion was often key in apprehending a villain. She had learned this in Commissioner Gordon's Understanding the Criminal Mind class.\n\nThe mirrors in the room and all the shattered pieces reflected Fake Harley and Real Harley. It was beyond confusing. \"Let's dance!\" Harley said to her doppelg\u00e4nger. The two began to spin around, reflecting each other's moves perfectly.\n\nIf the Harleys had competed in the dance contest, surely they would have won. Both gripped their mallets and held them out to their sides. With each spin, more mirrors shattered, leaving a trail of broken glass.\n\nMirror Master had been so focused on the Harleys that he didn't see Batgirl and The Flash sneak up on him. Suddenly, a streak of red rushed by.\n\n\"I got it!\" yelled The Flash, holding up Mirror Master's mirror equalizer and tossing it upward.\n\n\"No, _I_ got it!\" growled Mirror Master as he lunged for it.\n\n\"No, _I_ got it!\" said Batgirl triumphantly from the ceiling, where she was perched upside down. She dangled the equalizer from her B.A.T. wire.\n\n\"Give that to me!\" Mirror Master demanded.\n\n\"Okay, but first let me take a look,\" Batgirl said.\n\n\"Helloooooo!\" Harley called out. She was still spinning around the room with Fake Harley. \"I love to dance, but this is makin' me dizzy!\"\n\nBatgirl quickly reprogrammed the Mirror Master's equalizer, and suddenly, Fake Harley stopped dancing. \"Phew!\" Harley said as they both wobbled. \"I was runnin' out of dance moves.\"\n\n\"Harley, say goodbye to Harley,\" Batgirl said as she punched more buttons on the equalizer.\n\n\"Bye-bye,\" Harley said as Fake Harley disappeared with a digital _ping._ \"And don't come back!\"\n\n\"What have you done?\" Mirror Master yelled. \"I'm going to get in so much trouble now!\"\n\nBy then The Flash had tied him up with a length of blinking carnival lights. Batgirl removed the sailor hat from Mirror Master's head. \"Who are you working for?\" she demanded.\n\n\"I don't work for anyone,\" he said. \"Hey, does anyone have an aspirin? I have a huge headache.\"\n\n\"It's J.J., isn't it?\" asked Batgirl.\n\n\"I don't feel good,\" Mirror Master moaned. \"Stop asking me questions!\"\n\nThe Flash held on to the lights that bound the Mirror Master as they led him to the Lost and Found area, where the other carnival workers were being held. \"Got another one!\" he called out.\n\nMiss Martian was standing off to the side, her eyes closed. \"They're all thinking the same thing,\" she said.\n\n\"What's that?\" Harley asked.\n\n\"Mad Hatter,\" Miss Martian said. \"That's the name that keeps coming up when the carnival workers' hats come off.\"\n\n\" _ **WOWZA!**_ \" Harley declared. \"J.J. and Mad Hatter are the same person. That sneak!\" She tapped the side of her head. \"Everyone, quiet! I'm getting an idea, and it's a doozy! We get Mad Hatter, we get out of this bubble. We get out of this bubble, we save Metropolis. We save Metropolis, and I get exclusive footage! This Fake Harley business is old news. Although, it was cool having a sister, if only for a while.\"\n\n\"You can borrow mine,\" Thunder and Lightning said at the same time, then both burst out laughing.\n\n\"Well, there's only one real Harley Quinn,\" Harley said, dropping the mirror on the ground and raising her mallet. \"I won't be needing this anymore!\"\n\nHarley was about to smash it when Batgirl stopped her. \"Mind if I take that?\" she asked.\n\nMiss Martian scurried to keep up with Batgirl and Harley. \"I should have guessed J.J. and Mad Hatter were one and the same. Mad Hatter can get people to do his bidding by using mind control,\" she explained. \"The secret is his hat. The high-tech gizmos and gadgets in it enhance his powers.\"\n\n\"But Mirror Master is so strong, you'd think he could fight off this pest's mind games,\" Harley said.\n\nBatgirl nodded. \"Mirror Master may be physically strong and have the mirror tech, but he's no match for Mad Hatter's brains. And when someone wears one of his hats, Hatter's got even more control over them. It would take a person with incredible mental discipline to withstand his mind games. Look what happened to all the Supers!\"\n\n\"He's close,\" Miss Martian said, slowing down. \"I wish I could home in on him, but his thoughts are jumbled and I can't get a clean read. Wait...I'm getting stronger and stronger vibes. There!\" She pointed to the Amazing Maze.\n\nThe sign outside the Amazing Maze was lit up. Strobe lights made it look like a neon fireworks display. But with each step closer, a bank of lights would burn out with a sizzle and fizzle into darkness. By the time they were at the entrance, the marquee was practically dark.\n\n\"Let's storm the place!\" Harley suggested.\n\n\"Oh, um. Do we have to?\" Miss Martian squeezed her eyes shut. Then she said to herself, \"Yes, we do, Miss Martian. Get ahold of yourself.\" Her eyes fluttered open. \"Get ahold of yourself!\" she repeated, louder.\n\n\"What's going on?\" asked Harley.\n\n\"I'm getting a strong signal, and if I concentrate really hard, I can get a sense of Mad Hatter's thoughts!\"\n\n\"What's he thinking?\" Batgirl asked.\n\nMiss Martian closed her eyes again. \"His mind is difficult to read, but it is clear he wants to see Harley, alone. Just the two of them.\"\n\n\"That's weird,\" Harley said. \"I was thinking the exact same thing!\"\n\nIt had taken some convincing to get Batgirl and Miss Martian to stay behind, but in the end Harley won. \"Mad Hatter just wants me,\" she reasoned. \"If the three of us appear, he may not show up.\"\n\nSilently, Harley tiptoed into the Amazing Maze. It was dark and eerily quiet, and reminded her of when she was little and used to play hide-and-seek. She would hide in the closet, sometimes falling asleep when no one found her.\n\nThough Harley was usually boisterous and brave, she could feel her heart beat faster and faster. As she got closer to danger, it excited and scared her at the same time. Suddenly a projectile flew at her. Harley whipped her mallet around like a baseball bat, smashing it.\n\n\"Oh dear, why did you do that?\" A friendly voice from above asked as pieces of candied apple rained down. \"Is that any way to treat a gift?\"\n\nBefore Harley could say anything, something caught her attention. Across the room, at end of a long hallway, was a sign beckoning her.\n\n_**ON AIR**_ , the red neon flashed. _**ON AIR**_.\n\nHarley made her way down the corridor, which got narrower and narrower with each step. Finally, it spilled into a cavernous room.\n\nThe maze walls rose twelve feet high, too tall for Harley to see over. Taking a deep breath, she sprinted head-on toward one, using momentum to run up the side, flip herself over, and grab the ledge with two hands. Doing a pull-up, Harley peered over the top. She saw nothing but maze and more maze.\n\nUndaunted, she let go and continued her journey, wandering through the winding labyrinth, doubling back whenever she hit a dead end.\n\n\"What's taking you so long?\" Mad Hatter asked impatiently, his voice booming over a loudspeaker.\n\n\"I'm in no hurry, J.J.,\" Harley replied, careful to sound confident, even if she didn't feel that way. The maze was so confusing. Had she already walked this way? Everything looked the same. \"Or do you go by Mad Hatter?\"\n\n\"Oh, you can call me Mad Hatter,\" he said, letting out a long, gleeful laugh. \"Although some people just call me mad!\"\n\n\"I'd like to call you...when you're in prison,\" Harley quipped.\n\n\"What's that? I can't hear you,\" Mad Hatter said. \"What's the matter, Harley? I thought you'd be better at hide-and-seek.\"\n\nHarley looked around. The maze walls were a glaring white. She wished she had sunglasses. That's when she looked up.\n\n\"You're pretty quiet,\" Mad Hatter said. \"That's not like you. What's the matter? Scared?\"\n\n\"Scared, schmared. I'm not afraid of the likes of you,\" she said, shaking the inkling of self-doubt that had crept into her brain. Harley was used to having other Supers around her, backing each other up. But this was to be a solo performance. \"Focus, Harley,\" she reminded herself. She thought, _What would Batgirl do?_\n\nHarley fumbled around in her pocket. It was still there\u2014the little box from her friend. She opened it and smiled. Inside was the teeny-tiny QuinnCam drone camera. Harley slipped on the ring that controlled it\u2014and the drone. She wished Batgirl had also given her instructions. Then she noticed that when she moved her ring finger, the QuinnCam moved too. When Harley pointed the ring to the left, the camera turned left. When she pointed it to the right, it went right. And if she moved her hand up and pointed the ring skyward, that was where the camera went.\n\nHarley looked at the ring and could see what the camera was recording on a small screen built into the ring. She had a view of the entire maze! But where was Mad Hatter? Harley rotated the ring until\u2014at last\u2014she found what she was looking for.\n\nShe made the little drone rise a little bit higher, out of sight. She had a feeling it might come in handy later.\n\nHe was sitting on what looked like a red velvet throne in the middle of the maze, sipping from a dainty blue teacup. Harley nimbly wove her way around, using the images from the drone camera overhead as her guide. Finally, there was only a wall between them.\n\n\"Where are you, Harley Quinn?\" Mad Hatter's voice was almost a singsong. \"You're not scared, are you? I'd think someone of your stature, of your skills, and of your presence, wouldn't be scared of anything. Reveal yourself! I have a proposition to make!\"\n\nHarley took a step back, did a couple of sidewinders, and then ran up, up...and over the wall, landing in front of Mad Hatter. \"Ta-da! Here I am! Didja miss me?\" she said, looking fierce. \"Now, what's so all-fired important, before I take you in?\"\n\nMad Hatter didn't look surprised. In fact, he looked amused, as if he had anticipated this moment.\n\n\"Harley!\" he said, clasping his hands with joy. \"So glad that we can have this moment together.\"\n\nThough the maze walls had been austere white, where Mad Hatter sat looked like a cozy living room, complete with a fireplace. Harley's stomach made a loud growling sound, reminding her she hadn't eaten lunch.\n\nLaid out before her was a feast of colorful carnival food. Harley's eyes stopped at the sugar-and-cinnamon-powdered funnel cakes stacked so high they threatened to topple.\n\nAs if reading her mind, Mad Hatter said, \"This is all for you. Sit, sit, Harley. Have some cake and tea, have whatever you'd like. We have so much to talk about, you and me. We are much more alike than you realize.\"\n\nHarley stood warily. Mad Hatter didn't seem to have any bodyguards or villains at his side, and there were no weapons that she could see. _What does he want?_ she wondered. Perhaps it really was Mirror Master who was the villain, and he had been using Mad Hatter this whole time. After all, the man sitting in front of her seemed harmless.\n\nThe funnel cakes looked delicious, and Harley was hungry. \"Maybe just one bite,\" she said, picking up a gold plate. The initials _MH_ were written in the center in cursive.\n\nMad Hatter rubbed his hands together and encouraged Harley to pile her plate high with treats. \"More! More! Take more!\" he said. \"More is better!\"\n\n\"Thisissogood!\" Harley gushed after taking a bite. Crisp on the outside, the funnel cake was soft and warm inside. Harley made a mental note to tell Bumblebee about it. Surely it would taste even better drizzled with honey.\n\n\"Please sit, Harley,\" her genial host insisted.\n\nAs Harley joined him, she set her mallet aside, making sure she could grab it if needed. Harley tried to remember what Commissioner Gordon had told his students about getting information from a criminal.\n\nHarley watched Mad Hatter adjust his oversized top hat. It was green with a band of yellow around the base, and boasted a wide brim that didn't detract from the fancy deep blue stitching. It tipped to one side, making Mad Hatter look slightly lopsided, and the sparkles and lights were mesmerizing. Harley recalled that Miss Martian had said something about his hat. But what?\n\n_Well, it'll come to me_ , Harley thought. She'd never had a shortage of ideas.\n\nMad Hatter poured her a glass of iced tea. She drained it in one long swallow. She hadn't realized how thirsty she was. Harley wiped her mouth with the back of her hand, trying to remember why she was there. Perhaps it was to Save the Day, or the world. Or maybe to unmuddle the mystery of the big bubble and unmask the true villain. Was it Mirror Master or Mad Hatter...or someone else completely? Harley was confused. She wished she was as sleuthy as the Junior Detectives. Then again, there were some things she was terribly good at, like running Harley's Quinntessentials!\n\n\"Hey, Mr. Hatter,\" Harley said, trying to focus. Her thoughts were whirling around. She got up and poked at his hat with her index finger. \"That's some amazing _chapeau_ you got there. _Chapeau_ \u2014that's French for 'hat'!\"\n\nThe smile slid off his face for a moment before he laughed and said, \"Oh, Harley, you crack me up. _Merci!_ Thank you for the French lesson.\"\n\nBoth of his hands gripped the edge of his hat as he secured it tightly on his head. Luckily, Harley wasn't wearing a hat. There was nothing he could do to her, she thought.\n\n\"Do you know who your biggest fan is?\" Mad Hatter asked playfully. \"Care to guess?\"\n\n\"One of my viewers? Wait. I know...that lady who sends me pictures of her grandkids?\"\n\nMad Hatter laughed good-naturedly. \"No, not them. Though you do have legions of admirers. But your biggest fan? You're looking at him! I did this all for you, Harley Quinn! The Karnival, the Green Team\u2014it was all to get you here and for us to talk.\"\n\n\"The Big Bubble?\" Harley asked.\n\n\"Yes, the Big Bubble!\" Mad Hatter said, puffing himself up. \"Oh, Ms. Quinn, you've figured it out!\"\n\n\"I have?\" Harley was used to people saying she was funny, and that she could do the best acrobatics. But no one had ever pegged Harley Quinn as an intellectual. \"You think I'm smart?\" she asked, flattered.\n\n\"Of course you are,\" Mad Hatter said. \"You are are remarkably smart.\"\n\nHarley's brain was on overdrive. \"Okay, so as I see it, you worked with Mirror Master to duplicate the Green Team and make their mirror images rob Metropolis.\"\n\nHe looked at her admiringly. \"See?\" Mad Hatter leaned over and tapped Harley's forehead. \"Smart thinking. But I didn't do this just to rob Metropolis. That's child's play. Any common criminal can do that.\"\n\n\"I\u2014I don't understand,\" Harley sputtered. She was so confused, she stopped eating cake.\n\n\"Please, get comfortable and I'll tell you why,\" Mad Hatter said. \"I have been a fan of yours ever since you started Harley's Quinntessentials. In fact, I was one of your very first viewers. MH234. Recognize that?\"\n\n\"MH234? That's you?\" Harley exclaimed, her eyes wide. \"MH234 is always the first to cheer me up when things go wrong!\"\n\nMad Hatter beamed, wickedly delighted. \"That's me. Remember the time you crashed the Internet?\" Harley nodded. How could she forget that? Everyone was mad at her. Well...almost everyone. \"Do you remember what MH234 said?\" he asked, wagging a finger at her.\n\n\"MH234 said, 'You're just getting started, Harley Quinn. Keep going. Someday you're going to be big!' \" she quoted. She had memorized lots of MH234's messages.\n\nMad Hatter burst out laughing. Harley liked the way his eyes sparkled. \"Was I right, or was I right?\" he asked.\n\n\"You, sir, were right!\" Harley said, biting into a treat.\n\n\"I believe in you, Harley,\" Mad Hatter said sincerely. \"And even more now that we've met. You know, we should work together.\"\n\n\"How?\" she asked.\n\nMad Hatter stared into her eyes. \"I love your Web shows. You're so innovative. I mean, c'mon. That dance contest? The Super Bloopers, where the super heroes mess up? The 'Ask Harley' segment? Brilliant. All of them!\"\n\nHarley liked what she was hearing.\n\n\"May I ask ya something, Mr. Hatter?\"\n\n\"Anything, anything for you, my dear,\" he answered.\n\n\"How would we work together? I'm not saying that we would, but if we did, how would that be?\" she asked.\n\nMad Hatter set his teacup down. \"When we team up you will be the top media superstar in the world! With your personality and viewership, and my skills at marketing and planning\u2014\"\n\n\"Go on,\" Harley urged. This was getting interesting.\n\n\"Where is Mirror Master?\" Mad Hatter suddenly asked, looking around. \"He has a present for you! MIRROR MASTER!\"\n\nHarley tried not to smile. She knew Mad Hatter was in for a surprise when he found out that Mirror Master was in custody.\n\nIt was Harley Quinn who was surprised.\n\nMirror Master was standing in front of her. When she last saw him, he was in custody and being hauled away by The Flash toward the Lost and Found, where the Supers were guarding the criminals.\n\n\"Where have you been?\" Mad Hatter asked. Harley thought she saw his eyes flicker with disapproval. When she looked again, he was greeting Mirror Master with a toothy smile. \"Do you have the present for Ms. Quinn, here? That special one.\"\n\n\"I do!\" Mirror Master said. He held his mirror equalizer in one hand...and a hat in the other.\n\nHarley recognized it as the one he'd tried to give her earlier: the eccentric jester-hat-of-many-colors, adorned with jingly-jangly bells.\n\n\"For you, my dear Ms. Quinn,\" Mad Hatter said, bowing to her. He took the hat from Mirror Master and held it high above Harley's head, as if about to crown her.\n\nShe looked nervously at Mirror Master. His jaw was tight. He kept his mirror equalizer aimed right at her. Harley's mallet lay on the ground. She reached for it, but Mirror Master kicked it out of reach and held up his equalizer.\n\nMad Hatter had a delighted look on his face. \"Oh, pshaw! We won't need that,\" he said to Mirror Master. \"Put that thing away. Harley's on our team now, or at least she will be soon!\"\n\nHarley gripped the side of the chair as Mad Hatter slowly lowered the hat on her head, making sure it was on tight. \"Now, that's better,\" he said, grinning. \"You look great!\"\n\nHarley's eyes glazed over. She opened her mouth to speak but nothing came out. Finally she said, \"It. Fits. Great. We are a great fit, too.\"\n\n\"Oh, Harley!\" Mad Hatter crowed. \"Think of the two of us together. What a team we'd make! Hatter and Harley!\"\n\n\"Harley and Hatter,\" she began to correct him.\n\nHe chuckled good-naturedly. \"You are right. You're the star! It should be Harley and Hatter! One has to be flexible about these things, you know.\"\n\nHarley cocked her head. She was getting signals from the hat. Warm, fuzzy signals. They were telling her things. \"Okay!\" she shouted, then calmed down. \"Okay, Mr. Hatter. Working with you will be like a dream.\"\n\nMad Hatter whispered to Mirror Master, \"My mind-control hats work every time! But hats can only go so far. And it's so much work to get people to wear them. However, with this girl, well...\"\n\nHe turned to Harley. \"I'm your biggest fan. Harley's Quinntessentials has the built-in audience to get me started on the road to fame and fortune\u2014my fame and my fortune. Now I can mind-control the masses when they tune in. Everyone will be watching you, and that means they'll be seeing me, too. Everyone. Everywhere! And when they do, I'll rob them blind, and they will love me for it!\"\n\nHarley nodded slowly. \"Mind-control the masses!\" she repeated robotically. \"How?\"\n\nMad Hatter poured himself more tea. He dropped several lumps of sugar into it and stirred slowly. \"Simple,\" he explained. \"This is the new wave of crime. No more robbing banks and stores. That's so old-school\u2014plus, it can get messy. With Hatter and Harley, we will just tell everyone to send us their money and gems and jewels, and whatever we want! And they will because they will have no choice once they're tuned in to us. I'm going to mesmerize them via mass media!\"\n\nHarley's head was buzzing.\n\n\"I am so glad you came to your senses, my dear,\" Mad Hatter was saying. \"Even if I did have to give you a little nudge with that hat. And by the way, it looks marvelous on you. Your fans will love it. You and I are so much alike. We both want to be adored by the masses and will do anything to get what we crave: all eyes on us!\"\n\nHe smiled warmly and settled back in his chair to take a congratulatory sip of tea. Mad Hatter reveled in the moment, then leaned forward and asked, \"What do you say, Ms. Quinn? Shall we shake hands to seal our partnership?\"\n\nHarley stood up. She held out her hand. Mirror Master looked on from the sidelines, still aiming his equalizer at her.\n\n\"Okey-dokey, Mr. Hatter,\" Harley said, extending her hand. \"Let's do this!\"\n\nHarley and Mad Hatter gripped hands and shook, but she wouldn't let go, gripping tighter and tighter. Then Harley began to laugh. Softly at first, then louder and louder.\n\n_\"What?!_ \" Mad Hatter roared. \"Mirror Master! Get Harley!\"\n\nMirror Master raised his mirror equalizer.\n\n\"Go ahead, zap me,\" Harley dared him as she tightened her grip on Mad Hatter.\n\nMad Hatter looked from Mirror Master to Harley, then back again. His eyes narrowed and his jaw tightened. \"Zap her!\" Mad Hatter demanded. \"Do it now!\"\n\n\"Yes, boss,\" Mirror Master said, taking aim.\n\nHarley didn't even flinch when Mirror Master squeezed the trigger.\n\nBOOM!\n\nWhen the puff of vanilla-scented smoke cleared, colorful confetti and streamers rained down on them.\n\nMad Hatter was stunned.\n\nHarley could not stop laughing.\n\n\"Oh, that's not the real Mirror Master,\" she said. \"I knew when Mirror Master showed up that it couldn't be the real thing. Batgirl and The Flash would never let him escape\u2014so this guy had to be a fake!\"\n\n\"The jester hat...,\" Mad Hatter started to say.\n\n\"Ooh, you're so smart, Mr. H!\" Harley said, tapping his forehead. \"Yep. That's why I put on the hat. I also knew my friends wouldn't allow me to fall under your mind control.\"\n\n\"What?\" Mad Hatter sputtered.\n\n\"Oopsie, sorry,\" Harley said, not sounding sorry in the least. \"I forgot to tell you something important. Something really, awfully, terribly, superly important!\"\n\n\"What?\" he growled.\n\nHarley paused, then smiled. \"I've been broadcasting our little talk\u2014to the whole world!\" She waved to the QuinnCam hovering above.\n\nMad Hatter finally noticed the small drone sparkling in the dark. He was speechless.\n\n\"Aren't you gonna say anything? Congrats! You're suddenly famous\u2014but your fifteen minutes are up, in about\"\u2014she checked her watch\u2014\"in about six minutes. And now it's my responsibility to see that you're put away where you belong...in prison!\"\n\nMad Hatter's coloring went from red to white to green, and then back to its regular pale self. He cleared his throat and lowered his voice. \"Listen to me, Harley. We're a team, remember? Hatter and Harley, er...Harley and Hatter. Just put me in front of the camera and tell everyone to stare at their screens. We will have the biggest audience in the history of the world. You will be the most famous person on the planet! Everyone's going to want to know what the two of us now have in store for them.\n\n\"Harley,\" he whispered. \"We can say that the little scene they just witnessed was a prank. A joke!\" He forced a laugh. \"Like when you did 'Where's Harley?' Then we can rule the airwaves...and the world!\"\n\nHarley thought about this. She had always wanted more, more, more. More viewers, more fame, more everything. And now was her chance. Mad Hatter was handing it to her.\n\nHarley looked directly up at the QuinnCam, took a deep breath, and said, \"Hey, Harley's Quinntessentials viewers. This is really hard for me to say. But I've made my decision. Thank you for watching, but a girl's gotta do what a girl's gotta do.\"\n\nMad Hatter grinned and winked at Harley. He puffed himself up, but his smile quickly turned into a look of terror. \"Nooo!\" he cried as Harley grabbed her mallet. With one smooth swing, she threw it at the QuinnCam camera, smashing it to pieces.\n\nAll over the Krazy Karnival and beyond, Harley's Quinntessentials went dark.\n\n\"Now it's just between you and me,\" Harley said, staring down Mad Hatter. \"Let's leave the rest of the world out of this. You think I'd even consider teaming up with the likes of you? Uh, excuse me, but no!\"\n\nMad Hatter stood up and wagged his finger in her face. \"You want a fight, I'll give you one!\" he shouted.\n\n\"Catch me if you can!\" Harley said gleefully. Then she lowered her voice. \"Guide me outta here, Batgirl!\"\n\n\"Gladly, Harley,\" Batgirl said via the two-way communication device she had embedded in the hat. \"Oh, and Miss Martian says to tell you that she's finally got a lock on reading Mad Hatter's mind, but her reception is fuzzy. She says don't ever trust him. Mad Hatter seriously thought you'd be a great team and now he's out for revenge.\"\n\n\"Am I going too fast for you, Mr. Hatter?\" Harley said, laughing as she grabbed her mallet and weaved her way out of the maze. \"Ya know, I like to make people laugh, but just as much of the time, I seem to make people upset. And boy, you look really, totally, and impressively upset right now.\" Harley slowed down. \"Try to keep up, why don't you?\"\n\nMad Hatter was in pursuit, but not nearly as fast as the nimble Harley. The sun was setting outside the bubble as the two raced outside.\n\n\" _ **WOWZA!**_ Everyone is still here?\" Harley asked. By now she was running up and down and loop-de-looping around the roller coaster tracks with Mad Hatter huffing and puffing behind her. She could see the carnival was as crowded as ever with people. \"The bubble is still in place?\"\n\n\"A confirmation on both,\" Batgirl said. Harley stopped to adjust her hat to hear more clearly. \"We're still trying to break the bubble, but everyone is safe, and we've got the Krazy Karnival workers on lockdown while we sort out who's a true criminal and who was under mind control.\"\n\nBefore Harley could reply, someone grabbed her shoulder. \"GOTCHA!\" Mad Hatter cried triumphantly.\n\n\"No, got _you_!\" she said, doing a flip and ending up standing in front of him. The tracks began to shake as a roller coaster car came barreling at them at high speed.\n\n\"Yikes!\" both screamed.\n\nMad Hatter toppled headfirst into the roller coaster car. \"See you!\" he yelled to Harley, who had jumped over the car and was now standing on the tracks alone.\n\n\"Do you need backup?\" Batgirl asked.\n\n\"I got this,\" Harley assured her. \"You keep working on breaking the bubble. Mad Hatter is my battle to fight.\"\n\nMad Hatter was on the ground, holding two fistfuls of darts from the Balloon Pop game. \"You won't get me if I get you first, Harley!\" he yelled, tossing darts at her. But for a guy who ran a carnival, his aim was terrible, and Harley dodged the darts easily.\n\nHarley swung off the roller coaster track, twirled in a pike position in the air, and landed on her feet in front of Mad Hatter. \"I'm making this easy for you,\" she said. \"How nice am I? Come and get me, or maybe now I should get you!\"\n\nMad Hatter gulped as Harley swung her mallet around like she was twirling a baton, tossing it up a few times and then snatching it out of the air. She had blocked him and there was only one way he could escape. Holding on to his hat, Mad Hatter pivoted and headed toward the Ferris wheel. He grabbed on to a passenger car and was yanked off the ground.\n\nHarley leapt and climbed up the turning wheel until she landed safely in the car Mad Hatter clung to.\n\n\"Phew! This is comfy,\" she said, leaning back in the seat and admiring the view.\n\n\"Help!\" someone called.\n\nShe peered down to find Mad Hatter hanging to the bottom of the car with one hand.\n\n\"Harley, help me!\" he pleaded. \"I'm losing my grip.\"\n\n\"Aww, I dunno,\" she said. \"You were pretty mean, trying to use me to control the world. That's so not cool.\"\n\n\"That was the old me. This is the new me,\" Mad Hatter insisted. He looked frightened. \"Please, I'm scared.\"\n\nMad Hatter's face was drained of color. Tears puddled in his eyes. \"Please, Harley,\" he begged as the Ferris wheel continued to go round and round and round.\n\nShe took a breath. \"I'll help you so you don't fall,\" Harley finally said, offering him a hand, \"but first you have to tell me how to break the bubble.\"\n\n\"Listen,\" Mad Hatter said as his fingers laced with hers. \"Just get Obstreperous.\"\n\n\"Obstrep-who?\" Harley asked, confused.\n\n\"Obstreperous,\" Mad Hatter repeated. \"Harley, please,\" he yelled. \"A deal's a deal. I just told you how to break the bubble, now save me!\"\n\nMad Hatter's hand was shaking. Harley could feel his fear as he was about to plummet to the ground. She tightened her grip, and with an \"OOMPH!\" pulled him to safety. \"You can thank me now,\" she said.\n\n\"Certainly,\" he replied, catching his breath. \"How's about this for a thank you?\"\n\nBefore Harley could say \"you're welcome,\" Mad Hatter pushed her off the Ferris wheel.\n\n\"Not nice!\" Harley could be heard yelling as she fell from the Mad Hatter's sight. \"I thought a deal was a deal!\"\n\n\"Bye-bye, Harley Quinn,\" Mad Hatter said, flicking a piece of lint off his jacket. \"Pity. We could have been great together. But no one beats Mad Hatter.\"\n\n\"No one but me!\" said a gleeful voice. Harley pulled herself up and into the Ferris wheel car.\n\n\"How\u2014? What\u2014? Who\u2014? How\u2014?\" Mad Hatter sputtered. \"I pushed you. I saw you fall....\"\n\n\"You should have stayed tuned, Mr. Hatter.\" Harley pretended to look sad. \"Scene one: You pushed me. Scene two: I landed in the car below. Scene three: I vaulted back up here. Why? 'Cause, duh! I'm a gymnast. It's what we do,\" Harley pointed out. \"So, Mr. T., aka Mad Hatter, aka Mr. Soon to Be in Jail! Why don't ya tell us how to shut down your impenetrable bubble?\"\n\nFurious, Mad Hatter's face grew red as he summoned all the powers of his hat. His eyes narrowed as he focused on Harley, who scrunched her nose at him and swatted the air between them like she was batting away a fly.\n\n\"Hey, stop that!\" she ordered. \"You're buggin' me!\"\n\nHarley could hear Batgirl through the jester's hat telling her to bring Mad Hatter in, but something kept interrupting her. It was Mad Hatter repeating, \"You will surrender, you will surrender, you will surrender...\"\n\nHarley shut her eyes tight to block him out. Even though her hat had been deprogrammed and reprogrammed to sync with communications from Batgirl, Mad Hatter's hat still had some serious powers.\n\n\"Block him!\" Harley could hear Batgirl yelling. \"He can only mind-control someone who is vulnerable. Don't look at him. And think of something else, anything but Mad Hatter. He can't control you if you don't let him!\"\n\nThink of something else, Harley thought, scrunching her eyes closed. But what? Well, there's that. And that. Oh, and that's funny.\n\nWhen the Ferris wheel car neared the ground, Mad Hatter leapt out. When Harley opened her eyes the ride was now hundreds of feet up. She took a breath and dove out. Midair, Harley placed her body into a tuck. When she neared the ground, she rolled, then jumped up, unscathed.\n\nBy then Mad Hatter had a large lead. Harley knew she had to stop him before he got to the Lost and Found where his workers were being held. Though they were without their hats, he still had powers of mind control. She may have been able to block Mad Hatter but they were already predisposed to criminal inclinations and more likely to go along with whatever he demanded of them.\n\nIn fast pursuit, Harley threw her whole body into the maddest tumble she had ever attempted. She landed on Mad Hatter's shoulders, and his hat went flying as the two of them tumbled to the ground.\n\nAs he scrambled to pick up his hat, Harley beat him to it and put her foot down right on top of it. \"What's a Mad Hatter without a hat?\" Harley asked, staring down at him.\n\nMad Hatter, who looked surprisingly small and weak without his hat, glared at her. He sighed and shrugged. \"What?\"\n\n\"Just mad,\" Harley quipped as she raised her mallet high in the air.\n\n\"No, no, no!\" he shouted. \"No, not that!\"\n\nWith a gleam in her eyes, Harley brought her mallet crashing down with all her might. Instantly, the hat exploded with wiring, electrical components, and computer chips. It sparked colorfully for a few moments, then winked out.\n\nEverything went dark as all the rides stopped and the lights went out.\n\n\"My hat!\" Mad Hatter wailed.\n\n\"Oh, was that your hat?\" Harley asked, giving him a wink. \"The one that controlled the tech here at Krazy Karnival? The one that controlled the minds of the guests and carnival workers? Oops.\"\n\n\"Harley!\" she could hear Batgirl saying. \"When you destroyed his hat we got communication with the outside. Everything's back up and running.\"\n\n\"Hey, Batgirl,\" Harley said. \"You got a dictionary? Can you look up something for me?\"\n\n\"Sure,\" Batgirl said. \"But, Harley, we're still trapped in the bubble, remember?\"\n\n\"Not for long,\" Harley assured her.\n\n\"Hellloooooo, Harley Quinn here,\" Harley announced. Her face was on every screen at the Krazy Karnival, broadcasting to the world. \"It's good to be back! I promised you a rematch of Harley's Battle of the Bands, and here we go.\"\n\nCheetah, Batgirl, and other Supers stopped trying to break the bubble with their powers and weapons, wondering what Harley was up to. \"A music contest? Now?\" Hawkgirl asked.\n\nMiss Martian ran up to Harley. \"I'm not sure this is the right time for a contest,\" she said.\n\nHarley winked at her and said, \"Read my mind.\"\n\nMiss Martian shut her eyes, then nodded. \"Oh, I see!\" she said, not even hiding her delight.\n\n\"Battle of the Band contestants,\" Harley declared. \"Start playing AS LOUD AS YOU CAN. And everyone\u2014join in and MAKE SOME NOISE!\"\n\nThe bands, who were scattered all over the amusement park, hurried to get themselves together. Instruments were plugged in and amplifiers were turned all the way up. Soon every band began to play. At first it sounded like a clash of wildly different styles and sounds at war with each other. But then something strange started to happen. The music began to mesh into a fusion no one had ever heard before.\n\nThe musical vibration began to make the bubble quiver.\n\n\"LOUDER!\" Harley shouted. \"I CAN'T HEAR YOU!\"\n\n\"What's she doing?\" Big Barda asked as she covered her ears.\n\nMiss Martian closed her eyes and smiled. \"She's breaking the bubble,\" she said.\n\nHarley looked into her camera as the bubble began to shake, making its own deep trembling noise. \"Harley Quinn here, live at the Krazy Karnival, where the Battle of the Bands is in session. But the musicians can't do it alone. To break the bubble we need to make a boisterous sound! More noise than you've ever heard before! It's gotta be LOUD! It's gotta be a sound so obstreperous\u2014\" She paused and said slowly to the camera, \"That means noisy and difficult to control, according to the dictionary\u2014that it cracks this bubble where it counts.\"\n\nSupergirl and Wonder Woman began to fly around the amusement park to spread the news.\n\n\"Everyone make some noise!\" Supergirl said.\n\n\"Louder!\" Wonder Woman cried.\n\nBumblebee, Big Barda, Thunder, and Lightning began to sing. Beast Boy once more became a coqui frog and began to croak. Silver Banshee raised her sonic scream that was only matched by Captain Cold's wailing guitar solo.\n\nSoon all the other Supers joined in, encouraging everyone to shout, sing, stomp, and bang anything to add to the ocean of sound started by the bands. With each voice and sound added, the bubble began to tremble more. But it still wouldn't break.\n\nMiss Martian looked at Harley in desperation and cried out, \"It's not enough. We need something more.\"\n\nEverything that had happened lately raced through Harley's mind in fast-forward. Was she an Internet personality? A solid B student\u2014okay, B-minus? A class clown? An entertainment impresario? And then she remembered who she was and a mischievous grin crossed her face.\n\n_I'm a_ _**SUPER.**_\n\nHarley Quinn reached into her pocket and pulled out the strength-tester bell from earlier. Smiling, she tossed it into the air and then swung her mallet with all her might. _CLANG!_ the iron bell rang out as it rocketed into the sky. It hit the vibrating bubble and smashed through it.\n\nEveryone stopped making music and noise. For a moment, the absolute silence was as deafening as the cacophony.\n\n\" _ **YOWZA,**_ \" Harley said quietly under her breath. And with that, the bubble\n\nThe bubble broke into a million shards and began to rain down on Krazy Karnival. Poison Ivy cried, \"It's okay! It's safe! Look\u2014rainbows!\"\n\nSure enough, the big bubble that had once covered the Krazy Karnival turned into tiny rainbows that wafted downward and before they hit the ground.\n\n\"You're seeing it here in this Harley's Quinntessentials exclusive,\" Harley said, her signature smile broadcasting to her viewers. \"The Mad Hatter is caught. The bubble is broken, the bad guys are rounded up, and the carnivalgoers are safe. And, wait, wait, I'm getting some news from Metropolis\u2014\" Via the jester hat, Harley listened as Batgirl plugged her in to Lois Lane. \"Yes!\" she went on. \"I knew it! When the Mad Hatter's hat broke, so did the hold he had on the Green Team. They were under his control, but no more. In fact, they're apologizing and returning everything they took, right now. _**WOWZA! YOWZA!**_ This is turning out A-okay, and...\" Harley's smile froze on her face.\n\nPrincipal Waller was marching toward her with all the Super Hero High teachers behind her.\n\n\"We cut our conference short when danger arose, but we couldn't get past the bubble,\" Principal Waller said. Liberty Belle, Mr. Fox, Wildcat, and the other teachers nodded. Parasite, the janitor, looked around at the mess that was the Krazy Karnival and sighed.\n\nHarley shrugged. \"Um, I'm in trouble again, right?\" she asked. \"Hiya, VP Grodd, guess I'll see you in detention tomorrow!\"\n\n\"Quite the contrary,\" Waller informed her. \"What is happening is highly unorthodox\u2014but then, so are you. Harley Quinn,\" Principal Waller continued in a booming voice, \"it is my honor to name you Super Hero High's Super Hero of the Month!\"\n\nFor once Harley was speechless\u2014but not for long. \" _ **WOWZA!**_ \" she yelled as cheers erupted. \"ME?!\"\n\n\"YOU!\" Pied Piper called out. He turned to the bands and gave them the signal to start playing.\n\nWhen Waller handed Harley the official Hero of the Month award, Harley hugged it and then backflipped onto the top of a tall Sweet Treats stand. Harley looked out over all the Supers who had gathered around. With a mischievous glint in her eyes, Harley threw her award high into the air.\n\n\"This award doesn't belong to me. It belongs to all of us. Yes, I'm lookin' at you!\" she said when Miss Martian caught it. Harley pointed. \"And you, and you, and you, and you! I declare EVERYONE the winners of the Battle of the Bands, and the Battle Against Mad Hatter, and the Breakers of the Bubble! We are all winners here!\"\n\nCheetah looked up at Harley. \"Is there a class clown award?\"\n\nHarley winced. Waller had just named her a hero and now Cheetah was bringing up the class clown thing again?\n\nBut when Cheetah turned to the crowd, Harley could hardly believe what she was hearing. \"Hat's off to Harley Quinn, Super Hero High's very own one-of-a-kind class clown,\" Cheetah said. Breaking into a grin, Cheetah started to shout, \"Harley! Harley!\"\n\nHarley's heart swelled as the crowd began to chant \"HARLEY! HARLEY! HARLEY!\"\n\nAs the chant grew to a thunderous roar, Harley dove off the top of the Sweet Treats stand, and hundreds of hands rose to catch her.\n\nAs Lois interviewed Harley on camera in front of Capes & Cowls Caf\u00e9, Miss Martian stood off to the side, watching. She clutched a basket overflowing with fan letters from people who had been inside the bubble and outside who had learned of her bravery. While Harley chatted effortlessly, Miss Martian was trying not to disappear, since her interview was up next.\n\nThunder and Lightning waved to Harley as they raced inside. Beast Boy, as a baby kangaroo, kept jumping up and down, photobombing the interview. Bumblebee's phone rang with its familiar \"Flight of the Bumblebee\" ringtone. But Harley, ever the pro, stayed focused.\n\n\"The safety of the world was more important than how many people were watching my show,\" she was saying. \"Mad Hatter wanted the audience, but I wanted to save the world from him.\"\n\n\"You heard it here,\" Lois said to the camera. \"It's no joke that Harley Quinn is a real hero. So what's next for Harley's Quinntessentials?\"\n\n\"Well, now that the Green Team is taking over the Krazy Karnival and donating any profits to charity, I'll be covering that. Plus, I plan to start a new segment called 'Good Deed of the Day,' featuring Supers and citizens helping others....\"\n\nBumblebee started gasping for air as Harley was talking. Supergirl and Poison Ivy rushed to her. Lois cut off the interview. \"Are you okay?\" she asked.\n\nBy then Bumblebee was in tears.\n\n\"Bumblebee?\" said Harley.\n\nBumblebee put down her phone. \"My mom and dad are in danger!\" she cried. \"I have to go!\" She turned herself small and rushed to fly away before anyone could stop her.\n\nPoison Ivy shouted after her. \"Bumblebee, what's happening?\"\n\nBut Bumblebee couldn't hear her. By then she was already past Metropolis.\n\nTo be continued...\n\nMieke Kramer\n\nAfter writing jingles, restaurant menus, and TV shows, Lisa Yee won the prestigious Sid Fleischman Humor Award for her debut novel, _Millicent Min_ , _Girl Genius_. Her other novels for young readers include _Stanford Wong Flunks Big-Time_ , _Bobby vs. Girls (Accidentally)_ , and several books for American Girl, plus _Warp Speed_ , about a Star Trek geek. Her most recent original YA novel is _The Kidney Hypothetical_. She has also written for _Huffington Post_ and is a contributor to NPR.\n\nLisa's books have been named a _Washington Post_ Book of the Week, a _USA Today_ Critics' Pick, an NPR Best Summer Read, and more. Writing the DC Super Hero Girls series is a dream come true, says Lisa. \"I get to hang out with Wonder Woman, Batgirl, Katana, and the rest of the super heroes!\"\n\nYou can visit Lisa Yee at LisaYee.com.\n\n# _What's next on \nyour reading list?_\n\n[Discover your next \ngreat read!](http:\/\/links.penguinrandomhouse.com\/type\/prhebooklanding\/isbn\/9781524769253\/display\/1)\n\n* * *\n\nGet personalized book picks and up-to-date news about this author.\n\nSign up now.\n\n## Contents\n\n 1. Cover\n 2. Title Page\n 3. Copyright\n 4. Dedication\n 5. Contents\n 6. Prologue\n 7. Chapter 1\n 8. Chapter 2\n 9. Chapter 3\n 10. Chapter 4\n 11. Chapter 5\n 12. Chapter 6\n 13. Chapter 7\n 14. Chapter 8\n 15. Chapter 9\n 16. Chapter 10\n 17. Chapter 11\n 18. Chapter 12\n 19. Chapter 13\n 20. Chapter 14\n 21. Chapter 15\n 22. Chapter 16\n 23. Chapter 17\n 24. Chapter 18\n 25. Chapter 19\n 26. Chapter 20\n 27. Chapter 21\n 28. Chapter 22\n 29. Chapter 23\n 30. Chapter 24\n 31. Chapter 25\n 32. Chapter 26\n 33. Chapter 27\n 34. Chapter 28\n 35. Chapter 29\n 36. Chapter 30\n 37. Epilogue\n 38. About the Author\n\n 1. vi\n 2. vii\n 3. \n 4. \n 5. \n 6. \n 7. \n 8. \n 9. \n 10. \n 11. \n 12. \n 13. \n 14. \n 15. \n 16. \n 17. \n 18. \n 19. \n 20. \n 21. \n 22. \n 23. \n 24. \n 25. \n 26. \n 27. \n 28. \n 29. \n 30. \n 31. \n 32. \n 33. \n 34. \n 35. \n 36. \n 37. \n 38. \n 39. \n 40. \n 41. \n 42. \n 43. \n 44. \n 45. \n 46. \n 47. \n 48. \n 49. \n 50. \n 51. \n 52. \n 53. \n 54. \n 55. \n 56. \n 57. \n 58. \n 59. \n 60. \n 61. \n 62. \n 63. \n 64. \n 65. \n 66. \n 67. \n 68. \n 69. \n 70. \n 71. \n 72. \n 73. \n 74. \n 75. \n 76. \n 77. \n 78. \n 79. \n 80. \n 81. \n 82. \n 83. \n 84. \n 85. \n 86. \n 87. \n 88. \n 89. \n 90. \n 91. \n 92. \n 93. \n 94. \n 95. \n 96. \n 97. \n 98. \n 99. \n 100. \n 101. \n 102. \n 103. \n 104. \n 105. \n 106. \n 107. \n 108. \n 109. \n 110. \n 111. \n 112. \n 113. \n 114. \n 115. \n 116. \n 117. \n 118. \n 119. \n 120. \n 121. \n 122. \n 123. \n 124. \n 125. \n 126. \n 127. \n 128. \n 129. \n 130. \n 131. \n 132. \n 133. \n 134. \n 135. \n 136. \n 137. \n 138. \n 139. \n 140. \n 141. \n 142. \n 143. \n 144. \n 145. \n 146. \n 147. \n 148. \n 149. \n 150. \n 151. \n 152. \n 153. \n 154. \n 155. \n 156. \n 157. \n 158. \n 159. \n 160. \n 161. \n 162. \n 163. \n 164. \n 165. \n 166. \n 167. \n 168. \n 169. \n 170. \n 171. \n 172. \n 173. \n 174. \n 175. \n 176. \n 177. \n 178. \n 179. \n 180. \n 181. \n 182. \n 183. \n 184. \n 185. \n 186. \n 187. \n 188. \n 189. \n 190. \n 191. \n 192. \n 193. \n 194. \n 195. \n 196. \n 197. \n 198. \n 199. \n 200. \n 201. \n 202. \n 203. \n 204.\n\n 1. Cover\n 2. Cover\n 3. Title Page\n 4. Table of Contents\n 5. Start\n\n","meta":{"redpajama_set_name":"RedPajamaBook"}} +{"text":" \nIMAGES \n _of America_\n\nMERCEDES\n\nThis map was part of an accordion postcard from 1909 that showed a map of Mercedes's location and invited northerners to travel by train to visit and purchase land or start a business. The postcards were commissioned by the Mercedes Commercial Club, forerunner of the Mercedes Chamber of Commerce, as part of an aggressive marketing strategy. Mercedes is located in the southeast corner of Hidalgo County in South Texas, only five miles from the Rio Grande and the border with Mexico. (Courtesy of Vito Buenrostro.)\n\n**O N THE COVER:** Mercedes celebrates its 25th anniversary on September 15, 1932, with a historic parade. The town was founded in 1907 to serve as the headquarters of the American Rio Grande Land and Irrigation Company. The first residences and businesses were railroad boxcars, tents, and shanties, but by 1932, prosperous shops lined the main street in town and the population had grown to more than 5,000 inhabitants. (Courtesy of the Margaret H. McAllen Memorial Archives, Museum of South Texas History.)\nIMAGES \n _of America_\n\nMERCEDES\n\nBeatrice de Le\u00f3n Edwards, EdD\n\nCopyright \u00a9 2014 by Beatrice de Le\u00f3n Edwards, EdD \nISBN 978-1-4671-3206-0 \nEbook ISBN 9781439646946\n\nPublished by Arcadia Publishing \nCharleston, South Carolina\n\nLibrary of Congress Control Number: 2014943728\n\nFor all general information, please contact Arcadia Publishing: \nTelephone 843-853-2070 \nFax 843-853-0044 \nE-mail sales@arcadiapublishing.com \nFor customer service and orders: \nToll-Free 1-888-313-2665\n\nVisit us on the Internet at www.arcadiapublishing.com\n\nThe Mercedes City Hall and Fire Station, built in 1928, was designed by architect Roscious Newell Waters. The first floor held city offices, and the second floor housed a firemen's dormitory and city meeting rooms. The building is in a Gothic style with red brick with the exception of the replacement bricks on the end from repairs after the hurricane of 1933. It features a copper cupola to hold the fire alarm. (Courtesy of the City of Mercedes.)\nCONTENTS\n\nTitle Page \n--- \nCopyright Page \nAcknowledgments \nIntroduction \n1.| The Early Settlers \n2.| Founding a Town \n3.| Building the Community \n4.| Wars and Natural Disasters \n5.| The Rio Grande Valley Livestock Show\nACKNOWLEDGMENTS\n\nMany heartfelt thanks go out to all of the individuals who so generously allowed me to scan their personal family photographs and postcard collections for use in this book, including Vito Buenrostro; Carolyn Crenshaw L\u00f3pez; Irma Palacios; Rolando Hinojosa-Smith; Sylvia Arteaga Calles; the Riess family; the Garc\u00eda family; Robert, Loretta, Kenneth, and Debbie Eilers; Rosendo Gonzales; Eddie Howell Sr.; Helen Vogel; and Delia de Le\u00f3n. A very special thanks to Fran Isbell, whose in-depth knowledge of the Rio Grande Valley and its history were warmly shared with the author. Especially helpful also were the staff of the Weslaco Museum of Local History and Cultural Art; the members of the Hidalgo County Historical Commission; Janette Garc\u00eda of the University of Texas-Pan American; and Phyllis Kinnison and Esteban Lomas of the Museum of South Texas History. All images from the Museum of South Texas History (MSTH) come from the Margaret H. McAllen Memorial Archives of the Museum of South Texas History in Edinburg, Texas. A special thanks to Olga Hinds and Clarissa Mart\u00ednez of the _Mercedes Enterprise_ ; as well as the City of Mercedes; the members of the Mercedes Chamber of Commerce; Dr. Daniel Trevi\u00f1o Jr., superintendent of schools, Alicia Z. V\u00e1squez, district librarian, and Debbie Winslow of the Mercedes Independent School District; Sam MaGee, general manager, and Adell Dufour, museum director, of the Rio Grande Valley Livestock Show; Our Lady of Mercy Catholic Church; the Rub\u00e9n Hinojosa Congressional Office; and Marisol Vidales, library director at the Hector P. Garc\u00eda Memorial Library of Mercedes, Texas. Also invaluable have been the publications and work by the Mercedes Centennial Book Project Committee. Special thanks to the Carrizo\/Comecrudo Tribe of Texas for the use of its tribal seal. More information about this tribe is available at www.carrizocomecrudonation.com. Public domain images from the Library of Congress and the National Archives have also been used. Special thanks also go to Dr. Armando Alonzo, Borderlands historian at Texas A&M University, for reviewing text and making important recommendations. Heartfelt thanks for her patience and assistance go to my acquisitions editor, Stacia Bannerman; David Mandel, production coordinator; and Jennifer Sexton, sales manager, at Arcadia Publishing. Finally, thanks to all my family members for their love and encouragement on this project. Without these entities, this book would not have been possible.\nINTRODUCTION\n\nMercedes, Texas, the \"Queen City,\" is located in the southeastern corner of Hidalgo County only five miles from the Mexican border in South Texas in a geographic area known as the Lower Rio Grande Valley. The \"Valley\" is not a true valley, but a river delta formed as the Rio Grande empties into the Gulf of Mexico. Before the advent of river dams and levees, the Rio Grande flooded annually, much as the Nile did in Egypt, creating rich, fertile soil in a narrow band suitable for limited agriculture.\n\nThe earliest known inhabitants of this area were called Coahuiltecans by anthropologists who grouped all of the separate native indigenous groups together. Later studies of the copious annotations of Spanish _entradas_ , or exploratory expeditions, to this area in the 1600s revealed that many different groupings existed, each with their own language and customs. These early explorations noted that there were numerous native settlements the Spanish called _rancher\u00edas_.\n\nUnder the leadership of Jos\u00e9 de Escand\u00f3n, the Count of Sierra Gorda, Spanish colonists migrated in the mid-1700s to the northern reaches of Nueva Espa\u00f1a, or New Spain, to the region called _Nuevo Santander,_ which reached from Tampico to the Nueces River. On both the southern and northern banks of the lower Rio Grande, Escand\u00f3n established six villas or townships between 1749 and 1755, and numerous land grants called _porciones_ were apportioned out. These _porciones_ were narrow strips of land that each had access to the river to ensure that water was available to each landowner. Because of the climate, topography and soil composition, these Spanish colonists decided that ranching was best suited to the area, with some subsistence farming in selected areas near the river waters or the _resacas_ through the use of _acequias_ , or irrigation channels, that used gravity to move the water streams.\n\nIn 1778, Juan Jos\u00e9 Hinojosa, a captain and chief justice at the villa of Reynosa, petitioned the king of Spain for the Llano Grande land grant on the north side of the Rio Grande where the city of Mercedes is now located. This royal land grant contained 25 leagues of land with 15 miles of river frontage, or more than 100,000 acres. By the time the grant was approved in 1790, Hinojosa had died, and his grant was divided up amongst his eight heirs. Mercedes was later established on what were parts of shares five, six, and seven.\n\nMexico's separation from Spain in 1821 and the Texas Independence of 1836 disrupted the everyday business of the ranching communities, and many Mexican-heritage inhabitants of Texas began calling themselves Tejanos. The Mexican\u2013American War in 1848 profoundly impacted the area when the original landowners, suddenly now US citizens, were forced to protect their land claims in land adjudication courts. Being land-rich but cash-poor, many were able to do so successfully but still lost land when they were forced to pay the American lawyers' fees and their property taxes with acreage.\n\nDuring the Civil War, when the Rio Grande was the only waterway available to the Confederate cotton growers for shipping to market, the value of the river and the region was noted by northern venture capitalists. Many Anglos had come to the Valley during the Mexican\u2013American War and the Civil War to make their fortunes, and many married Mexican heiresses. By 1865, northern eyes were set on the Rio Grande Valley and interest grew in developing international trade and commercialized agriculture in this region.\n\nIn July 1904, the Sam Fordyce Branch of the St. Louis, Brownsville and Mexico Railway reached Section 14 and established the stop that would later become Mercedes, declared the \"Sweetheart of the Branch.\" Upon visiting the Valley, railroad magnate Benjamin F. Yoakum became convinced that commercialized agriculture was a viable venture in the Rio Grande Valley. Yoakum convinced a group of investors to form the American Rio Grande Land and Irrigation Company to purchase land and develop an irrigation system that would transform the Lower Rio Grande Valley into an area of profitable commercialized agriculture.\n\nThe American Rio Grande Land and Irrigation Company purchased land from the Capisallo Town and Improvement Company belonging to Lon C. Hill in 1907 with the intention of making the town its company headquarters. Hill had already platted a town and named it Capisallo, then later renamed it Lonsboro. The American Rio Grande Land and Irrigation Company then decided to move the site west about a mile to an area called the Pear Orchard. It was so named because of the abundance of cacti bearing prickly pear fruit in that location. Mercedes was officially founded on September 15, 1907.\n\nBy sheer force of manual labor, thousands of Mexican and Tejano laborers with pick, shovel, and hoe cleared the land, and the town was finally mapped out in its present location. The American Company directors decided to rename the town D\u00edaz because they greatly admired Mexican president Porfirio D\u00edaz but then changed it to Mercedes, somehow erroneously believing that President D\u00edaz's wife's name was Mercedes. But D\u00edaz's first wife was named Delfina, and his second wife was named Carmen, so the choice of name remains a mystery to this day. No known primary sources exist explaining the choice of name. Unfortunately, numerous published works since the early days have reported that the name Mercedes referred to President D\u00edaz's wife, and the inaccuracy has been repeated many times.\n\nIt should be noted that the phrase _mercedes reales_ means \"royal grants\" and _mercedes de tierra_ means \"land grants.\" It is possible that somehow, someone who heard these phrases mistakenly believed Mercedes to be a person; namely, President D\u00edaz's wife. The phrase _mercedes reales_ also gives a connection to the choice of the nickname \"Queen City\" for the town of Mercedes because \" _real_ \" which means \"royal\" could have made someone think Mercedes referred to a royal person; namely, a queen. In reality, _mercedes reales_ referred to the fact that the _porciones_ and the larger land grant tracts such as the Llano Grande were royal gifts.\n\nOn March 8, 1909, Mercedes became incorporated and elected a mayor and city council. The town grew rapidly as the Mercedes Commercial Club, forerunner of the Mercedes Chamber of Commerce, aggressively promoted land development. The winter vegetable and citrus farms began producing immediately, and Mercedes became a major exporter of produce, citrus fruits, and cotton. In 1939, Mercedes promoted an annual agricultural and livestock show that became the Rio Grande Valley Livestock Show. In 2014, the Rio Grande Valley Livestock Show celebrated its 75th anniversary.\n\nAs did most Valley cities, Mercedes experienced growing pains with bandit troubles, the effects of World War I and II, influenza and smallpox epidemics, hurricanes, floods, droughts, freezes, and the Great Depression. Mercedes overcame these obstacles and continued to thrive. The town established many churches and businesses and an excellent school system. Mercedes has produced notable citizens in the fields of art, literature, music, business, education, government, athletics, and science among others; and although it has produced excellence, its noble work is not yet done.\n_One_\n\nTHE EARLY SETTLERS\n\nSpanish explorers first came to the area where Mercedes is now located in the 1600s. The expeditions found that the land was covered with heavy brush similar to that of this photograph. Mesquite, cactus, huisache, and other native plants covered the land thickly. When the Spanish colonists arrived in the 1700s, they decided to use the land for ranching with some subsistence farming where water was available. (MSTH.)\n\nThe Spanish made several expeditions or _entradas_ into the Rio Grande Valley in the 17th century. They reported finding many _rancher\u00edas_ , or settlements of nomadic bands that historians first called Coahuiltecans. After rereading Spanish chronicles, later historians discovered more than 50 different indigenous groups inhabited this region. The Carrizo\/Comecrudo were most associated with the Rio Grande river delta. Once thought extinct, descendants have resurfaced although they were displaced to other Texas areas. (Carrizo\/Comecrudo Tribe of Texas.)\n\nSpanish explorer Alonso de Le\u00f3n led four expeditions between 1686 and 1689 to explore the area around the mouth of the Rio Grande, also known as the Rio Bravo. After finding the ruins of a French settlement on his fourth expedition, the Spanish king commanded that settlers be brought in to establish a more solid claim to this area. In 1746, Jos\u00e9 de Escand\u00f3n, the Count of Sierra Gorda, was commissioned to explore the area between Tampico and the San Antonio River. The province of Nuevo Santander, which corresponds generally to the Mexican state of Tamaulipas and south Texas, is pictured in this adaptation of a 1792 Spanish map. (Courtesy University of Texas-Pan American.)\n\nJos\u00e9 de Escand\u00f3n was a Spaniard who chose a military career and immigrated to New Spain in 1715. By 1740, he had risen through the ranks and was lieutenant captain general of the Sierra Gorda frontier. His successful strategies for pacification of the region while remaining fair-minded with all groups brought him the title of Count of Sierra Gorda as well as the charge of leading colonists to the Rio Grande region. After determining which areas were suitable for settlement and carefully choosing which colonists to take, Escand\u00f3n brought in more than 400 families and founded Camargo, Reynosa, Mier, Revilla, Laredo, and Nuestra Se\u00f1ora de los Dolores on the banks of the lower Rio Grande. For this reason, he is often called the \"father\" of the lower Rio Grande Valley. Beginning in 1755 with the founding of Laredo, Spanish colonists began establishing ranching communities on the northern banks of the river, including the area where Mercedes is today. (University of Texas-Pan American.)\n\nThis map shows the _porciones,_ or long narrow strips of land, and larger land grants owned by the original Spanish colonizers of southern Hidalgo County in the late 1800s. In 1778, Juan Jos\u00e9 Hinojosa, a captain and chief justice at the villa of Reynosa, petitioned the king of Spain for the Llano Grande grant where the city of Mercedes is now located. This grant contained 25 leagues of land with about 15 miles of river frontage. Hinojosa died before he was finally granted the land in 1790, and his children inherited the land in eight equal shares. Mexico's separation from Spain in 1821, the Texas Independence of 1836, and the Mexican\u2013American War of 1846 created turmoil in the region. In 25 years, these first families' citizenships changed three times. At the end of the Mexican\u2013American War, they were forced to prove their land ownership in Texas state courts. Although most of them retained title to their land grants, many lost acreage when they were forced to pay their attorneys and taxes in land. (Hidalgo County Historical Commission.)\n\nBy the end of the 19th century, there were hundreds of ranches on the northern side of the Rio Grande. Although the brush land was thick with mesquite, cactus, huisache, and native grasses, the land was suitable for grazing cattle. Every ranch had access to water, either directly from the river or from the _resacas_ , the old river channels of the Rio Grande. (MSTH.)\n\nIn the 19th century, the most obvious choice as a building material in the valley was mesquite wood. Even though it was twisted rather than straight, it was abundant, strong, and durable. The wood is so hard that it is sometimes called \"Texas Ironwood.\" Corrals and fences made of mesquite such as the one seen here were common sights on valley ranches of that era and are still seen today. (National Archives.)\n\nThis map is a partial replica of one of the hand-drawn maps used by the Missionary Oblates of Mary Immaculate from around 1849 to serve the Catholics living on the scattered ranches of south Texas. These missionary priests had established headquarters in Brownsville before the advent of the railroad or even of paved roads. They traveled their lonely trails through the wild brush land alone, mounted on horseback. Their circuits usually lasted about six weeks during which time they traveled 100 miles or more. The Oblate Trail in the Rio Grande Valley stretched from Port Isabel and Brownsville up the river to Laredo, a distance of more than 200 miles. They also traveled north to service ranches and townsites farther away from the river. In 1949, the Brownsville Historical Association designated the trail by erecting road markers. (Hidalgo County Historical Commission.)\n\nThe Missionary Oblates of Mary Immaculate were founded in France in 1816 by Blessed Eugene de Mazenod. In south Texas, they were commonly known as the Cavalry of Christ because they served their parishioners as circuit-riders on horseback. Their black soutane habits, black rounded hats, and silver Oblate cross worn round their necks were widely recognized in the region. (MSTH.)\n\nFr. Pierre Yves Keralum was an Oblate priest who, despite his advanced age, continued to serve his people. In November 1872, he set out on his circuit and never returned, being last seen at a ranch north of Mercedes. His remains were found in 1882. In 1920, a memorial was erected to the much-loved Padre Pedrito at the Catholic cemetery in Mercedes. (Our Lady of Mercy Catholic Church.)\n\nBefore Mercedes was founded, many ranches were located in the area, including the Anacuitas (Anacahuitas), Los Burros or Guadalupe, Parajitos, Rel\u00e1mpago, Rosario, San Jos\u00e9 or Solises, Tampacu\u00e1s (also known as Campacu\u00e1s), and Toluca Ranches. This aerial view shows the Toluca Ranch, located about a mile south of US 281 (Military Highway) and a quarter mile east of Farm to Market Road 1015. It is remarkable for having survived almost intact until the present time and is a good model of what a _hacienda_ ranch of the past century would have looked like with its main house, its chapel, a school, a store, the ranch hands' houses, work sheds, vegetable gardens, and corrals. At one time, Toluca Ranch had a post office from which mail was distributed to surrounding ranches by horseback, or farther away by stagecoach or steamboat. At its largest, Toluca Ranch had around 12,000 acres with river frontage and stretched northward 17 miles. (MSTH.)\n\nPictured here are S\u00f3stenes Cano (right) and Florencio S\u00e1enz. After working for many years as a bookkeeper for don Antonio Cano of the Tampacu\u00e1s Ranch, don Florencio S\u00e1enz married S\u00f3stenes Cano, youngest daughter of Antonio and Mauricia Fern\u00e1ndez Cano. Don Antonio Cano of Reynosa had purchased acreage in 1862 from the descendants of Juan Jos\u00e9 Hinojosa of the Llano Grande land grant; specifically, from Cirildo Hinojosa's fifth share. As her inheritance, S\u00f3stenes received a tract of land in the southern part of the Tampacu\u00e1s Ranch that the couple named the Toluca Ranch. The name of the ranch is likely a reference to the town of Toluca in south-central Mexico. The word \"Toluca\" comes from the indigenous word \"Tollocan,\" which means \"place of the god Tolloh\" in n\u00e1huatl, the language of the Aztecs. (Both, MSTH.)\n\nSt. Joseph's Chapel was built in 1896 by don Florencio S\u00e1enz in thanksgiving for when he was finally able to dig a well that yielded sweet, drinkable water. Many previous attempts had only yielded salty, brackish and undrinkable water. The chapel was designed by the Oblate priest Pierre Keralum. The pews accommodate 85 people. Don Florencio's grandson Santiago Fern\u00e1ndez and his great-granddaughter Florence stand in the doorway in this photograph taken in 1951. (MSTH.)\n\nThe interior of St. Joseph's Chapel is decorated with statues purchased in Spain by the S\u00e1enz-Fern\u00e1ndez family. Some of the statues were donated to Our Lady of Mercy Catholic Church in the town of Mercedes in 1947 in thanksgiving after do\u00f1a Manuela Fern\u00e1ndez's five sons all returned safely from World War II. (MSTH.)\n\nThis is the wedding portrait of Manuela Cano Champion (left) and Amador Fern\u00e1ndez, a Spanish \u00e9migr\u00e9. Don Florencio and do\u00f1a S\u00f3stenes S\u00e1enz were unable to have any children, so they decided in 1882 to adopt their three-month-old niece Manuela Cano Champion, daughter of Pedro and Gumecinda Cano Champion. Manuela met and married Amador Fern\u00e1ndez in 1908. They eventually had eight children: Jos\u00e9 Florencio, Jos\u00e9 August\u00edn, Guadalupe Anastasio, Joaqu\u00edn Jorge, Ernesto M\u00f3nico, Santiago \"Jimmy,\" Manuela Lourdes, and Amador Tom\u00e1s. All the children were well educated and several participated in Mercedes city and school district positions. Some of the children and grandchildren continue living in Toluca Ranch to this day. Toluca Ranch was well known for having a brick factory that supplied bricks for many buildings in Mercedes and for a ferry landing where steamboats stopped to load farm and ranch products and unload supplies. (MSTH.)\n\nIn 1914, the S\u00e1enz-Fern\u00e1ndez family built this home in Mercedes on the corner of Missouri Avenue and Fourth Street. They were forced to move to town after their Toluca Ranch was attacked four different times by roving bands of Mexican revolutionaries. The spillover violence of the Mexican Revolution, which lasted from 1910 to 1920, greatly affected the lower Rio Grande Valley region. (Carolyn C. L\u00f3pez.)\n\nThe Fern\u00e1ndez family is depicted in this reunion photograph taken in the early 1950s. Amador and Manuela Fern\u00e1ndez are seated in the center with their eight children, sons-in-law, daughtersin-law, and grandchildren surrounding them. In the early 1900s when Mercedes was still young, Amador Fern\u00e1ndez had a dry goods store just opposite the First National Bank on Texas Avenue. ( _Mercedes Enterprise_.)\n\nWater has always been a precious commodity in the lower Rio Grande Valley since its settlement in the 18th century. In areas where there was no access to river water or lakes, wells had to be dug but these often produced brackish or salty water. Frequently, communities had to rely on water sellers such as this one who brought water in barrels to sell. (MSTH.)\n\nMost ranches had developed into small communities by the end of the 19th century. Ranch workers and their families also lived on the ranch. Workers included vaqueros, or cowboys, blacksmiths, cooks, storekeepers, brick makers, carpenters, and masons among others. When Mercedes was founded, there were several ranches in the surrounding areas including among others: Toluca, Tampacu\u00e1s, Los Burros, Anacuitas (Anacahuitas), Rel\u00e1mpago, Parajitos, Los Ebanos, and El Fuste. (National Archives.)\n\nWhen the lower Rio Grande Valley became part of the United States in 1848, the Spanish and Mexican land grant holders were forced to defend their land claim in state courts. Many landholders were land-rich but cash-poor and were forced to pay their American lawyers' fees in acreage. The document above was Juan Jos\u00e9 Hinojosa's (sometimes spelled Ynojosa) Llano Grande Land Grant title, finally approved and certified by the Texas State Legislature in 1852 for his heirs. Large land grants such as this one were awarded only to favorites of the king or other crown officials. Called _mercedes reales_ , or \"royal grants,\" or _mercedes de tierra_ , \"land grants,\" these larger grants were intended to support hacienda-type ranching ventures. Before the 20th century in Hidalgo County alone, there were 43 porciones granted through the Reynosa jurisdiction, 12 intermediate grants, and 14 large land grants such as Hinojosa's. (Hidalgo County Historical Commission.)\n\nThe map shown here of Hinojosa's Llano Grande grant is called the Dupouy Partition. It was originally prepared in 1848 by Alfredo Dupouy, the court surveyor in Matamoros, Tamaulipas, Mexico. By 1919, Hinojosa's children had already sold land to others as noted here. This map was used as part of the abstract of title obtained by the American Rio Grande Land and Irrigation Company on March 5, 1919, to show clean title to its purchase of lands in the Rio Grande Valley. Share one belonged to Julia de la Garza; share two belonged to Mat\u00edas Cavazos; share three belonged to Leonardo Manso; share four belonged to Manuel Hinojosa, Francisca Hinojosa, and Ygnacia Hinojosa; share five belonged to Vicenta Hinojosa, share six belonged to Gregoria Longoria and Cipriano Hinojosa; share seven belonged to Juan Hinojosa, and share eight belonged to Rosa Maria Hinojosa. There was also a separately sectioned area called the Adams Tract, owned by William T. Adams and his wife, Virginia Adams. Mercedes is located in portions of shares five, six, and seven. (Hidalgo County Historical Commission.)\n\nAlthough in the 1900s large-scale ranching in the Valley was gradually replaced by commercialized farming with the arrival of northern land developers, the love of the ranching era still survives today in many Mercedes residents. Pictured in 1975, seated on his Lineback Dun horse, is Rosendo Gonzales and his grandson Paul. Gonzales belongs to the Mid-Valley Horseman's Association. (Rosendo Gonzales.)\n\nBy 1868, as shown in this early postcard, the railroad had reached Brownsville. On July 8, 1904, the Sam Fordyce Branch of the St. Louis, Brownsville and Mexico Railway reached Section 14, the stop that would later become Mercedes, nicknamed \"Sweetheart of the Branch.\" The coming of the railroad would be the first step in the development of the Rio Grande Valley into a highly profitable agricultural region. (Vito Buenrostro.)\n_Two_\n\nFOUNDING A TOWN\n\nMercedes was founded in 1907 to serve as the headquarters of the American Rio Grande Land and Irrigation Company. The company was formed expressly for the purpose of constructing an irrigation system pumping water from the Rio Grande to irrigate about 250,000 acres of land in Hidalgo and Cameron Counties. The first ARGL&I building seen here was located facing Texas Avenue near the corner with Second Street. (MSTH.)\n\nBenjamin Franklin Yoakum was born in Tehuacana, Texas, in 1859. He worked all his life in the railroad industry and knew every facet from surveying to engineering, construction, traffic, operating, and finance. Yoakum visited the Rio Grande Valley on various occasions and knew that by extending the railroad into the valley, commercialized agriculture was possible. With the help of Col. Sam Fordyce, he convinced a group of St. Louis investors to develop the American Rio Grande Land and Irrigation Company with a capital stock of $1,250,000. Early stockholders included Benjamin F. Yoakum, Sam Fordyce, Thomas W. Carter, Thomas H. West, Edward Whittaker, Edmund E. Elliot, Silas P. Silver, and DuVal West. The company was granted incorporation by the State of Texas on September 30, 1905. Although Yoakum never lived in Mercedes, he and his New York socialite daughter Bessie Yoakum frequently visited the town to see friends. (MSTH.)\n\nYoakum knew that three things would be needed to make commercialized agriculture succeed in the Rio Grande Valley: an extensive irrigation system to water the farmlands, a railroad system to take the produce to northern markets, and a cheap labor force to clear the land, dig the canals, and work the fields once they were planted. Clearing the land, called \"grubbing,\" was achieved by a large Mexican labor force that worked for pennies a day. (MSTH.)\n\nCol. Sam Robertson was the contractor for the earthwork on the Main North Canal built by the American Rio Grande Land and Irrigation Company. As seen in this photograph, he used 300 mule teams to dig a strip of land seven miles long from the river to the railroad in Mercedes to lay the Main Canal in 1906. (MSTH.)\n\nThe first order of business in developing Mercedes and the surrounding mid-Valley area was to build a pumping plant on the Rio Grande. This was achieved in 1906 when the pumping plant was completed about eight miles south of Mercedes. A settling basin was also built west of the plant, with the Main Canal to carry water north by means of gravity; that is, utilizing the natural slope of the land to propel the water along the canals. The water must first be lifted out of the Rio Grande by the pumping plant. The pumping plant had a capacity of 300,000 gallons of water per minute, or 432,000,000 gallons every 24 hours. By 1923, the canal system totaled over 300 miles of canals, not including the smaller laterals serving individual farm tracts. (MSTH.)\n\nWilliam Francis Shaw served as chief engineer and vice president of the American Rio Grande Land and Irrigation Company in 1908. He also served the company as general manager from 1912 to 1930. He was the contact man for the American Company in setting up the canal system in the Mercedes area, and he assisted in laying out the town site of Mercedes and in organizing the electricity and water systems. ( _Mercedes Enterprise_.)\n\nThe river pumping plant had four pumps, two of which were 36 inches in size and were the largest pumps in the world at that time. Electrical power to run the pumps was run down from the electrical plant built in Mercedes. This 1915 photograph with unidentified persons shows some of the intricate machinery required to do the job. (MSTH.)\n\nThe American Company decided to name their headquarters \"D\u00edaz\" in honor of Mexican president Porfirio D\u00edaz, seen here, who was friendly toward American investors. Fearing the development of a revolt in Mexico and the inadvisability of that name, \"Mercedes\" was then chosen, supposedly to honor D\u00edaz's wife; but D\u00edaz was married first to Delfina Ortega and later to Carmen Romero. The origin of the name remains a mystery today. (National Archives.)\n\nIn this c. 1912 postcard, the photograph was taken facing west from the top of the Mercedes power plant next to the Main Canal. The Mercedes Hotel can partially be seen in the middle background. To the right of the hotel across Second Street can be seen the American Rio Grande Land and Irrigation headquarters, the Mercedes Drug Store, and the Hotel Annex. (Vito Buenrostro.)\n\nIn December 1907, the original townsite of Mercedes was platted by American Company chief engineer Chester B. Davis. Streets were named and the map recorded in the Hidalgo County Courthouse. The large sign in this photograph encourages visitors to purchase land and homes in this growing community. (MSTH.)\n\nOne of the first buildings in the new town was the Mercedes Hotel. When the engineers, railroad men, and other professionals came to Mercedes to work, there were no homes available yet. Many lived in boxcars on sidings when they first arrived, and they were greatly relieved when the hotel was completed. The hotel served very well until suitable homes could be built. (Vito Buenrostro.)\n\nSilas Percy Silver served as the general manager of the American Rio Grande Land and Irrigation Company in 1905 and was instrumental in completing the irrigation system. He also ensured that land was sold, businesses were started, and city and school services were properly provided in Mercedes' early days. Under his direction, the American Company also donated land to churches and for cemeteries. Silver was born on November 3, 1866, in Mobile, Alabama. He was a graduate of Washington University with a degree in architecture. Examples of Silver's architectural talent are still evident in many of the buildings in Mercedes. Silver was the Hidalgo County judge when county residents voted to move the county seat from Hidalgo to Chapin (now Edinburg) in 1908. He served one term, from 1908 to 1909. Silas Percy Silver died on December 20, 1938, in Shreveport, Louisiana. (MSTH.)\n\nWhen Silas P. Silver, his wife, and young daughter arrived in the fledgling town of Mercedes in 1905, they were forced to live in a boxcar on a railroad siding because there were no homes built yet. Within a year, the American Company, as it was frequently called, had built the Silver family a company home, which is the house pictured on the right of the photograph. By 1908, Silver built his own home, the house on the left. The Silver house is still standing, located on South Missouri Avenue on the corner of Third Street. These homes both adhered to the restrictions placed by the city on new residences. The city ordinance required homes to be built of brick or stucco and not cost less than $2,000, which was a considerable amount in those days. Business buildings must be of brick or stucco and not cost less than $3,000. The early founders hoped to make the Mercedes downtown area a showplace that would attract new homeowners, farmers, and businessmen. (MSTH.)\n\nIn this photograph, Silas Percy Silver rides his horse into a flume built as part of the canal system. One of the engineering advancements of this time was the use of reinforced concrete in the construction of the head gates, siphons, and flumes. The introduction in 1906 of this man-made \"rock\" by the American Company was new to Texas. (MSTH.)\n\nIn the early days, there were no city services such as trash pickup or street repair, so a city ordinance was passed that required all male persons between 21 and 45 to work on, repair, and clean the public roads and streets. Ministers and firemen were exempt; however, just $2.50 would exempt any citizen for a year. (MSTH.)\n\nSome of the irrigation system construction was contracted out to Col. Sam Robertson until the crews of the American Company took over, extending the canals to Mile 12 North and Mile 2 1\/2 West by 1912. This photograph shows the Main Canal, which runs just east of Mercedes. It was from 90 to 120 feet wide in places and from 15 to 20 feet deep. (MSTH.)\n\nIn this 1910 scene on a postcard, cars are parked at a slant down the center of Texas Avenue, the main street. City records show that uniform traffic laws were not adopted until 1930 and officers did not start handing out traffic tickets until 1939. Parking meters were installed in 1946, undoubtedly much to the dismay of downtown shoppers. (Vito Buenrostro.)\n\nPostcards were very popular as a means of communicating with friends and family during the early 20th century. This is the cover of a used postcard that unfolded accordion-style to show many scenes of Mercedes around 1909. The stamp was cut off, but the postmark can still be partially seen. (Vito Buenrostro.)\n\nWithin a few years of its founding, Mercedes was already producing large quantities of vegetables and fruits for shipping to northern and international markets. The Bermuda onion had already been introduced to south Texas in 1898 near Cotulla. With irrigation, onion farms like Theodore M. Plummer's (seen here) were highly successful, yielding about 3,000 crates per acre during a growing season. (Vito Buenrostro.)\n\nThe gentlemen in this photograph are Mercedes's first mayor and city council after incorporation in 1909. From left to right are John Puckett, Gouverneur K. Wattson, Mayor William Lingenbrink, Dr. Edward C. Schoonmaker, Fred Cutting, and Lytle Harrison. They are sitting at the City Park, a popular gathering area because of its lush grass and palm trees. (Vito Buenrostro.)\n\nThe Mercedes Railroad Depot was built to accommodate the thousands of visitors that came to the Valley, but the railroad was also important for the transport of produce to northern markets, and many packing sheds located just north of the railway lines. In the early years, it was popular to take day trips on the train to Brownsville for shopping and socializing purposes. (MSTH.)\n\nIn this panel of an accordion postcard, the Mercedes Commercial Club, forerunner of the Mercedes Chamber of Commerce, listed all of the amenities to be had in the new city. Mercedes had grown very quickly by 1909 with more than 1,000 inhabitants, but the American Company still had many farm tracts to sell and hoped to attract buyers from the northern and Midwestern states. The use of postcards was one of the marketing strategies, since the new citizens of Mercedes were sure to send them to friends and family where they would be seen by potential investors. The scene below shows the train depot in the background with the \"beautiful tropical park,\" as described above, shown in the foreground of the photograph. (Vito Buenrostro.)\n\nMost of the vegetables and fruits produced in the Valley faced a long train trip to northern and sometimes international markets. This required the produce to be iced down for shipping. Icehouses such as this one were common sights near the packing sheds and railroad tracks. With the advent of mechanically refrigerated boxcars in the late 1940s, icehouses became largely obsolete. (MSTH.)\n\nThe first business owners in the new town of Mercedes were John D. White, general foreman of all laborers and construction work; Fred Cutting and Charles Campbell, who built the first lumber yard, the Mercedes Lumber Company as seen here; and Alex Champion, who built the first general merchandise store. The first blacksmiths were Ben Brooks Jr. and Pablo L\u00f3pez. (Vito Buenrostro.)\n\nAs shown in this postcard, on June 22, 1910, the first bale of cotton in the United States for the season was ginned in Mercedes. Cotton was sometimes planted between rows of cabbage or corn that was harvested first while the cotton grew to maturity. This gave the cotton a head start at being ginned first in the nation. (Vito Buenrostro.)\n\nThe _Mercedes Enterprise_ is the local newspaper whose origins go back to 1908 when Isadore Moritz, previously of the _Brownsville Herald_ , decided to start up a periodical in the fledgling town. The _Enterprise_ is still being published today with its original name. In this issue, the big story was the ginning of the nation's first bale of cotton for the 1910 season in Mercedes. ( _Mercedes Enterprise_.)\n\nIn this aerial view of Mercedes looking southeastward, packing sheds are seen in the bottom left area, located alongside the railroad tracks. The Main Canal can be seen running behind the power plant, the building with the arches in front. The main roadway going from top left to bottom right is Second Street after it was designated US Highway 83. This photograph was taken around 1935. (Weslaco Museum.)\n\nIn this early scene looking north on Texas Avenue, the Empire Theater is seen on the right side of the street next to the columns of the First National Bank. The Empire changed to the Capitol after the hurricane of 1933, and later to the State Theater. Across the street on the corner is the mercantile store opened by Amador Fern\u00e1ndez of the Toluca Ranch. (MSTH.)\n\nThe Sanborn map shown here was commissioned and completed in July 1917 for the purpose of obtaining fire insurance for Mercedes buildings. It shows the contours of the early city. The darker areas were the original downtown area and more expensive residential areas. The railroad track may be seen cutting across east and west about three-quarters of the way up the map. The main irrigation canal (not marked) of the American Rio Grande Land and Irrigation Company ran north and south to the right of Capisallo Road. Generally speaking, the Anglo-Americans had their businesses and homes south of the railroad tracks with the exception of the packing sheds which were just north of the railroad track; and the Mexican American community was located north of the railroad tracks. This type of separation occurred in every town of the lower Rio Grande Valley of this era, with exceptions sometimes made when the Mexican American family or business owner was well-to-do. (City of Mercedes.)\n\nIn the above 1922 photograph of the Mercedes downtown area, the cars are parked at a slant and next to the sidewalks rather than in the middle of the street. This is Texas Avenue looking north. The two-story building on the right with light-colored brick is the second building used by the Hidalgo County Bank and Trust. It was located on the northeast corner of Texas Avenue and Third Street. In 1928, the bank built a new brick three-story building across the street on the southwest corner of Texas and Third Streets as seen in the photograph below. This edifice still exists today although it has been remodeled to face a new parking lot south of the building. (Above, MSTH; below, _Mercedes Enterprise_.)\n\nThis small frame building, which faced Third Street downtown, was first used by the Hidalgo County Bank and Trust Company in 1907. When the new brick building on South Texas Avenue was built later that same year, the frame building was used as a primary classroom with Miss Boyd as teacher. ( _Mercedes Enterprise_.)\n\nAfter holding classes in several buildings in town, a more permanent structure was finally completed facing Texas Avenue. This school, built in 1912, housed students from primary grades to high school grades. It was named for Harriet Claycomb Buck who was the mother of Nannie Mer Buck, the Mercedes superintendent of schools from 1915 to 1923. The building was demolished after irreparable damage in the hurricane of 1933. (Mercedes ISD.)\n\nElizabeth Riess (left), Gustavus K. Riess, and their two children Marion and Malcolm relocated to Mercedes from the northeast in 1910. Both \"Gus\" and \"Lizzie\" were active in their community, serving on the school board and city council from 1912 to 1914. Gus was a railroad station agent, and Lizzie is reputed to have developed the first pink grapefruit in the Rio Grande Valley. (Riess family.)\n\nAlthough schoolchildren in Mercedes had been attending school in makeshift classrooms beginning in 1907, the first student to complete her studies and graduate from the Mercedes school district in 1914 was Marion Riess, daughter of Gus and Lizzie Riess. She later became a teacher and principal in Mercedes. She married Rev. Herbert Haslam of Philadelphia, had five children, and helped with her husband's ministry while also continuing to teach. (Mercedes ISD.)\n\nIn 1914, only one person graduated from high school\u2014Marion Riess. The next year, Mercedes High School graduated four students\u2014Pearl Hearing, Nellie Linemann, Martha Wright, and Albert Rothrock. The program shown here describes the graduation ceremonies held on May 21, 1915, at the Moving Picture Theater. The program included poetry recitations, songs, several speeches, piano pieces, presentation of the diplomas, and a short play with the graduates participating. This play was the forerunner of the \"Senior Play\" tradition at Mercedes High School, although the play is no longer presented during the graduation ceremonies because of time constraints. On May 18, 1915, the junior class had honored the senior class with a banquet given at the Mercedes Hotel. On the menu were fruit cocktail, fried chicken, cream gravy, hot biscuits, currant jelly, mashed potatoes, string beans, pears, olives, and the new sensation from New York City: Waldorf salad. (Mercedes ISD.)\n\nSouth School, later renamed for Leon R. Graham, the superintendent of schools from 1941 to 1951, was built in 1921 facing Ohio Avenue between Ninth and Tenth Streets. Since its construction and through various remodeling projects and additions, Graham School served as a primary school, a junior high, a high school, and a migrant school. (Mercedes ISD.)\n\nNorth School, later renamed John F. Kennedy Elementary School, was built in 1910 but underwent numerous remodeling projects. School board minutes first called it the \"Mexican\" school, and later the \"Preparatory\" school. It served only Mexican American children from the north side of town until 1971 when the district desegregated and went to \"single-line\" (one or two grades) campuses rather than multi-grade neighborhood schools. (Mercedes ISD.)\n\nIn 1909, the first Presbyterian congregation of 19 members was organized by Rev. William W. Doggett. The church seen in this photograph was built in 1912, located on the corner of Fourth Street and Missouri Avenue with the Rev. Samuel M. Glasgow as the first resident pastor. (Vito Buenrostro.)\n\nThis photograph shows the first building of the First United Methodist Church built in 1936. It was later used for the Spanish-speaking congregation with the name El Buen Pastor Iglesia Metodista, or the Good Shepherd Methodist Church. A new structure was built on Sixteenth Street in the 1960s. (Vito Buenrostro.)\n\nRaquel Gonzales Palacios stands in the center front during an Easter Pageant with other unidentified girls in the spring of 1932. They are holding palm leaves and flowers as is traditional for this religious holiday. According to family members, the steps where the girls posed are most likely those of the rectory at Our Lady of Mercy Catholic Church. (Irma Palacios.)\n\nThe First Baptist Church of Mercedes was organized in 1907 with four charter members: Mrs. Fred Cutting, Mrs. Jimmy Johnson, and Mr. and Mrs. Lewis Boothe. They were served by missionaries until the building of the present church seen in the photograph. The new complex includes an auditorium, Sunday school classrooms, kitchen, and fellowship hall; it was erected in 1920 during the pastorate of the Rev. John C. Boyd. ( _Mercedes Enterprise._ )\n\nThe Immanuel Lutheran Church, first called the German Lutheran Church, was the first Lutheran church established in the Rio Grande Valley in 1910. The first pastor, Rev. Ernest J. Moebus stands on the steps in this early photograph. Using the Mercedes church as his headquarters, Rev. Moebus founded many preaching stations in the Valley. Most of the town's population of German heritage attended this church in the early days. (Library of Congress.)\n\nThe Immanuel Lutheran Church was moved to its present location at South Washington Avenue and Third Street where this brick structure was completed in 1929. Later additions included a parochial school, meeting rooms and a kitchen. Well known in the community is the excellent school that, although it has had to close on past occasions, is fully operating again. ( _Mercedes Enterprise_.)\n\nPictured here is a Baptist mission group in 1916 in a temporary building on North Missouri Avenue with Howell and Zepeda family members among others. This group would meet in the Mercedes Community Building at first but later built the Primera Iglesia Bautista Mexicana, or First Mexican Baptist Church. (Eddie Howell Sr.)\n\nThe Primera Iglesia Bautista Mexicana shown here was built around 1918, with Joseph Henry Howell as the first missionary preacher. Howell's father, William Albert Howell, had been a Union soldier captured by the Confederacy who escaped to Mexico and later wound up in Port Isabel. He opened a dry goods store there and raised a family, with Joseph Henry eventually relocating to Mercedes. (Carolyn C. L\u00f3pez.)\n\nThe first frame building of Our Lady of Mercy Catholic Church was erected on the north side of Hidalgo Street in 1909 on land donated by the American Rio Grande Land and Irrigation Company. The new church was built in its present location on Vermont Avenue and Third Street as seen here, and it was formally dedicated on October 22, 1922. (Our Lady of Mercy Church.)\n\nPictured here on horseback is Fr. Adrian Bornes of the Oblates of Mary Immaculate. He and Fr. Paul Hally were the first resident priests assigned permanently to Our Lady of Mercy Church at Mercedes in 1909. They served not only Mercedes but the surrounding missions as well, traveling to them on horseback. (Our Lady of Mercy Church.)\n\nThe first baptisms were performed and recorded in this registry at Our Lady of Mercy Catholic Church in February 1909. The children baptized were Jos\u00e9 M\u00e9ndez, Pedro Gregorio Garc\u00eda, and Eugene Harold Thomas. All three were born in late 1908 but had to wait for the priest to arrive early the next year in order to be baptized. The first two entries are written in Spanish and the third is written in English, undoubtedly to conform to the identities and ethnicities of the parents. The entries contain the date of baptism, the date of birth for the child, the condition of legitimacy, the parents' names, the \"padrinos\" or sponsors' names, and the priest's signature, Fr. Adrian Bornes, OMI. Baptismal records such as these are very important resources not only for genealogists or those who wish to trace their ancestry but also for historians. In many baptismal registries, if the family was an important one, the grandparents' names would also be included. (Our Lady of Mercy Church.)\n\nThis was the first Mercedes Telephone Directory issued in November 1909. It was reprinted in the 25th anniversary issue of the _Mercedes News-Tribune_ on September 16, 1932. After only two years of founding, Mercedes had more than 1,000 inhabitants and more than 30 businesses that included two hotels, several drugstores, dry goods and general merchandise stores, a newspaper office, hardware and lumber companies, pharmacies, churches, hospitals, and doctors. Notice in the listings that the town still accommodated those who used horses, buggies, and wagons with a livery stable. In 1909, the streets in Mercedes were not yet paved, but business was brisk and the downtown area was very active. At that time, Mercedes was considered the \"Queen City\" because it was the premier mid-Valley town and the fastest growing settlement in Hidalgo County. ( _Mercedes Enterprise_.)\n\nMercedes had become very prosperous very quickly. The Mercedes Commercial Club had succeeded in attracting a large number of \"newcomers\" to the town through its aggressive marketing strategies. The town was well-tended and progressive, with important Valley-wide meetings sponsored by the American Rio Grande Land and Irrigation Company often held at the Mercedes Hotel pictured here. (MSTH.)\n\nCato Palacios goes for a ride in the 1932 Chevrolet two-door coupe owned by his father, Abraham Palacios. By 1915, Mercedes had streets paved with caliche (or gravel) and had added streetlights to the downtown area. In 1933, Second Street was widened to asphalt-paved two lanes with shoulders, and it became US Highway 83. (Irma Palacios.)\n\nThe Baker, Montgomery, and Closner families enjoy a picnic at Lake Campacu\u00e1s c. 1915. The lake, also known as Tampacu\u00e1s or Carter's Lake, is about two miles north of Mercedes. It is part of the delta system of _resacas_ and arroyos that once were channels of the Rio Grande. It is about two miles long and is 700 feet wide at its broadest point. (MSTH.)\n\nPictured here in 1920 is Juli\u00e1n Villarreal (standing) with his daughter Adela. Juli\u00e1n and his bride, Dolores, arrived in Mercedes in 1912 and established a small grocery store at 117 North Texas Avenue. He also operated a bakery and often served as a foreman for agricultural work crews. Adela, now Mrs. Ram\u00edrez, says they took the picture while waiting for a train to Brownsville, where she was to see a doctor for an ear infection. ( _Mercedes Enterprise_.)\n\nThese gentlemen belonging to the Mercedes Mexican American Chamber of Commerce posed for a group picture in 1926. Mexican American businessmen in Mercedes organized early compared to other Valley cities in order to mutually support their business efforts. In the early years, most Mexican American businesses were located north of the railroad tracks because of residential segregation. ( _Mercedes Enterprise_.)\n\nPictured here is Alma Whatley's fifth-grade class at North Ward School in 1935. The front row includes, from left to right, Whatley, Andrea Barrera, Guadalupe Galv\u00e1n, Cuitl\u00e1huac Garc\u00eda, Guadalupe Casta\u00f1eda, unidentified, Juventino de Le\u00f3n Jr., Juan Torres, and Adelita Marroqu\u00edn. In the back rows are unidentified students. Whatley later taught English classes for many years at the Mercedes High School. (Delia de Le\u00f3n.)\n\nWord of the bonanza, or \"abundance of work,\" in the newly formed town of Mercedes reached the ears of workers on existing ranches as well as Mexican nationals. Many came seeking work, and they were readily hired to clear the land, work on the new farms, construct businesses and residences, and do general labor. (MSTH.)\n\nSome labor families were able to move into town where their housing was better. For those who lived in town, there was ample work at canning factories, produce sheds, and downtown stores and businesses. This home at 106 North Ohio Avenue, built around 1918, belonged to Calixta Ruelas Ortega, who willed it to her brother Severo Ruelas and family in 1936. (Carolyn C. L\u00f3pez.)\n\nMany labor families lived in small huts, or _jacales_ , made of available mesquite wood or old boards with thatched roofs. Water was available from wells or had to be purchased from water sellers. Winters were especially difficult because of the cold and wet. Many of these jacales did not survive the hurricane of 1933. (National Archives.)\n\nJos\u00e9 Garc\u00eda was a schoolteacher in Mexico who fled with his family in 1910 to the United States when the Mexican Revolution brought great disorder in Mexico. Together with several brothers, they opened multiple businesses in Mercedes including a drugstore, a clothing store, and many grocery stores. (Garc\u00eda family.)\n\nThe Garc\u00eda family opened this store, A.G. Garc\u00eda and Brothers Confectionery, on the corner of Hidalgo Street and Texas Avenue in 1920. The original store was started in 1913 and had customers from as far away as Brownsville and Rio Grande City. This store later burned down and was not rebuilt. (Garc\u00eda family.)\n\nA drugstore and fountain was run in one corner of the Garc\u00eda store. Pictured from left to right are Jos\u00e9 T. Leal, Octavio Garc\u00eda, Leopoldo Sol\u00eds, Elizandro Pe\u00f1a, Od\u00f3n G. Garc\u00eda (seated), and an unidentified patron standing to the back. (Garc\u00eda family.)\n\nWhen the American Rio Grande Land and Irrigation Company was scouting a location for its pumping plant in 1906, it wished to avoid the possibility of the river suddenly changing course. Without seeking permission, the company dug a channel at the Horc\u00f3n Tract site to divert the river flow, illegally changing an international boundary. The company paid a fine and the channel stayed. (Hidalgo County Historical Commission.)\n\nA bridge was built to connect the small town of R\u00edo Rico on the Mexican side in the Horc\u00f3n Tract site to Thayer on the American side. Both sides of the river had custom houses, and the bridge allowed both Mexicans and Americans to buy products available only in the other's country. (Hidalgo County Historical Commission.)\n\nMany visiting land parties and excursion groups were taken to Rio Rico for entertainment. In this photograph, an excursion group is watching a cockfight, and undoubtedly laying wagers on the outcome. In addition to cockfights, northerners could attend dog races and bullfights and could dine and dance. During Prohibition, R\u00edo Rico was a popular destination for many Valley residents. (Hidalgo County Historical Commission.)\n\nThe Rio Grande flooded regularly before Falcon Dam was built upriver in 1954. This photograph shows the Thayer\u2013R\u00edo Rico Bridge in 1941 when a severe flood caused great devastation in the area. Both American and Mexican businesses in R\u00edo Rico suffered great losses. (Hidalgo County Historical Commission.)\n\nThe 1941 flood caused the riverbanks to erode and the R\u00edo Rico Bridge to collapse completely. Previous floods had curtailed tourism in R\u00edo Rico, but the collapse of the bridge ended almost all river crossings. Only those willing to cross over on small boats provided any commerce to R\u00edo Rico businesses. (Hidalgo County Historical Commission.)\n\nWilliam \"Andy\" Tullis (left) and immigration officer White stand in front of the customs booth at the R\u00edo Rico Bridge in 1932. Tullis was manager of the B&P Bridge Company and oversaw operations there for many years. When the R\u00edo Rico Bridge collapsed in 1941, a new site was selected two miles upriver. The B&P completed the Nuevo Progreso Bridge in 1952. (Hidalgo County Historical Commission.)\n\nJudge Silas P. Silver, general manager of the American Rio Grande Land and Irrigation Company, rides as a passenger while driven by his chauffer in a Packard Touring car in this c. 1930 image. In his later years, Silver suffered a stroke and was partially disabled, but he remained active in city and county politics for many years. (MSTH.)\n\nSilas P. Silver's grandson Albert Stephens, seen here wearing short pants, was the son of Silver's only daughter, Mary Ellen, who married Charles Stephens of Louisiana. Here, Albert is shown on a trip to Silver's hometown of St. Louis, Missouri, in the 1920s. The boy on the horse is unidentified. (MSTH.)\n_Three_\n\nBUILDING THE COMMUNITY\n\nOn September 15, 1932, Mercedes celebrated its 25th anniversary with a variety of events including the parade shown in this photograph. All the Valley towns were invited to the celebration. The highlight of the first day was the Cavalcade of the Lower Rio Grande Valley, an elaborate pageant with more than 400 characters depicting the history of the area from 1519 to 1932. (MSTH.)\n\nThis 1932 photograph shows one of the more popular floats on which the Silver Queen of the 25th anniversary celebrations, Ida Greene Wattson, rides with her court. Elaborate costumes in white, gold, and silver were worn by all. Also included in the day's celebration were an art exhibit, a banquet, the Cavalcade performance, and a Founders' Day Ball at the Elks' new hall. (MSTH.)\n\nThe Founders' Day Ball was held in the Elks Lodge the night of September 15, 1932. Many Valley towns were represented in the queen's court by the duchesses. Participating towns included Alamo, Brownsville, Edinburg, Harlingen, La Feria, McAllen, Mission, San Benito, San Juan, and Weslaco. The Elks Lodge building still exists today but is now known as the second Mercedes Hotel. (MSTH.)\n\nIda Greene Wattson was crowned \"Silver Queen\" by Mercedes mayor William D. Chadick during the presentation ceremonies at the Founders' Day Ball. Chadick was the nephew of entrepreneur Col. Sam Fordyce and was involved in city and Hidalgo County politics. He was elected mayor of Mercedes in 1932. (MSTH.)\n\nThese gentlemen participated in the celebration of Mercedes's 25th Anniversary on September 16, 1932, with some dressed in their Mexican Independence Day costumes. Pictured from left to right are Jos\u00e9 T. Leal, Alfredo Garc\u00eda, David S\u00e1enz, Candelario Mar\u00edn, Rafael Hinojosa, Rogelio Hinojosa, and Jes\u00fas Garc\u00eda. ( _Mercedes Enterprise_.)\n\nThe Mercedes General Hospital seen here was organized in 1922. It was first located on Ohio Avenue and Sixth Street but was later moved to South Texas Avenue. It was originally set up by doctors Charles B. Buck, John G. Webb, and Daniel L. Heidrick, who bought the instruments and equipment from the Malone Brothers Hospital. (Carolyn C. L\u00f3pez.)\n\nDr. Manuel de la Torre's office and clinic faced North Texas Avenue in 1963. Early hospitals in Mercedes included an army hospital at Llano Grande and one at Camp Mercedes; the Malone Brothers Hospital, set up by the mid-1920s at 430 South Texas Avenue; the Mercedes General Hospital; the Lawler Clinic; and the Caballero Clinic. (Carolyn C. L\u00f3pez.)\n\nDr. Gonzalo Caballero's home was on the corner of Third Street and Missouri Avenue, and his clinic was just across the street. The clinic used to be Dr. Robert Johnston's when he still practiced. Today, the Caballero Clinic is still run by Gonzalo's son Dr. Eduardo Caballero. (Carolyn C. L\u00f3pez.)\n\nDr. Daniel L. Heidrick came to Mercedes with the 16th Cavalry when he was the Army camp doctor. When he was discharged from military service he returned to Mercedes to practice. Many said he must have delivered at least half the babies in Mercedes, and he is remembered for never turning anybody away because they could not pay. His home and office were located at 446 South Texas Avenue. ( _Mercedes Enterprise_.)\n\nThe Copacaba\u00f1a was a popular night spot in Mercedes beginning right after World War II. It was established by the S\u00e1enz brothers and their brother-in-law Ciro L. Uribe. It had a restaurant, a banquet room, and a terrace on the second floor for dances and parties. It was also later used for vocational training for returning GIs and later served as a migrant worker recruitment center. (Carolyn C. L\u00f3pez.)\n\nLocal newspaper the _Mercedes Enterprise_ is still located in the old Rex Theater building on Texas Avenue in downtown Mercedes. When first established, it also took care of other printing needs for the community such as billboards, posters, flyers, brochures, and pamphlets. It has previously also had the names _Mercedes Tribune_ , _Mercedes News-Item_ , _Mercedes News_ , and _News-Tribune_. (Carolyn C. L\u00f3pez.)\n\nThe De Le\u00f3n Swing Band entertained many Mercedes residents in the 1930s and 1940s with popular American and Mexican dance music. Pictured from left to right are two unidentified musicians, Felipe \"Pipe\" Oliv\u00e1rez, Jos\u00e9 Serna, Octavio Garc\u00eda, Concepci\u00f3n \"Chon\" Garc\u00eda, and band leader Juventino \"El Maestro\" de Le\u00f3n Sr. (Delia de Le\u00f3n.)\n\nThe Mercedes Pool Hall was owned by Florencio P\u00e9rez Sr., who established the business on North Texas Avenue and First Street in 1940. Later also known as the Latin American Club, it was frequented by patrons from all over the Valley. By 1948, P\u00e9rez had expanded the business to hold 14 pool tables and was also selling billiard supplies to other pool halls. (Carolyn C. L\u00f3pez.)\n\nLloyd P. Nolen acquired a P-40 Warhawk like the one shown above in 1951. The P-51 Mustang like the one shown below flew during World War II and was the second purchase by Lloyd P. Nolen and other partners in 1957 to found the Confederate Air Force, later renamed the Commemorative Air Force, flying out of the Central Valley Airport in Mercedes. The group continued to purchase, repair, and fly vintage World War II airplanes as a means of preserving aircraft that would otherwise have wound up as scrap metal. The central CAF headquarters moved to Harlingen in 1968, and later to Midland, Texas, in 1990. The Rio Grande Valley Wing of the CAF relocated to Brownsville, Texas, where they still have air shows. (Both, National Archives.)\n\nPictured here at an event of the Confederate Air Force are, from left to right, ? Edwards, Cedric Wood, and Lloyd P. Nolen. Nolen was a World War II flight instructor who ran the Mercedes Dusting Service in the 1950s at the Central Valley Airport. All members of the CAF were called \"Colonel\" as an honorary title. (Weslaco Museum.)\n\nThe Central Valley Airport is located on Mile 2 East, or Farm to Market Road 1425, and Mile 8 North. It is home base for crop-dusting planes since 1946. The airport was called Old Rebel Field when the Confederate Air Force began using it for air shows in the 1960s. (Vito Buenrostro.)\n\nPictured here is the Hidalgo and Cameron County Irrigation District No. 9 office building at 301 East Second Street (US Business Highway 83). This building was the second office of the American Rio Grande Land and Irrigation Company until 1927 when a group of farmers petitioned for the establishment of a regulatory group for water control and distribution, forming what became District No. 9. (Carolyn C. L\u00f3pez.)\n\nWorkers at the Hidalgo and Cameron County Irrigation District No. 9 posed for this impromptu photograph taken in the 1940s. Third from left is Cato Palacios, and last on the right is his brother Juan Palacios. All others are unidentified. In 2009, District No. 9 relocated its offices to 2304 North Farm to Market Road 491. (Irma Palacios.)\n\nIn the early 1900s, several Hidalgo and Cameron County families founded a small Jewish congregation. Lay readers led the services and the congregation met in private homes or rented space. In 1935, Temple Beth Israel pictured here was erected on the southwest corner of Tenth Street and Texas Avenue. In 1948, the congregation voted to dissolve and began attending synagogues in Harlingen or McAllen. (Hidalgo Country Historical Commission.)\n\nPictured in 1964 at the counter of the Farris Paint Store are, from left to right, storeowner E. Quincy Farris, his son James Farris, and friend Rosa Mae Wheeler. Farris owned several businesses including the Farris Lumber Company. He served as president of the Valley Lumbermen's Association in the 1950s and was well known in the community. (Mercedes ISD.)\n\nCharles P. Melton owned the Superior Citrus Fruits Packing Shed in Mercedes, shown above in 1946, to process the fruit from his R\u00edo Banco Farms. It was but one of many citrus packing sheds in Mercedes that organized through the Texas Citrus Growers Association. By 1929, this new fast-growing citrus industry was cultivated on more than 100,000 acres in Hidalgo County. (Carolyn C. L\u00f3pez.)\n\nMercedes has always been heavily involved in the citrus industry. Here, workers begin the sorting process of grapefruit at this packing shed. Grapefruit dominates the Texas citrus industry, with most of the remainder being oranges. The South Texas region is home to all Texas citrus production. Hidalgo County contains 85 percent of all citrus acres in Texas, with the remainder in Cameron and Willacy Counties. (National Archives.)\n\nIn this photograph, grapefruit is further separated for shipping whole or using it for juice processing. The earliest record of citrus in the Rio Grande Valley was seedling orange trees planted in 1882 by the Vela family at the Laguna Seca Ranch. Col. William A. Fitch was the first grower in Mercedes to plant oranges and grapefruit. The first commercial shipments from Mercedes began in 1918. (National Archives.)\n\nIn this juicing plant, cans are prepared to be filled with grapefruit juice. During the 1930s, whole-fruit markets slowed and juice became the most profitable commodity to sell. The Texsun canning plant in neighboring Weslaco was often used by Mercedes growers to process their oranges and grapefruit. (National Archives.)\n\nShown here is a Mercedes High School diploma from 1935 given to graduate William \"Billy\" Taylor. It is signed by Robert H. Kern, president of the school board; Fred Johnston, school board secretary; Ernest H. Poteet, superintendent of schools; and Leon R. Graham, principal of the Mercedes high school. The format shown here has changed little over the years. In 1935, the number of credits required to graduate from high school was 18. By 1968, the number of credits required had increased to 24. The number of years of schooling it took to graduate also changed. Up until 1941, only 11 years of school were required; from 1942 on, 12 years of schooling were required for graduation. (Mercedes ISD.)\n\nR. Newell Waters was the architect for the redbrick Mercedes High School that was completed and occupied in 1932 on the west side of Ohio Avenue and Eighth Street. It continued to be used as the high school until 1967, when a new high school was built east of the Main Canal at 1200 South Florida Avenue. (Mercedes ISD.)\n\nThe photograph here shows the building used as the high school gymnasium from 1940 to 1967. It was built together with the cafeteria in a Spanish revival style and was located at the same complex where the high school and junior high were on South Ohio Avenue. (Mercedes ISD.)\n\nShown here posing in front of the Mercedes High School on the right and the Mercedes Junior High School on the left is the 1936 Mercedes High School Pep Squad. The Pep Squad was formed to assist cheerleaders in generating enthusiasm from the fans at sports events, particularly football games. (Vito Buenrostro.)\n\nLeon R. Graham was superintendent of Mercedes schools from 1941 to 1951, having served as a teacher and a principal at various Mercedes schools before this post. After leaving the Mercedes school district, he worked at the Texas Education Agency in Austin eventually attaining the title of associate commissioner of education. (Mercedes ISD.)\n\nPosing here is the 1945 Mercedes Tiger Football Team: from left to right are (first row) Noel Caldeira, Angel Gonz\u00e1lez, Louis E. Drawe, James B. Taylor, and Anthony Caldeira; (second row) Ismael Gonz\u00e1lez, Bob Steer, Charles Eldridge, Kenneth Clarke, and Rudy Garza; (third row) coach Henry D. Crawford, Ernest Newmann, Senobio Uresti, Luis Garibay, Roy T. Pinkerton, Elmo Wade, Derald Hentrich, and Robert Crenshaw. (Mercedes ISD.)\n\nKathleen Twenhafel (left) and her sister Helen Twenhafel pose in 1937 in their orange and black Mercedes high school band uniforms, worn that year for the first time. Their father, Albert F. Twenhafel, came to Mercedes from Illinois in 1914 with a land party and purchased 52 acres on which he raised vegetables, citrus, cotton and corn. Helen married Herbert Vogel and is still active in Mercedes where the family continues the farming and ranching tradition. (Helen Vogel.)\n\nAlicia Garc\u00eda is shown here in 1951 winning the title of \"Fiestas Patrias Queen\" at an annual event sponsored by Our Lady of Mercy Catholic Church celebrating Mexican Independence Day. The daughter of Jes\u00fas and Enriqueta Salinas Garc\u00eda, she was crowned on September 16, 1951, by Lauro Izaguirre, the Mexican Consul based in McAllen, at the Mercedes High School Auditorium on Ohio Avenue. Tragically, Garc\u00eda was diagnosed with leukemia just weeks after the celebration, and by December of that year she had died, leaving her family and friends stunned by her loss. This photograph appeared in the 1952 Bengal yearbook, which was dedicated to her memory by the Mercedes High School students and staff. (Mercedes ISD.)\n\nThe all-female members of the Zeta Eta Sigma organization of the Mercedes High School pose here in this 1949 photograph in the Bengal yearbook. The club honors girls who are scholastically outstanding. Members must have made the honor roll to qualify for the organization. (Mercedes ISD.)\n\nMercedes High School 1962 freshman class officers stop to pose for a photograph as they prepare to decorate the football stadium on a Friday afternoon for a game later that night. From left to right are Stella Marroqu\u00edn, Lillian Billings, Vito Buenrostro, Cynthia Hoverson, and Joan Wilt. (Mercedes ISD.)\n\nFrederick L. Johnston was involved in Mercedes education all his life. By the age of 15 he was already teaching children at a ranch school. In 1908, he and Agapita Tijerina were the first teachers at North School. That year, they taught English to 189 Mexican American students in a two-room frame schoolhouse. Johnston also served many years as secretary to the Mercedes ISD School Board. (Mercedes ISD.)\n\nThe 1954 Mercedes Independent School District Board of Trustees is pictured here. Seated from left to right are Helen M. Watson, Dr. Thomas G. Edwards, Joe Winston, superintendent of schools Lawrence W. St. Clair, and Clyde Hollon. Standing are Ernest E. Marchant, Thomas B. Ewing, Frederick L. Johnston, James McElyea, and Joaqu\u00edn Fern\u00e1ndez. (Mercedes ISD.)\n\nBilly Gene Pemelton, 1960 Mercedes graduate and outstanding athlete, participated in the 1964 Summer Olympics in Tokyo, Japan, placing in the top 10 in the men's pole vault. For the Mercedes Tigers, he won the Texas state class 2A title in the pole vault (1959\u20131960) and in the high hurdles (1960). (Mercedes ISD.)\n\nPictured at this 1954 Campo Gardenia No. 3155 Woodmen of the World (WOW) award ceremony are, from left to right, (standing) Florentino Zamora, Amalia Zamora, and Juventino de Le\u00f3n Sr.; (seated) Jos\u00e9 \"Pepe\" D\u00edaz and Severo D\u00edaz. The WOW organization was very active in Mercedes, sponsoring events for schoolchildren, fundraising for scholarships, and taking part in patriotic events such as flag presentations. (Delia de Le\u00f3n.)\n\nThe Honorable Rub\u00e9n Hinojosa graduated from Mercedes High School in 1958, having demonstrated early leadership abilities. After earning business degrees from the University of Texas at Austin, he served 20 years as president and chief financial officer of the family business H&H Foods. He was elected to Congress in 1996 and is currently serving his ninth term as representative of the 15th District of Texas. He serves on the House Committee on Education and the Workforce and the Committee on Financial Services. He serves as ranking member of the Subcommittee on Higher Education and Workforce Training as well as serving on the Subcommittee on Health Employment Labor and Pensions. By popular acclamation, he was selected in 2012 to be chairman of the Congressional Hispanic Caucus for the 113th Congress (2013\u20132015). (Rub\u00e9n Hinojosa Congressional Office.)\n\nDr. Rolando Hinojosa-Smith is a 1946 graduate of Mercedes High School. He is an award-winning novelist of the _Klail City Death Trip Series_ , which comprises 15 volumes to date and for which he has received two prestigious awards: the Premio Casa de las Am\u00e9ricas and the Premio Quinto Sol _._ After serving in the Korean conflict and then completing a doctorate in Spanish literature, he held several teaching assignments, including Chairman of Chicano Studies at Minnesota. In the early 1980s he switched academic departments to become a professor of English and Creative Writing at the University of Texas at Austin. Currently, he holds the Ellen Clayton Garwood Chair in the English department at the University of Texas at Austin. He focuses on American literature, specializing in life and literature of the Southwest. He continues to teach and travels extensively. He has visited more than 250 colleges and universities in the United States and abroad, where he reads from his books and gives classes. In March 2014, Dr. Hinojosa-Smith received the Ivan Sandrof Lifetime Achievement Award given by the National Book Critics Circle. (Debbie Winslow.)\n\nHector P. Garc\u00eda, a 1932 Mercedes graduate, became a medical doctor and served in the US Army during World War II. He later founded the American GI Forum to assist Mexican American veterans who were struggling with discrimination and being denied veterans' benefits. He was named alternate ambassador to the United Nations in 1967; was appointed to the United States Commission on Civil Rights in 1968; was awarded the Presidential Medal of Freedom, the nation's highest civilian honor, in 1984; and was named to the Order of Saint Gregory the Great by Pope John Paul II in 1990. In 1998, he was posthumously awarded the Aguila Azteca, or Aztec Eagle, Mexico's highest award for foreigners, in a ceremony in Corpus Christi, Texas. Mercedes has honored him by naming its library for him\u2014the Dr. Hector P. Garc\u00eda Memorial Library. (Hector P. Garc\u00eda family.)\n\nThis image of the Mercedes High School Class of 1932 hangs on the \"Wall of Fame\" at the newest Mercedes High School Cafeteria along with all graduates since 1914. In the upper left corner of this class is Hector P. Garc\u00eda. Only seven of the 32 graduates were Mexican American, although they were the majority population of the city at that time. (Mercedes ISD.)\n\nPosing for Bengal yearbook pictures are the 1957 Mercedes High School \"class favorites.\" From left to right are (first row) Marie Watson, Patsy O'Shea, and Nancy Archer; (second row) Joseph Fern\u00e1ndez, Bud Terry, and Rub\u00e9n Hinojosa. (Mercedes ISD.)\n\nThe R\u00edo Theater was one of three theaters in Mercedes. The other two were the Rex and the State. The State was previously the Capitol and the Empire. This 1940 photograph shows the first R\u00edo Theater before it was remodeled. Standing in front are, from left to right, Mary Guerrero, Mary Zamora, Olga Ochoa, Raul Galv\u00e1n, Carlos \"Chale\" Leal, Cato Palacios, and two unidentified young boys (at right and in back). (Irma Palacios.)\n\nThe R\u00edo Theater was remodeled in 1946 with a brand new marquee, as shown in this photograph, and a capacity of 639 seats. The Rio Theater specialized in Spanish-language movies, while the Rex showed Westerns, and the State showed first-run movies. Alberto Arteaga worked at the R\u00edo since 1935, eventually becoming the manager. (Sylvia Arteaga Calles.)\n\nThe R\u00edo Theater often had a capacity crowd such as this one gathered for opening night of the remodeled theater on May 17, 1946. The R\u00edo was located on North Texas Avenue near Hidalgo Street; the Rex was located on South Texas Avenue on the 200 block; and the State was also located on South Texas Avenue next to the First National Bank on the 300 block. (Sylvia Arteaga Calles.)\n\nThe Rio Theater did not just show movies, it also featured \"Amateur Night,\" during which local talent could perform for prizes. Pictured here in this 1955 photograph are, from left to right, announcer Mart\u00edn Rosales, Carlota Cant\u00fa (in the white dress), Olga Rodr\u00edguez (with the black skirt), and two unidentified girls. Competitors mostly sang and danced, but some did specialty acts such as juggling or gymnastic tumbling. (Sylvia Arteaga Calles.)\n\nProjectionist Emilio Ybarra Sr. (standing at left) explains how it all works to several unidentified men who are interested in movie theaters in this 1954 photograph. Ybarra worked for all of the Mercedes Theaters: the Rex, the State, the R\u00edo, and the Wes-Mer Drive-In Theater west of town. (Sylvia Arteaga Calles.)\n\nRaquel Gonzales Palacios (left) stands in as _madrina_ , or female sponsor, for Emilia Marroqu\u00edn as she makes her first communion at Our Lady of Mercy Catholic Church on May 21, 1949. _Padrinos_ and _madrinas_ agreed to assist parents with the responsibility for a child's religious upbringing in the Catholic faith. (Irma Palacios.)\n\nIn the center wearing a hat is architect Roscious Newell Waters with unidentified friends or associates. He designed many Mercedes businesses and residences, including, among many others, city hall, the Llano Grande Clubhouse, and the Mercedes High School and auditorium on Ohio Street. Waters's architectural styles changed over the years and included Spanish, Gothic, Princeton, and Early Modern designs. (Hidalgo County Historical Commission.)\n\nThe building pictured here was constructed in 1928 in a Mediterranean or Spanish style according to a design by architect Roscious Newell Waters. It was originally built as a private residence for Harold Lehman at a cost of $20,000. It later became the clubhouse for the Llano Grande Resort and Golf Club. (Vito Buenrostro.)\n\nFerguson \"Ferg\" Wood was the owner and manager of Ferg's Foodland, a popular grocery store located at 425 Second Street, also known as US Business Highway 83. Wood learned the grocery business from Robert H. Kern, working at Kern's grocery store from 1928 to 1958. In 1972, Wood retired and sold the store to Wendel Drefke. (Carolyn C. L\u00f3pez.)\n\nO'Shea Furniture was located on the northeast corner of US Business Highway 83 and Texas Avenue. The owners were Eugene and Anne O'Shea, who had relocated to Mercedes from Arkansas in the 1940s. The building was later demolished in the 1960s to make way for other businesses. (Carolyn C. L\u00f3pez.)\n\nAnother popular grocery store was Salinas Grocery, founded by brothers Luis and Pedro Salinas and Luis's son Rigoberto in 1946. In 1957, they expanded to the larger building seen here and renamed the business Salinas Food Store. Don Luis and his son Rigoberto were very involved citizens and remembered by their patrons for excellent service. (Carolyn C. L\u00f3pez.)\n\nEl Sombrero Restaurant was a well-known eating place that had many local and Valley-wide clients. It was located on US Business Highway 83 and first opened by Arturo Arredondo in the 1940s. It was later purchased by Wayne and Mary Love. Many prom attendees may recall having dined there after the junior-senior prom at their high school. (Carolyn C. L\u00f3pez.)\n\nPictured here are Marguerite (left) and Shelley H. Collier Sr. Collier was well known in banking circles and came to work at the First National Bank in 1923. An active and involved citizen in Mercedes, he stayed with the bank until 1972 when he retired. Personally as well as through the bank, Collier supported educational ventures through scholarships and gifts to students and often made charitable contributions to many organizations. (Mercedes Centennial Committee.)\n\nThe second building used by the First National Bank was designed by Austin architect Hugo Franz Kuehne and was occupied by the end of 1921. Chatting in front of the building in this 1960 photograph are, from left to right, Daniel Barrientos, Domingo Buenrostro, and Cristina C. Buenrostro with an unidentified man walking by. (Vito Buenrostro.)\n\nLion's Club members pose in Western dress in 1957. Seated from left to right are Shelly Collier Jr., Eli R\u00edos, Ad\u00e1n Longoria, and Fleet S. Lentz. Standing are Bill Basinger, Joe Adame, Dennis Clifford, Gordon Leonard, James Van Burkleo, William B. \"Dub\" Lauder, and James Kirber. ( _Mercedes Enterprise_.)\n\nThe temporary location of the First National Bank when it first opened in January 1921 was in this building. Under the direction of Pres. John Hackney, the bank moved that same year into a beautiful new brick building on South Texas Avenue. Today, the bank is on the corner of Texas Avenue and US Business Highway 83 as the Texas National Bank. ( _Mercedes Enterprise_.)\n\nThe 1940s and 1950s were some of the most prosperous years for Mercedes. Many businesses had recovered from the Depression of the 1930s, and the post\u2013World War II boom was at its highest point. In 1940, the population was 7,624, but by 1950 it had grown to 10,065. In this downtown scene of Mercedes, every building is occupied by a thriving business. (MSTH.)\n\nSisters Ida (left) and Irma \"Nellie\" Palacios dress up in their Fiestas Patrias costumes in 1954. The celebrations recognize the area's Mexican heritage and recall the independence won by Mexico from Spain in 1821. In earlier days, the city sponsored the celebrations but later the Catholic churches became sponsors of the event. (Irma Palacios.)\n\nHowell family members are pictured here in a late 1940s photograph. From left to right are (seated) Jacinto Howell, Joseph Henry Howell Sr., Pauline Howell Gorena, Mar\u00eda Escobedo Howell, and Casimiro Howell; (standing) William Howell, Henry Joseph Howell, Albert Howell, Charles Howell, and Joseph Henry Howell Jr. Children in arms are Beatriz Gorena (left) and Edna Gorena, Pauline's children. (Eddie Howell Sr.)\n\nMany Mercedes residents remember the good old days when gasoline was 27\u00a2 a gallon in the 1960s. This Kayo Is O.K. gas station was located on the northeast corner of US Business Highway 83 and Missouri Avenue. By then, gasoline stations were \"self-serve,\" although the pumps were still not accepting credit cards. (Carolyn C. L\u00f3pez.)\n\nThe Borderland Hardware Company, now in its 95th year, is the oldest hardware store in the Rio Grande Valley. It was first opened for business by owner Ellery E. \"Jack\" Johnson in 1919 on the southeast corner of US Business Highway 83 and Texas Avenue, as pictured above. Robert Eilers, pictured below at a Rio Grande Valley Livestock Show display in 1955, moved to Mercedes after serving in the US Army and began working at Borderland in 1949. He became Mercedes manager in 1955 and bought the store in 1969. In 1999, the family built a completely new 25,000-square-foot store on the northeast corner of US Business Highway 83 and Ohio Avenue, occupying almost the complete block. Robert and his wife, Loretta, along with their son Kenneth and his wife, Debbie, remain very active today in the family-owned operation. (Both, Eilers family.)\n\nIn October 1953, Pres. Dwight D. Eisenhower rode through Mercedes on his way to the dedication of Falcon Dam in neighboring Starr County. Hundreds of Mercedes citizens turned out to line US Business Highway 83 to get a glimpse of the president as he rode by in a red 1953 Lincoln Capri convertible. (Delia de Le\u00f3n.)\n\nZeferino and Eli R\u00edos, custom boot makers in Mercedes since 1935, presented these boots to President Eisenhower in 1954 to commemorate his visit to the Rio Grande Valley the year before. Their design includes the Capitol, the Great Seal of the United States, sunflowers from Eisenhower's home state of Kansas, and \"Ike,\" the president's nickname. They are currently housed at the National Archives in Washington, DC. (National Archives.)\n\nThis photograph shows the bus station once located between the McAfee Insurance Building and the Hidalgo and Cameron County Water District No. 9 Building on US Business Highway 83. Valley Transit Company and Greyhound buses stopped here to pick up passengers traveling up and down the Valley as well as out-of-state. (Carolyn C. L\u00f3pez.)\n\nBy the middle of the 20th century, Mercedes had nearly 11,000 inhabitants and was a busy, prosperous city. In addition to the surrounding thriving farms and ranches, the downtown area on both the north and the south side boasted many shops and businesses. But Mercedes did not always experience sunny days. This photograph captures the rains that accompanied Beulah, the 1967 hurricane that caused widespread flooding in the Valley. ( _Mercedes Enterprise_.)\n_Four_\n\nWARS AND \nNATURAL DISASTERS\n\nThe map here shows the disputed territory called the Nueces Strip that resulted from Texas Independence in 1836 and led to the Mexican\u2013American War. The land was claimed by both Mexico and the United States after it annexed Texas in 1845. People living in the Rio Grande Valley at that time were caught in a dangerous situation, particularly when the United States sent troops to secure the area. (National Archives.)\n\nGen. Zachary Taylor, pictured here, was sent to Texas by Pres. James K. Polk. In March 1846, Taylor marched to the Rio Grande, a move that was interpreted by Mexican forces as an invasion of their country. The Battle of Palo Alto near Brownsville in May 1846 was the first official battle of the Mexican\u2013American War, followed soon after by the nearby Resaca de la Palma engagement. (National Archives.)\n\nThe lower Rio Grande became important during the Civil War in 1863 as the only waterway available for the export of Confederate cotton. This sketch by L. Avery in _Frank Leslie's Illustrated Newspaper_ shows the cotton being ferried across to Mexico for transport to British ships trading arms for cotton. Involvement in trade by Anglo-Americans during this time caused increased interest in the Rio Grande Valley. (Library of Congress.)\n\nIn the late 1800s, steamboats became important to the Valley in conducting trade with Mexico and with European countries. They provided another means of transporting goods up and down the Rio Grande Valley besides by mule train. Steamboat _Bessie_ , pictured here, was the last of the Mifflin Kenedy\u2013Richard King Rio Grande shipping fleet. It made its final trip on the river in 1902. (National Archives.)\n\nAfter years of social turmoil in Mexico, the Mexican Revolution broke out in 1910. By then, the Rio Grande Valley had established several towns, including Mercedes, founded in 1907. Between 1914 and 1918, various Mexican revolutionary factions raided on the US side, usually attempting to get food and other supplies needed to conduct their war. Many Mercedes and other Valley residents lived in terror of spillover violence from Mexico. (National Archives.)\n\nTensions in the Valley grew higher when Mexican general Lucio Blanco's revolutionaries took Matamoros on June 4, 1913, just across the river from Brownsville and only 39 miles away from Mercedes. Some Mercedes residents wrote memoirs later describing their trip to Matamoros to see the executions by firing squad of the captured federal soldiers. Many people fled Mexico and came to the Valley seeking refuge from the war. (National Archives.)\n\nWhen Mexican revolutionary caudillo Pancho Villa crossed into US territory in March 1916 and attacked Columbus, New Mexico, over an arms deal gone bad, US residents along the southern border began clamoring Washington to send troops for their protection. By August 1916, an estimated 117,000 national guardsmen were stationed along the border in Texas, New Mexico, Arizona, and California. (National Archives.)\n\nTwo Army camps were set up near Mercedes in 1916. One was the Llano Grande camp between Weslaco and Mercedes on both north and south sides of now US Business Highway 83. The other was Camp Mercedes, shown in this photograph, the large bulk of which was located east of the Mercedes Main Canal and south of Tenth Street. (Library of Congress.)\n\nThe guardsmen assigned to the Valley camps trained in all aspects of warfare available at that time including artillery fire as seen here, something which would serve them well when the United States entered World War I in Europe in 1917. During this time of the Mexican Border Service, motor vehicles and aircraft were first used in the US military forces. (National Archives.)\n\nShown here is part of a 1917 hand-drawn map prepared by Sgt. Charles A. Rice based on field notes taken while out on patrol with the US Army while stationed in the Rio Grande Valley. The map shows the winding Rio Grande forming the boundary between Mexico and the United States. The present-day towns of McAllen, Pharr, San Juan, Donna, Mercedes, and La Feria can be seen along the track of the St. Louis, Brownsville and Mexico Railway. The Military Highway is labeled as having been built by Gen. Zachary Taylor in 1847, but many historians dispute this statement due to lack of documented evidence. In his Valley campaign during the Mexican\u2013American War, Taylor used steamships and the road running south of the river to transport his troops and supplies upriver to Camargo. (Hidalgo County Historical Society.)\n\nSoldiers from Camp Mercedes are pictured stationed at the Toluca Ranch. The Toluca Ranch south of Mercedes was considered a likely target for a Mexican raid during that era, and it was raided on four separate occasions. There were several skirmishes with Mexican \"bandits\" in the Valley in the early 1900s, but no major invasions by Mexicans ever occurred. (MSTH.)\n\nOne of early Mercedes's greatest problems was flooding. In 1909, Mercedes suffered the worst flood in its history. At that time, there were no flood controls on the river such as dams or levees. During this natural disaster some parts of Mercedes were 14 feet deep in floodwaters. This photograph shows the northeast corner of Texas Avenue and Second Street. (MSTH.)\n\nThe Howell family is pictured in 1916 standing outside a community building on North Missouri Avenue that was used for church services. From left to right are Mary, Henry Joseph, William, Albert, Jacinto, Joseph Henry Jr. (in arms), Pauline, Casimiro, Mar\u00eda Howell, and Joseph Henry Howell Sr. Tragically, little Mary died in 1918 during an influenza pandemic. Both influenza and smallpox took a deadly toll in the Valley during the early 1900s. (Eddie Howell Sr.)\n\nThe Great Depression hit the Rio Grande Valley with a vengeance. In Mercedes, many businesses failed and farmers went broke. Many people from other states came to the Valley looking for work and often clashed with locals that also needed work. Tent cities like this one in Mercedes in 1939 could be found all over the Valley. (Library of Congress.)\n\nMercedes businesses also suffered devastating fires such as this one on North Texas Avenue when Leal's Electric business burned down in 1954. The girl is unidentified, but Alberto Arteaga, manager of the Rio Theater next door to Leal's Electric, captured her frightened look in this photograph. (Sylvia Arteaga Calles.)\n\nUnidentified persons in this photograph prepare smoke pots to protect a citrus crop during an anticipated hard freeze in 1920. Smoke pots contained kerosene and were placed between the rows of grapefruit or orange trees to keep them warm during nights of low temperatures. A severe freeze could destroy the citrus crop and ruin agricultural investments in a single night of low temperatures. (Weslaco Museum.)\n_Five_\n\nTHE RIO GRANDE VALLEY \nLIVESTOCK SHOW\n\nRio Grande Valley Livestock Show cover girls and alternates pose for this 1956 photograph. The Rio Grande Valley Livestock Show officially began in 1939 as an annual project of the Mercedes Chamber of Commerce in efforts to promote livestock and poultry production. Although the livestock show began in Mercedes, it quickly included Cameron, Willacy, Starr, and Hidalgo Counties in the project. (Rio Grande Valley Livestock Show Museum.)\n\nAn aerial view of the Rio Grande Valley Livestock Show grounds covering more than 100 acres at the north end of Texas Avenue was taken in 1955 when many metal and wood buildings were used to replace tents and other less durable structures. With more than 1,000 volunteers and 4,000 exhibitors expected, the 2014 show was a far cry from the earliest shows. The earliest documented show was a one-day affair in 1913 held at the Mercedes Power Plant, a two-story building located on Second Street (US Business Highway 83) and the Main Canal. It was so popular that the next year, in 1914, it was a three-day event with many exhibits of livestock and agricultural products, lectures, a US Cavalry sham battle, and boat rides on the Main Canal. It did not become an annual event, however, until 1939. Unfortunately, in 1965, a fire destroyed much of the early records of the show, and photographs such as this one have slowly been recovered from other sources. (Mercedes ISD.)\n\nSun Valley Horse Show Queen Pip Setter and her horse Rex pose for a photograph in 1964. The Rio Grande Livestock Show grounds host many events other than the annual March livestock show. The Sun Valley Horse Show is a Mercedes High School FFA Club fundraiser that accepts Valley-wide competitors in various events. Many other horse shows are held annually at the livestock show grounds. (Weslaco Museum.)\n\nThomas Treasure (left) awards the \"Best Cowboy Trophy\" to 12-year-old Kenny Reger mounted on his horse Mr. Red, which is held by an unidentified girl, in the Sun Valley Horse Show held October 1964 at the Rio Grande Valley Livestock Show grounds. Competitive events included barrel races, stake races, pole bending races, and children's showmanship. (Weslaco Museum.)\n\nThe traditional opening of the Rio Grande Valley Livestock Show is the parade held on the first day of the show. It always includes decorated floats, trail riders from various horseman's associations, marching school bands, cover girl candidates, show officials, city officials, local clubs and organizations either walking or riding floats, and singing or acting stars invited to perform. (Sylvia Arteaga Calles.)\n\nA guest band from the Justo Sierra Boy's Orphanage and Military School in Monterrey, Nuevo Leon, Mexico marches in the Rio Grande Valley Livestock Show Parade in March 1956. Special arrangements were made to allow members of the school to attend the livestock show, and local families agreed to house the younger students in order to help defray lodging costs. (Sylvia Arteaga Calles.)\n\nMimi Garibay, 1956 cover girl winner sponsored by the Brownsville FFA organization rides in a 1956 Dodge convertible in the Rio Grande Valley Livestock Show Parade as it wends its way up Texas Avenue to end at the show grounds on North Texas Avenue. (Sylvia Arteaga Calles.)\n\nMembers of the Mid-Valley Horseman's Association pictured here begin their trail ride in Roma about 50 miles west and ride toward Mercedes for two days, camping out and eating from a chuck wagon to finally arrive in time to participate in the Rio Grande Valley Livestock Show Parade and other activities. (Rosendo Gonzales.)\n\nSinger, film actor, and songwriter Rex Allen (in the center) poses with 1962 cover girl alternates. At left is second alternate Sherrie Gallaway, and at right is first alternate Pam Knapp. Rex Allen, called the Arizona Cowboy, was well known for starring in 19 of Hollywood's Western movies with Buddy Ebsen and Slim Pickens as his sidekicks. (Mercedes ISD.)\n\nEnjoying the various food booths available at the Rio Grande Valley Livestock Show are many show visitors. Thousands of local visitors as well as visitors from other states and even other countries visit the Rio Grande Valley Livestock Show every year. It is considered one of the Top Ten Shows in Texas and recently draws close to 200,000 visitors annually. (Rio Grande Valley Livestock Show Museum.)\n\nParthenia Archer (left) receives two free rodeo tickets from show director Frances Cooper to see movie star Ken Curtis, who starred as Festus in the television show _Gunsmoke_ and was featured at the 1967 Rio Grande Valley Livestock Show. Two unidentified children help hold up the poster announcing the event. (Weslaco Museum.)\n\nIn this 1961 photograph, Mar\u00eda Buenrostro (center back) prepares to take these children to the Rio Grande Valley Livestock Show. Children are, from left to right, N\u00e1tiz Buenrostro, Yolanda Jilpas, and Guadalupe Jilpas. Their activities include visiting the children's barnyard, the arts and crafts exhibits, the show animal pens, the rodeo, the midway carnival, antique farm equipment exhibit, a magician show, and enjoying live music. (Vito Buenrostro.)\n\nCharles \"Charlie\" Rankin, a popular Rio Grande Valley radio and television personality who was considered the \"voice of agriculture\" in the Valley for many years for his informative noon radio programs, takes part in a \"wild\" cow-milking contest during the 1971 Rio Grande Valley Livestock Show. From left to right, the competitors are Bob McDonald of KRGV holding the cow's tail, Rankin milking the cow, and Burt Johnson of KRIO holding the cow's head. Rankin was declared the winner. Rankin attended Texas A&M University after two years in the US Navy on an aircraft carrier during World War II. While at the university, he was instrumental in establishing the National Intercollegiate Rodeo Association, serving as its first president in 1949. He was often invited to serve as a judge or an announcer at the Rio Grande Livestock Show and Rodeo in Mercedes. (Rio Grande Valley Livestock Show Museum.)\n\nThe Rio Grande Valley Livestock Show cover girl parade float every year features the winning cover girl and the first and second alternates. The parade is the opening event every March that kicks off the livestock show. The young ladies posing here are 1986 cover girl Claudette Smith and unidentified alternates. (Rio Grande Valley Livestock Show Museum.)\n\nCharles \"Charlie\" Rankin, well-known radio and television personality in the Valley for his farm bureau talk shows, interviews Lorne Green and Ben Cartwright of the television show _Bonanza_. The two stars were featured guests of the Rio Grande Valley Livestock Show in 1973. The show often brought big name stars, including Gene Autry, Lynn Anderson, Johnny Rodr\u00edguez, Dwight Yoakum, and many others. (Rio Grande Valley Livestock Show Museum.)\n\nAn unidentified rider competes in the saddle-bronc riding event at the Rio Grande Valley Livestock Show and Rodeo in 1959. In saddle-bronc riding, the rider holds a braided line with only one hand and attempts to stay on for at least eight seconds. Scores range from zero to 100 with 50 points depending on the horse's bucking moves and 50 depending on the rider's skill. (Rio Grande Valley Livestock Show Museum.)\n\nTaken at the fryer pens at the Rio Grande Livestock Show in 1965, this photograph shows Steven Dollery (left) and his sister Stephanie Dollery, 4-H members and children of James Dollery. James Dollery was an agriculture teacher at Mercedes High School and head sponsor of the FFA club in the 1950s and 1960s. (Weslaco Museum.)\n\nLeading the 1971 Rio Grande Valley Livestock Show Parade are two unidentified men wearing chaps with the famous HK brand of the 825,000-acre King Ranch. The HK brand was one of two official brands registered in 1859 for the King Ranch. The letters were the initials of Henrietta King, wife of King Ranch founder Richard King. In 1869, the Running W brand was registered and it remains the official brand today. The King Ranch is well known for developing the Santa Gertrudis cattle breed now recognized as a superior beef cattle breed. In its horse breeding efforts, the King Ranch has produced 1946 US Triple Crown winner Assault and 1950 Kentucky Derby winner Middleground. A King Ranch Quarter Horse named Wimpy was the very first registered horse of the American Quarter Horse Association in 1940, receiving the designation \"P-1.\" (Rio Grande Valley Livestock Show Museum.)\n\nFrom left to right, 1959 cover girl Ann Watson poses in this photograph with Al Martin and Sherry Tripp, 4-H participants, and their \"Grand Champion Pen of Fryers\" at the 1958 Rio Grande Valley Livestock Show, as well as Dr. Joseph Townsend of Texas A&M University, who served as a judge at the event. (Rio Grande Valley Livestock Show Museum.)\n\nThe Studebaker military escort wagon in this photograph is part of the 1st Cavalry Division from Fort Hood, Texas. The group formed in 1972 under the direction of Maj. Gen. James C. Smith and represents an 1870 era \"horse soldier\" troop wearing standard issue Civil War Union uniforms. They perform mounted drills and weapons demonstrations and were featured guest performers at the 1973 Rio Grande Valley Livestock Show. (Rio Grande Valley Livestock Show Museum.)\n\nCharles \"Charlie\" Rankin (left) poses with an unidentified member of the Texas A&M University's Parson's Mounted Cavalry, a ceremonial horse cavalry unit founded in 1974 to preserve traditions of the Texas A&M Cavalry of the 1920s and 1930s. The Cavalry is part of the Corps of Cadets, which was established in 1876 as a student military organization. Texas A&M University is one of six US colleges classified as a senior military college. The Corpsman shown here with Rankin is wearing \"senior boots,\" brown leather boots to the knees worn only by Texas A&M seniors. Parson's Mounted Cavalry represents the university at parades, agricultural fairs, livestock shows, and equestrian events in Texas. The group performed military maneuvers on horseback at the 1975 Rio Grande Valley Livestock Show. (Rio Grande Valley Livestock Show Museum.)\n\nVincent Neuhaus, left, and Earl Neuhaus, mounted, participate in a steer-riding event at the Rio Grande Valley Livestock Show in 1964. Both attended Texas A&M University in College Station, Texas. Both own several successful farm equipment businesses although in different cities, and Earl also has served as president of the Rio Grande Valley Livestock Show. (Rio Grande Valley Livestock Show Museum.)\n\nIn this September 1959 photograph, members of the Board of Directors of the Rio Grande Valley Livestock Show get an update on planning activities for the upcoming 1960 Show. The board is limited to 24 members as set forth in its bylaws, and board members all work for the Livestock Show on a voluntary basis. (Rio Grande Valley Livestock Show Museum.)\n\nPictured recently are Dario \"D.V.\" Guerra (left), president emeritus of the Rio Grande Valley Livestock Show, and grande dame Frances Richmond Cooper, show director. Guerra is the owner of the D.V. Guerra Ranch in Edinburg and is a longtime volunteer with the livestock show. Cooper first went to work for the Rio Grande Valley Livestock Show in December 1954 as secretary to the manager. In 1959, she became show manager and remained in that position until she retired in 1986. Upon her retirement, she served on the board of directors as a volunteer until her death in 2009. She always declared she loved best the awards she received from the Texas FFA and the 4-H clubs. The Texas Association of Fairs and Events, in which she served 13 years as executive secretary, awarded her with its lifetime achievement award in 2002. In 2004, the International Association of Fairs and Expositions presented her with the prestigious Heritage Award for promoting not only the Rio Grande Valley Livestock Show but also fairs across the United States. (Rio Grande Valley Livestock Show Museum.)\nDISCOVER THOUSANDS OF LOCAL HISTORY BOOKS \nFEATURING MILLIONS OF VINTAGE IMAGES\n\nArcadia Publishing, the leading local history publisher in the United States, is committed to making history accessible and meaningful through publishing books that celebrate and preserve the heritage of America's people and places.\n\nFind more books like this at\n\n**www.arcadiapublishing.com**\n\nSearch for your hometown history, your old stomping grounds, and even your favorite sports team.\n","meta":{"redpajama_set_name":"RedPajamaBook"}} +{"text":"# Table of Contents\n\n 1. Title Page\n 2. Table of Contents\n 3. Copyright\n 4. Preface\n 5. Introduction\n 6. The Basics\n 7. The Order of a Business Meeting\n 8. Presenting Business to the Assembly\n 9. Debating the Motion\n 10. Voting\n 11. Motions\n 12. Using Subsidiary Motions to Help Adopt a Main Motion\n 13. Using Privileged Motions\n 14. Using Incidental Motions\n 15. Using Motions That Bring a Question Again Before the Assembly\n 16. Officers\n 17. Nominations and Elections\n 18. Committees\n 19. The Role of the Member\n 20. Discipline\n 21. Meetings\n 22. Strategies for Individual Motions Illustrated\n 23. Most Frequently Asked Questions\n 24. Various Types of Governing Documents\n 25. Bylaws\n 26. Homeowners' Associations (HOAs)\n 27. Appendix A\n 28. Appendix B\n 29. Appendix C\n 30. Appendix D\n 31. Appendix E\n 32. Appendix F\n 33. Appendix G\n 34. Index\n 35. DVDs for Parliamentarians\n 36. About Robert McConnell Productions\n\n","meta":{"redpajama_set_name":"RedPajamaBook"}} +{"text":" \n# Table of Contents\n\n 1. Series Page\n 2. Title Page\n 3. Copyright\n 4. About The Author\n 5. Introduction to The Ultimate Algorithmic Trading Systems ToolBox\n 6. Chapter 1: Introduction to Trading: Algorithm Development\n 1. What Is an Algorithm?\n 2. How to Get My Trading Idea into Pseudocode\n 3. Summary\n 7. Chapter 2: Stochastics and Averages and RSI! Oh, My!\n 1. Oscillators\n 2. Price-Based Indicators\n 3. Summary\n 8. Chapter 3: Complete Trading Algorithms\n 1. Trend-Trading Battle Royale\n 2. Portfolio Composition\n 3. Multi-Algorithm Strategy (MAS)\n 4. Summary\n 9. Chapter 4: Introduction to AmiBroker's AFL\n 1. Quick Start\n 2. Price Bar Interface\n 3. AFL Array Programming\n 4. Syntax\n 5. AFL Wizard\n 6. AmiBroker Loop Programming\n 7. Summary\n 10. Chapter 5: Using Microsoft Excel to Backtest Your Algorithm\n 1. VBA Functions and Subroutines\n 2. Data\n 3. Software Structure\n 4. Programming Environment\n 5. Summary\n 11. Chapter 6: Using Python to Backtest Your Algorithm\n 1. Why Python?\n 2. Python Installation\n 3. PSB Installation\n 4. PSB Structure\n 5. Getting Down to Business\n 6. Summary\n 12. Chapter 7: An Introduction to EasyLanguage\n 1. TradeStation IDE\n 2. Syntax\n 3. Samples of EasyLanguage\n 4. Summary\n 13. Chapter 8: Genetic Optimization, Walk Forward, and Monte Carlo Start Trade Analysis\n 1. Utilizing TradeStation and AmiBroker\n 2. Computers, Evolution, and Problem Solving\n 3. Population\n 4. Initial Population Setup Using VBA Excel\n 5. Testing Fitness of Chromosomes Using VBA Excel\n 6. Selection\n 7. Reproduction\n 8. Mutation\n 9. Using Genetic Algorithms in Trading System Development\n 10. Preventing Over-Curve-Fitting\n 11. Walk-Forward Optimizer: Is It Worth the Extra Work and Time?\n 12. Monte Carlo Analysis\n 13. Start Trade Drawdown\n 14. Summary\n 14. Chapter 9: An Introduction to Portfolio Maestro, Money Management, and Portfolio Analysis\n 1. Fixed Fractional\n 2. Portfolio Maestro\n 3. Summary\n 15. Appendix A: AmiBroker\n 1. Keywords\n 2. Flow Control Structures\n 3. Functions\n 4. Utilizing Exploration for Debugging\n 5. Position Sizing in Futures Mode\n 16. Appendix B: Excel System Backtester\n 1. Data Arrays\n 2. Keywords\n 3. Functions and Subroutines\n 17. Appendix C: Python System Backtester\n 1. Data Arrays or Lists\n 2. Keywords and Identifiers\n 3. Classes\n 4. Indicator Classes and Functions\n 5. Python-Specific Keywords\n 18. Appendix D: TradeStation and EasyLanguage\n 1. Importing ELD file from Book Website\n 2. Keywords and Functions\n 3. Sample Algorithm Codes\n 19. Appendix E\n 20. About the Companion Website\n 21. Index\n 22. End User License Agreement\n\n## Pages\n\n 1. ii\n 2. iv\n 3. ix\n 4. x\n 5. xi\n 6. xii\n 7. xiii\n 8. xiv\n 9. xv\n 10. xvi\n 11. xvii\n 12. xviii\n 13. \n 14. \n 15. \n 16. \n 17. \n 18. \n 19. \n 20. \n 21. \n 22. \n 23. \n 24. \n 25. \n 26. \n 27. \n 28. \n 29. \n 30. \n 31. \n 32. \n 33. \n 34. \n 35. \n 36. \n 37. \n 38. \n 39. \n 40. \n 41. \n 42. \n 43. \n 44. \n 45. \n 46. \n 47. \n 48. \n 49. \n 50. \n 51. \n 52. \n 53. \n 54. \n 55. \n 56. \n 57. \n 58. \n 59. \n 60. \n 61. \n 62. \n 63. \n 64. \n 65. \n 66. \n 67. \n 68. \n 69. \n 70. \n 71. \n 72. \n 73. \n 74. \n 75. \n 76. \n 77. \n 78. \n 79. \n 80. \n 81. \n 82. \n 83. \n 84. \n 85. \n 86. \n 87. \n 88. \n 89. \n 90. \n 91. \n 92. \n 93. \n 94. \n 95. \n 96. \n 97. \n 98. \n 99. \n 100. \n 101. \n 102. \n 103. \n 104. \n 105. \n 106. \n 107. \n 108. \n 109. \n 110. \n 111. \n 112. \n 113. \n 114. \n 115. \n 116. \n 117. \n 118. \n 119. \n 120. \n 121. \n 122. \n 123. \n 124. \n 125. \n 126. \n 127. \n 128. \n 129. \n 130. \n 131. \n 132. \n 133. \n 134. \n 135. \n 136. \n 137. \n 138. \n 139. \n 140. \n 141. \n 142. \n 143. \n 144. \n 145. \n 146. \n 147. \n 148. \n 149. \n 150. \n 151. \n 152. \n 153. \n 154. \n 155. \n 156. \n 157. \n 158. \n 159. \n 160. \n 161. \n 162. \n 163. \n 164. \n 165. \n 166. \n 167. \n 168. \n 169. \n 170. \n 171. \n 172. \n 173. \n 174. \n 175. \n 176. \n 177. \n 178. \n 179. \n 180. \n 181. \n 182. \n 183. \n 184. \n 185. \n 186. \n 187. \n 188. \n 189. \n 190. \n 191. \n 192. \n 193. \n 194. \n 195. \n 196. \n 197. \n 198. \n 199. \n 200. \n 201. \n 202. \n 203. \n 204. \n 205. \n 206. \n 207. \n 208. \n 209. \n 210. \n 211. \n 212. \n 213. \n 214. \n 215. \n 216. \n 217. \n 218. \n 219. \n 220. \n 221. \n 222. \n 223. \n 224. \n 225. \n 226. \n 227. \n 228. \n 229. \n 230. \n 231. \n 232. \n 233. \n 234. \n 235. \n 236. \n 237. \n 238. \n 239. \n 240. \n 241. \n 242. \n 243. \n 244. \n 245. \n 246. \n 247. \n 248. \n 249. \n 250. \n 251. \n 252. \n 253. \n 254. \n 255. \n 256. \n 257. \n 258. \n 259. \n 260. \n 261. \n 262. \n 263. \n 264. \n 265. \n 266. \n 267. \n 268. \n 269. \n 270. \n 271. \n 272. \n 273. \n 274. \n 275. \n 276. \n 277. \n 278. \n 279. \n 280. \n 281. \n 282. \n 283. \n 284. \n 285. \n 286. \n 287. \n 288. \n 289. \n 290. \n 291. \n 292. \n 293. \n 294. \n 295. \n 296. \n 297. \n 298. \n 299. \n 300. \n 301. \n 302. \n 303. \n 304. \n 305. \n 306. \n 307. \n 308. \n 309. \n 310. \n 311. \n 312. \n 313. \n 314. \n 315. \n 316. \n 317. \n 318. \n 319. \n 320. \n 321. \n 322. \n 323. \n 324. \n 325. \n 326. \n 327. \n 328. \n 329. \n 330. \n 331. \n 332. \n 333. \n 334. \n 335. \n 336. \n 337. \n 338. \n 339. \n 340. \n 341. \n 342. \n 343. \n 344. \n 345. \n 346. \n 347.\n\n## Guide\n\n 1. Cover\n 2. Table of Contents\n 3. Begin Reading\n\n## List of Illustrations\n\n 1. Chapter 1: Introduction to Trading: Algorithm Development\n 1. Figure 1.1 Examples of strength differences between pivot high points on daily bars.\n 2. Figure 1.2 A depiction of the variable-bar sequence described by the long entry signal.\n 3. Figure 1.3 An FSM that models the workings of a combination lock.\n 4. Figure 1.4 An FSM that models the pivot-point long-entry algorithm described in this chapter.\n 5. Figure 1.5 A very simple FC.\n 6. Figure 1.6 An FC of a trading algorithm.\n 2. Chapter 2: Stochastics and Averages and RSI! Oh, My!\n 1. Figure 2.1 Examples of directional movement.\n 2. Figure 2.2 ADX as a trend detector.\n 3. Figure 2.3 Wilder's directional movement algorithm.\n 4. Figure 2.4 Example of a trade generated by RSI.\n 5. Figure 2.5 Flowchart diagram of RSI trading algorithm.\n 6. Figure 2.6 Example of RSI divergence.\n 7. Figure 2.7 Example of FSM modeling RSI Swing Failure.\n 8. Figure 2.8 Chart showing trade signals from stochastic crossover algorithm.\n 9. Figure 2.9 The flowchart for an algorithm using a stochastic oscillator crossover as an entry signal.\n 10. Figure 2.10 Trades generated by the CCI algorithm when it crosses above 100 and below \u2212100.\n 11. Figure 2.11 The CCI system detecting a downturn in the Eurocurrency.\n 12. Figure 2.12 Histogram pivot points can initiate trade signals.\n 13. Figure 2.13 Three different 20-day moving averages.\n 14. Figure 2.14 A 60-day, two-SD Bollinger Band on crude oil.\n 15. Figure 2.15 Keltner Channels and Bollinger Bands applied to the same data.\n 16. Figure 2.16 Bollinger Band optimization.\n 17. Figure 2.17 Keltner Channel optimization.\n 3. Chapter 3: Complete Trading Algorithms\n 1. Figure 3.1 Turtle trading algorithm flowchart.\n 2. Figure 3.2 A three-dimensional contour chart of Bollinger performance across a subset of the parameters that were originally optimized.\n 3. Figure 3.3 A snapshot of a portion of the current portfolio correlation matrix.\n 4. Figure 3.4 Walk-forward testing begins with a backtest used to derive the desired parameter. Then, it applies that parameter going forward.\n 5. Figure 3.5 AmiBroker's walk-forward optimizer in action.\n 6. Figure 3.6 Parameters selected to carry forward for the following year.\n 7. Figure 3.7 Performance of the WFO of the Bollinger Band system.\n 8. Figure 3.8 Equity curve that reflects a pattern system.\n 9. Figure 3.9 Mini-Russell day trading system using a narrow range day. It initially puts on two contracts, pulling the first one off after a certain profit is reached and leaving the second to run its course.\n 4. Chapter 4: Introduction to AmiBroker's AFL\n 1. Figure 4.1 Launching AmiBroker's AFL editor.\n 2. Figure 4.2 The AmiBroker Editor window.\n 3. Figure 4.3 The AFL Editor's auto-completion tool.\n 4. Figure 4.4 AFL Editor function helper.\n 5. Figure 4.5 The AFL Check icon.\n 6. Figure 4.6 An error warning.\n 7. Figure 4.7 The \"Send to Analysis\" window icon.\n 8. Figure 4.8 Apply the algorithm to the current data.\n 9. Figure 4.9 Set the parameters for the backtest.\n 10. Figure 4.10 Set Futures mode.\n 11. Figure 4.11 The trade-by-trade report.\n 12. Figure 4.12 The portfolio results.\n 13. Figure 4.13 A 3D optimization chart.\n 14. Figure 4.14 The AFL Code Wizard button.\n 15. Figure 4.15 A new AFL Code Wizard window.\n 16. Figure 4.16 Add item in AFL Code Wizard.\n 17. Figure 4.17 The AFL Code Wizard \"Edit Rule\" dropdown list.\n 18. Figure 4.18 Changing the parameters in the \"Edit Rule\" pane.\n 19. Figure 4.19 Click the exclamation point to send your request to AmiBroker.\n 20. Figure 4.20 Automatic Analysis dialog box.\n 21. Figure 4.21 Sample loop programming code.\n 5. Chapter 5: Using Microsoft Excel to Backtest Your Algorithm\n 1. Figure 5.1 Once you define the Bollinger Band routine, you can easily incorporate it into trading.\n 2. Figure 5.2 The structure of the backtesting software.\n 3. Figure 5.3 A typical Excel data worksheet.\n 4. Figure 5.4 The DataMaster worksheet can help you store the values of your commodities and futures contracts.\n 5. Figure 5.5 The Results worksheet lists multiple trades and their associated performance metrics.\n 6. Figure 5.6 The EquityStream worksheet has a button that launches a macro to create a chart that plots the cumulative daily equity and drawdown.\n 7. Figure 5.7 Customize your Excel ribbon. Make sure you check the box next to the Developer tab option.\n 8. Figure 5.8 The Developer tab in Microsoft Excel.\n 9. Figure 5.9 The Visual Basic Editor (VBE) in Microsoft Excel.\n 10. Figure 5.10 Comment text in VBA code is written in gray. It is also indicated by the single quote at the beginning of each line.\n 11. Figure 5.11 This is where the VBA comments end and the actual source code begins.\n 12. Figure 5.12 This error message appears if your algorithm does not have enough ramp-up data.\n 13. Figure 5.13 This tiny snippet of code contains five arguments, which are all necessary for the Trade subroutine.\n 6. Chapter 6: Using Python to Backtest Your Algorithm\n 1. Figure 6.1 NotePad++'s collapsible text feature.\n 2. Figure 6.2 A Python syntax error message.\n 3. Figure 6.3 In this case, the syntax error was the result of confusion between the assignment operator (=) and the comparison operator (==). Python highlights the problematic code.\n 4. Figure 6.4 A Python run-time error resulting from using parentheses instead of square brackets.\n 7. Chapter 7: An Introduction to EasyLanguage\n 1. Figure 7.1 The TradeStation home screen.\n 2. Figure 7.2 TradeStation's trading apps.\n 3. Figure 7.3 The initial screen of the TradeStation Development Environment.\n 4. Figure 7.4 The EasyLanguage editor in the TradeStation Development Environment.\n 5. Figure 7.5 The algorithm with a single, complete portion of the strategy marked.\n 6. Figure 7.6 The EasyLanguage editor monitors what you are typing and provides likely functions.\n 7. Figure 7.7 How to apply a strategy to your chart.\n 8. Figure 7.8 A reversion analysis strategy shown on a chart.\n 9. Figure 7.9 How to change the inputs and adjust your strategy.\n 10. Figure 7.10 The four input variables to adjust the mean reversion strategy.\n 11. Figure 7.11 A message confirming that your code was verified and will be recalculated based on the new inputs.\n 12. Figure 7.12 TradeStation lists any syntax errors it finds during verification in the bottom pane of the screen. The line number of the error is provided so you can easily find it in your code.\n 13. Figure 7.13 The EasyLanguage editor can display line numbers to make it easy to navigate your code.\n 14. Figure 7.14 To create a new project using your strategy, select Project from the File menu.\n 15. Figure 7.15 How to add an existing strategy to a new project.\n 16. Figure 7.16 All dependencies and functions are nested inside their strategy algorithm.\n 8. Chapter 8: Genetic Optimization, Walk Forward, and Monte Carlo Start Trade Analysis\n 1. Figure 8.1 Iteration growth rate of five parameters.\n 2. Figure 8.2 An illustration of our chromosomes with different genetic values.\n 3. Figure 8.3 Chromosome dartboard.\n 4. Figure 8.4 At split 1 the genes that will be passed onto the offspring by the father and the mother.\n 5. Figure 8.5 Robust parameter sets are found on a level plateau.\n 6. Figure 8.6 A graphic representation of how the walk-forward analysis (WFA) rolls forward.\n 7. Figure 8.7 How four years of hindsight are used to predict unseen data for the following year.\n 8. Figure 8.8 The Cluster WFO results matrix.\n 9. Figure 8.9 AmiBroker Monte Carlo settings dialog.\n 10. Figure 8.10 Monte Carlo Straw Broom chart of multiple randomized equity curves.\n 9. Chapter 9: An Introduction to Portfolio Maestro, Money Management, and Portfolio Analysis\n 1. Figure 9.1 TradeStation's Portfolio Maestro (PM) launch window.\n 2. Figure 9.2 Add a strategy to your strategy group.\n 3. Figure 9.3 The Turtle 55 strategy is now in your strategies window.\n 4. Figure 9.4 Add a symbol by clicking the Symbol Lists tab (indicated by Arrow 1), then clicking on Add Symbol List (shown with Arrow 2).\n 5. Figure 9.5 After selecting the UGTATS list, it will appear in your symbol list window.\n 6. Figure 9.6 The UGTATS markets and their corresponding symbols.\n 7. Figure 9.7 A list of available strategy groups, including MyFirstStrategyGroup, which we are using for this exercise.\n 8. Figure 9.8 After selecting MyFirstStrategyGroup, you will see it in MyFirstPortfolio. In the expanded view, you can see the strategies and symbols that are part of your group.\n 9. Figure 9.9 How to adjust the settings for a strategy group. Arrow 1 indicates the Manage Strategy Group button. Arrow 2 highlights the Strategy Group Settings button. Arrow 3 points to the controls that change the commission and slippage inputs.\n 10. Figure 9.10 As you prepare to backtest your portfolio, ensure the settings are correct. Begin by clicking the Backtest Portfolio button (marked 1 in the figure). Then, check the initial capital, test period, and backtest type in the appropriate fields (marked with 2). When everything looks good, click the Perform Backtest button (number 3 in the figure).\n 11. Figure 9.11 A backtest performance report.\n 12. Figure 9.12 The Trade Analysis window displays trading statistics. To get to this screen, click the Trade Analysis tab (marked 1). The View\/Hide Symbols button (marked 2) reveals the performance metric for every market in your portfolio (item 3).\n 13. Figure 9.13 An equity curve chart that shows the maximum drawdown.\n 14. Figure 9.14 The Total P\/L option displays individual profit and loss data for every market in the portfolio.\n 15. Figure 9.15 The Returns and Equity tab displays the portfolio's maximum drawdown in this case.\n 16. Figure 9.16 The arrows indicate the parameters that you can change from the Money Management window. For now, keep the ATR lookback set to 10 and the round quantity set to 1.\n 17. Figure 9.17 The equity curve of the backtest reveals a profit of nearly $1 million.\n 18. Figure 9.18 Profit and drawdown are directly proportional to position size. As your position size changes, so do your commissions and profits and losses.\n 19. Figure 9.19 Under Portfolio Settings (marked as 1), go to the Portfolio Stops tab (marked as 2) and set the stop strategy of your choosing. Under the dropdown menu, there is a description of how the selected strategy will impact your portfolio (marked as 3).\n 20. Figure 9.20 To set the portfolio stop loss, you can adjust the loss target percentage (marked as 1), loss target (marked as 2), and period (marked as 3).\n 21. Figure 9.21 To set the portfolio profit target, you can adjust the period, profit target percentage, and profit target. These options align with those in the stop loss tab.\n 22. Figure 9.22 The portfolio profit target and stop loss now appear as strategies in your portfolio.\n 23. Figure 9.23 At the bottom of your screen, you should see the portfolio stop option.\n 24. Figure 9.24 The equity curve of the portfolio once the stops have been added.\n\n## List of Tables\n\n 1. Chapter 2: Stochastics and Averages and RSI! Oh, My!\n 1. Table 2.1 Performance of Directional Movement Algorithm\n 2. Table 2.2 Performance of RSI Algorithm\n 3. Table 2.3 Performance of RSI Failure Swing Algorithm\n 4. Table 2.4 Performance of Stochastic Algorithm\n 5. Table 2.5 Performance of CCI algorithm\n 6. Table 2.6 Performance of CCI Algorithm as Coincident Indicator\n 7. Table 2.7 Examples of Trades Generated by Stochastics\n 8. Table 2.8 Performance of Bollinger Band Algorithm Version 1\n 9. Table 2.9 Performance of Bollinger Band Algorithm Version 2\n 10. Table 2.10 Bollinger Benchmark versus Keltner Challengers\n 11. Table 2.11 Best Parameter Sets of Bollinger Bands Algorithm\n 12. Table 2.12 Best Parameter Sets of Keltner Channel Algorithm\n 2. Chapter 3: Complete Trading Algorithms\n 1. Table 3.1 Turtle System 1 without LTLF for the Sample Portfolio\n 2. Table 3.2 Turtle System 2 for the Sample Portfolio\n 3. Table 3.3 Turtle System 1 with LTLF for the Sample Portfolio\n 4. Table 3.4 Tandem Performance of Turtle System 1 with LTLF and Turtle System 2 for the Sample Portfolio\n 5. Table 3.5 Single Moving Average (SMA) Crossover Algorithm\n 6. Table 3.6 Double Moving Average (DMA) Crossover Algorithm\n 7. Table 3.7 Triple Moving Average (TMA) Crossover Algorithm\n 8. Table 3.8 Donchian Channel Breakout for Different Donchian Lengths\n 9. Table 3.9 Bollinger Band Breakout\n 10. Table 3.10 Comparison of Parameters for Algorithms Based on Different Strategies\n 11. Table 3.11 Top 10 Parameter Sets for Each Algorithm\n 12. Table 3.12 The Best Parameter Sets for Each Optimization\n 13. Table 3.13 The Best Results for the Donchian Algorithm for In-Sample Time Period\n 14. Table 3.14 Results for the Donchian Algorithm when Walked Forward across an Out-of-Sample (OOS) Time Period\n 15. Table 3.15 The Best Parameters for the Portfolio over the Out-Of-Sample (OOS) Time Period\n 16. Table 3.16 The Optimization of the Bollinger Algorithm for the In-Sample (IS) Time Period\n 17. Table 3.17 Results for the Donchian Algorithm when Walked Forward across an Out-of-Sample (OOS) Time Period\n 3. Chapter 7: An Introduction to EasyLanguage\n 1. Table 7.1 EasyLanguage Keywords and Abbreviations\n 4. Chapter 8: Genetic Optimization, Walk Forward, and Monte Carlo Start Trade Analysis\n 1. Table 8.1 Results from the Exhaustive Search Algorithm's Five Parameters\n 2. Table 8.2 Results from the Genetic Search Algorithm's Five Parameters\n 3. Table 8.3 In-Sample Testing TA2\n 4. Table 8.4 Out-of-Sample Testing\n 5. Table 8.5 WFA Report on TA2\n 6. Table 8.6 The Out-of-Sample (OOS) Report\n 7. Table 8.7 WFO Report Card TA3\n 8. Table 8.8 Distribution Statistics from Monte Carlo Simulations\n 5. Chapter 9: An Introduction to Portfolio Maestro, Money Management, and Portfolio Analysis\n 1. Table 9.1 Portfolio Trades without Stops\n 2. Table 9.2 Portfolio Trades with Stops in Place\n\nThe Wiley Trading series features books by traders who have survived the market's ever changing temperament and have prospered\u2014some by reinventing systems, others by getting back to basics. Whether a novice trader, professional, or somewhere in between, these books will provide the advice and strategies needed to prosper today and well into the future. For more on this series, visit our website at www.WileyTrading.com.\n\nFounded in 1807, John Wiley & Sons is the oldest independent publishing company in the United States. With offices in North America, Europe, Australia, and Asia, Wiley is globally committed to developing and marketing print and electronic products and services for our customers' professional and personal knowledge and understanding.\n\n# THE ULTIMATE \nALGORITHMIC \nTRADING SYSTEM \nTOOLBOX \n\\+ Website\n\n## Using Today's Technology to Help \nYou Become a Better Trader\n\n**George Pruitt**\n\nCopyright \u00a9 2016 by George Pruitt. All rights reserved.\n\nPublished by John Wiley & Sons, Inc., Hoboken, New Jersey.\n\nPublished simultaneously in Canada.\n\nNo part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600, or on the Web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at .\n\nLimit of Liability\/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.\n\nFor general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.\n\nWiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at . For more information about Wiley products, visit www.wiley.com.\n\n**_Library of Congress Cataloging-in-Publication Data:_**\n\nNames: Pruitt, George, 1967- author.\n\nTitle: The ultimate algorithmic trading system toolbox + website : using today's technology to help you become a better trader\/George Pruitt.\n\nDescription: Hoboken : Wiley, 2016. | Series: Wiley trading | Includes index.\n\nIdentifiers: LCCN 2016010889 (print) | LCCN 2016011196 (ebook) | ISBN 9781119096573 (hardback) | ISBN 9781119262961 (pdf) | ISBN 9781119262978 (epub)\n\nSubjects: LCSH: Electronic trading of securities. | Investment analysis. | Futures. | BISAC: BUSINESS & ECONOMICS\/Finance.\n\nClassification: LCC HG4515.95 .P788 2016 (print) | LCC HG4515.95 (ebook) | DDC 332.640285\/4678\u2014 dc23\n\nLC record available at \n\nCover Design: Wiley\n\nCover Images: \u00a9 agsandrew\/Shutterstock\n\n# About The Author\n\nIt was March of 1989 as I drove my beat-up Dodge up Hillside Rd. in Hendersonville, NC. In an attempt to pay for my last semesters of college I was answering a classified ad that was looking to hire a computer programmer. As I drove up the thin drive I passed several houses and then through a gate attached to two large stone pillars. I stopped the car and looked down at the ad again to make sure I was at the right place. I proceeded down the country lane and the view opened up into a large meadow. At the end of the lane was a circular drive and large farm house. As I circled and went back down the road I thought to myself I must have the wrong address or directions. So I followed the small road back down the main highway and then to a small convenient store. Once there I asked myself again what type of business was this Futures Truth and if I should call and get directions or just simply forget about it. Curiosity and the need for money were too much so I used the store's pay phone and called the number once again.\n\n\"Hello\u2014Futures Truth, may I help you?\" a lady's voice answered.\n\n\"Yes, this is George Pruitt and I made an appointment for an interview but I can't seem to find your office.\"\n\n\"Do you drive a red Dodge?\" she asked.\n\n\"Yes I do. How did you know?\"\n\n\"We saw you drive right by the office. When you come through the two stone pillars turn immediately to the left. Don't go all the way down the drive\u2014that's the owner's house.\"\n\nSo I follow the directions and find myself in front of a small house. I knock on the door and John Fisher opens and invites me in. We go through the normal Q and A for a job interview and he finally asks if I knew FORTRAN. My first college programming class was FORTRAN so I confidently answered, \"Sure!\"\n\nHe then asked me if I knew anything about the Futures market. I vaguely remembered the term from one of my economics classes and of course from the Eddie Murphy movie and answer him with the question, \"You mean like Trading Places with Eddie Murphy?\"\n\nJohn Fisher said \"Sort of like that\u2014yes.\"\n\nHe went on to explain how Futures Truth tried to determine market direction in the most widely traded futures contracts by using trading systems. The trading systems were programmed in FORTRAN and they needed help with the programming. In addition to trading they also published a newsletter in which they tracked publicly offered trading systems.\n\nI asked, \"Do people really buy these programs?\"\n\nJohn Fisher said yes and by that time an older gentlemen walked into the office and stated that he had spent thousands of dollars on these programs and was ultimately ripped off. John Hill stated this was the main reason he started Futures Truth. He wanted to bring truth to the trading system industry. Both Johns told me that most traders couldn't afford to validate the trading systems because of the cost of the computer equipment, data, and software. John Fisher pointed to the computer he was working on and asked, \"How much do you think this Macintosh II cost?\"\n\nI answered him, \"I am not that familiar with Macs but I know they aren't cheap.\"\n\nMy mouth fell open when he said \"$4,000 and we have three of them.\" Remember this was way back in 1989 when computers were not cheap.\n\nI was thinking to myself that they got ripped off because they could have got a much cheaper and better computer with the IBM PS\/2. And what was up with using FORTRAN? Did they not know \"C\" was the new programming language of the 1990s? John Fisher chose the Apple Macintosh because of its easy-to-use graphical user interface (GUI) and FORTRAN because many traders and hobbyist programmers had knowledge of this language.\n\nJohn Fisher also said that he and John Hill had developed what they considered the best testing platform, \"Excalibur.\" This platform could load decades of daily and intraday data and test any trading idea that could be defined in an algorithmic form. He also said the only thing that was missing was a charting application and that was where they also needed help.\n\nI explained that I would be wrapping up my degree after summer and both Johns agreed that I could work part time in the evening until I graduated and then we could go from there.\n\nWell that was 27 years ago and I did work part time until I graduated with a degree in computer science from the University of North Carolina at Asheville. The \"Excalibur Chart\" project turned into my senior project, which blew my professors away. Over the years I have worked with many trading firms in the development of trading algorithms and testing platforms. I have seen it all and have had the great pleasure to be educated by some of the greatest minds in the industry, including John Fisher, John Hill Sr. and John Hill Jr. Even with this experience and education the ultimate trading system still eludes me. As John Hill has stated many times, \"A speculator who dies rich, dies before his time!\" This may be true, but I have seen traders make millions, lose millions, and make millions again. The one thing they always do when they fail is get right back up, dust themselves off, and start searching for the next great trading algorithm.\n\n# Introduction to The Ultimate Algorithmic Trading Systems ToolBox\n\nIf you want to learn more about high-frequency trading utilizing special order placement\/replacement algorithms such as Predatory trading, Pinging, Point of Presence, or Liquidity Rebates, then this book is not for you. However, if you want to learn about trading algorithms that help make a trading decision, trade size, money management, and the software used to create these algorithms, then you're in the right place.\n\nThis book is designed to teach trading algorithm development, testing, and optimization. Another goal is to expose the reader to multiple testing platforms and programming languages. Don't worry if you don't have a background in programming; this book will provide enough instruction to get you started in developing your own trading systems. Source code and instructions will be provided for TradeStation's EasyLanguage, AmiBroker's AFL, and my own Python and Excel testing engines. I chose these platforms because they give a nice overview of different scripting languages and trading platforms. Users of different testing\/trading platforms may criticize my decision to use just these platforms, but the EasyLanguage source code that will be provided can be easily ported into Multi-Charts, and AmiBroker's unique and powerful platform provides a complete trading solution. My Python and Excel software, including all source code, are included on the associated website as well as the EasyLanguage and AFL source code for the other platforms. I didn't include the use of Python's scientific libraries, NumPy or SciPy, because I wanted to keep things as simple as possible. Also I used the bare-bones IDLE (Python's own simple Integrated Development Environment) to cut down on the learning curve\u2014I wanted to get to the bare essentials of Python without muddying the water with a sophisticated IDE. Many successful Quants utilize **R** (a GNU project for statistical computing), but again to keep things simple I stuck with the easy-to-learn Python. The majority, if not all algorithms were tested utilizing commodity and futures data only. All the testing platforms in the book can be used to test stocks and ETFs, and all the included trading algorithms can be applied to these assets as well. Stock and ETF data is very simple to acquire. Getting commodity and futures data in an easily usable format is a little more difficult. Deep histories for commodity and futures can be acquired for as little as $100 from Pinnacle Data. I have used CSI data since the late 1980s and it is the data I used for a good portion of the testing carried out in the book. I would definitely take a look at Pinnacle and CSI data, especially if you wanted your database updated daily. If you are not familiar with Quandl, then you might want to take the time to do so. Quandl is a search engine for numerical data. I was pleasantly surprised to find a free continuous futures database (Wiki Continuous Futures) on Quandl. Keep in mind this data is free and is no way as good as premium data such as CSI and Pinnalce\u2014it is missing multiple days and data points and the continuous data is simply created by concatenating data from individual contracts. The gaps between contracts are included, which cannot be utilized on any testing platform. In real life, a futures position is \"rolled-over\" from one contract to another by liquidating the front-month position and initiating the same position in the next contract. This \"rollover\" trade eliminates the gap. I have written a Python application that takes the Wiki Futures data and creates a back-adjusted continuous contract that can be imported into the Python and Excel System Back Tester software. Since I needed the data to do testing, I have also included a 10-plus-year ASCII back-adjusted futures database for 30-plus markets on the companion website. Directions on how to use the software and download futures data from Quandl are included along with the software.\n\nThe one thing I really wanted to include in this book was the \"Holy Grail\" of algorithmic trading systems. I have analyzed many algorithms that claimed to be the Grail, but after rigorous testing they failed to break even. So go ahead and check this off your list. Even though the \"Holy Grail\" will remain hidden you will find the following:\n\n * Twenty-seven years of experience working with non-programmers in the development of their own trading algorithms\n * The tools or building blocks that are used most often in the development cycle\n * The core trading models that make up the majority of publicly offered trading systems\n * The most important and simplest programming techniques to transform a non-quant into a not-so-non-quant\n * Simple examples and explanations of complex trading ideas such as Walk Forward and Genetic Optimization and Monte Carlo simulation\n * A complete toolbox to help algorithm development from idea to a finished tradable solution\n\nThe majority of successful trading algorithms utilize quantitative analysis (QA). QA is simply the application of mathematical formulae to a financial time series. This book will solely focus on this type of analysis in the design of trading algorithms. Fundamental analysis, which is used in many trading plans, will be used, too, but it will be reduced and simplified into a pure and easily digestible data format. Fundamental data is huge and diverse and in many cases market movement reacts to it in an unpredictable manner. A good example that I have dealt with for many years is the monthly unemployment report. At the time of the writing of this book unemployment has been on a downward trend, which is usually a bullish indicator for the stock market. However, with interest rates at the time being close to 0% the market could react opposite due to the fear of the Federal Reserve doing away with quantitative easing and raising rates. This type of fundamental analysis requires many different inputs and trying to reduce it down to something testable is nearly impossible.\n\nQuantitative analysis focuses on just the data included in a chart. Price action and price translations are easily definable and therefore can be tested. The ability to test and evaluate a trading algorithm is a tremendous tool as it shows how a model can accurately map a market's behavior. If you can interpret a market's behavior, you can take advantage of its inefficiencies. If an algorithm has been capable of exploiting a market's inefficiencies on a historic basis, then there is a possibility it will do so in the future. This hope of future performance is the only leg an algorithmic trader has to stand upon. We all know historic performance is not necessarily an indicator of future results, but what else do we have? An algorithmic trader who quickly defines and tests his system and immediately takes a leap of faith because the historic performance looks great is doomed. Doesn't this contradict what I just said about historical performance being a system trader's only gauge of quality? A good trading algorithm not only demonstrates profitability but also robustness. Robustness is an expression of how well a trading system performs on diverse markets and diverse market conditions. An algorithm can be improved to a point where the trader can feel somewhat confident putting on those first few trades as well as continuing to put trades on after a losing streak. Improving an algorithm is not simply tweaking it until the historic results look utterly fantastic (aka curve fitting); it is taking the time to learn and work with tools that are designed to make a trading algorithm fail. That's the ultimate objective\u2014making your trading algorithm fail before any money is put on the line. Remember the absence of failure is success and if your algorithm survives the brutal gauntlet of in depth analysis, then you know you might, just _might_ have a winner.\n\nThis book starts out simple in Chapter 1 with the definition and examples of algorithms. The chapter is a little longwinded but I know that the inability to put a trading idea onto paper and then into pseudocode and finally actual computer code is the biggest stumbling block for traders who want to test their own trading ideas. All trading algorithms that are reducible to a set of instructions can be properly programmed using one of two different modeling methods or paradigms. These two paradigms, Finite State Machine and Flow Chart, are fully discussed and utilized to translate written descriptions first into diagrams and then into actual pseudocode. The diagrammatic approach as well as the simple pseudocode language used to formulate trading algorithms is introduced in this chapter. It doesn't matter how sophisticated your testing software is if you can't define a testable algorithm and this chapter shows you how to do so.\n\nChapter 2 may be a refresher for those who are familiar with the basic building blocks of trading algorithms, indicators; however, the chapter not only explains the logic behind the indicators but shows how they can be incorporated into complete entry and exit techniques. Diagrams and pseudocode are carried on through this chapter to aid in the understanding of each indicator, its purpose, and its place in a trading algorithm. In addition, the first look at indicator-based trading algorithm performance is presented as well.\n\nChapter 3 introduces complete trading algorithms and their associated historical performance. Most, if not all, testing was performed on historical commodity\/futures data. This data gave rise to the concept of systematic trading more than 50 years ago. Now this doesn't mean the ideas aren't transferable to the stock market. In most cases they are. However, I stuck with commodity data because that is where my expertise lies. The complete pseudocode and actual computer code of these algorithms are revealed as well. The key metrics for determining algorithm robustness are explained and utilized in the evaluation of the algorithms' results.\n\nChapter 4 starts the section that highlights different testing\/trading software platforms that can either be purchased or leased. AmiBroker is introduced in this chapter and the most important components of a trading platform are highlighted: integrated development environment and its associated scripting\/programming language, individual market and portfolio testing, and algorithm performance metrics. These components are then highlighted again in Chapter 5 with VBA for Excel, Chapter 6 with Python, and finally Chapter 7 with TradeStation.\n\nChapter 8 delves into the concepts of Genetic and Walk Forward Optimization, Walk Forward Analysis, and Monte Carlo simulation. A genetic optimizer is built using VBA and used to help explain the ideas of synthesizing computers with biology. The core concepts of Genetic Algorithms, fitness, selection, reproduction, and mutation are fully explained and illustrated utilizing Excel. Artificial intelligence is here to stay in the study of trading algorithms and this chapter tries to pull back the veil of mystery and show how these tools should be used, and in some cases, must be used to develop that elusive robustness. Along these lines, Machine Learning has become a very highly discussed and somewhat controversial topic in today's trading. Also \"Big Data\" analysis has found its way to the front as well. These topics are highly advanced and I felt beyond the scope of this book. I can state I have worked with the algorithms that were derived with machine-only input and they have stood the test of time.\n\nA trading algorithm must work over a diverse portfolio of markets before it can be sufficiently considered useful and robust. Chapter 9 utilizes the portfolio-level testing capabilities of TradeStation and AmiBroker to demonstrate different money and portfolio management techniques. The Fixed Fractional approach, by far the most popular, will be highlighted.\n\nThe complete source code for the Python System Back Tester is included on the website. Python is the new language of many a quant and the source shows how the language can be used to develop a simple, yet powerful, back tester. Important language concepts and syntax are used to open ASCII files, and import the data into a LIST data structure, create classes and modules, and loop through the entire database while applying a trading algorithm. All the parts of building a testing platform are revealed in the source code, including Monte Carlo and Start Trade Drawdown simulation.\n\nMost traders have Microsoft Excel on their computers and the complete source for a more simplified version of the Python back tester using VBA is included on the website as well.\n\nThis book is a toolbox and a guide and touches upon many different facets of algorithmic trading. As with any toolbox it will take time and effort to apply the tools found within to replicate the trader's ideas in a form that not only can be tested and evaluated but fully implemented.\n\n# Chapter 1 \nIntroduction to Trading \n _Algorithm Development_\n\n## What Is an Algorithm?\n\n> _An Algorithm is an effective procedure, a way of getting something done in a finite number of discrete steps._\n\nDavid Berlinski\n\nBerlinski's definition is exactly right on the money. The word _algorithm_ sounds mysterious as well as intellectual but it's really a fancy name for a recipe. It explains precisely the stuff and steps necessary to accomplish a task. Even though you can perceive an algorithm to be a simple recipe, it must, like all things dealing with computers, follow specific criteria:\n\n 1. _Input_ : There are zero or more quantities that are externally supplied.\n 2. _Output_ : At least one quantity is produced.\n 3. _Definiteness_ : Each instruction must be clear and unambiguous.\n 4. _Finiteness_ : If we trace out the instructions of an algorithm, then for all cases the algorithm will terminate after a finite number of steps.\n 5. _Effectiveness_ : Every instruction must be sufficiently basic that it can in principle be carried out by a person using only pencil and paper. It is not enough that each operation be definite as in (3), but it must also be feasible. [ _Fundamentals of Data Structures_ : Ellis Horowitz and Sartaj Sahni 1976; Computer Science Press]\n\nThese criteria are very precise because they can be universally applied to any type of problem. Don't be turned off thinking this is going to be another computer science text, because even though the criteria of an algorithm seem to be very formal, an algorithm really is straightforward and quite eloquent. It is basically a guide that one must follow to convert a problem into something a computer can solve. Anybody can design an algorithm following these criteria with pencil and paper. The only prerequisite is that you must think like a Vulcan from _Star Trek_. In other words, think in logical terms by breaking ideas down into rudimentary building blocks. This is the first step\u2014translation of idea into an algorithm. It takes practice to do this, and this is in part why programming can be difficult.\n\nAnother thing that makes programming difficult is understanding a computer language's syntax. Most people who have been exposed to a programming or scripting language at one time or another in their lives have probably exclaimed something like, \"I forgot one stupid semicolon and the entire program crashed! Isn't the computer smart enough to know that? _Arrgh!_ I will never be a computer programmer!\" The question that is proffered in this temper tantrum is the question of the computer's intelligence. Computers are not smart\u2014they only do what we tell them. It doesn't matter if you spend $500 or $5,000 on the hardware. They do things very quickly and accurately, but their intelligence is a reflection of their programmer's ability to translate idea into algorithmic form and then into proper syntax.\n\nAlgorithmic (algo) traders don't necessarily need to be programmers, but they must understand what a computer needs to know to carry out a trading signal, position sizing, and money management. If you can create an algorithm, then you are more than 50 percent there. I say more than 50 percent because most traders will utilize trading software and its associated programming or scripting language. Learning the syntax of a scripting language or a small subset of a programming dialect is much easier than learning an entire programming language like C# or C++. An algo trader only needs to be concerned with the necessary tools to carry out a trading system. The developers of EasyLanguage, AmiBroker, or TradersStudio's main objective was to provide only the necessary tools to put a trading idea into action. They accomplished this by creating a vast library of trading functions, easy access to these functions, and a simplified programming syntax. Now if you want to develop your own testing platform and want to use a full-blown programming language to do so, then you will need to know the language inside-out. If you are interested in doing this, chapters 5 and will give you a head start. In these chapters, I show how I developed testing platforms in Python and Microsoft VBA from scratch.\n\nHowever, at this introductory stage, let's take a look at a very simple trading algorithm and the possible exchange between a computer and trader. Pretend a trader wants to develop and test a simple moving-average crossover system and wants to use software specifically designed for system testing. Let's call this first trader AlgoTrader1, and since he has used this particular testing platform he knows it understands a trading vernacular and provides access to the common indicator functions and data. Box 1.1 shows a possible exchange between trader and computer.\n\n* * *\n\n### Box 1.1 Algo Testing Software\n\n AlgoTrader1 \u2013 AlgoTester ON\n Computer \u2013 AlgoTester ready\n AlgoTrader1 \u2013 **load** crude oil futures data\n Computer \u2013 data loaded\n AlgoTrader1 \u2013 **buy** whenever **close** is above **moving average**\n Computer \u2013 \" **moving average** \" function requires three inputs\n AlgoTrader1 - help with **moving average** function\n Computer - function calculates simple, weighted, exponential average\n Computer - function syntax **moving average (type, price, length)**\n AlgoTrader1 - buy whenever **close** is above **moving average (simple,close,21)**\n Computer \u2013 command completed\n AlgoTrader1 \u2013 **short** whenever **close** is below **moving average (simple,close,21)**\n Computer \u2013 command completed\n AlgoTrader1 \u2013 **save** algorithm as **MovAvgCross**\n Computer \u2013 command completed\n AlgoTrader1 \u2013 **run MovAvgCross** algorithm\n Computer \u2013 run completed and results are:\n **$12,040 profit, $8,500 draw down, $1,200 avg. win**\n AlgoTrader1 \u2013 **load** euro currency data\n Computer \u2013 command completed\n AlgoTrader2 \u2013 **run MovAvgCross** algorithm\n Computer \u2013 run completed and results are:\n **-$32,090 profit, $40,000 draw down, $400 avg. win**\n AlgoTrader1 \u2013 **edit** **MovAvgCross** algorithm\n Computer \u2013 command completed\n AlgoTrader2 \u2013 **edit moving average** function\n Computer - command completed\n AlgoTrader2 \u2013 **change** **length input** to 30\n Computer \u2013 command completed\n AlgoTrader2 \u2013 **run MovAvgCross** algorithm\n Computer \u2013 run completed and blah blah blah\n\n* * *\n\nAs you can see, the computer had to be somewhat spoon-fed the instructions. The software recognized many keywords such as: **load** , **buy** , **short** , **run** , **edit** , **change** , and **save**. It also recognized the moving average function and was able to provide information on how to properly use it. The trading algorithm is now stored in the computer's library and will be accessible in the future.\n\nThis simple exchange between computer and AlgoTrader1 doesn't reveal all the computations or processes going on behind the scene. Loading and understanding the data, applying the algorithm properly, keeping track of the trades, and, finally, calculating all of the performance metrics did not involve any interaction with the trader. All this programming was done ahead of time and was hidden from the trader and this allows an algo trader to be creative without being bogged down in all the minutiae of a testing platform.\n\nEven though the computer can do all these things seamlessly it still needed to be told exactly what to do. This scenario is similar to a parent instructing a child on how to do his first long-division problem. A child attempting long division probably knows how to add, subtract, multiply, and divide. However, even with these \"built-in\" tools, a child needs a list of exact instructions to complete a problem. An extended vocabulary or a large library of built-in functions saves a lot of time, but it doesn't necessarily make the computer any smarter. This is an example of knowledge versus intelligence\u2014all the knowledge in the world will not necessarily help solve a complex problem. To make a long story short, think like a computer or child when developing and describing a trading algorithm. Box 1.2 shows an algorithmic representation of the long-division process to illustrate how even a simple process can seem complicated when it is broken down into steps.\n\n* * *\n\n### Box 1.2 Procedure for Long Division\n\n 1. Suppose you are dividing two large numbers in the problem _n_ \u00f7 _m_. In this example, the dividend is _n_ and the divisor is _m_.\n 2. If the divisor is not a whole number, simplify the problem by moving the decimal of the divisor until it is to the right of the last digit. Then, move the decimal of the dividend the same number of places. If you run out of digits in the dividend, add zeroes as placeholders.\n 3. When doing long division, the numbers above and below the tableau should be vertically aligned.\n 4. Now you are ready to divide. Look at the first digit of the dividend. If the divisor can go into that number at least once, write the total number of times it fits completely above the tableau. If the divisor is too big, move to the next digit of the dividend, so you are looking at a two-digit number. Do this until the divisor will go into the dividend at least once. Write the number of times the divisor can go into the dividend above the tableau. This is the first number of your quotient.\n 5. Multiply the divisor by the first number of the quotient and write the product under the dividend, lining the digits up appropriately. Subtract the product from the dividend. Then, bring the next digit from the quotient down to the right of the difference. Determine how many times the divisor can go into that number, and write it above the tableau as the next number of the quotient.\n 6. Repeat this process until there are no fully divisible numbers left. The number remaining at the bottom of the subtraction under the tableau is the remainder. To finish the problem, bring the remainder, _r_ , to the top of the tableau and create a fraction, _r_ \/ _m_.\n\n* * *\n\nA few years ago a client came to me with the following trading system description and hired me to program it. Before reading the description, see if you can see any problems the programmer (me) or a computer might encounter before the directives can be properly carried out.\n\n> Buy when the market closes above the 200-day moving average and then starts to trend downward and the RSI bottoms out below 20 and starts moving up. The sell short side is just the opposite.\n\nDid you see the problems with this description? Try instructing a computer to follow these directions. It doesn't matter if a computer has a vast library of trading functions; it still would not understand these instructions. The good news was, the trader did define two conditions precisely: close greater than 200-day moving average and relative strength index (RSI) below 20. The rest of the instructions were open to interpretation. What does _trending downward_ or _bottoming out_ mean? Humans can interpret this, but the computer has no idea what you are talking about. I was finally able, after a couple of phone calls, to discern enough information from the client to create some pseudocode. _Pseudocode_ is an informal high-level description of the operating principle of a computer program or algorithm. Think of it as the bridge between a native language description and quasi-syntactically correct code that a computer can understand. Translating an idea into pseudocode is like converting a nebulous idea into something with structure. Here is the pseudocode of the client's initial trading idea:\n\n#### _Algorithm Pseudocode_\n\n* * *\n\n if close > 200 day moving average and\n close < close[1] and close [1] < close [2] and\n close[2] < close[3] and yesterday's 14 day RSI < 20 and\n yesterday's 14 day RSI < today's 14 day RSI then **BUY**\n\n* * *\n\nIf this looks like Latin (and you don't know Latin), don't worry about it. The 1] in the code just represents the number of bars back. So close [2] represents the close price prior to yesterday. If you are not familiar with RSI, you will be after [Chapter 2. By the time you are through with this book you will be able to translate this into English, Python, EasyLanguage, AmiBroker, or Excel VBA. Here it is in English.\n\n> If today's close is greater than the 200-day moving average of closing prices and today's close is less than yesterday's close and yesterday's close is less than the prior day's close and the prior day's close is less than the day before that and the 14-day RSI of yesterday is less than 20 and the 14-day RSI of yesterday is less than the 14-day RSI of today, then buy at the market.\n\nNotice how the words _downward_ and _bottoming out_ were removed and replaced with exact descriptions:\n\n 1. **downward** : today's close is less than yesterday's close and yesterday's close is less than the prior day's close and the prior day's close is less than the day before. The market has closed down for three straight days.\n 2. **bottoming out** : the 14-day RSI of yesterday is less than 20 and the 14-day RSI of yesterday is less than the 14-day RSI of today. The RSI value ticked below 20 and then ticked up.\n\nAlso notice how the new description of the trading system is much longer than the original. This is a normal occurrence of the evolution of idea into an exact trading algorithm.\n\nAnd now here it is in the Python programming language:\n\n#### _Actual Python Code_\n\n* * *\n\n if myClose[D0] < sAverage(myClose,200,D0,1) and myClose[D0] < myClose[D1] and myClose[D2] < myClose[D3] and myClose[D1] < myClose[D2] and rsiVal[D1] < 20 and rsiVal[D1] < rsiVal[D0]:\n buyEntryName = 'rsiBuy'\n entryPrice = myOpen\n\n* * *\n\nDon't get bogged down trying to understand exactly what is going on; just notice the similarity between pseudo and actual code. Now this is something the computer can sink its teeth into. Unfortunately, reducing a trading idea down to pseudocode is as difficult as programming it into a testing platform. The transformation from a trader to an algo trader is very difficult and in some cases cannot be accomplished. I have worked with many clients who simply could not reduce what they saw on a chart into concise step-by-step instructions. In other cases the reduction of a trading idea removes enough of the trader's nuances that it turned something that seemed plausible into something that wasn't.\n\nIt goes without saying that if you don't have an algorithm, then all the software in the world will not make you a systematic trader. Either you have to design your own or you have to purchase somebody else's. Buying another person's technology is not a bad way to go, but unless the algorithm is fully disclosed you will not learn anything. However, you will be systematic trader. I have spent 27 years evaluating trading systems and have come across good and bad and really bad technology. I can say without a doubt that one single type of algorithm does not stand head and shoulders above all the others. I can also say without a doubt there isn't a correlation between the price of a trading system and its future profitability. The description in Box 1.3 is very similar to a system that sold for over $10,000 in the 1990s.\n\n* * *\n\n### Box 1.3 Trading Algorithm Similar to One That Sold for $10K in the 1990s Description\n\n#### Entry Logic:\n\nIf the 13-day moving average of closes > the 65-day moving average of closes and the 13-day moving average is rising and the 65-day moving average is rising then buy the next day's open\n\nIf the 13-day moving average of closes < the 65-day moving average of closes and the 13-day moving average is falling and the 65-day moving average is falling then sell the next day's open\n\n#### Exit Logic:\n\n 1. If in a long position then \n 1. set initial stop at the lowest low of the past 13 days\n 2. If in a short position then \n 1. set initial stop at the highest high of the past 13 days\n 3. Once profit exceeds or matches $700 pull stops to break even\n 4. If in a long position use the greater of: \n 1. Breakeven stop\u2014if applicable\n 2. Initial stop\n 3. Lowest low of a moving window of the past 23 days\n 5. If in a short position use the lesser of: \n 1. Breakeven stop\u2014if applicable\n 2. Initial stop\n 3. Highest high of the moving window of the past 23 days\n\n* * *\n\nThat is the entire system, and it did in fact sell for more than $10K. This boils down to a simple moving-average crossover system trading in the direction of the shorter- and longer-term trend. The description also includes a complete set of trade management rules: protective, breakeven, and trailing stop. This is a complete trading system description, but as thorough as it seems there are a couple of problems. The first is easy to fix because it involves syntax but the second involves logic. There are two words that describe market direction that cannot be interpreted by a computer. Do you see them? The two words in question are: _rising_ and _falling_. Again, descriptive words like these have to be precisely defined. This initial problem is easy to fix\u2014just inform the computer the exact meaning of _rising_ and _falling_. Second, it has a weakness from a logical standpoint. The algorithm uses $700 as the profit level before the stop can be moved to break even. Seven hundred dollars in the 1990s is quite a bit different than it is today. The robustness of this logic could be dramatically improved by using a market-derived parameter. One could use a volatility measure like the average range of the past N-days. If the market exhibits a high level of volatility, then the profit objective is larger and the breakeven stop will take longer to get activated. You may ask, \"Why is this beneficial?\" Market noise is considered the same as volatility, and the more noise, the higher likelihood of wide market swings. If trading in this environment, you want to make sure you adjust your entries and exits so you stay outside the noise bands.\n\nThis algorithm was very successful in the 1980s and through a good portion the 1990s. However, its success has been hit-and-miss since. Is this algorithm worth $10K? If you were sitting back in 1993 and looked at the historical equity curve, you might say yes. With a testing platform, we can walk forward the algorithm, and apply it to the most recent data and see how it would have performed and then answer the question. This test was done and the answer came out to be an emphatic _no!_\n\nHad you bought this system and stuck with it through the steep drawdowns that have occurred since the 1990s, you would have eventually made back your investment (although not many people would have stuck with it). And you would have learned the secret behind the system. Once the secret was revealed and your checking account was down the $10K, you might have been a little disappointed knowing that basic tenets of the system had been around for many years and freely disseminated in books and trade journals of that era. The system may not be all that great, but the structure of the algorithm is very clean and accomplishes the tasks necessary for a complete trading system.\n\nThe most time-consuming aspect when developing a complete trading idea is coming up with the trade entry. This seems somewhat like backward thinking because it's the exit that determines the success of the entry. Nonetheless, the lion's share of focus has always been on the entry. This system provides a very succinct trade entry algorithm. If you want to develop your own trading algorithm, then you must also provide the computer with logic just as precise and easy to interpret. Getting from the nebula of a trading idea to this point is not easy, but it is absolutely necessary. On past projects, I have provided the template shown in Box 1.4 to clients to help them write their own entry rules in a more easily understood form. You can download this form and a similar exit template at this book's companion website:www.wiley.com\/go\/ultimatealgotoolbox.\n\n* * *\n\n### Box 1.4 Simple Template for Entry Rules\n\n#### Long \/ Short Entries\n\nCalculations and\/or Indicators Involved (specify lookback period). Don't use ambiguously descriptive words like _rising_ , _falling_ , _flattening_ , _topping_ or _bottoming out_.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\nBuy Condition\u2014What must happen for a long signal to be issued? List steps in chronological order. And remember, don't use ambiguously descriptive words like _rising_ , _falling_ , _flattening_ , _topping_ , or _bottoming out_.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\nSell Condition\u2014What must happen for a short signal to be issued? List steps in chronological order.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\nHere is one of the templates filled out by a one-time client:\n\n 1. Calculations and\/or Indicators Involved (specify lookback period) \n 1. Bollinger Band with a 50-day lookback\n 2. Buy Condition\u2014What must happen for a long signal to be issued? List steps in chronological order. \n 1. Close of yesterday is above 50-day upper Bollinger Band\n 2. Today's close < yesterday's close\n 3. Buy next morning's open\n 3. Sell Condition\u2014What must happen for a short signal to be issued? List steps in chronological order. \n 1. Close of yesterday is below 50-day lower Bollinger Band\n 2. Today's close > yesterday's close\n 3. Sell next morning's open\n\n* * *\n\nThe simple Bollinger Band system shown in Box 1.4 is seeking to buy after the upper Bollinger Band penetration is followed by a down close. The conditions must occur within one daily bar of each other. In other words, things must happen consecutively: the close of yesterday is > upper Bollinger Band and close of today < yesterday's close. The sell side of things uses just the opposite logic. The template for exiting a trade is very similar to that of entering. Box 1.5 contains a simple template for exit rules and shows what the client from Box 1.4 had completed for his strategy.\n\n* * *\n\n### Box 1.5 Simple Template for Exit Rules\n\n#### Exits\n\nCalculations and\/or Indicators Involved (specify lookback period). Don't use ambiguously descriptive words like _rising_ , _falling_ , _flattening_ , _topping_ , or _bottoming out_.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\nLong Liquidation Condition\u2014What must happen to get out of a long position? List steps in chronological order.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\nShort Liquidation Condition\u2014What must happen to get out of a short position? List steps in chronological order.\n\n___________________________________________________\n\n___________________________________________________\n\n___________________________________________________\n\n 1. Calculations and\/or Indicators Involved (specify lookback period) \n 1. Average true range (ATR) with a 10-day lookback\n 2. Moving average with a 50-day lookback\n 2. Long Liquidation Condition\u2014What must happen to get out of a long position? List steps in chronological order. \n 1. Close of yesterday is less than entry price \u22123 ATR\u2014get out on next open\n 2. Close of yesterday is less than 50-day moving average\u2014get out on next open\n 3. Close of yesterday is greater than entry price +5 ATR\u2014get out on next open\n 3. Short Liquidation Condition\u2014What must happen to get out of a short position? List steps in chronological order. \n 1. Close of yesterday is greater than entry price +3 ATR\u2014get out on next open\n 2. Close of yesterday is greater than 50-day moving average\u2014get out on next open\n 3. Close of yesterday is less than entry price \u22125 ATR\u2014get out on next open\n\n* * *\n\nThere are three conditions that can get you out of a long position. Unlike the entry logic, the timing or sequence of the conditions do not matter. The exit algorithm gets you out on a volatility-based loss, a moving average\u2013based loss\/win, or a profit objective. The short liquidation criteria are just the opposite of the long liquidation criteria.\n\nThis is a complete, fully self-contained trend-following trading algorithm. It has everything the computer would need to execute the entries and exits. And it could be made fully automated; the computer could analyze the data and autoexecute the trading orders. Any platform such as AmiBroker, TradeStation, Ninja Trader, and even Excel could be used to autotrade this type of system. Any trading idea, if reduced to the exact steps, can be tested, evaluated, and autotraded. Once the programming code has been optimized, verified, validated, and installed on a trading platform, the trader can just let the system run hands off. This is the true beauty of algorithmic system trading: A computer can replicate a trader's ideas and follow them without any type of human emotion.\n\n## How to Get My Trading Idea into Pseudocode\n\nThe aforementioned template is a great way to get your ideas into written instructions. However, just like with great writing, it will take many revisions before you get to the pseudocode step. Over the years, I have discovered there are two different paradigms when describing or programming a trading system. The first is the easier to program and can be used to describe a system where events occur on a consecutive bar basis. For example: _Buy when today's close is greater than yesterday's and today's high is greater than yesterday's high and today's low is less than yesterday's low_. The other paradigm can be used to describe a trading system that needs things to happen in a sequence but not necessarily on a consecutive bar-by-bar basis. Unfortunately, the latter paradigm requires a heightened level of description and is more difficult to program. Many trading systems can fit inside a cookie-cutter design, but most traders are very creative, and so are their designs. Don't fret, though, because any idea that is reducible to a sequence of steps can be described and programmed.\n\n### The Tale of Two Paradigms\n\nI have developed names for these two different models of describing\/programming trading algorithms:\n\n 1. The variable bar liberal sequence paradigm\n 2. The consecutive bar exact sequence paradigm\n\nThe variable bar paradigm can provide a very robust algorithm and at the same time provide a nearly limitless expression of a trader's creativity. We will begin with this one since it is the less intuitive of the two. What you learn about the variable bar sequence will make shifting to the simpler consecutive bar sequence that much easier. The consecutive bar sequence can usually be programmed by using a single if-then construct. You can see this by referring to my earlier example:\n\n> **If** today's close is greater than yesterday's close and today's high is greater than yesterday's high and today's low is less than yesterday's low, **then** buy at the market.\n\nThis paradigm is simple to explain, program, and deploy. There is nothing wrong with this and, remember, many times a simple approach or idea to trading the markets can deliver a very robust algorithm. Both paradigms will be exemplified in different algorithms through the rest of the book. All trading algorithms fall into either paradigm or across both, meaning that some systems require both approaches to be fully described and programmed. Most traders can easily describe and probably program a consecutive bar-type algorithm. However, traders that can't put their ideas into such a simple form and have had little or no programming experience have a more difficult time reducing their ideas into a formal description, not to mention pseudocode.\n\n#### The Variable Bar Sequence\n\nJumping headfirst into paradigm #1, the variable bar sequence, here is a somewhat creative design that incorporates pivot points and a sequence that can occur over a variable amount of days. For those of you who are not familiar with pivot points, Figure 1.1 shows different examples of pivot high points on daily bars and their differing strengths.\n\n**Figure 1.1** Examples of strength differences between pivot high points on daily bars.\n\nThe strength of the pivot bar is based on the number of bars preceding and following the high bar. A two-bar pivot is simply a high bar with two bars before and after that have lower highs. The preceding\/following highs do not necessarily have to be in a stairstep fashion. Here is our long entry signal description using step-by-step instructions.\n\n**Buy:**\n\n 1. **Step 1:** Wait for a pivot high bar of strength 1 to appear on the chart and mark the high price.\n 2. **Step 2:** Wait for the first low price that is 2 percent lower than the high price marked in Step 1. If one occurs, move to Step 3. If the market moves above the high marked in Step 1, then go back to Step 1 and wait for another pivot high bar.\n 3. **Step 3:** Wait for another pivot high bar that exceeds the price in Step 1. Once a high bar pivot occurs that fits the criteria, mark the high price.\n 4. **Step 4:** Once the subsequent pivot high bar is found, then wait for another low price that is 2 percent below the high marked in Step 3. When a bar's low price fulfills the criteria buy that bar's close. If the market moves above the high marked in Step 3, then go back to Step 3 and wait for another pivot high bar. The new high that just occurred may turn out to be the pivot high bar that you are looking for in Step 3.\n\nAdditional notes: If 30 days transpire before proceeding from Step 1 to Step 4, then reset.\n\nFigure 1.2 illustrates the sequence the above description is trying to capture. Ignore the state designations for now. They will become apparent in the following discussion.\n\n**Figure 1.2** A depiction of the variable-bar sequence described by the long entry signal.\n\nIt is easy to see the designer\/trader of this entry signal is trying to buy after two pivot highs are separated and followed by a pullback of 2 percent. In addition, there are a couple of conditions that must also be met before a buy signal is triggered: (1) the second pivot high price must be higher than the first, and (2) the whole sequence must take less than 30 bars to complete. When a system allows its entry criteria to work across an unknown number of days or price levels, conditions must be used to keep the integrity of the entry signal and limit the duration of the sequence.\n\nSince there is variability in the instruction set, the programming of this paradigm is definitely more difficult. However, as mentioned earlier, it is very doable. As a young and inexperienced trading system programmer, I tried to program these variable sequences using a bunch of true\/false Boolean flags. Box 1.6 shows an initial attempt using this method to describe the pivot point sequence. The flags are bolded so you can easily see how they are turned on and off. Comments are enclosed in brackets { }.\n\n* * *\n\n### Box 1.6 Using Boolean Flags to Program a Trading Algorithm\n\n HighPivotFound = High of yesterday > High of today and High of yesterday > High of two days ago\n If **HPivot1** = False and HighPivotFound then {first Pivot high found}\n\n 1. **HPivot1** = True\n HPivot1Price = high of yesterday\n HPivot1Cnt = currentBar\n\n If **HPivot1** = True and Low < HPivot1Price * 0.98 then {2% retracement after first Pivot high}\n\n 1. **LRetrace** = True\n\n If **HPivot1** = True and **LRetrace** = False and High of today > HighPivot1Price then\n\n 1. HPivot1Price = High of yesterday {another higher high but not a 2% retracement \u2013 start over}\n HPivot1Cnt = currentBar\n\n If **LRetrace** = True and HighPivotFound and High of yesterday > HPivot1Price then\n\n 1. **HPivot2** = True {second Pivot high > first Pivot high and 2% retracement between the two}\n HPivot2Price = High of yesterday\n\n If **HPivot2** = True and High of today > HPivot2Price then\n\n 1. HPivot2Price = High of today {another higher high > second Pivot High \u2013 keep track of it}\n\n If **HPivot2** = True and Low < HPivot2Price * 0.98 then\n\n 1. Buy this bar on close {Buy Order Placed \u2013 entry criteria has been met}\n **HPivot1** = False {Start Over}\n **LRetrace** = False\n **HPivot2** = False\n\n HPivot1Cnt = HPivot1Cnt + 1\n If HPivot1Cnt >= 30 then {reset all Boolean flags \u2013 start over}\n\n 1. **HPivot1** = False\n **LRetrace** = False\n **HPivot2** = False\n\n* * *\n\nAs you can see, the description using these flags is somewhat laborious and not that flexible. The flags have to have descriptive names so that the correct flag is being tested and subsequently turned on or off. In addition, all flags must eventually be turned off when either the HPivot1Cnt variable grows equal to or greater than 30 or a LONG position is established. This type of programming will work but isn't very eloquent. Good programmers don't like to use superfluous variable names and many lines of code to complete a task. And really good programmers like for others to easily read their code and comment on how clever the solution was to the problem. Eloquent code is precise and clever. So, after much trial and error as a young programmer, I finally realized that these types of trading algorithms (the paradigm #1 variety) were simply looking for an occurrence of a certain sequence or pattern in the data. When I say pattern, I don't mean a certain price pattern like a candlestick formation. As we have seen before, a trading algorithm is just a sequence of instructions. Remembering back to my compiler design class in college and how we had to write computer code to recognize certain tokens or words (patterns) in a string of characters I felt I could use the same model to program these types of systems, a universal model that could be molded to fit any trading system criteria. This model that programmers use to parse certain words from a large file of words is known as a finite state machine (FSM). The FSM concept is not as daunting as it sounds. If we translate the geek-speak, a FSM is simply a model of a system that shows the different possible states a system can reach and the transitions that move the system from one state to another. The machine starts at a START state and then moves methodically through several states by passing certain logical criteria and then arrives at an ACCEPT state.\n\nDon't let this idea blow your mind because it is quite easy to understand and implement. Let's start off with a very simple FSM to illustrate its simplicity and eloquence. Think of a combination lock that can only be unlocked by inputting the following numbers: 6, 4, 2, 7, 5, and 1. Like most combination locks the numbers need to be inputted in the exact sequence described or the lock will not open. This lock is not very good because it lets you test to see if you have the right number before proceeding to the next input. So you plug in a number, test it, and either try again if it fails or move onto the next number if it is correct. Eventually, with time the correct combination will be inputted and the lock will open. Remember this is just a very simple example of something that can be modeled by a FSM. Without an illustration or diagram, most nonprogrammers could not design even this simple example. A picture is always worth a minimum of a thousand words and the easiest way to create an appropriate FSM is to create a diagram. The diagram in Figure 1.3 describes the FSM that models the combination lock.\n\n**Figure 1.3** An FSM that models the workings of a combination lock.\n\nThe diagram is made up of circles, which represent the different **STATES** and connectors that show how the machine moves from one state to another. This FSM has a total of seven states that include a **START** and **ACCEPT** state. Pretend you are sitting in front of a small screen and a numeric touchpad similar to one that is found on a cell phone, and it is prompting you to input a number from one to nine. At this point, the machine is set to the START state. If you get lucky right off the bat, you input the number six and the screen prompts you to input the second number. If you aren't lucky, it will ask you to re-input the first number in the combination. So following along with the diagram, you can see how the number six moves the machine from the START state to STATE 1. If the number six is not inputted, it moves right back to the START state. The machine moves along the paths visiting each STATE as long as the proper number is inputted. Notice you are not penalized if you don't input the proper number; the machine just sits in that particular state until the proper number is inputted.\n\nIn our pivot point example, there will also be a START and ACCEPT state. Refer back to the step-by-step instructions of the pivot point entry technique and visualize the steps as different states. The START (STEP 1) state will be assigned the value 0 and the ACCEPT (STEP 4) state will have the value 4. In between, the START and ACCEPT states will be three other states that the FSM can assume. These are intermediate states that must be achieved in sequential order. The START state tries to get the ball rolling and looks at every bar to see if a pivot high (of strength 1) has occurred. If one does, then the machine moves onto the next state, and then on to the next, and then on to the next, and then finally to the ACCEPT state. As soon as the FSM assumes the ACCEPT state, a buy order is placed at the market. The illustration in Figure 1.4 is the FSM diagram of our pivot-point long-entry algorithm.\n\n**Figure 1.4** An FSM that models the pivot-point long-entry algorithm described in this chapter.\n\nThis FSM diagram looks to be much more complicated than the combination lock, but it really isn't. There are fewer states but many more connectors. In the combination lock FSM there was only one connector connecting the different states together and the machine never went backward. Once a state was attained, the machine stayed there until the criteria were met to advance to the next state. This pivot-point FSM can move forward and backward.\n\nStepping through this diagram will help make it less scary. Keep in mind that all of these machines gobble up one bar at a time and then make a decision. Starting at the START state the machine looks for a pivot high of strength one. Once the machine finds this pivot point it then moves to STATE1 and starts looking for a low price that is 2 percent or less than the pivot high found in the START state. There are four paths out of STATE1: (1) a low is found that fits the criteria, (2) a low price fitting the criteria is not found, stay in STATE1, (3) 30 bars have occurred since the pivot high is found, and (4) a high exceeds the pivot high price. Only one path leads to STATE2. All other paths either return to the START state or loop back to the current state. Once the machine attains STATE2 it starts analyzing the data by gobbling each bar and searches for a higher pivot high point. Unlike STATE1 there are only three paths coming out of this state: (1) a higher pivot high is found, (2) a higher pivot high is not found, and (3) 30 bars have occurred since the pivot high was found in the START state. There is only one path to STATE3 and that is a higher pivot high. All other paths either loop or return the machine to the START state. Assuming a higher pivot high is found the machine moves to STATE3. Once in STATE3 the machine will only return to the START state if 30 bars have come and gone before the machine can attain the ACCEPT state. If new highs are found, the machine continues to stay in STATE3 and keeps track of the new highs, all the while looking for that particular low that is 2 percent or lower than the most recent pivot high. Eventually things fall into place and the machine attains the ACCEPT state and a buy order is placed. You can now refer back to Figure 1.2 and see when the machine attains the various states.\n\nThe diagram in Figure 1.4 looks clean and neat, but that's not how it started out. When I diagram a trading algorithm, I use pen\/pencil and paper. A pencil is great if you don't want to waste a lot of paper. Also, you don't have to have a complete diagram to move onto the pseudocode step. Trust me when I say a diagram can help immensely. Something that seems impossible to program can be conquered by drawing a picture and providing as much detail on the picture as possible. Box 1.7 contains the pseudocode for the pivot point entry algorithm using the FSM diagram.\n\n* * *\n\n### Box 1.7 Pivot Point Entry Algorithm for Figure 1.4\n\n If initialize then\n State = Start\n HiPivotFound = High of yesterday > High of today and\n High of yesterday > High of prior day\n If State = Start and HiPivotFound then\n State = 1\n BarCount = 1\n Pivot1Hi = High price of HiPivotFound\n If State <> Start then BarCount = BarCount + 1\n If State = 1 then\n If Low of today < Pivot1Hi * 0.98 then\n State = 2\n If High of today > Pivot1Hi then\n State = Start\n If State = 2 then\n If HiPivotFound then\n Pivot2Hi = High Price of HiPivotFound\n If Pivot2Hi > Pivot1Hi then\n State = 3\n If State = 3 then\n If Low of today < Pivot2Hi * 0.98 then\n State = Accept\n If High of today > Pivot2Hi then\n Pivot2Hi = High of today\n If State = Accept then\n Buy this market on close\n State = Start {start over}\n If BarCount = 30 then\n State = Start\n BarCount = 0\n\n* * *\n\nYou might understand this code or you may not. If you have never programmed or scripted, then you might have a problem with this. If you fully understand what is going on here, just bear with us a few moments. Even if you understood the diagram, this code may not be fully self-explanatory. The reason you may not understand this is because you don't know the _syntax_ or the _semantics_ of this particular language. Syntax was discussed earlier in this chapter, and remember, it's just the structure of the language. I tried my best to utilize a very generic pseudocode language for all the examples throughout the book and hopefully this will help with its understanding. In the pseudocode example, the language uses _if_ s and _then_ s to make yes-or-no decisions. If something is true, then do something, or if something is false, then do something. These decisions divert the flow of the computer's execution. The code that is indented below the if-then structure is controlled by the decision. This structure is the syntax. Now the logic that is used to make the decision and then what is carried out after the decision is the semantics. In our example, we will eventually tell the computer that if State = 1, then do something. Syntax is the grammatical structure of a language and semantics is the meaning of the vocabulary of symbols arranged within that structure. You many notice the similarity in the pseudocode and the FSM diagram. The logic that transitions the pivot point FSM from one **state** to another is mirrored almost exactly in the code. This tells you the time you spent planning out your program diagram is time well spent. So let's start with the pseudocode and make sure the FSM diagram is fully implemented.\n\nThe START state is simply looking for a pivot point high of strength 1. When one occurs the machine then shifts gears and enters STATE1. Once we have entered the STATE1 phase, the machine stays there until one of three criteria is met: (1) the elusive low that is 2 percent or lower than the Pivot1Hi, (2) a high price that exceeds the Pivot1Hi, or (3) 30 bars transpire prior to attaining the ACCEPT state. If you look at the STATE1 block of code, you will only see the logic for the first two criteria. You may ask where is the logic that kicks the machine back to the START state once 30 bars have been completed prior to the ACCEPT state. If you look further down in the code, you will see the block of code that keeps track of the BarCount. If at any time the BarCount exceeds 30 and the machine is not in the START state, the machine is automatically reset to the START state. If a low price is observed that is lower than 2 percent of the Pivot1Hi price, then the machine transitions to STATE2. However, if a high price is observed that exceeds Pivot1Hi, then the machine reverses back to the START state and it once again starts looking for a new PivotHi. Assuming the machine does make it to STATE2, it then starts looking for another PivotHi price that is greater than Pivot1Hi. A transition from STATE2 can only occur when one of two criteria are met: (1) BarCount exceeds 30, then it's back to the START state, or (2) a higher HiPivot than Pivot1Hi is observed. If the latter criterion is fulfilled, then it is onto STATE3. STATE3 looks for a low price that is 2 percent less than the Pivot2Hi price so it can transition to the ACCEPT state. At this point the BarCount is its only enemy. It doesn't care if a high price exceeds the Pivot2Hi. If it does, then it simply replaces the Pivot2Hi with this price and continues searching for a price that is 2 percent lower than Pivot2Hi. Eventually, the machine resets itself or it finally transitions to the ACCEPT state and buys market on close (MOC).\n\nAs you can see, the description of the FSM diagram is all almost completely repeated in the description of the pseudocode. If the two descriptions agree, then it is on to the actual programming of the algorithm. Now that this more complicated paradigm has been explained, I think it is time to give it a better name. How about the _FSM paradigm_? Sounds better than _the variable bar liberal sequence paradigm_ , doesn't it?\n\n#### _The Consecutive Bar Sequence_\n\nI saved _the consecutive bar exact sequence paradigm_ for the end because the FSM paradigm is much more difficult to understand and much less intuitive. Armed with our new knowledge of diagrams, it is now time to move to this simpler paradigm because it will be used a lot more in your programming\/testing of trading algorithms. As I stated before, most trading algorithms will be fully describable in a step-by-step fashion. Here the logic will not be needed to be modeled by a machine; a recipe approach will do just fine. Guess what type of diagram is used to model these recipe types of instructions. If you guessed a flowchart (FC), then pat yourself on the back. A good computer programming 101 instructor introduces her students to the flowchart concept\/diagram way before they even sit down in front of a keyboard. Figure 1.5 shows a very simple FC.\n\n**Figure 1.5** A very simple FC.\n\nCan you see what is being modeled there? It's quite simple; the FC diagram starts at the top and makes one decision and, based on that decision, it carries out its objective. It starts out with you waking up and observing the time and making a decision to take the bus or the subway. This is a way oversimplified example, but it covers everything an FC is designed to do: start, make decisions, carry out the appropriate instructions based on the decisions, and then finish. Figure 1.6 shows an ever so slightly more complicated FC that deals with what this book is all about, a trading algorithm.\n\n**Figure 1.6** An FC of a trading algorithm.\n\nThis diagram is a flowchart of the entry technique of a very popular mean reversion trading system. This system trades in the direction of the long-term trend after a price pullback. The trend is reflected by the relationship of the closing price and its associated 200-day moving average. If the close is greater than the average, then the trend is up. The pullback is reflected by the 14-period RSI indicator entering into oversold territory\u2014in this case, a reading of 20 or less. The diagram illustrates two decisions or tests and, if both tests are passed, then the system enters a long position on an MOC order. The flow of the algorithm is linear, meaning it flows from top to bottom. The flow is diverted based on simple decisions, but it always ends at the bottom of the flowchart\u2014either buying MOC or starting on a new bar of data. Here is the pseudocode of this mean reverting system; look quickly or you will miss it:\n\n* * *\n\n 'Simple FC type trading algorithm\n 'An example of a mean reversion system\n If Close of today > 200 day average of Close then\n If RSI(14) < 20 then\n Buy MOC\n\n* * *\n\nThat's the entire entry technique, in a nutshell. Was it necessary to create a flowchart diagram? In this case, no. But as you will find out in later chapters, most trading algorithms are not this easily definable.\n\n## Summary\n\nIn this chapter, the necessary tools for creating a trading algorithm were introduced. Describing your ideas on paper (real or virtual) is the very first step in the algorithm development process. A template was shown that can be used to help facilitate this. Just getting a trading idea on paper is not sufficient to move onto the pseudocode phase. All ideas must be translated into mathematical expressions and Boolean logic. These expressions and logic must be in a form a computer can understand. Ambiguous directions must be eliminated and replaced with pure logic. Once the idea is written down and further reduced into an extremely logical list of directives and calculations or formulae, the trader must then decide what type of paradigm to use to get the logic into something that can be eventually programmed or scripted. The FSM, as well as the FC methods, were both introduced and used to convert trading schemes into complete pseudocodes. These two paradigms have always been present, and many algorithmic traders have used them without realizing the different programming methods. With knowledge of the two different methods, hopefully an algorithmic trader can make a choice on which is best to use and get from idea to actual code in a lot less time and a lot less frustration.\n\nHere again is a summary of the two methods:\n\n * **Flowchart** : The \"flow\" of a flowchart is a process. The flowchart shows the steps and actions to achieve a certain goal. Use this method if you can define your trading logic in a step-by-step or bar-by-bar basis. A large portion of trading systems will fit into this programming paradigm.\n * **Finite state machine** : The \"flow\" in a state diagram is always from state to state. Most FSMs have a START and ACCEPT state, similar to the beginning and end of a flowchart. Machine diagrams describe a closed system composed of multiple discrete states. The \"state\" in this case determines how a system behaves to stimulus or events. Use this method if criteria have to be met in a sequential manner, but the amount of time between the beginning and criteria completion is variable. Pattern-based systems will usually fall into this paradigm.\n\nOnce a potential programming method is chosen, it is time to \"draw\" the corresponding diagram. A diagram doesn't have to be pretty, but it must try to cover all the bases or what-if scenarios a trading system may encounter to carry out its objectives. A thoroughly thought-out diagram providing as much information as possible will definitely enable a trading algorithm to be quickly translated into pseudocode and eventually programmed into a testing platform. Over time, as your experience grows with programming trading systems, these diagrams will begin to appear in your mind's eye. However, this takes time and a lot of experience.\n\nIf you made it through this chapter, then, at least, you are now in possession of a trading algorithm that is quite similar to one that actually sold for thousands of dollars in the 1990s.\n\n# Chapter 2 \nStochastics and Averages and RSI! Oh, My!\n\nIndicators and price bar patterns are the most widely used building blocks of trading algorithms. Of the many trading systems I have programmed over the years, at least 90 percent utilized an indicator either straight out of the box or customized in some form or fashion. The trading community is split right down the middle when it comes to the perceived effectiveness of these price transformations. An indicator is simply a price transformation; price is transformed or changed into something that is thought to be more illustrative of the current market condition. There have already been many articles and books written about most indicators. And it is true that these indicators do not work all of the time as standalone signal generators. It is also true that there is redundancy among many of the different indicators. However, I want to discuss the mathematically simple indicators that are easily implemented into a trading algorithm and when used in concert with other ideas can produce a slight technical advantage.\n\nIndicators fall into basically two categories, _oscillator_ (usually predictive) and _price based_ (lagging). Oscillators are depicted on charts that plot a value that is banded by two extremes. This information is most commonly used for short-term forecasting, but it can also reveal longer term market behavior. Price-based indicators are displayed on charts as a real price of the underlying instrument and are used to determine trend and\/or volatility. These indicators are reporting back what is currently going on after the fact, hence the term _lagging_.\n\n## Oscillators\n\nOscillators are normalized, in most cases, to fall between two extreme levels, and are usually plotted in a subgraph. Certain indicator-based levels are then superimposed on the oscillators as benchmarks. The relationships of oscillator value and the benchmarks are then used to predict short-term market direction. The normalization process allows the oscillator family of indicators to be universally applicable to all markets. Oscillators are most often used to predict but can also be used as lagging indicators.\n\n### Average Directional Movement Index (ADX)\n\nThis oscillating indicator is one of the more popular as it measures a market's trendiness. The underlying concept of _Directional Movement_ was introduced in J. Welles Wilder's 1978 book, _New Concepts in Technical Trading Systems_. As a side note, this was the book I first used to help program many of the more popular indicators into our Excalibur software in the late 1980s. Many algorithmic traders are trend followers, even though it is been proven that markets only trend a very small portion of time.\n\nIf this is the case, then why do many traders claim that \"the trend is your friend\"? Trend followers hope that by diversifying across many markets, they will hit upon one or two markets that sufficiently trend enough that they can negate all of the other losing markets and still make enough money to provide a profitable year. While trend followers tread water by capturing a few trends a year, they are constantly waiting and hoping they will be poised for that once-in-a-lifetime trend event. These once-in-a-lifetime trend events do happen more frequently than once in a lifetime, and most trend-following algorithms are more than capable of catching and holding on for the long haul.\n\nThe realization that commodities are limited resources and the fact that trend following has had success in the past has promoted this trading algorithm class as the most widely used in the managed futures arena. However, commodity markets over the past few years have been unkind to trend following, and if this \"trend\" continues, then you might see a gradual exodus of these types of traders. Stock traders, as of the writing of this book, have been riding a bull trend for several years, which has bolstered the buy-and-hold mentality. I guess the phrase about the trend could be changed to, \"The trend is rarely your friend, but it's the only friend in town.\"\n\nThe main weakness of trend following is, of course, whipsaw trades\u2014the ones you get into and very quickly get stopped out or, worse in some cases, reversed. Another common weakness is lack of profit retention when the ride is over. The ADX indicator is here to save the day\u2014well, sort of. This indicator attempts to define the current market's trendiness over the past _n_ -days into one simple value. The ADX value is high when the market is trending and low when it is in congestion.\n\nThe basic theory behind the ADX is based on market directional movement. This movement is either positive, negative, or neutral. In Wilder's vernacular, positive direction was described as plus directional movement (+DM) and negative as minus directional movement (\u2212DM). Directional movement is calculated by comparing the difference between two consecutive bars' lows and the difference between their respective highs. Movement is positive (plus) when the current bar's high minus the prior bar's high is greater than the prior bar's low minus the current bar's low. This plus directional movement (+DM) then equals the current high minus the prior bar's high as long as this value is positive. If the value is negative, then the +DM would be set to zero. Negative movement or minus directional movement (\u2212DM) does the same comparison. A \u2212DM occurs when the prior bar's low minus the current is greater than the current bar's high minus the prior. In this case the difference between the two lows is assigned to the \u2212DM as long as the value is positive. If the value is negative, it is assigned zero just like the +DM. Sounds a bit confusing but Figure 2.1 should help clarify things.\n\n**Figure 2.1** Examples of directional movement.\n\nFigure 2.1 shows four calculation examples for directional movement. The first pairing shows a big positive difference between the highs for a strong plus directional movement (+DM). The second pairing shows an outside day with minus directional movement (\u2212DM) getting the edge. The third pairing shows a big difference between the lows for a strong minus directional movement (\u2212DM). The final pairing shows an inside day, which amounts to no directional movement (zero). Both plus directional movement (+DM) and minus directional movement (\u2212DM) are negative and cancel out each other. Negative values revert to zero. Keep in mind all inside days will have zero directional movement.\n\nThe ADX index incorporates moving averages of true range and both +DM and \u2212DM. Data averaging is also the same as data smoothing. A moving average function cuts down the impact of abnormal data points and creates a more robust model of the data. Wilder created his indicators without the use of a computer and created a shortcut to average his data points. This Wilder's smoothing is more like an exponential calculation. Different trading\/testing\/charting platforms use different smoothing functions for Wilder's indicators, so be sure to check your user's manual and see which form is being utilized by your particular software. Assuming a 14-day ADX length, Wilder would sum up the first 14-day values and then divide by 14. Once these initial averages were calculated the subsequent bar values were calculated by first dividing the previous sum by 14 and subtracting it from the previous sum and then adding today's values:\n\nThis form of smoothing eliminates keeping track of the prior 14 bar values and accomplishes the desired effect (reducing the impact of outlying data points) on plus DM, minus DM, and true range. Remember, Wilder probably had the use of just a calculator, and instead of inputting 42 numbers (summing three sets of 14 numbers), he simply used the above formula and whipped out the values in a minute or less. Most of today's charting software utilizes an exponential moving average to smooth the ADX. This smoothing method creates results that can be quite different than Wilder's original method.\n\nThe smoothing factor (2\/(N+1)) or in this case (2\/15) can be changed to (1\/N) to arrive at Wilder's calculation. This becomes more like a 27 period exponential moving average than a 14. However, this exponential method is considered accurate, but, in some cases, different charting software will offer both versions: ADX and Wilder ADX.\n\n**Calculation for a 14-day ADX:**\n\n 1. Calculate the true range (TR), plus directional movement (+DM), and minus directional movement (\u2212DM) for each bar.\n 2. True range (TR ) = max(C[1],H) \u2212 min(C[1],L). In other words: Take the higher of yesterday's close and today's high and subtract the lower of yesterday's close and today's low. Basically, you are expanding today's range to incorporate the prior day's close if it is outside of today's range.\n 3. Smooth these periodic values using a 14-day moving average. You will either have to wait until 14 days have transpired or you can simply look at 14 days of prior history before commencing the ADX calculation.\n 4. Divide the 14-day smoothed plus directional movement (+DM) by the 14-day smoothed true range to find the 14-day plus directional indicator (+DI14). Multiply by 100 to move the decimal point two places. This +DI14 is the plus directional indicator that is plotted along with ADX.\n 5. Divide the 14-day smoothed minus directional movement (\u2212DM) by the 14-day smoothed true range to find the 14-day minus directional indicator (\u2212DI14. Multiply by 100 to move the decimal point two places. This \u2212DI14 is the minus directional indicator that is plotted along with ADX.\n 6. The Directional Movement Index (DX) equals the absolute value of +DI14 less \u2212DI14 divided by the sum of +DI14 and \u2212DI14.\n 7. After all these steps, it is time to calculate the Average Directional Index (ADX). The ADX value is initially simply a 14-day average of DX.\n 8. Wilder went one step further and created the ADXR, which is simply the average of an _N_ -day differential of the ADX. Continuing with our 14-day example, the ADXR would be calculated by applying the following formula:\n\nFigure 2.2 illustrates how the ADX can be used to help determine the trendiness of a market. A rising ADX, as shown in the early part of the price chart, demonstrates a trending market condition, whereas a falling ADX is saying the market has stopped trending and is entering a congestion phase. This information is very useful but very limited as well. The computer cannot determine which way the market is trending by simply looking at the ADX value. The solution to this problem can be found by comparing the +DI to the \u2212DI. If the +DI crosses above the \u2212DI, then the market is considered in an uptrend. When the \u2212DI crosses above the +DI, then the market is in a downtrend.\n\n**Figure 2.2** ADX as a trend detector.\n\nSource: TradeStation\n\nUsing this indicator in concert with a trend-following system may produce more robust entry signals. I have seen many systems incorporating the ADX in an attempt to eliminate \"whipsaw\" trades. Welles Wilder developed his own system around the ADX, +DI, and \u2212DI. Box 2.1 is a description of a system that incorporates the ADX and a trailing stop for both long and short trades. The stop will get out of longs when the market closes lower than the prior three-day closings and get out of shorts when the market closes higher than the prior three days. This type of stop is not fixed as it varies based on market movement. In other words, it is a dynamic stop. If we are lucky to get in on a nice intermediate trend, the stop will follow the market in the direction of the movement and hopefully lock in some profit.\n\n* * *\n\n### Box 2.1 Welles Wilder's Directional Movement System Description\n\n 1. If 14-day ADX is greater than 35 then \n 1. If +DI > \u2212DI, then Buy market on close\n 2. If \u2212DI > +DI, then SellShort market on close\n 2. If 14-day ADX is less than 35, then \n 1. If position is long and close is less than lowest close of prior three days, then Sell market on close.\n 2. If position is short and close is greater than highest close of prior three days, then BuyToCover market on close.\n\n#### Welles Wilder's Directional Movement p\u2013code\n\n `Wilder's Directional Movement System\n `Assuming Wilder's Indicator\/Functions are built\u2013in\n `Also Highest and Lowest functions\n myADX = ADX(14) `14 period ADX calculation\n myPlusDI = PDI(14) ` 14 period Plus DI\n myMinusDI = MDI(14) ` 14 period Minus DI\n if myADX> 35 then\n if myPlusDI> myMinusDI then\n Buy this bar on close\n if myMinusDI> myPlusDI then\n SellShort this bar on close\n if myADX < 35 then\n if MarketPosition = 1 and close < Lowest(close[1],3) then\n Sell this bar on close\n if MarketPosition = -1 and close > Highest(close[1],3) then\n BuyToCover this bar on close\n\n* * *\n\nThe directional movement algorithm description is straightforward and can be modeled by a flowchart. A finite state machine is not needed because, as we discussed in Chapter 1, this system follows a certain flow that is directed by a combination of logical steps and decisions that eventually lead to termination of the process. Figure 2.3 shows the flowchart of this algorithm.\n\n**Figure 2.3** Wilder's directional movement algorithm.\n\nLike the description, the diagram is straightforward as well. It might look complicated, but that is only because of the many different decisions that must be evaluated before an action is carried out. In the case of this very simple system, a flowchart diagram isn't really all that necessary. However, it is great practice, and eventually you will come across a trading scheme that will be complicated enough to merit a properly thought-out diagram.\n\nBefore proceeding to the next indicator, I must mention that the ADX along with all other indicators are just building blocks and are not to be used by themselves. Many successful trading algorithms utilize indicators but not strictly by themselves and in many cases the indicators are augmented or filtered. Many traders change some of the logic of an indicator and therefore make it their own and in doing so bring their own creativity into the process. Most trading algorithms are built on the shoulders of others. More frequently, traders will utilize a filtering process that will eliminate excessive trade signals generated by an indicator. In doing so, the trader is hoping to skip the less productive trades and target the really good ones. Table 2.1 shows the performance of the pure ADX applied to several markets.\n\n**Table 2.1** Performance of Directional Movement Algorithm\n\n**Ticker** | **Net Profit** | **Max. Sys DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% of Winners** \n---|---|---|---|---|---|--- \nAD0_E0B | \u221221140.0 | \u221226030 | 43 | \u2212491.63 | 13.53 | 32.56 \nBP0_E0B | \u22125825.0 | \u221227925 | 39 | \u2212149.36 | 12.74 | 38.46 \nC20_E0B | 737.5 | \u221210000 | 43 | 17.15 | 15.51 | 44.19 \nCC20_E0B | \u22124050.0 | \u221213560 | 35 | \u2212115.71 | 14.86 | 42.86 \nCL20_E0B | 41350.0 | \u221226750 | 36 | 1148.61 | 14.67 | 41.67 \nCT20_E0B | 44530.0 | \u221220220 | 46 | 968.04 | 16.7 | 39.13 \nCU0_E0B | 5712.5 | \u221220925 | 47 | 121.54 | 15.81 | 40.43 \nDX20_E0B | 150.0 | \u22129990 | 51 | 2.94 | 14.51 | 41.18 \nED0_E0B | 2009.4 | \u22121513 | 58 | 34.64 | 18.12 | 29.31 \nEMD0_E0B | \u221233400.0 | \u221243910 | 31 | \u22121077.42 | 13.81 | 29.03 \nES0_E0B | \u221218837.5 | \u221223050 | 26 | \u2212724.52 | 15.96 | 30.77 \nFC0_E0B | 20087.5 | \u22129588 | 45 | 446.39 | 17.04 | 35.56 \nFV0_E0B | 8226.4 | \u22127203 | 49 | 167.89 | 17.41 | 34.69 \nGC20_E0B | \u221232870.0 | \u221241560 | 43 | \u2212764.42 | 12.84 | 27.91 \nHG20_E0B | 300.0 | \u221241338 | 34 | 8.82 | 14.5 | 29.41 \nHO20_E0B | 20139.0 | \u221240286 | 46 | 437.8 | 13.17 | 39.13 \nKC20_E0B | \u221232606.3 | \u221242413 | 36 | \u2212905.73 | 11.61 | 25 \nKW20_E0B | 9887.5 | \u221215863 | 43 | 229.94 | 16.56 | 39.53 \nLB0_E0B | 957.0 | \u221217259 | 39 | 24.54 | 15.62 | 38.46 \nLC0_E0B | \u22121230.0 | \u22129550 | 41 | \u221230 | 17.24 | 26.83 \nLH0_E0B | 1510.0 | \u221210710 | 40 | 37.75 | 15.65 | 37.5 \nMP0_E0B | 4775.0 | \u22125295 | 33 | 144.7 | 14.42 | 39.39 \nNG20_E0B | 54440.0 | \u221269390 | 38 | 1432.63 | 16.11 | 39.47 \nNK0_E0B | \u22128425.0 | \u221215125 | 28 | \u2212300.89 | 15.39 | 46.43 \nOJ20_E0B | \u221216620.0 | \u221217790 | 45 | \u2212369.33 | 15.18 | 28.89 \nPL20_E0B | 16610.0 | \u221230895 | 36 | 461.39 | 16.39 | 33.33 \nRB0_E0B | \u221217665.2 | \u221246813 | 26 | \u2212679.43 | 13.62 | 23.08 \nS20_E0B | \u221212212.5 | \u221231463 | 50 | \u2212244.25 | 14.94 | 28 \nSB20_E0B | 6563.2 | \u221211995 | 61 | 107.59 | 12.95 | 26.23 \nSI20_E0B | 40400.0 | \u221251735 | 44 | 918.18 | 14.14 | 25 \nTF0_E0B | \u221224920.0 | \u221232610 | 33 | \u2212755.15 | 12.61 | 24.24 \nTU0_E0B | 12124.8 | \u22124156 | 42 | 288.69 | 17.1 | 33.33 \nTY0_E0B | 12109.6 | \u22127531 | 48 | 252.28 | 16.69 | 35.42 \nUS0_E0B | 14906.4 | \u221218031 | 45 | 331.25 | 16.67 | 37.78 \nW20_E0B | \u221219462.5 | \u221231188 | 45 | \u2212432.5 | 14.64 | 26.67\n\n### Relative Strength Index (RSI)\n\nContinuing on with Welles Wilder, the next indicator that we will discuss will be the Relative Strength Index (RSI). This indicator is a momentum oscillator that measures the speed and change of price movements. RSI oscillates between 0 and 100. Traditionally, and according to Wilder, RSI is considered overbought when above 70 and oversold when below 30. After moving averages, RSI might be the most popular indicator out there; every popular charting package includes it in its library.\n\nIts popularity might be partially attributed to its simplicity. The indicator is simply measuring the momentum of the market over the past number of days. Momentum indicates the direction and strength of the market. A quickly moving uptrend will be reflected by consecutive higher-high RSI values. And consecutive lower-low RSI values will represent just the opposite, a quickly moving downtrend.\n\n**Calculation for a 14-day RSI:**\n\n 1. Going back in time 14 bars compare the closing price of a bar with its prior bar. If the difference is positive, then accumulate the amount to an upSum variable. If the difference is negative, then remove the sign and accumulate the difference to a dnSum variable.\n 2. If C > C[1], then upSum = upSum + (C \u2212 C[1]). If C < C[1], then dnSum = dnSum + \u22121 \u00d7 (C \u2212 C[1]).\n 3. Once these values are summed, simply divide them by the RSI period. In doing so, you will have two new values: avgUp and avgDn. In a strong upward-moving market, the upSum and corresponding avgUp will be much greater than the dnSum and avgDn.\n 4. Once you have arrived to the avgUp and avgDn values the relative strength (RS) is simply the quotient of the two values:\n\n 5. The RS is the ratio of the changes in up closes to down closes. If the market is in a strong uptrend, the avgUp will be large in relation to the avgDn, thus generating a larger number. The opposite is true if the avgDn is much greater than the avgUp (an occurrence of a downward trending market).\n 6. The RSI is a bound indicator, meaning that it will stay within an upper and lower constraint. In the case of the RSI, as we mentioned earlier, these constraints are 0 and 100. The simple ratio of avgUp and avgDn can go from a small number to a large one. We can normalize the RS for any market and constrain it between 0 and 100 by applying the following formula:\n\nLet's assume a strong upwardly trending market with an upAvg of 60 and a dnAvg of 20. Inputting this information into the formula, we arrive at the following:\n\n 7. Just like the ADX, subsequent values are smoothed utilizing either an exponential moving average or Wilder's homebrew.\n\nThe default period length for the RSI is 14 so it is easy to see that this indicator was designed for a short-term approach. When using RSI in an overbought\/oversold application, traders are looking for a reversion to a mean type movement\u2014what goes up must eventually come down. Through Wilder's research he observed his indicator usually topped\/bottomed out prior to an actual market top\/bottom. Figure 2.4 shows a highly successful RSI trade.\n\n**Figure 2.4** Example of a trade generated by RSI.\n\nSource: TradeStation\n\nBox 2.2 shows a trading system description incorporating the RSI, a volatility-based profit objective, and protective stop. The profit and stop are based off a 10-day average true range\u2014wider profit targets and stops in high volatility. Notice how the system is trying to cut losses short and let profits run using a 3:1 ratio. I have noticed in situations where a system is trying to trade shorter-term to intermediate-term trends a 1:3 ratio, albeit somewhat illogical, works better. Continuing along with our diagrams, Figure 2.5 shows the very simplistic flowchart.\n\n**Figure 2.5** Flowchart diagram of RSI trading algorithm.\n\n* * *\n\n### Box 2.2 Welles Wilders RSI System Description\n\n 1. If 14-day RSI is less than 30, then \n 1. Buy MOC\n 2. If 14-day RSI is greater than 70, then \n 1. Sell Short MOC\n 3. If position is long \n 1. Take Profit: If close > entry price + 3 ATR Sell MOC\n 2. Protective Stop: If close < entry price \u2212 1 ATR Sell MOC\n 4. If position is short \n 1. Take Profit: If close < entry price \u2212 3 ATR BuyToCover MOC\n 2. Protective Stop: If close > entry price + 1 ATR BuyToCover MOC\n\nNote that MOC stands for market on close.\n\n#### Welles Wilders RSI System p\u2013code\n\n `Wilders Simple RSI OB\/OS system\n utilizing a 3 ATR profit objective\n and a 1 ATR stop\n If rsi(c,14) < 30 then buy this bar on close\n If rsi(c,14) > 70 then sellShort this bar on close\n If marketPosition = 1 then\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close\n If marketPosition = 1 then\n begin\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close\n\nSimple enough!\n\n* * *\n\nNow don't get carried away, because the RSI can call an intermediate top\/bottom but it can also be faked out by a strong trend move. If you simply use it as an overbought\/oversold indicator, you will be disappointed. Table 2.2 shows the performance of the RSI across a portfolio of futures.\n\n**Table 2.2** Performance of RSI Algorithm\n\n**Ticker** | **Net Profit** | **Max. Sys DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% of Winners** \n---|---|---|---|---|---|--- \nAD0_E0B | \u221217229.99 | \u221219850 | 87 | \u2212198.05 | 8.4 | 16.09 \nBP0_E0B | \u221219812.5 | \u221249600 | 68 | \u2212291.36 | 8.16 | 23.53 \nC20_E0B | \u221210550 | \u221214250 | 87 | \u2212121.26 | 9.63 | 21.84 \nCC20_E0B | 5240 | \u22127280 | 87 | 60.23 | 8.07 | 28.74 \nCL20_E0B | \u221254340 | \u221267120 | 89 | \u2212610.56 | 9.21 | 21.35 \nCT20_E0B | \u22126600 | \u221237295 | 93 | \u221270.97 | 7.37 | 22.58 \nCU0_E0B | \u221224200 | \u221238887.5 | 93 | \u2212260.22 | 9.16 | 20.43 \nDX20_E0B | \u221224370 | \u221233510 | 83 | \u2212293.61 | 8.14 | 13.25 \nED0_E0B | \u22122128.13 | \u22122137.5 | 136 | \u221215.65 | 7.51 | 14.71 \nEMD0_E0B | \u221216730 | \u221238240 | 79 | \u2212211.77 | 8.75 | 24.05 \nES0_E0B | \u221216275 | \u221229087.5 | 69 | \u2212235.87 | 7.68 | 17.39 \nFC0_E0B | \u221227862.5 | \u221239787.5 | 105 | \u2212265.36 | 7.84 | 15.24 \nFV0_E0B | \u22129165.59 | \u221210417 | 96 | \u221295.47 | 8.9 | 21.88 \nGC20_E0B | 5020 | \u221242850 | 91 | 55.16 | 7.89 | 27.47 \nHG20_E0B | \u221221250 | \u221245787.5 | 86 | \u2212247.09 | 7.92 | 24.42 \nHO20_E0B | \u221270366.8 | \u221297671 | 92 | \u2212764.86 | 8.85 | 21.74 \nKC20_E0B | 21693.75 | \u221231125 | 74 | 293.16 | 9.41 | 32.43 \nKW20_E0B | \u22125025 | \u221218762.5 | 99 | \u221250.76 | 8.4 | 26.26 \nLB0_E0B | 10010 | \u22127667 | 100 | 100.1 | 8.27 | 28 \nLC0_E0B | \u22124850 | \u221211780 | 80 | \u221260.63 | 8.63 | 25 \nLH0_E0B | \u22122900 | \u221211160 | 83 | \u221234.94 | 8.13 | 25.3 \nMP0_E0B | 675 | \u22126430 | 90 | 7.5 | 8.31 | 25.56 \nNG20_E0B | 1830.01 | \u221242839.99 | 80 | 22.88 | 10.68 | 26.25 \nNK0_E0B | 625 | \u221213850 | 69 | 9.06 | 8.38 | 24.64 \nOJ20_E0B | 5070 | \u22127170 | 102 | 49.71 | 7.48 | 26.47 \nPL20_E0B | \u22124425 | \u221222415 | 86 | \u221251.45 | 9.62 | 26.74 \nRB0_E0B | \u221210894.8 | \u221256884.8 | 92 | \u2212118.42 | 6.02 | 32.61 \nS20_E0B | \u221213237.5 | \u221227787.5 | 93 | \u2212142.34 | 7.62 | 22.58 \nSB20_E0B | \u22127056 | \u221221649.6 | 94 | \u221275.06 | 7.5 | 23.4 \nSI20_E0B | \u221228240 | \u221278915 | 82 | \u2212344.39 | 10.57 | 28.05 \nTF0_E0B | 3750 | \u221221400 | 66 | 56.82 | 8.42 | 25.76 \nTU0_E0B | \u221213703.6 | \u221216806.2 | 95 | \u2212144.25 | 10.99 | 20 \nTY0_E0B | \u2212500.4 | \u221213046.8 | 88 | \u22125.69 | 8.68 | 26.14 \nUS0_E0B | 11843.4 | \u221220343.8 | 86 | 137.71 | 9 | 27.91 \nW20_E0B | \u221231037.5 | \u221234112.5 | 73 | \u2212425.17 | 8.7 | 16.44\n\nSignals can also be generated using the RSI by looking for divergences, failure swings, and centerline crossovers. Wilder suggests that divergence between an asset's price movement and the RSI oscillator can signal a potential reversal. This divergence occurs when the RSI continues in the opposite direction of the underlying asset: RSI trends down while price trends upward or RSI trends up while price trends down.\n\nA bullish divergence forms when the underlying asset makes a lower low and RSI makes a higher low. RSI diverges from the bearish price action in that it shows strengthening momentum, indicating a potential upward reversal in price. A bearish divergence forms when the underlying asset makes a higher high and RSI forms a lower high. RSI diverges from the bullish price action in that it shows weakening momentum, indicating a potential downward reversal in price. As with overbought and oversold levels, divergences are more likely to give false signals in the context of a strong trend.\n\nA TOP failure swing occurs when the RSI forms a pivot high in overbought territory and then pulls back and forms a pivot low and then another pivot high forms that is less than the original. A sell signal is triggered at the intervening RSI pivot low level. A BOTTOM failure is the inversion of the TOP; RSI forms a pivot low below the oversold value and then moves up and forms a pivot high and then a pivot low greater than the original pivot low. Figure 2.6 illustrates these failure swings.\n\n**Figure 2.6** Example of RSI divergence.\n\nAccording to Wilder, trading the failure swings might be more profitable than simply trading the RSI overbought\/oversold model. Let's see if this is the case by testing this idea. The RSI failure swing algorithm is going to be more complicated than our last RSI algorithm, but with the use of an FSM it is readily doable. Let's attack it from the short side only to start (Box 2.3).\n\n* * *\n\n### Box 2.3 Welles Wilders RSI Failure Swing System Description\n\nSellShort Setup: The 14-day RSI rises above 70, then pulls back below 70 and forms a low pivot. The RSI then rallies but does not take out the original pivot high level. A SellShort signal is generated once the RSI retraces to the pivot low level that was established between the two prior consecutive pivot highs. ( _Note_ : MOC stands for market on close.)\n\n 1. If position is short \n 1. Take Profit: If close < entry price \u2212 1 ATR BuyToCover MOC\n 2. Protective Stop: If close > entry price + 3 ATR BuyToCover MOC\n\n#### Welles Wilders RSI Failure Swing System p\u2013code\n\n rsiVal = RSI(C,14)\n If rsiVal[1] > rsiVal and rsiVal[1] > rsiVal[2] then\n rsiPvtHiFound = true\n rsiPvtHiVal = rsiVal[1]\n else\n rsiPvtHiFound = False\n If rsiVal[1] < rsiVal and rsiVal[1] < rsiVal[2] then\n rsiPvtLoFound = true\n rsiPvtLoVal = rsiVal[1]\n else\n rsiPvtLoFound = False\n If state = 0 then\n if rsiPvtHiFound = true and rsiPvtHiVal > 70 then\n state = 1\n If state = 1 then\n state1Val = rsiPvtHiVal\n if rsiVal > state1Val then state = 0\n if rsiPvtLoFound = true then\n state = 2;\n If state = 2 then\n state2Val = rsiPvtLoVal\n if rsiVal > state1Val then state = 0\n if rsiPvtHiFound = true then\n if rsiPvtHiVal < 70 then state = 3\n If state = 3 then\n if rsiVal < state2Val then state = 4\n If state = 4 then\n sellShort this bar on close\n state = 0;\n If state > 0 and rsiVal < 30 then state = 0\n If marketPosition =-1 and close > entryprice + 1* avgTrueRange(10) then\n BuyToCover this bar on close\n If marketPosition =-1 and close < entryPrice - 3* avgTrueRange(10) then\n BuyToCover this bar on close;\n\n* * *\n\nFigure 2.7 illustrates the model of the RSI failure swing algorithm. As you can see from the diagram, this isn't a flowchart. It's our old friend the FSM, so let's move through the different states of the machine. We start off gobbling one bar at a time until we come across a RSI pivot high with a value of 70 or greater. Once this occurs, the machine goes into **State 1** and starts gobbling more bars. The machine can only transition out of **State 1** if one of three events occur: an occurrence of a RSI pivot low, an RSI value > the original RSI pivot high value, or an RSI value that is less than 30. Only an occurrence of an RSI pivot low can propel the machine to **State 2**. The other two conditions will reverse the machine to the **Start** state. Once in **State 2** , the machine looks for yet another RSI pivot high. In addition to a new pivot high, another condition must be met before moving onto **State 3** , and that is the RSI pivot high must be less than the original RSI pivot high. The same conditions that reset the machine to the **Start** state exist at **State 2**. After the machine attains **State 3** , it then tries to propel itself to **State 4** by finding an RSI value less than the RSI pivot low found in **State 1**. If this occurs, an order to sell short the market is placed on an MOC basis. Again, the exact same criteria for reversing the machine back to the **Start** state are in force in **State 3**.\n\n**Figure 2.7** Example of FSM modeling RSI Swing Failure.\n\nTable 2.3 shows the results of the RSI Failure Swing Algorithm from both the long and short side utilizing the same profit objective and stop used in the first RSI test.\n\n**Table 2.3** Performance of RSI Failure Swing Algorithm\n\n**Ticker** | **Net Profit** | **# Trades** | **Avg P\/L** | **Avg Bars Held** \n---|---|---|---|--- \n@KC | $11,381.25 | 45 | $252.92 | 16.58 days \n@SB | \u2212$8,162.60 | 40 | \u2212$198.40 | 15.13 days \n@ES | \u2212$20,375.00 | 39 | \u2212$522.44 | 12.44 days \n@DX | \u2212$23,245.00 | 44 | \u2212$528.30 | 13.89 days \n@C | $6,312.50 | 40 | $157.81 | 13.38 days \n@BP | \u2212$1,225.00 | 38 | \u2212$32.24 | 18.66 days \n@CT | \u2212$21,485.00 | 47 | \u2212$456.60 | 13.83 days \n@OJ | $7,115.00 | 53 | $134.25 | 18.49 days \n@CC | $18,785.00 | 55 | $324.00 | 14.36 days \n@HG | \u2212$14,250.00 | 51 | \u2212$279.41 | 17.8 days \n@EC | \u2212$35,550.00 | 43 | \u2212$826.74 | 17.33 days \n@HO | \u2212$58,426.40 | 52 | \u2212$1,123.58 | 12.42 days \n@TU | \u2212$7,850.00 | 42 | \u2212$186.90 | 16.26 days \n@US | \u2212$11,568.75 | 42 | \u2212$275.45 | 17.62 days \n@FV | \u2212$4,939.06 | 43 | \u2212$114.86 | 13.86 days \n@ED | $3,025.00 | 44 | $68.75 | 18.18 days \n@TY | \u2212$6,540.63 | 43 | \u2212$152.11 | 14.21 days \n@CL | \u2212$45,050.00 | 52 | \u2212$866.35 | 12.25 days \n@RB | \u2212$51,377.40 | 45 | \u2212$1,141.72 | 17.24 days \n@PL | $7,980.00 | 41 | $194.63 | 13.83 days \n@GC | $7,570.00 | 46 | $164.57 | 18.26 days \n@AD | \u2212$27,980.00 | 44 | \u2212$635.91 | 14.93 days \n@SI | \u2212$9,300.00 | 53 | \u2212$175.47 | 12.34 days \n@NG | $28,730.00 | 38 | $756.05 | 15.76 days \n@EMD | \u2212$20,780.00 | 43 | \u2212$483.26 | 13.05 days \n@TF | $16,760.00 | 40 | $419.00 | 15.35 days \n@S | $10,325.00 | 38 | $271.71 | 14.18 days \n@W | \u2212$3,112.50 | 35 | \u2212$88.93 | 14.71 days \n@LH | $15,190.00 | 41 | $370.49 | 16.41 days \n@LC | \u2212$21,160.00 | 29 | \u2212$729.66 | 12.9 days \n@FC | \u2212$25,212.50 | 37 | \u2212$681.42 | 12.92 days \n@KW | $8,925.00 | 24 | $371.88 | 14.42 days\n\n### George Lane's Stochastics\u2014Fast %K: Fast %D: Slow %K: Slow %D\n\nDeveloped by George C. Lane in the late 1950s, the stochastic oscillator, like the RSI, is a momentum indicator that shows the location of the close relative to the high\u2013low range over a set number of periods. Mr. Lane stated in an interview the following concerning the oscillator: \"It doesn't follow price, it doesn't follow volume or anything like that. It follows the speed or the momentum of price. As a rule, the momentum changes direction before price.\" The word _stochastic_ is defined as a random pattern that may be analyzed statistically but may not be predicted precisely. An appropriate name, if you ask me. In similar fashion to the RSI, bullish and bearish divergences in the stochastic oscillator can be used to foreshadow reversals. In other words, if the stochastic says one thing but the market says another, then be on the lookout for a market reversal. This is very useful information from a technician's point of view but very little for the quant trader looking for a very precise entry definition. However, because the stochastic oscillator is range bound, it is also useful for identifying overbought and oversold levels.\n\n**Calculation for a 14-day stochastic [FAST]:**\n\n 1. Going back in time 14 bars, calculate the highest high and lowest low prices during this period.\n 2. Subtract the lowest low from the current closing price and divide the difference by the range between the highest high and lowest low. Multiply this quotient by 100 and you will arrive at %K, or fast K.\n\n 3. Fast %D is a simple three-period moving average of the fast %K.\n\nIf the current close is near the lowest low, then the numerator in the %K formula will be small and will produce a low stochastic reading. If the close is near the highest high, then the numerator will be large. A strong %K indicates a strong uptrend, whereas a weak %K indicates the opposite, a strong downtrend. Both %D and %K are plotted alongside each other with the %K line acting as a signal or trigger line. The slow variation of this indicator is simply a further smoothing of the %K and %D. In the slow framework the fast %D becomes the slow %K and the slow %D becomes a three-period moving average of the slow %K. The two versions can be confusing so most people simply use the slow variety. Through my obeservations the fast stochastic seems to be very erratic.\n\nThe default parameters for the slow stochastic are (14, 3, 3) where the 14 represents the raw %K calculation period, the first 3 is the initial smoothing length, and the second 3 is the secondary smoothing.\n\nAs you can see from the %K formula, the numerator will always be less than or equal to the denominator and therefore produce a reading between 0 and 100. If the close is near the lowest low, then the formula will produce a low stochastic.\n\nMost traders utilize the stochastic (STO) as an overbought\/oversold indicator with 80 and 20 as the corresponding thresholds. If the STO is high, then the momentum is very bullish, and if it's low\u2014well, it's pretty obvious. Just like the RSI, the STO can be faked out into believing a market has become overbought\/sold when in fact the market is in a very strong trend. A unique feature of the STO (and some other oscillators) is that it incorporates a _trigger_. Instead of simply buying\/selling in the oversold\/overbought territory a trader can wait until the slow %K crosses above\/below the slow %D. Remember, these calculations are simple moving averages of the raw %K and when a shorter-term average crosses the longer term, this indicates a short-term shift in momentum.\n\nFigure 2.8 shows trades where the slow %K crosses slow %D in overbought and oversold territories.\n\n**Figure 2.8** Chart showing trade signals from stochastic crossover algorithm.\n\nSource: TradeStation\n\nEntry signals for a stochastic oscillator crossover algorithm can be defined by simple if\u2013then constructs. So a simple flowchart can be used to model this type of trading algorithm. The flowchart is shown in Figure 2.9.\n\n**Figure 2.9** The flowchart for an algorithm using a stochastic oscillator crossover as an entry signal.\n\nBox 2.4 gives a description of a simplistic version of a stochastic crossover system utilizing the same profit-and-loss objectives as the RSI algorithms. The results of this stochastic algorithm applied to several markets are shown in Table 2.4.\n\n**Table 2.4** Performance of Stochastic Algorithm\n\n**Ticker** | **Net Profita** | **Max. Sys DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% of Winners** \n---|---|---|---|---|---|--- \nAD0_E0B | \u221234820 | \u221250330 | 356 | \u221297.81 | 7.6 | 26.69 \nBP0_E0B | 41213 | \u221240563 | 324 | 127.2 | 8.42 | 31.17 \nC20_E0B | 8400 | \u221215675 | 358 | 23.46 | 7.58 | 29.89 \nCC20_E0B | 44010 | \u22128170 | 341 | 129.06 | 8.21 | 35.19 \nCL20_E0B | \u221254320 | \u2212115190 | 346 | \u2212156.99 | 7.92 | 27.46 \nCT20_E0B | \u22125770 | \u221251165 | 362 | \u221215.94 | 7.81 | 30.11 \nCU0_E0B | \u2212287 | \u221253163 | 348 | \u22120.83 | 8.01 | 27.87 \nDX20_E0B | 4120 | \u221220390 | 362 | 11.38 | 7.33 | 27.9 \nED0_E0B | \u22124066 | \u22124103 | 255 | \u221215.94 | 8.93 | 21.96 \nEMD0_E0B | \u221253730 | \u221289300 | 350 | \u2212153.51 | 7.29 | 24.86 \nES0_E0B | \u221252200 | \u221275975 | 359 | \u2212145.4 | 7.15 | 25.07 \nFC0_E0B | \u221217425 | \u221232575 | 369 | \u221247.22 | 7.41 | 26.83 \nFV0_E0B | \u221217699 | \u221225463 | 345 | \u221251.3 | 7.66 | 25.8 \nGC20_E0B | \u221227470 | \u221267650 | 353 | \u221277.82 | 7.54 | 29.18 \nHG20_E0B | \u221248938 | \u2212106225 | 343 | \u2212142.67 | 7.65 | 26.82 \nHO20_E0B | 36343 | \u221296319 | 340 | 106.89 | 8.07 | 30 \nKC20_E0B | 16838 | \u221230375 | 334 | 50.41 | 8.26 | 28.74 \nKW20_E0B | \u2212188 | \u221241688 | 350 | \u22120.54 | 7.67 | 30.86 \nLB0_E0B | 5302 | \u221234562 | 418 | 12.68 | 6.53 | 28.95 \nLC0_E0B | 42500 | \u22128750 | 344 | 123.55 | 7.98 | 34.3 \nLH0_E0B | \u221214110 | \u221217640 | 363 | \u221238.87 | 7.2 | 26.17 \nMP0_E0B | 1730 | \u221210580 | 297 | 5.82 | 8.34 | 28.96 \nNG20_E0B | \u2212193860 | \u2212199740 | 336 | \u2212576.96 | 7.95 | 25.3 \nNK0_E0B | 17300 | \u221238025 | 375 | 46.13 | 7.34 | 30.4 \nOJ20_E0B | 34275 | \u22128055 | 321 | 106.78 | 8.3 | 32.4 \nPL20_E0B | 25415 | \u221240470 | 341 | 74.53 | 7.91 | 30.5 \nRB0_E0B | \u221248266 | \u2212101884 | 406 | \u2212118.88 | 5.96 | 28.33 \nS20_E0B | \u221248888 | \u221261063 | 367 | \u2212133.21 | 7.18 | 26.16 \nSB20_E0B | \u22127045 | \u221233309 | 380 | \u221218.54 | 6.9 | 28.68 \nSI20_E0B | \u2212122305 | \u2212186355 | 323 | \u2212378.65 | 8.44 | 27.86 \nTF0_E0B | \u221248910 | \u221280540 | 333 | \u2212146.88 | 7.56 | 26.43 \nTU0_E0B | \u221221736 | \u221224441 | 309 | \u221270.34 | 8.3 | 24.92 \nTY0_E0B | \u221237139 | \u221254734 | 350 | \u2212106.11 | 7.52 | 25.71 \nUS0_E0B | \u221274827 | \u221274859 | 359 | \u2212208.43 | 7.67 | 25.07 \nW20_E0B | \u221227838 | \u221243613 | 351 | \u221279.31 | 7.98 | 29.06\n\n* * *\n\n### Box 2.4 George Lane's Slow Stochastic System Description\n\n 1. If 14-day slow %K crosses below slow %D and slow %D is greater than 80, then \n 1. Buy MOC\n 2. If 14-day slow %K crosses above slow %D and slow %D is less than 20, then \n 1. Sell Short MOC\n 3. If position is long \n 1. Take Profit: If close > entry price + 3 ATR Sell MOC\n 2. Protective Stop: If close < entry price \u2212 1 ATR Sell MOC\n 4. If position is short \n 1. Take Profit: If close < entry price \u2212 3 ATR BuyToCover MOC\n 2. Protective Stop: If close > entry price + 1 ATR, BuyToCover MOC\n\nNote that MOC stands for market on close.\n\n#### _George Lane's Slow Stochastic System p\u2013code_\n\n `Most software will provide a function that\n `provides all the components of the stochastic\n Value1 = stochastic(h,l,c,rawKLen,smooth1,smooth2,1,myFastK,myFastD,mySlowK,mySlowD)\n If mySlowK crosses above mySlowD and mySlowD < 20 then buy this bar on close\n If mySlowK crosses below mySlowD and mySlowD > 80 then sellShort this bar on close\n If marketPosition = 1 then\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close\n If marketPosition =-1 then\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close\n\n* * *\n\n### Donald Lambert's CCI\u2014Commodity Channel Index\n\nDonald Lambert developed the CCI in 1980, and it was featured in _Commodities_ magazine that same year. The Commodity Channel Index can be used in the same vein as RSI and stochastic: trend determination or warning of extreme conditions. Lambert originally developed CCI to identify cyclical turns in commodities, but the indicator can be successfully applied to indices, ETFs, stocks, and other securities. In general, CCI measures the current price level relative to an average price level over a given period of time. CCI is relatively high when prices are far above their average, and conversely, CCI is relatively low when prices are far below their average\u2014hence its application as reversion to the mean tool.\n\nThe main difference between CCI and other similar oscillators is that it is not necessarily range bound. Most of the time, the CCI will oscillate between two extremes, but as you will see in its calculations, there is not a fixed boundary. The CCI introduces the concept of typical price and utilizes it in its calculations. Typical price is just the average of a bar's high, low, and close: Typical price (TP) = (High + Low + Close)\/3. This calculation looks at the three most important price points on a price bar and many believe it reveals a more realistic picture of the day's action than just the close. The TP is also known as the daily pivot point. In the day, floor traders used this easily calculable price to determine current support and resistance levels.\n\n**Calculation for a 20-day CCI:**\n\n 1. Going back in time, calculate the average of the past 20 days' typical prices.\n 2. Calculate the one standard deviation of the average found in step 1. This is where a computer\/calculator comes in handy.\n 3. Divide the difference between today's TP and the 20-day average of TP by the product of the standard deviation times 0.015.\n\nLambert set the constant at 0.015 in the denominator to ensure that approximately 70 to 80 percent of CCI values would fall between \u2212100 and +100. Since the numerator can be positive or negative, so can the CCI. The standard deviation is inversely proportional to sample size; the larger the sample the smaller the deviation. Since the standard deviation is in the denominator, a small lookback period will cause a more volatile CCI. A shorter CCI (10 periods) will also produce a smaller percentage of values between +100 and \u2212100. Conversely, a longer CCI (40 periods) will have a higher percentage of values between +100 and \u2212100.\n\nSince this oscillator usually falls between +100 and \u2212100 and is momentum based, most traders will use it as an overbought\/oversold indicator. However, since it is boundless extended readings above +100 or below \u2212100 can indicate very strong trend moves.\n\nThe weakness of the CCI is its variability due to the volatile nature of the underlying instrument that is being applied to. A volatile stock will cause the indicator to behave erratically and jump well above\/below the standard +100 and \u2212100. These benchmarks may have to be expanded based on the market being analyzed. Many traders also apply a smoothing function to the CCI in an attempt to eliminate knee-jerk reactions.\n\nWe will be discussing two trading algorithms based on the CCI (Box 2.5). The first will utilize the CCI in the same manner as the RSI and stochastic. The second algorithm will use the CCI in a completely opposite manner\u2014trend confirmation.\n\n* * *\n\n### Box 2.5 Donald Lambert's CCI OB\/OS System Description\n\n 1. If 9-day average of the CCI 20-day crosses above \u2212100, then \n 1. Buy MOC\n 2. If 9-day average CCI 20-day crosses below + 100, then \n 1. Sell Short MOC\n 3. If position is long \n 1. Take Profit: If close > entry price + 3 ATR Sell MOC\n 2. Protective Stop: If close < entry price \u2212 1 ATR Sell MOC\n 4. If position is short \n 1. Take Profit: If close < entry price \u2212 3 ATR BuyToCover MOC\n 2. Protective Stop: If close > entry price + 1 ATR, BuyToCover MOC\n\nNote that MOC indicates market on close.\n\n#### Donald Lambert's CCI OB\/OS System p\u2013code\n\n `Donald Lambert CCI OB\/OS\n `\n myCCIVal = average(cci(cciLen),smooth);\n If myCCIVal crosses above -100 then buy this bar on close\n If myCCIVal crosses below 100 then sellShort this bar on close\n If marketPosition = 1 then\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close\n If marketPosition =-1 then\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close\n\n* * *\n\nThe description of this algorithm looks very similar to the RSI and stochastic overbought\/oversold, but there is one esoteric difference. Notice how the entries are initiated. Long entries require the CCI to cross above \u2212100, meaning that the CCI has been in the oversold territory for at least one bar. Just the opposite is true for short entries; CCI must cross below +100. This is different from the other algorithms in that entries are delayed until the indicator starts moving in the same direction as the desired market direction. This delay is a double-edged sword in that you might get confirmation of market direction but at the cost of worse price.\n\nMany of today's trading and testing platforms have the keywords CROSS ABOVE and CROSS BELOW built into the programming language. These keywords are simple shortcuts meant to make programming easier to understand and implement. Using the CCI indicator as an example, here are the equivalent computer codes to the keywords:\n\n 1. **CROSS ABOVE** \u2212100 : CCI[1] < \u2212100 and CCI[0] > \u2212100\n 2. **CROSS BELOW** +100 : CCI[1] > +100 and CCI[0] < +100\n\nRemember the values inside the square brackets indicate the number of bars\/days in the past. In later chapters, where different platforms are discussed, you will see these keywords. Figure 2.10 shows some trades generated by this first CCI algorithm.\n\n**Figure 2.10** Trades generated by the CCI algorithm when it crosses above 100 and below \u2212100.\n\nSource: TradeStation\n\nSince the flowchart for this algorithm is so similar to the RSI and stochastic, it will not be shown for brevity's sake. However, the all-important performance metrics are shown in Table 2.5.\n\n**Table 2.5** Performance of CCI algorithm\n\n**Ticker** | **Net Profit** | **Max. Sys DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% of Winners** \n---|---|---|---|---|---|--- \nAD0_E0B | \u221238040.0 | \u221247030 | 156 | \u2212243.85 | 10.9 | 28.85 \nBP0_E0B | 7962.5 | \u221259875 | 144 | 55.3 | 12.38 | 35.42 \nC20_E0B | \u22122975.0 | \u221211538 | 151 | \u221219.7 | 9.61 | 30.46 \nCC20_E0B | 27820.0 | \u22128400 | 147 | 189.25 | 11.15 | 38.1 \nCL20_E0B | \u221222830.0 | \u221289180 | 154 | \u2212148.25 | 10.72 | 35.71 \nCT20_E0B | \u22127615.0 | \u221244780 | 145 | \u221252.52 | 10.82 | 35.86 \nCU0_E0B | \u221210900.0 | \u221241075 | 147 | \u221274.15 | 11.96 | 31.97 \nDX20_E0B | \u221237060.0 | \u221237110 | 148 | \u2212250.41 | 10.56 | 27.7 \nED0_E0B | \u2212353.1 | \u22121847 | 138 | \u22122.56 | 14.39 | 34.06 \nEMD0_E0B | \u221227880.0 | \u221247890 | 146 | \u2212190.96 | 10.93 | 29.45 \nES0_E0B | \u221234525.0 | \u221256038 | 152 | \u2212227.14 | 10.18 | 29.61 \nFC0_E0B | \u22121225.0 | \u221225213 | 146 | \u22128.39 | 10.16 | 32.19 \nFV0_E0B | \u22125656.1 | \u221211047 | 146 | \u221238.74 | 10.96 | 31.51 \nGC20_E0B | \u221226150.0 | \u221249330 | 152 | \u2212172.04 | 11.16 | 32.24 \nHG20_E0B | \u221234350.0 | \u221253500 | 129 | \u2212266.28 | 12.94 | 34.11 \nHO20_E0B | \u221253932.2 | \u2212112518 | 157 | \u2212343.52 | 10.13 | 31.85 \nKC20_E0B | \u221232737.5 | \u221254263 | 149 | \u2212219.71 | 11.17 | 29.53 \nKW20_E0B | 10325.0 | \u221224513 | 154 | 67.05 | 10.6 | 38.31 \nLB0_E0B | 21406.0 | \u221214058 | 150 | 142.71 | 9.41 | 36.67 \nLC0_E0B | \u221231750.0 | \u221242120 | 145 | \u2212218.97 | 10.19 | 24.14 \nLH0_E0B | \u2212860.0 | \u221213530 | 152 | 38.55 | 10.74 | 35.53 \nMP0_E0B | \u2212565.0 | \u22129145 | 146 | \u22123.87 | 12.99 | 36.99 \nNG20_E0B | \u221246040.0 | \u221281490 | 145 | \u2212317.52 | 10.99 | 29.66 \nNK0_E0B | \u221217900.0 | \u221254000 | 144 | \u2212124.31 | 9.93 | 29.86 \nOJ20_E0B | 26655.0 | \u22129105 | 159 | 167.64 | 11.19 | 39.62 \nPL20_E0B | 14920.0 | \u221240290 | 147 | 101.5 | 9.9 | 34.01 \nRB0_E0B | \u2212155710.8 | \u2212163069 | 155 | \u22121004.59 | 6.61 | 21.29 \nS20_E0B | 0.0 | 0 | 0 | N\/A | N\/A | N\/A \nSB20_E0B | \u22127604.8 | \u221225458 | 142 | \u221253.55 | 10.7 | 35.92 \nSI20_E0B | 77875.0 | \u221239745 | 155 | 502.42 | 11.57 | 39.35 \nTF0_E0B | \u221223300.0 | \u221247340 | 146 | \u2212159.59 | 9.36 | 30.14 \nTU0_E0B | \u22125704.0 | \u221211907 | 143 | \u221239.89 | 11 | 34.97 \nTY0_E0B | \u221230233.9 | \u221234125 | 140 | \u2212215.96 | 10.73 | 25 \nUS0_E0B | \u221263453.1 | \u221271422 | 151 | \u2212420.22 | 10.3 | 25.83 \nW20_E0B | 0.0 | 0 | 0 | N\/A | N\/A | N\/A\n\nNow, switching gears and using the CCI as a coincident indicator, Box 2.6 provides the description of a trend-following algorithm. A coincident indicator simply means it is confirming the current market direction.\n\n* * *\n\n### Box 2.6 Donald Lambert's CCI Trend-Following System\n\nmyCCIVal = 9-day average of the 20-day CCI\n\n 1. If the lowest myCCIVal for the past 3 days > 100, then \n 1. Buy MOC\n 2. If the highest myCCIVal for the past 3 days < \u2212100, then \n 1. Sell Short MOC\n 3. If position is long \n 1. Take Profit: If close > entry price + 5 ATR Sell MOC\n 2. Protective Stop: If close < entry price \u2212 3 ATR, Sell MOC\n 4. If position is short \n 1. Take Profit: If close < entry price \u2212 5 ATR, BuyToCover MOC\n 2. Protective Stop: If close > entry price + 3 ATR, BuyToCover MOC\n\nNote that MOC stands for market on close.\n\n#### Donald Lambert's CCI Trend-Following System p \u2212 code\n\n myCCIVal = average(cci(cciLen),smooth);\n If lowest(myCCIVal,3) > 100 then buy this bar on close;\n If highest(myCCiVal,3) < -100 then sellShort this bar on close;\n If marketPosition = 1 then\n If c > entryPrice + 5* avgTrueRange(10) then sell this bar on close\n if c < entryPrice - 3* avgTrueRange(10) then sell this bar on close\n If marketPosition =-1 then\n If c < entryPrice - 5* avgTrueRange(10) then buyToCover this bar on close\n if c > entryPrice + 3* avgTrueRange(10) then buyToCover this bar on close\n\n* * *\n\nThis trading algorithm description is somewhat different from the others we have thus discussed in this chapter. Instead of repeating the words for the 9-day average of the 20-day CCI, I simply assigned it to the variable myCCIVal. This is just like you would do in an actual programming language. The words _lowest_ and _highest_ were also introduced and used as a shortcut to see if the myCCIVal variable was above or below a certain level for the past three days. If the lowest myCCIVal for the past three days is greater than 100, then we know that the CCI did not dip below 100 during that time period. Trend detection occurs when the CCI stays in an extreme territory for several bars. This system is triggering a buy signal when the 9-day smoothed CCI stays above 100 for three days straight. The sell signal is triggered if the indicator stays below \u2212100 for three days straight. Since we are dealing with a trend-following approach, the profit objective as well as the stop loss has been increased to five and three times the average true range, respectively. As you can see, the instructions for entries are contained within a very precise if\u2013then construct and therefore can be represented by a flowchart. Again, this flowchart is so similar to the RSI, stochastic, and CCI #1 flowcharts that it would be terribly redundant to show it. Figure 2.11 does show how the system is more than capable of capturing the recent downturn in the Eurocurrency.\n\n**Figure 2.11** The CCI system detecting a downturn in the Eurocurrency.\n\nSource: TradeStation\n\nTable 2.6 shows the performance of the CCI Trend-Follower algorithm.\n\n**Table 2.6** Performance of CCI Algorithm as Coincident Indicator\n\n**Ticker** | **Net Profit** | **Max. Sys DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% of Winners** \n---|---|---|---|---|---|--- \nAD0_E0B | 36660.0 | \u221230990 | 105 | 349.14 | 32.94 | 42.86 \nBP0_E0B | \u221235562.5 | \u221295325 | 106 | \u2212335.5 | 32.35 | 34.91 \nC20_E0B | \u221212000.0 | \u221236738 | 104 | \u2212115.38 | 31.46 | 35.58 \nCC20_E0B | \u221251890.0 | \u221259700 | 112 | \u2212463.3 | 29.7 | 29.46 \nCL20_E0B | 55630.0 | \u221271870 | 111 | 501.17 | 31.23 | 39.64 \nCT20_E0B | \u221216015.0 | \u221239350 | 124 | \u2212129.15 | 27.79 | 37.1 \nCU0_E0B | 25037.5 | \u221272988 | 103 | 243.08 | 32.71 | 41.75 \nDX20_E0B | 40065.0 | \u221223940 | 106 | 377.97 | 33.84 | 43.4 \nED0_E0B | 6471.9 | \u22122294 | 95 | 68.13 | 36.76 | 48.42 \nEMD0_E0B | 18790.0 | \u221256220 | 101 | 186.04 | 34.5 | 42.57 \nES0_E0B | 23250.0 | \u221238975 | 96 | 242.19 | 36.84 | 39.58 \nFC0_E0B | 37612.5 | \u221222688 | 114 | 329.93 | 28.22 | 45.61 \nFV0_E0B | 26687.9 | \u221213273 | 104 | 256.61 | 34.76 | 41.35 \nGC20_E0B | \u221218150.0 | \u221276330 | 102 | \u2212177.94 | 35.28 | 39.22 \nHG20_E0B | 105212.5 | \u221252388 | 97 | 1084.66 | 35.79 | 47.42 \nHO20_E0B | 15036.0 | \u2212128789 | 107 | 140.52 | 31.31 | 36.45 \nKC20_E0B | 15881.3 | \u221261125 | 103 | 154.19 | 32.87 | 34.95 \nKW20_E0B | \u221226350.0 | \u221250213 | 116 | \u2212227.16 | 28.53 | 32.76 \nLB0_E0B | \u22127458.0 | \u221240667 | 126 | \u221259.19 | 25.39 | 39.68 \nLC0_E0B | \u22123700.0 | \u221222240 | 100 | \u221237 | 33.59 | 39 \nLH0_E0B | \u22124210.0 | \u221224600 | 110 | \u221238.27 | 31.46 | 36.36 \nMP0_E0B | 2385.0 | \u221212575 | 101 | 23.61 | 34.02 | 35.64 \nNG20_E0B | 84340.0 | \u2212118220 | 96 | 878.54 | 34.81 | 44.79 \nNK0_E0B | 29625.0 | \u221243025 | 102 | 290.44 | 32 | 41.18 \nOJ20_E0B | \u221223430.0 | \u221231785 | 111 | \u2212211.08 | 29.85 | 34.23 \nPL20_E0B | \u221219845.0 | \u221285060 | 116 | \u2212171.08 | 28.65 | 37.93 \nRB0_E0B | 78246.0 | \u221291774 | 118 | 663.1 | 25.95 | 43.22 \nS20_E0B | 0.0 | 0 | 0 | N\/A | N\/A | N\/A \nSB20_E0B | 23598.4 | \u221216733 | 108 | 218.5 | 30.12 | 42.59 \nSI20_E0B | \u221297730.0 | \u2212186135 | 113 | \u2212864.87 | 31.5 | 34.51 \nTF0_E0B | \u221230550.0 | \u221255750 | 92 | \u2212332.07 | 35.45 | 36.96 \nTU0_E0B | 21468.0 | \u22128188 | 93 | 230.84 | 38.05 | 38.71 \nTY0_E0B | 6578.6 | \u221222531 | 98 | 67.13 | 35.56 | 36.73 \nUS0_E0B | 40874.3 | \u221228375 | 99 | 412.87 | 35.38 | 41.41 \nW20_E0B | 0.0 | 0 | 0 | N\/A | N\/A | N\/A\n\n### Gerald Appel's MACD\u2014Moving Average Convergence Divergence\n\nThe Moving Average Convergence Divergence (MACD) indicator was created in the late 1970s by Gerald Appel. Basically, the indicator plots the difference between a fast and slow exponential moving average. The difference line is usually plotted oscillating around a zero line. Another line representing a smoothed version of the difference line is plotted as well. The smoothed version of the difference between the two moving averages is considered the trigger. Action is usually taken when the trigger crosses the difference line. In addition, it is common to see a histogram representation of the relationship between the difference line and the trigger. The MACD is a quick snapshot summary of the relationship between two different length-moving averages.\n\nWe will discuss moving averages in the last part of this chapter, but a little knowledge of averages is necessary to fully grasp the MACD. A trend change is usually indicated when a shorter (more sensitive) average crosses above\/below a longer (less sensitive) average. Unfortunately, moving average crossovers lag current market conditions, and here is where the real beauty of the MACD is revealed. The histogram component can quickly reveal when the difference between the two moving averages (MACD) and the smoothed version of MACD (trigger) is converging or diverging. Convergence means the MACD line and its associated trigger are coming together and divergence means simply the two are growing apart. As prices of an instrument increase, the short-term moving average will grow quicker than a longer-term average. The MACD histogram will reflect this momentum. As prices start to slow, the histogram will start moving in the opposite direction.\n\n**Calculation of MACD using 12-day and 26-day moving averages:**\n\n 1. Calculate a 12-period EMA of price for the chosen time period.\n 2. Calculate a 26-period EMA of price for the chosen time period.\n 3. Subtract the 26-period EMA from the 12-period EMA.\n 4. Calculate a 9-period EMA of the result obtained from step 3.\n\nThis 9-period EMA line is overlaid on a histogram that is created by subtracting the 9-period EMA from the result in step 3, which is called the MACD line, but it is not always visibly plotted on the MACD representation on a chart.\n\nA trading algorithm can be derived by waiting for the histogram to form a two-bar high pivot (two bars to the left and to the right are shorter than the center bar) and then entering a short position. Momentum has been positive but it is beginning to slow. A long position can be initiated when a two-bar pivot low is formed in the MACD histogram. Figure 2.12 shows how the pivot points in the histogram can initiate trade signals.\n\n**Figure 2.12** Histogram pivot points can initiate trade signals.\n\nBased on our knowledge of the MACD and the chart examples, Box 2.7 shows a simple MACD histogram-trading algorithm.\n\n* * *\n\n### Box 2.7 Gerald Appel's MACD Histogram System\n\nNotice how the algorithm description in this example is getting closer and closer to pseudocode. As you evolve as a system tester, you will notice how the lines that separate description, pseudocode, and actual code start to blur. LeftBar2 is the second bar to the left of the pivot high\/low bar and LeftBar1 is the first bar to the left of the pivot. The other variable names should be self-explanatory.\n\n 1. myMACD = MACD(C,12,26)\n 2. myMACDAvg = Xaverage(MACD,9)\n 3. myMACDDiff = myMACD \u2212 myMACDAvg\n 4. leftBar2 = myMACDDiff[4]\n 5. leftBar1 = myMACDDiff[3]\n 6. centerBar = myMACDiff[2]\n 7. rightBar1 = myMACDDiff[1]\n 8. rightBar2 = myMACDDiff[0]\n 9. If leftBar2 < 0 and rightBar2 < 0 and centerBar < leftBar1 and centerBar < leftBar2 and centerBar < rightBar1 and centerBar < rightBar2, then \n 1. Buy MOC\n 10. If leftBar2 > 0 and rightBar2 > 0 and centerBar > leftBar1 and centerBar > leftBar2 and centerBar > rightBar1 and centerBar > rightBar2, then \n 1. SellShort MOC\n 11. If position is long \n 1. Take Profit: If close > entry price + 3 ATR Sell MOC\n 2. Protective Stop: If close < entry price \u2212 1 ATR Sell MOC\n 12. If position is short \n 1. Take Profit: If close < entry price \u2212 3 ATR BuyToCover MOC\n 2. Protective Stop: If close > entry price + 1 ATR, BuyToCover MOC\n 3. *MOC = market on close\n\n#### Gerald Appel's MACD Histogram System p \u2013 code\n\n `Gerald Appels MACD histogram algorithm\n `Buys \u2013 histogram forms a low 2 bar pivot with all bars below 0\n `Shorts \u2013 histogram forms a high 2 bar pivot with all bars above 0\n MACDAvg = XAverage( MyMACD,9)\n MACDDiff = myMACD \u2013 MACDAvg\n leftBar2 = MACDDiff[4]\n leftBar1 = MACDDiff[3]\n centerBar = MACDDiff[2]\n rightBar1 = MACDDiff[1]\n rightBar2 = MACDDiff[0]\n If leftBar2 < 0 and rightBar2 < 0 and centerBar < leftBar1 and centerBar < leftBar2 and\n centerBar < rightBar1 and centerBar < rightBar2 then\n Buy this bar on close\n If leftBar2 > 0 and rightBar2 > 0 and centerBar > leftBar1 and centerBar > leftBar2 and\n centerBar > rightBar1 and centerBar > rightBar2 then\n SellShort this bar on close\n If marketPosition = 1 then\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close\n If marketPosition =-1 then\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close\n\n* * *\n\nThe MACD can be classified as an absolute price oscillator (APO), due to the fact it deals with the actual prices of moving averages rather than percentage changes. This makes the MACD different from the other indicators we have thus discussed. A percentage price oscillator (PPO) computes the difference between two moving averages of price divided by the longer moving average value.\n\nWhile an APO will show greater levels for higher-priced securities and smaller levels for lower-priced securities, a PPO calculates changes relative to price. Subsequently, a PPO is preferred when comparing oscillator values between different types of trading instruments, especially those with substantially different prices, or comparing oscillator values for the same instrument at significantly different times. The manner in which we developed the MACD algorithm does not care about absolute prices because it looks at the difference between the moving averages as either positive or negative; it does not care about the magnitude of difference.\n\n## Price-Based Indicators\n\nPrice-based indicators reflect trend and volatility. As we stated earlier, applying a moving average to an instrument's historical data will smooth out the data and soften wild market swings. In other words, a moving average eliminates a good portion of the noise associated with daily price changes.\n\n### Simple, Exponential, and Weighted Moving Averages\n\nThe most often used moving average is the simple version. Here, you sum up the closing prices over the past _N_ days and then divide by _N_. The exponential moving average calculation uses a smoothing factor to place a higher weight on recent data points and is regarded as much more efficient than the linear weighted average. Having an understanding of the calculations is not generally required for most traders because most charting packages do the calculation for you. But if you are interested in the calculations, here are the steps involved in calculating the exponential and weighted moving averages:\n\n 1. Seed the exponential average initially with a simple moving average.\n 2. Calculate the smoothing factor: multiplier = 2 \/ (EMA length + 1).\n 3. EMA[0] = (close[0] \u2212 EMA[1]) * multiplier + EMA[1].\n\nThe key to the EMA calculation is the smoothing factor multiplier. If we were calculating a 20-day EMA, the multiplier would be equal to 2 \/ 21, or 0.0952. In this example, a weighting of nearly 10 percent is applied to the most recent data point. A weighted moving average is slightly more complicated to calculate. Sticking with 20 periods, here are the steps involved in the calculation:\n\n 1. Sum up the values of the length of moving average : 20 + 19 + 18 + 17 +16 +15 + 14 + 13 + 12 + 11 + 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 +1 = 210.\n 2. Multiply the oldest price by 1 \/20 and second oldest by 2\/20 and third oldest by 3\/20 and so on.\n 3. Sum up the products and you will have a weighted moving average. As you can see, the most recent data is weighted the most.\n\nThe weighted moving average addresses the problem of equal weighting. Figure 2.13 shows the three different 20-day moving averages across several days of data.\n\n**Figure 2.13** Three different 20-day moving averages.\n\nSource: TradeStation\n\nSo which moving average is the best? It depends on the situation and the data that is being analyzed. As a pure price\/average crossover-trading algorithm the following table might provide some insight. An 80-day period of each moving average was analyzed across 35 futures markets over a test period of 30 years and the results are shown in Table 2.7.\n\n**Table 2.7** Examples of Trades Generated by Stochastics\n\n**Ticker** | **Simple Moving Average** | **Exponential Moving Average** | **Weighted Moving Average** \n---|---|---|--- \n**Net Profit** | **MAX. Sys. DD** | **Trds** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** | **Net Profit** | **MAX. Sys. DD** | **Trds** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** | **Net Profit** | **MAX. Sys.Drawdown** | **Trds** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** \nAD0_E0B | \u22122640 | \u221270090 | 404 | \u22126.53 | 18.62 | 15.59 | 7700 | \u221253380 | 446 | 17.26 | 16.96 | 16.14 | \u22123270 | \u221273090 | 493 | \u22126.63 | 15.59 | 17.04 \nBP0_E0B | 74113 | \u2212179000 | 440 | 168.44 | 18.52 | 15.91 | 58013 | \u2212183950 | 488 | 118.88 | 16.8 | 16.6 | 40463 | \u2212203063 | 566 | 71.49 | 14.62 | 18.2 \nC20_E0B | 18213 | \u221226463 | 378 | 48.18 | 21.41 | 17.72 | \u221229388 | \u221246100 | 484 | \u221260.72 | 16.94 | 14.67 | \u221210388 | \u221232075 | 512 | \u221220.29 | 16.07 | 17.77 \nCC20_E0B | \u2212117190 | \u2212120040 | 487 | \u2212240.64 | 16.74 | 14.37 | \u2212108430 | \u2212111280 | 533 | \u2212203.43 | 15.38 | 15.38 | \u2212109730 | \u2212113060 | 575 | \u2212190.83 | 14.33 | 16 \nCL20_E0B | 171330 | \u221287180 | 375 | 456.88 | 21.48 | 19.47 | 126550 | \u221285620 | 425 | 297.76 | 19.07 | 19.76 | 148610 | \u221271240 | 519 | 286.34 | 15.8 | 20.81 \nCT20_E0B | 39545 | \u221248520 | 435 | 90.91 | 18.64 | 17.01 | 34695 | \u221239435 | 485 | 71.54 | 16.82 | 16.49 | 1405 | \u221268055 | 561 | 2.5 | 14.68 | 17.47 \nCU0_E0B | 90850 | \u221254625 | 401 | 226.56 | 20.23 | 18.95 | 94900 | \u221255238 | 437 | 217.16 | 18.65 | 18.76 | 120775 | \u221267600 | 477 | 253.2 | 17.17 | 20.75 \nDX20_E0B | 16685 | \u221249235 | 400 | 41.71 | 19.82 | 16.5 | 34655 | \u221227280 | 431 | 80.41 | 18.46 | 19.26 | 41255 | \u221230580 | 490 | 84.19 | 16.53 | 18.98 \nED0_E0B | \u221217053 | \u221219866 | 355 | \u221248.04 | 22.72 | 12.68 | \u221211034 | \u221214566 | 339 | \u221232.55 | 23.75 | 14.16 | \u221215378 | \u221219566 | 414 | \u221237.15 | 19.63 | 14.98 \nEMD0_E0B | 20970 | \u221234960 | 293 | 71.57 | 20.91 | 18.43 | 26900 | \u221232140 | 340 | 79.12 | 18.16 | 19.71 | \u221288920 | \u221289980 | 450 | \u2212197.6 | 14.14 | 17.56 \nES0_E0B | \u221250000 | \u221267588 | 470 | \u2212106.38 | 17.43 | 14.68 | \u221269200 | \u221270688 | 500 | \u2212138.4 | 16.44 | 15.4 | \u221275350 | \u221275613 | 578 | \u2212130.36 | 14.36 | 17.47 \nFC0_E0B | 49313 | \u221229350 | 358 | 137.74 | 22.56 | 18.16 | 83288 | \u221218063 | 374 | 222.69 | 21.64 | 22.73 | 73038 | \u221233000 | 480 | 152.16 | 17.08 | 20.21 \nFV0_E0B | \u22121805 | \u221228908 | 345 | \u22125.23 | 20.61 | 15.07 | 17213 | \u221221032 | 381 | 45.18 | 18.76 | 17.32 | \u221215784 | \u221235951 | 479 | \u221232.95 | 15.29 | 16.28 \nGC20_E0B | \u2212114780 | \u2212125070 | 471 | \u2212243.69 | 17.32 | 12.95 | \u2212127580 | \u2212137870 | 565 | \u2212225.81 | 14.6 | 13.63 | \u2212126260 | \u2212137290 | 591 | \u2212213.64 | 14.01 | 14.89 \nHG20_E0B | 134138 | \u221239163 | 417 | 321.67 | 19.43 | 17.03 | 79013 | \u221258988 | 477 | 165.64 | 17.11 | 17.61 | 61863 | \u221274013 | 541 | 114.35 | 15.21 | 19.59 \nHO20_E0B | 22025 | \u2212154637 | 457 | 48.19 | 17.8 | 15.54 | 418 | \u2212152914 | 507 | 0.82 | 16.15 | 17.16 | 39118 | \u2212102509 | 571 | 68.51 | 14.45 | 18.04 \nKC20_E0B | 99019 | \u2212152544 | 405 | 244.49 | 19.92 | 17.04 | 45844 | \u2212167219 | 501 | 91.5 | 16.3 | 15.97 | 122619 | \u221293356 | 517 | 237.17 | 15.82 | 18.76 \nKW20_E0B | \u221216163 | \u221241075 | 465 | \u221234.76 | 17.59 | 15.7 | 2588 | \u221229713 | 495 | 5.23 | 16.59 | 16.77 | \u221242938 | \u221259900 | 591 | \u221272.65 | 14.06 | 16.24 \nLB0_E0B | 87685 | \u221226515 | 392 | 223.69 | 20.69 | 20.92 | 68033 | \u221223342 | 442 | 153.92 | 18.46 | 20.14 | 70031 | \u221226345 | 534 | 131.14 | 15.46 | 21.35 \nLC0_E0B | \u221225000 | \u221241790 | 398 | \u221262.81 | 20.39 | 16.33 | \u221233400 | \u221249230 | 464 | \u221271.98 | 17.64 | 17.03 | \u221250560 | \u221266380 | 566 | \u221289.33 | 14.64 | 17.67 \nLH0_E0B | 280 | \u221229220 | 394 | 0.71 | 20.59 | 18.02 | \u221210340 | \u221236880 | 484 | \u221221.36 | 16.95 | 18.39 | \u22127820 | \u221234840 | 520 | \u221215.04 | 15.84 | 19.42 \nMP0_E0B | 16770 | \u221222620 | 238 | 70.46 | 22.1 | 18.07 | 5320 | \u221226255 | 274 | 19.42 | 19.33 | 17.52 | 21125 | \u221224845 | 307 | 68.81 | 17.62 | 22.15 \nNG20_E0B | 238960 | \u221288090 | 306 | 780.92 | 21.52 | 20.26 | 161390 | \u2212116370 | 380 | 424.71 | 17.53 | 18.95 | 209010 | \u2212121120 | 394 | 530.48 | 17.14 | 19.04 \nNK0_E0B | 69875 | \u221268250 | 306 | 228.35 | 21.24 | 21.57 | 47275 | \u221275975 | 379 | 124.74 | 17.34 | 21.37 | \u221262625 | \u221272225 | 472 | \u2212132.68 | 14.29 | 19.07 \nOJ20_E0B | \u22128818 | \u221239850 | 386 | \u221222.84 | 20.87 | 17.1 | \u221232283 | \u221254738 | 448 | \u221272.06 | 18.12 | 17.86 | \u221225903 | \u221255323 | 530 | \u221248.87 | 15.47 | 18.11 \nPL20_E0B | 33180 | \u221260775 | 457 | 72.6 | 17.8 | 15.32 | 52050 | \u221264165 | 507 | 102.66 | 16.15 | 16.57 | \u22123540 | \u221261390 | 585 | \u22126.05 | 14.13 | 17.09 \nRB0_E0B | 60850 | \u221268858 | 410 | 148.41 | 19.58 | 18.78 | 92216 | \u221287668 | 458 | 201.35 | 17.63 | 21.83 | 181639 | \u221261591 | 537 | 338.25 | 15.3 | 21.97 \nS20_E0B | \u221255025 | \u221267225 | 454 | \u2212121.2 | 17.99 | 15.42 | \u221239125 | \u221256238 | 528 | \u221274.1 | 15.61 | 15.91 | \u221216825 | \u221259150 | 560 | \u221230.04 | 14.78 | 17.14 \nSB20_E0B | 6410 | \u221233259 | 383 | 16.74 | 21.01 | 17.49 | \u221212279 | \u221242206 | 485 | \u221225.32 | 16.8 | 14.64 | 5026 | \u221236258 | 501 | 10.03 | 16.3 | 16.57 \nSI20_E0B | \u2212132065 | \u2212180155 | 449 | \u2212294.13 | 18.12 | 14.25 | \u2212171125 | \u2212205775 | 523 | \u2212327.2 | 15.7 | 14.53 | \u2212101005 | \u2212146075 | 583 | \u2212173.25 | 14.18 | 16.64 \nTF0_E0B | \u221230230 | \u221264260 | 191 | \u2212158.27 | 18.95 | 17.8 | \u221239050 | \u221268200 | 217 | \u2212179.95 | 16.8 | 18.43 | \u221298130 | \u2212119750 | 262 | \u2212374.54 | 14.39 | 18.7 \nTF20_E0B | \u221230155 | \u221263300 | 193 | \u2212156.24 | 18.74 | 17.62 | \u221240420 | \u221269560 | 217 | \u2212186.27 | 16.78 | 18.43 | \u221298140 | \u2212119760 | 262 | \u2212374.58 | 14.37 | 18.7 \nTU0_E0B | 22205 | \u221219544 | 325 | 68.32 | 20.19 | 13.23 | 37415 | \u221213961 | 311 | 120.3 | 21.06 | 16.08 | 18004 | \u221224410 | 392 | 45.93 | 17.11 | 16.07 \nTY0_E0B | 28377 | \u221229506 | 385 | 73.71 | 21.01 | 17.4 | 38757 | \u221222544 | 429 | 90.34 | 18.96 | 18.18 | 15044 | \u221234222 | 488 | 30.83 | 16.78 | 19.88 \nUS0_E0B | \u221212731 | \u221273538 | 437 | \u221229.13 | 18.63 | 18.31 | \u22123851 | \u221269806 | 501 | \u22127.69 | 16.38 | 18.16 | 6405 | \u221248757 | 520 | 12.32 | 15.81 | 20.96 \nW20_E0B | \u221240788 | \u221257050 | 464 | \u221287.9 | 17.63 | 15.3 | \u221234238 | \u221249750 | 516 | \u221266.35 | 15.95 | 14.73 | \u221235588 | \u221246250 | 551 | \u221264.59 | 15 | 17.06\n\nThe performances for the three averaging methods aren't too dissimilar; they seem to make or lose money in the same sectors. However, on closer examination, at the portfolio level, notice the average trade for the weighted average is considerably lower than its siblings. This might indicate why it is the least used averaging method in technical analysis. While reviewing the performance, keep in mind that this testing did not take into consideration trade management other than allowing the algorithm to reverse its position; there weren't any protective stops or profit objectives. The fact is, trend following doesn't use a lot of trade management. Many trend algorithms will utilize a disaster stop but usually will let profits run until a reversal is signaled. If you think about this, it makes sense; a moving average is an indicator of trend and it will put you into the market in the direction it thinks the trend is going. It is self-adapting. The following is the pseudocode used in the testing of these three simplistic methodologies:\n\n `Trend Following with Different Averaging Methods\n `Simple Price MAV Cross Over\n myAVG = SMA(C,80) `Comment out the two you do not want to use\n `myAVG = WMA(C,80) `by placing a single quote at the start of the line\n `myAVG = EMA(C,80)\n If close of today > myAVG then\n Buy this bar on close\n If close of today < myAVG then\n SellShort this bar on close\n\n### Bollinger Bands\n\nJohn Bollinger is the originator of this volatility-based channel indicator. It is considered a channel because the indicator consists of two lines that never intersect. The channel width is based on a standard deviation value, which is derived from an _N_ -length moving average. Most Bollinger Bands are one or two standard deviations above\/below the moving average. In a perfectly \"normal\" world, 95 percent of values from a sample will stay within two standard deviations of its mean. Theoretically speaking, would it not make sense that once price rises to the upper channel\/band there exists a higher probability of price reverting to its mean? Or does it make more sense that a penetration of a band indicates strong momentum and the beginning of a trend. Like many indicators, Bollinger Bands can be used as mean reversion as well as trend following. The most successful trend-following systems use a longer-length Bollinger Band penetration algorithm for trade entry. Mean-reversion traders use a much shorter length input for this indicator.\n\nIf the market demonstrates enough momentum to carry price through two standard deviations, it seems there is a real good chance it has enough gusto to continue on in that direction. Well, this is what the trend followers of the 1990s thought, and they turned out to be right.\n\nFigure 2.14 shows a 60-day two-standard-deviation (SD) Bollinger Band on crude oil. The Bollinger Bands are the outside lines and the centerline is the moving average. This is a perfect example of why this trend entry technique gained so much popularity in the 1990s and in the new millennium. Crude penetrated the lower band and never looked back until the trend entered into a congestive phase\u2014a $50 move or $50,000 per contract. That's right, $50,000! And you thought I wasn't going to reveal the Holy Grail! Remember, one monster trade doesn't make a trading algorithm.\n\n**Figure 2.14** A 60-day, two-SD Bollinger Band on crude oil.\n\nSource: TradeStation\n\nHere's how you calculate Bollinger Bands:\n\n**Calculation of Bollinger Bands using 60 days and 2 standard deviations:**\n\n 1. Calculate a 60-period SMA of price for the chosen time period.\n 2. Calculate the standard deviation of the 60-day sample (use a computer).\n 3. The top or upper band is the 60-period SMA + 2 standard deviations.\n 4. The bottom or lower band is the 60-period SMA \u2212 2 standard deviations.\n\nLet's put the Bollinger Band indicator to a test utilizing a common trend-following algorithm (Box 2.8).\n\n* * *\n\n### Box 2.8 Using John Bollinger's Bands as a Trend Follower\n\n 1. Buy when market closes above top band.\n 2. Sell short when market closes below bottom band.\n 3. Sell when market position is long and market closes below average.\n 4. Cover when market position is short and market closes above average.\n 5. myAvg = Average(C,60) ' 60-day moving average calculation\n 6. myTopBand = BollingerBand(C,60,+2) ' 2 std dev above average\n 7. myBotBand = BollingerBand(C,60, \u22122) ' the \u2212 2 means below average\n 8. If close crosses above myTopBand, then \n 1. Buy MOC\n 9. If close crosses below myBotBand, then \n 1. SellShort MOC\n 10. If position is long, then \n 1. If close crosses below myAvg, then \n 1. Sell MOC\n 11. If position is short, then \n 1. If close crosses above myAvg, then \n 1. BuyToCover MOC\n\n* * *\n\nThe beauty of this algorithm is in its simplicity; we don't even need to sketch a flowchart. There is another facet of this algorithm that makes it a winner\u2014it's self-adaptive. Meaning the bands are moving (adapting) around the average based on an intrinsic property of the underlying instrument. And that property is volatility. Volatility reveals one of the most important things we need to know about an instrument, and that is risk. Risk is directly proportional to volatility\u2014the larger the swings, the riskier the market. I am jumping the gun here, but we will use this risk measure as a filter in version 2 of the Bollinger Band trend algorithm. Volatility also informs us of market noise. When the Bollinger Bands expand during high levels of volatility, they are indicating a chaotic situation\u2014a situation where entry criteria should be made more difficult to trigger. The following is the pseudocode for version 1 of the trading algorithm:\n\n `Trend Following with Bollinger Bands\n `Utilizing 60-day average and 2 standard deviations\n `Version 1\n myAVG = SMA(C,60)\n myTopBand = BollingerBand(C,60,+2)\n myBotBand = BollingerBand(C,60,-2)\n If close > myTopBand then\n Buy this bar on close\n If close < myBotBand then\n SellShort this bar on close\n If marketPosition = 1 and c > myAvg then sell this bar on close\n If marketPosition =-1 and c < myAvg then buyToCover this bar on close\n\nTable 2.8 shows the individual results of Bollinger Band version 1 across 35 futures markets.\n\n**Table 2.8** Performance of Bollinger Band Algorithm Version 1\n\n**Bollinger Band [60 Days 2 Standard Deviations]** | | | \n---|---|---|--- \n**Ticker** | **Net Profit** | **Max DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% Winners** \n**_< Portfolio>_** | **_1319369_** | **_\u2212380897_** | **_3580_** | **_369_** | **_44_** | **_36_** \nAD0_E0B | 30100 | \u221225600 | 95 | 317 | 45 | 35 \nBP0_E0B | 86888 | \u221290825 | 107 | 812 | 41 | 34 \nC20_E0B | \u22121263 | \u221223038 | 119 | \u221211 | 42 | 35 \nCC20_E0B | \u221267870 | \u221269300 | 123 | \u2212552 | 33 | 22 \nCL20_E0B | 168160 | \u221255940 | 101 | 1665 | 47 | 47 \nCT20_E0B | 54050 | \u221234175 | 112 | 483 | 40 | 31 \nCU0_E0B | 167738 | \u221227425 | 91 | 1843 | 50 | 44 \nDX20_E0B | 84575 | \u221213820 | 94 | 900 | 49 | 47 \nED0_E0B | 4997 | \u22123363 | 105 | 48 | 48 | 31 \nEMD0_E0B | \u221218880 | \u221238940 | 92 | \u2212205 | 39 | 29 \nES0_E0B | \u221241925 | \u221252213 | 120 | \u2212349 | 36 | 31 \nFC0_E0B | 55438 | \u221225650 | 101 | 549 | 49 | 41 \nFV0_E0B | 23631 | \u221215335 | 89 | 266 | 45 | 39 \nGC20_E0B | \u221219280 | \u221259660 | 111 | \u2212174 | 39 | 32 \nHG20_E0B | 76650 | \u221242513 | 111 | 691 | 44 | 37 \nHO20_E0B | 74941 | 71391 | 116 | 646 | 39 | 37 \nKC20_E0B | 100294 | \u2212108269 | 99 | 1013 | 45 | 38 \nKW20_E0B | 10800 | \u221221350 | 109 | 99 | 41 | 31 \nLB0_E0B | 37973 | \u221224997 | 109 | 348 | 44 | 38 \nLC0_E0B | \u221211770 | \u221230010 | 121 | \u221297 | 39 | 28 \nLH0_E0B | 10880 | \u221225480 | 113 | 96 | 42 | 37 \nMP0_E0B | 6755 | \u221225070 | 68 | 99 | 45 | 37 \nNG20_E0B | 175690 | \u221299650 | 87 | 2019 | 47 | 45 \nNK0_E0B | 48150 | \u221241675 | 85 | 566 | 46 | 36 \nOJ20_E0B | \u221210130 | \u221245408 | 110 | \u221292 | 43 | 36 \nPL20_E0B | 55340 | \u221234340 | 109 | 508 | 41 | 31 \nRB0_E0B | 124147 | \u221258171 | 109 | 1139 | 44 | 39 \nS20_E0B | 19475 | \u221238125 | 115 | 169 | 41 | 36 \nSB20_E0B | 31944 | \u221213788 | 100 | 319 | 48 | 42 \nSI20_E0B | \u221225660 | \u2212113680 | 111 | \u2212231 | 39 | 29 \nTF0_E0B | \u221214570 | \u221251590 | 49 | \u2212297 | 41 | 37 \nTU0_E0B | 37075 | \u22126975 | 78 | 475 | 50 | 42 \nTY0_E0B | 42466 | \u221219490 | 98 | 433 | 46 | 40 \nUS0_E0B | 22038 | \u221242338 | 109 | 202 | 42 | 39 \nW20_E0B | \u221219475 | \u221234225 | 114 | \u2212171 | 38 | 32\n\nIn the prior paragraphs, I hinted of a version 2 of this algorithm utilizing the volatility as trading filter. Risk aversion is most often the number-one consideration in the development of a trading algorithm, and we can use the volatility as a risk measure and modify version 1 to make it more risk averse. Looking back at the results you will notice a relatively high maximum drawdown at the portfolio level\u2014greater than 30 percent. In the world of hedge funds, this is an acceptable level\u2014I am not kidding! Some of the most successful hedge fund managers have taken their clients down more than 40 percent before rebounding. This is the main difference between hedge fund participants and the typical investor. The trade-off for higher returns is, of course, higher risk. Let's see if we can be a better hedge fund manager and reduce that 30 percent plus drawdown. Let's assume we have a million-dollar allocation (remember, we are in a dream world), we only want to risk 0.2 percent (0.002 or $2,000 per trade), and we don't want to reinvest profits (at this point). How can we use this information to reduce drawdown in version 2 of our trading algorithm?\n\nVersion 1 buys on penetration of upper Bollinger Band and gets out on the penetration of the moving average. So our initial trade risk can be defined as the distance between the upper band and the moving average. If we equate this distance to dollars, then we can filter out any trades that exceed our acceptable risk amount of $2,000. Now, will this guarantee that our largest loss will be $2,000 or less? No! Remember when I stated the bands were self-adapting? During the life of any given trade, the bands could expand and the distance between the outer bands and the moving average could grow well beyond our $2,000. This could result in an individual trade loss greater than that amount. Well, can we at least guarantee the maximum drawdown will decrease? Again, no! Maximum drawdown is a consequence of a losing streak. Even though we are filtering trades (eliminating what we consider too risky), that doesn't necessarily mean the trades involved in the losing streak will be eliminated. The filtering process might even eliminate the trades that pull the equity curve out of the drawdown. So, theoretically the risk aversion overlay might not help at all and might even make matters worse. Let's see for ourselves and use the following pseudocode on the same 35 markets:\n\n `Trend Following with Bollinger Bands\n `Utilizing 60-day average and 2 standard deviations\n `Version 2 - don't take any trade with risk > $2,000\n myAVG = SMA(C,60)\n myTopBand = BollingerBand(C,60,+2)\n myBotBand = BollingerBand(C,60,-2)\n filterTrade = false\n `convert price range to dollars by multiplying by dollar value of points\n If (myTopBand - myAvg) * BigPointValue > 2000 then\n filterTrade = true\n If filterTrade = false then\n If close > myTopBand then\n Buy this bar on close\n If close < myBotBand then\n SellShort this bar on close\n If marketPosition = 1 and c < myAvg then sell this bar on close\n If marketPosition =-1 and c > myAvg then buyToCover this bar on close\n\nBefore hitting the **TEST** button, let's quickly go over the pseudocode. The only code that was added was the Boolean (true or false) typed variable **filterTrade** and its calculation. On every bar, it is initially turned off. The only way it is turned on is when the distance in terms of dollars between the upper band and the moving average exceeds $2,000. If **filterTrade** is on or true, the trade entry logic is bypassed, thereby skipping the trade. Why did we just use the top band and the moving average in our risk calculation? Shouldn't we use the bottom band and the average for short trades? One calculation is all that is needed since the distance between the top band and the average is always the same as the distance between the average and the bottom band\u2014in this case, two standard deviations. Ready to hit the test button? Table 2.9 shows the results of version 2 of the algorithm.\n\n**Table 2.9** Performance of Bollinger Band Algorithm Version 2\n\n**Bollinger Band [60 Days 2 Standard Deviations with $2,000 Trade Filter]** \n--- \n**Ticker** | **Net Profit** | **Max DD** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **% Winners** \n**_< Portfolio>_** | **_513207_** | **_\u2212103462_** | **_2224_** | **_231_** | **_43_** | **_34_** \nAD0_E0B | 7360 | \u221219900 | 57 | 129 | 42 | 35 \nBP0_E0B | 10625 | \u22127075 | 1 | 10625 | 69 | 100 \nC20_E0B | \u22122788 | \u221215050 | 108 | \u221226 | 42 | 34 \nCC20_E0B | \u221248940 | \u221249270 | 110 | \u2212445 | 33 | 22 \nCL20_E0B | 29460 | \u22129970 | 45 | 655 | 50 | 51 \nCT20_E0B | 12385 | \u221231030 | 77 | 161 | 39 | 30 \nCU0_E0B | 50688 | \u22126488 | 4 | 12672 | 114 | 75 \nDX20_E0B | 71510 | \u221211830 | 56 | 1277 | 49 | 48 \nED0_E0B | 4997 | \u22123363 | 105 | 48 | 48 | 31 \nEMD0_E0B | 19720 | \u22128640 | 37 | 533 | 44 | 27 \nES0_E0B | \u221240288 | \u221244075 | 80 | \u2212504 | 33 | 23 \nFC0_E0B | 57950 | \u221214975 | 75 | 773 | 51 | 41 \nFV0_E0B | 25318 | \u221212041 | 84 | 301 | 45 | 40 \nGC20_E0B | 5840 | \u221221110 | 74 | 79 | 39 | 32 \nHG20_E0B | 6450 | \u221218325 | 65 | 99 | 42 | 29 \nHO20_E0B | 24291 | \u221227344 | 50 | 486 | 38 | 36 \nKC20_E0B | 51275 | \u221235669 | 22 | 2331 | 39 | 41 \nKW20_E0B | 7188 | \u221223375 | 90 | 80 | 40 | 27 \nLB0_E0B | 53134 | \u221212761 | 51 | 1042 | 49 | 43 \nLC0_E0B | \u221212630 | \u221230100 | 117 | \u2212108 | 39 | 27 \nLH0_E0B | 12690 | \u221220690 | 97 | 131 | 41 | 38 \nMP0_E0B | 2770 | \u221222135 | 62 | 45 | 43 | 34 \nNG20_E0B | 38580 | \u221214000 | 16 | 2411 | 50 | 50 \nNK0_E0B | 35250 | \u221212925 | 12 | 2938 | 50 | 33 \nOJ20_E0B | \u221216875 | \u221249565 | 99 | \u2212170 | 41 | 34 \nPL20_E0B | \u221211870 | \u221230065 | 72 | \u2212165 | 38 | 25 \nRB0_E0B | 20830 | \u221220086 | 40 | 521 | 43 | 43 \nS20_E0B | \u221210763 | \u221234438 | 79 | \u2212136 | 37 | 35 \nSB20_E0B | 17097 | \u221212638 | 91 | 188 | 47 | 42 \nSI20_E0B | \u22124305 | \u221242550 | 66 | \u221265 | 40 | 27 \nTF0_E0B | 18470 | \u22126380 | 3 | 6157 | 78 | 67 \nTU0_E0B | 28837 | \u22127888 | 76 | 379 | 48 | 41 \nTY0_E0B | 37841 | \u221219212 | 73 | 518 | 46 | 41 \nUS0_E0B | 39185 | \u221216650 | 38 | 1031 | 44 | 47 \nW20_E0B | \u221228075 | \u221236663 | 92 | \u2212305 | 37 | 28\n\nMission accomplished! Or was it? The maximum drawdown was reduced from to $381K to $103K\u2014a whopping 73 percent. However, as we all know, reward is proportional to risk and the total profit dropped from $1.3M to less than $600K, or more than 50 percent. Was it worth it? What if we used $2,500 risk instead, or what if... You can see how this stuff can become addictive. We could optimize the per-trade risk amount at the portfolio level or at the individual market level. Does it make sense to have a different risk level for crude oil than gold? If the equity curve looks better, why not? We could even eliminate all the markets that show a negative expectancy. We could work all day on different portfolios and what-if scenarios and create one great-looking equity curve. But who would we be fooling? If it was the 1980s or 1990s, the public. If we were unscrupulous and wanted to sell this miraculous algorithm, we could mislead the public with the guarantee that every number shown was generated by an exact trading algorithm. The general trading public of the latter part of the twentieth century didn't know any better and didn't understand the term \"with benefit of hindsight.\" Nowadays, with the computer power and data at our fingertips, we would be fooling ourselves because the trading public now has the same computers and data and has been fully educated on \"with benefit of hindsight.\" We can still fall into this same old trap, though, if we don't fully utilize the tools at our disposal.\n\n### Keltner Channel\n\nChester Keltner brought this volatility-based indicator to public attention in 1960 through his book, _How to Make Money in Commodities_. The Keltner Channels are very similar to Bollinger Bands except the centerline is a moving average of typical price ((H + L + C) \/ 3) and the outer bands are calculated using average true range instead of standard deviation. Volatility can be measured in many different ways, but standard deviation and average true range are probably the two most popular.\n\nThe two key components of this indicator that set it apart from Bollinger's are the use of the typical price (TP) and the average true range. TP is simply the average of the high, low, and close prices. The TP takes into consideration the range of the day as well as the close, and as stated earlier, many feel this price is more indicative of the daily price action than simply the close. Since Bollinger and Keltner indicators are so similar, you will notice that the calculations aren't that different:\n\n**Calculation of Keltner Channels using 60 days and 2 ATR:**\n\n 1. Calculate a 60-period SMA of the TP for the chosen time period.\n 2. Calculate the ATR of the 60-day sample (use a computer).\n 3. The top or upper band is the 60-period SMA + 2 ATR.\n 4. The bottom or lower band is the 60-period SMA \u2212 2 ATR.\n\nBox 2.9 shows a Keltner Channel trading algorithm that will be used throughout the rest of this chapter.\n\n* * *\n\n### Box 2.9 Using Chester Keltner's Channels as a Trend Follower\n\n 1. Buy when market closes above top channel.\n 2. Sell short when market closes below bottom channel.\n 3. Sell when market position is long and market closes below average.\n 4. Cover when market position is short and market closes above average.\n 5. myTypicalPrice = (H + L + C);\n 6. myAvg = Average(myTypicalPrice,60) ' 60-day moving average of TP\n 7. myATR = AverageTrueRange(60)\n 8. myTopChannel = myAvg + 2 * myATR ' 2 ATR above average\n 9. myBotChannel = myAvg \u2212 2 * myATR '\u2212 2 ATR below average\n 10. If close crosses above myTopChannel, then \n 1. Buy MOC\n 11. If close crosses below myBotChannel, then \n 1. SellShort MOC\n 12. If position is long, then \n 1. If close crosses below myAvg, then \n 1. Sell MOC\n 13. If position is short, then \n 1. If close crosses above myAvg, then \n 1. BuyToCover MOC\n\nHere is the pseudocode for the algorithm:\n\n `Trend Following with Keltner Channels\n `Utilizing Typical Price = (H + L + C)\/3\n `Utilizing 60-day average and 2 average true ranges\n myAVG = SMA(C,60)\n myTypicalPrice = (H + L + C)\/3\n myTopChannel = KeltnerChan(myTypicalPrice,60,+2)\n myBotChannel = KeltnerChan(myTypicalPrice,60,-2)\n If close > myTopChannel then\n Buy this bar on close\n If close < myBotChannel then\n SellShort this bar on close\n If marketPosition = 1 and c < myAvg then sell this bar on close\n If marketPosition =-1 and c > myAvg then buyToCover this bar on close\n\n* * *\n\nUsing the ATR instead of standard deviation creates smoother outer Bands due to how ATR reacts slower than deviation. Figure 2.15 shows a chart with both Keltner Channels (60 length and 2 ATR) and Bollinger Bands (60 length and 2 STDDEV) applied to the underlying data.\n\n**Figure 2.15** Keltner Channels and Bollinger Bands applied to the same data.\n\nSource: TradeStation\n\nNotice how much smoother the Keltner Channels are compared to the Bollinger Bands. Does this mean they are better? Since the TP takes into consideration more data, is it a better gauge than just the close? Looking at the chart it seems like both indicators got into the short crude position at about the same time. This is a difficult question so let's use the computer tell us which is the better algorithm. This is not going to be an easy task because it is difficult to equate standard deviation to ATR. As you can tell by the chart, the Bollinger Bands encompass the Keltner Channels a majority of the time. This is a consequence of using the same settings for both indicators. We can plainly see that different settings need to be used if we want the indicators to behave in somewhat similar fashion. In other words, the Keltner Channel parameters need to be normalized in terms of the Bollinger Band parameters. This is the only way a fair test can be carried out. The parameters in question are the indicator length and the width of the bands\/channels. We must find out the number of ATRs that are nearly equivalent to two standard deviations. Is two deviations comparable to one ATR, or is it two ATR to one standard deviation? Again, referring back to the chart, we now know that in all likelihood, two ATR does not equal two standard deviations. We know that trades are generated when price penetrates the bands\/channels, and if the bands\/channels are somewhat close to each other or overlapping, then a similar number of trades should be generated. Using the number of trades as the objective, a set of normalized parameters can be determined through optimization of each algorithm across different indicator lengths and channel widths. Since both standard deviation and average true range are functions of the size of the sample (length of days, in our case), both length and width will be optimized. The number of trades will be recorded for each step of the optimization. If a 60-period two-standard-deviation Bollinger Band generates 3,000 trades, then an equivalent parameter set for the Keltner algorithm would be those parameters that generated a similar number of trades. Figure 2.16 shows the number of trades generated utilizing the Bollinger algorithm by varying the length and width parameters over a basket of 36 futures markets.\n\n**Figure 2.16** Bollinger Band optimization.\n\nThis is an unusual graph, so let me explain what exactly is being plotted. The _x_ -axis plots bins of varying lengths at different width values. The _y_ -axis is the number of trades generated by the combination of differing lengths and widths. The length was optimized from 10 to 80 in steps of 2.0 and the width was optimized from 0.25 to 3 in steps of 0.25. The first bin holds all the results of the different-length variables while holding the width at 0.25. Like the first bin the second bin varies the lengths while holding the width to 0.50. Notice how large an impact the length parameter has on the number of generated trades in the different-width bins. Also notice initially how congruent the bars are in each bin. It seems like the drop-off of trades as we move from one bin to another occurs in a linear fashion\u2014that is, up until bins with width values greater than 2.0. An inversion occurs in these bins (shorter lengths begin to create less trades). In addition, the number of trades start demonstrating a parabolic theme. Let's do the same exact analysis with the Keltner Channel algorithm utilizing the same data and optimization ranges. Figure 2.17 utilizes the exact same chart properties but with the newly derived results.\n\n**Figure 2.17** Keltner Channel optimization.\n\nThis graph starts out looking like the Bollinger Band graph; initially, the length parameter has a large impact in the 0.25 bin, just like the Bollinger chart. However, as we span across the different-width bins, the length parameter has less and less impact. By the time we reach the 1.50 bin, an inversion occurs, just like the Bollinger, where the lower-length parameters start to generate less trades. The two algorithms are quite similar but these graphs illustrate the difference between utilizing ATR and standard deviation.\n\nArmed with this information, can a normalized parameter set for both the Bollinger and Keltner algorithms be derived? The 60-day two-standard-deviation algorithm generated 3,580 trades. Let's see which parameters generated nearly the same number for the Keltner algorithm. If you refer back to Figure 2.17, you will see several instances where a set of parameters generated nearly the same number of trades. I scanned the Keltner Channel results and pulled out the parameter sets that generated trades within +\/\u2212 2 percent of the 3,580. Most of the selected parameter sets included the same 3.0 width. There are a couple of outliers, though. Table 2.10 shows the performance of the Bollinger Band algorithm that was derived earlier using (len = 60, stdDev = 2) and the Keltner Channel algorithm utilizing the different parameter sets that generated nearly the same number of trades.\n\n**Table 2.10** Bollinger Benchmark versus Keltner Challengers\n\n**Set** | **Net Profit** | **Max. Sys DD** | **CAR\/MDD** | **Profit Factor** | **Sharpe Ratio** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **L. Avg. Bars Held** \n---|---|---|---|---|---|---|---|---|--- \nBB [60,2.00] | 1677369.47 | \u2212345343 | 0.27 | 1.4 | 0.2 | 3580 | 469 | 43.59 | 23.72 \n| | | | | | | | | \n**Plateau** | | | | | | | | | \n**Set** | **Net Profit** | **Max**. **Sys DD** | **CAR\/ MDD** | **Prft**. **Factor** | **Sharpe Ratio** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **L. Avg**. **Bars Held** \nKC[56,3] | 1253131.73 | \u2212443724 | 0.16 | 1.27 | 0.14 | 3612 | 347 | 44.47 | 24.65 \nKC[58,3] | 1318378.23 | \u2212434112 | 0.17 | 1.29 | 0.15 | 3593 | 367 | 44.53 | 24.66 \nKC[60,3] | 1338616.09 | \u2212409094 | 0.18 | 1.29 | 0.15 | 3579 | 374 | 44.56 | 24.6 \nKC[62,3] | 1391495.03 | \u2212404823 | 0.19 | 1.31 | 0.16 | 3564 | 390 | 44.64 | 24.69 \nKC[64,3] | 1449520.83 | \u2212410137 | 0.2 | 1.33 | 0.17 | 3535 | 410 | 44.82 | 24.69 \nKC[66,3] | 1506179.43 | \u2212375805 | 0.23 | 1.35 | 0.17 | 3523 | 428 | 44.86 | 24.68 \nKC[68.3] | 1520843.29 | \u2212386511 | 0.22 | 1.35 | 0.18 | 3516 | 433 | 44.81 | 24.61 \n**Outliers** | | | | | | | | | \nKC[12,2.5] | 1085527.09 | \u2212300175 | 0.18 | 1.27 | 0.15 | 3521 | 308 | 37.83 | 20.75 \nKC[26,3.0] | 1299080.88 | \u2212407407 | 0.18 | 1.29 | 0.15 | 3589 | 362 | 42.1 | 22.21\n\nFrom this information, we might be able to derive that a Bollinger Band (60, 2) is similar to a Keltner Channel (60, 3). If we accept this assumption, then the winner is easy to pick from this table. The Bollinger Band algorithm performed much better than the Keltner with these parameters. However, with such stringent criteria and utilizing the Bollinger algorithm as the benchmark, are we being fair to Keltner? We forced the Keltner to fit into criteria where a similar number of trades were generated. Let's take the gloves off and again do the same optimization and pick the top five parameter sets for both algorithms based on the average profit and net profit. In this analysis, a $50 round-turn commission will be deducted from each trade\u2014this will take execution costs into consideration, which will in turn provide a level playing field for parameter sets that do not generate a large number of trades.\n\nTables 2.11 and 2.12 show the best performers for the Bollinger Band algorithm. The first set of performance metrics were derived by sorting by average profit\/loss and the second set was derived by sorting by net profit. Table 2.12 shows the same metrics for the Keltner Channel algorithm.\n\n**Table 2.11** Best Parameter Sets of Bollinger Bands Algorithm\n\n**Ranking Based on Average Trade** | | | | | \n---|---|---|---|---|--- \n**No.** | **Net Profit** | **Max. Drawdown** | **Sharpe Ratio** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** | **Len** | **Width** \n360 | $1,157,014 | \u2212$302,350 | 0.22 | 1769 | 654.05 | 61.25 | 40.64 | 80 | 2.5 \n359 | $1,147,202 | \u2212$308,547 | 0.22 | 1788 | 641.61 | 59.79 | 40.6 | 78 | 2.5 \n358 | $1,158,434 | \u2212$358,085 | 0.22 | 1827 | 634.06 | 58.48 | 40.56 | 76 | 2.5 \n324 | $1,427,825 | \u2212$323,166 | 0.21 | 2271 | 628.72 | 59.56 | 39.89 | 80 | 2.25 \n323 | $1,442,568 | \u2212$379,483 | 0.21 | 2340 | 616.48 | 58.16 | 39.74 | 78 | 2.25 \n**Ranking Based on Net Profit** | | | | | | | \n**No**. | **NetProfit** | **Max**. **Drawdown** | **Sharpe Ratio** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** | **Len** | **Width** \n216 | $1,792,835 | \u2212$397,785 | 0.19 | 3622 | 494.98 | 51.55 | 34.65 | 80 | 1.5 \n211 | $1,789,623 | \u2212$395,046 | 0.18 | 4092 | 437.35 | 45.71 | 34.41 | 70 | 1.5 \n180 | $1,788,584 | \u2212$400,129 | 0.18 | 4149 | 431.09 | 48.06 | 33.29 | 80 | 1.25 \n179 | $1,765,374 | \u2212$392,321 | 0.17 | 4257 | 414.7 | 46.82 | 33 | 78 | 1.25 \n215 | $1,754,942 | \u2212$408,842 | 0.18 | 3726 | 471 | 50.16 | 34.33 | 78 | 1.5\n\n**Table 2.12** Best Parameter Sets of Keltner Channel Algorithm\n\n**Ranking Based on Average Trade** | | | | | \n---|---|---|---|---|--- \n**No.** | **Net Profit** | **Max. Drawdown** | **Sharpe Ratio** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** | **Len** | **Width** \n397 | $576,442 | \u2212$216,503 | 0.19 | 1193 | 483.19 | 44.77 | 36.88 | 10 | 3 \n400 | $1,131,833 | \u2212$291,100 | 0.18 | 2648 | 427.43 | 42.88 | 36.44 | 16 | 3 \n431 | $1,497,797 | \u2212$399,590 | 0.17 | 3568 | 419.79 | 43.92 | 37.3 | 78 | 3 \n398 | $755,357 | \u2212$277,970 | 0.17 | 1804 | 418.71 | 44.11 | 37.03 | 12 | 3 \n432 | $1,500,595 | \u2212$394,719 | 0.17 | 3598 | 417.06 | 43.59 | 37.13 | 80 | 3 \n**Ranking Based on Net Profit** | | | | | | | \n**No**. | **NetProfit** | **Max**. **Drawdown** | **SharpeRatio** | **# Trades** | **AvgProfit\/Loss** | **AvgBars Held** | **% ofWinners** | **Len** | **Width** \n180 | $1,626,520 | \u2212$406,001 | 0.14 | 7293 | 223.02 | 29.87 | 29.14 | 80 | 1.25 \n141 | $1,623,026 | \u2212$420,401 | 0.13 | 8051 | 201.59 | 28.45 | 27.76 | 74 | 1 \n140 | $1,622,844 | \u2212$415,479 | 0.13 | 7974 | 203.52 | 28.83 | 27.77 | 72 | 1 \n179 | $1,606,297 | \u2212$409,864 | 0.14 | 7243 | 221.77 | 30.21 | 29.32 | 78 | 1.25 \n103 | $1,596,825 | \u2212$422,709 | 0.13 | 9129 | 174.92 | 26.26 | 25.74 | 70 | 0.75\n\nAnd the winner is? Tough call\u2014I lean toward the Bollinger Bands because of the higher Sharpe ratios. The Sharpe ratio is just an indicator of consistency, and we will go over it and many more performance metrics in the next chapter. One thing that does stand out is the holding periods of the two systems and how different they are. The profit\/loss is somewhat similar but the Bollinger algorithm holds on to trades anywhere from 20 to 50 percent longer. There might be some synergy here. Diversification is not only achieved through different markets but also through different algorithms.\n\n## Summary\n\nAnother chapter, and still no Holy Grail. However, using indicators as building blocks might get you very close to one. Several oscillators and trend indicators were discussed but these are just a few out of many. The overall purpose of this chapter was to show how to integrate these indicators into a trading algorithm. The flowcharts and FSM diagrams that were introduced in Chapter 1 were carried over and used to help explain this integration. Pseudocode was also used to demonstrate how the indicators can be programmed. Keep in mind the actual computer code will be shown in the appendices. The development of a mean reversion algorithm can be accomplished by incorporating any of the oscillators and trend detection. A trend-following algorithm is best achieved by incorporating moving averages and\/or their derivatives such as Bollinger Bands and Keltner Channels. Trust me when I tell you the most successful trend-following systems incorporate either one or both.\n\nHow did we get through this chapter without talking about the Turtles, Richard Dennis, or Richard Donchian? If you are not familiar with these names, just Google them. Richard Donchian created the _N_ -week breakout rule and Richard Dennis built a complete trading scheme around it. Richard Dennis was very successful and spawned Turtle trading. The _N_ -week breakout is a channel indicator that uses the highest high of _N-_ weeks\/days as the upper channel and the lowest low of _N_ -weeks\/days as the lower channel. Just like a Bollinger Band algorithm, trades are initiated by the penetration of the channels. Richard Dennis and his partner Bill Eckhardt believed anybody could be trained to trade futures successfully if a trading plan was provided. So they placed classified ads in the newspaper looking for new talent. They weren't going after the prototypical Ivy Leaguer economist types. They wanted smart people who understood human behavior and who were willing to be trained. The training involved the ideas and concepts that Dennis had used to make millions. Many of the recruited traders, aka Turtles, went on to be extremely successful. Now was this a consequence of a superior algorithm or the inherent talents of the traders or being in the right spot at the right time or more simply just having a trading plan? I think it was a combination of all of the above. Don't think such a famous algorithm is going to be left out of this book. It will be introduced in the next chapter, as well as several others. Also, the Turtle money management algorithm (aka Fixed Fractional) will be discussed in Chapter 9.\n\n# Chapter 3 \nComplete Trading Algorithms\n\nWe ended the last chapter discussing one of the most famous trading algorithms of all times. Figure 3.1 is a flowchart I used to program the famous algorithm many years ago. The flowchart looks extremely complicated, but keep in mind the complete Turtle system includes two trading systems, money management, and a simulated trading module. If you break down the flowchart into its components, you will see that it is not as complicated as it seems. Most of the calculations in the Turtle system are used to determine market risk, capital allocation, market selection, and position sizing. All these components are quite important, but the meat of the diagram and the system are the two trading entry\/exit algorithms and the switch that determines which system is applied. Let's go right to the heart of the Turtle by breaking just the trade entry\/exit algorithms out of the complete model. The other components will be discussed a little later.\n\n**Figure 3.1** Turtle trading algorithm flowchart.\n\nThe first of the two entry\/exit algorithms, let's call it System 1, is the shorter-term entry technique and is based on a very simple technique. Basically, it will buy\/sell short on a 20-day Donchian breakout and exit the trade by risking whichever is closer: a 10-day Donchian breakout or a maximum of 2 percent of capital. System 1 (Box 3.1) can trade quite frequently in a choppy market. This type of start and stop can lead to a long list of losses. This choppiness can be very devastating to a trader's account and psychology. Richard Dennis tried to help alleviate this by implementing a trade filter. The Turtles were instructed to skip System 1 entries if the last trade was a winner. If the last trade was a winner, then the next trade is not \"actually\" executed but it is simulated. In other words, the trader would paper trade the system until a loss occurs.\n\n* * *\n\n### Box 3.1 Turtle System #1\n\n 1. Buy one tick above the highest high of the past 20 days stop.\n 2. Sell short one tick below the lowest low of the past 20 days stop.\n 3. If position is long, then\n\nSell next bar at the maximum of:\n\n 1. one tick below the lowest low of the past 10 days stop, or\n 2. entryPrice \u2013 (0.02 * initialCapital) \/ bigPointValue stop\n 4. If position is short, then\n\nBuy next bar at the minimum of:\n\n 1. one tick above the highest high of the past 10 days stop, or\n 2. entryPrice + (0.02 * initialCapital) \/ bigPointValue stop\n\n* * *\n\nThis description does not utilize the \"last trade was a loser filter\" (LTLF). Even with the application of the LTLF, this system is very easy to trade. A simple spreadsheet is all it takes to help keep track of actual and simulated trades. Remember a simulated trade occurs after a winning trade is realized. Real trading is turned back on once a simulated losing trade occurs.\n\nSystem 2 (Box 3.2) entries are congruent with System 1, but require a much longer lookback period\u201455 days. Even though the Donchian Channel exit is wider, the same 2 percent maximum loss is still used.\n\n* * *\n\n### Box 3.2 Turtle System #2\n\n 1. Buy one tick above the highest high of the past 55 days stop.\n 2. Sell short one tick below the lowest low of the past 55 days stop.\n 3. If position is long, then\n\nSell next bar at the maximum of:\n\n 1. one tick below the lowest low of the past 20 days stop or\n 2. entryPrice \u2013 (0.02 * initialCapital) \/ bigPointValue stop\n 4. If position is short, then\n\nBuy next bar at the minimum of:\n\n 1. one tick above the highest high of the past 10 days stop or\n 2. entryPrice + (0.02 * initialCapital) \/ bigPointValue stop\n\n* * *\n\nThe LTLF does not apply to these longer-term entries. If the market is making a new 55-day high\/low, then the Turtle system thinks a new trend has definitely begun and the trader must be on board. This entry was considered the failsafe breakout.\n\nThis is the Turtle system in a nutshell, or should I say a turtle shell. The full-blown Turtle model involves many more calculations, pyramiding, and a totally separate position sizing and market selection algorithm. Some of these topics will be discussed in Chapter 8 and a full-blown version (except for market selection) will be provided at the end of this chapter in EasyLanguage.\n\nEven though the complete Turtle \"approach\" isn't being applied here, the two systems are indeed complete trading algorithms; they both have entry and trade management techniques. System 1 was designed to capture shorter-term swings, whereas System 2 was the true trend-following component. Trading the two systems simultaneously was undoubtedly considered synergistic to the Turtles. The key to getting the benefit from both systems lies in the LTLF\u2014it must be engaged. If it's not, then you end up just trading System 1, the 20-day breakout. A 20-day breakout will always be closer or equal to the current market price than a 55-day breakout. Here again is the idea of creating an additional level of diversification through the use of multiple systems. However, the amount of capital to allocate to the different systems was left up to the individual Turtle (trader). He or she could commit 100 percent to either system or 50 percent to one and 50 percent to the other or some other combination. How to determine how much of each system to use was obviously a very difficult question to answer, even for a Turtle. Which system would you use? If I had been a Turtle faced with this decision, I would have done the research by backtesting both systems and allocating more toward the better of the two.\n\nAs a Turtle you had three choices to make: Trade System1, trade System 2, or trade a combination of the two. Let's pretend we are a Turtle and let's see if we can make the decision. The research necessary requires each system to be tested independently and simultaneously to see if \"the whole is greater than the sum of its parts.\" Tables 3.1 and 3.2 show the performance of each system, respectively, across the same portfolio over the same time period. Note that System 1 was initially tested without the LTLF. In these tests, the maximum loss was set to $2,000 and $100 was deducted for commission and slippage on a round-turn basis.\n\n**Table 3.1** Turtle System 1 without LTLF for the Sample Portfolio\n\n**Total Return** | **$439,471.42** | **Market** | **PNL** \n---|---|---|--- \nTotal Realized Return | $416,450.17 | @AD | ($6,110.00) \nGross Profit | $5,182,686.04 | @BP | ($6,543.75) \nGross Loss | \u2212$4,766,235.87 | @C | ($6,987.50) \nOpen Trade P\/L | $23,021.25 | @CC | ($36,020.00) \n| | @CL | $77,690.00 \nNumber of Trades | $5,234.00 | @CT | $20,065.00 \nNumber of Winning Trades | $1,751.00 | @DX | ($14,590.00) \nNumber of Losing Trades | $3,481.00 | @EC | $84,150.00 \n% Profitable | 33.45% | @ED | ($10,800.00) \n| | @EMD | ($70,700.00) \nAverage Trade | $79.57 | @ES | ($36,162.50) \nAverage Trade (%) | 0.39% | @FC | $39,675.00 \nStandard Deviation | $3,566.48 | @FV | ($11,335.93) \nStandard Deviation Trade % | 28.39% | @GC | ($19,480.00) \nLargest Winning Trade | $53,275.00 | @HG | $101,125.00 \nLargest Losing Trade | \u2212$8,375.00 | @HO | $97,287.00 \n| | @KC | ($34,106.25) \nProfit Factor | 1.09 | @KW | ($2,975.00) \nAverage Win\/Average Loss | 2.16 | @LC | ($32,130.00) \nSharpe Ratio | 0.12 | @LH | $16,570.00 \nK-Ratio | 0.16 | @NG | $28,550.00 \nReturn Retracement Ratio | 0.54 | @OJ | $3,977.50 \n| | @PL | $90,825.00 \n| | @RB | $45,105.20 \n| | @S | $32,693.75 \n| | @SB | $20,252.00 \n| | @SI | $182,700.00 \n| | @TF | ($104,090.00) \n| | @TU | ($9,174.97) \n| | @TY | $16,871.88 \n| | @US | ($12,581.25) \n| | @W | ($5,512.50)\n\n**Table 3.2** Turtle System 2 for the Sample Portfolio\n\n**Summary** | **Value** | **Markets** | **PNL** \n---|---|---|--- \nTotal Return | $949,937.69 | @AD | $40,250.00 \nTotal Realized Return | $889,799.88 | @BP | $3,987.50 \nGross Profit | $3,444,084.89 | @C | $11,225.00 \nGross Loss | \u2212$2,554,285.01 | @CC | ($34,600.00) \nOpen Trade P\/L | $60,137.81 | @CL | $174,440.00 \n| | @CT | $20,720.00 \nNumber of Trades | $2,324.00 | @DX | $21,150.00 \nNumber of Winning Trades | $726.00 | @EC | $83,600.00 \nNumber of Losing Trades | $1,597.00 | @ED | $1,743.75 \n% Profitable | 31.24% | @EMD | $4,490.00 \n| | @ES | $11,587.50 \nAverage Trade | $382.87 | @FC | $31,825.00 \nAverage Trade (%) | 0.67% | @FV | ($585.93) \nStandard Deviation | $5,477.96 | @GC | $57,530.00 \nStandard Deviation Trade % | 56.38% | @HG | $91,425.00 \nLargest Winning Trade | $90,440.00 | @HO | $173,699.40 \nLargest Losing Trade | \u2212$7,590.00 | @KC | ($19,500.00) \n| | @KW | $22,500.00 \nProfit Factor | 1.35 | @LC | ($14,740.00) \nAverage Win\/Average Loss | 2.97 | @LH | $19,660.00 \nSharpe Ratio | 0.16 | @NG | $102,840.00 \nK-Ratio | 0.19 | @OJ | ($1,155.00) \nReturn Retracement Ratio | 1.19 | @PL | $70,340.00 \n| | @RB | $80,879.40 \n| | @S | $70,162.50 \n| | @SB | $28,963.20 \n| | @SI | $134,575.00 \n| | @TF | ($13,100.00) \n| | @TU | $7,437.50 \n| | @TY | ($6,156.25) \n| | @US | $10,687.50 \n| | @W | $3,612.50\n\nTable 3.1 shows the net performance along with individual market results as well. A profit of more than $430k was generated along with a hefty $220k maximum drawdown. Make a mental checkmark on the markets that showed the best results. I have a feeling you will notice a pattern among the best-performing markets throughout the rest of this chapter. Let's see how the 55-day breakout faired (Table 3.2).\n\n_Wow!_ The profit nearly doubled and the maximum drawdown was reduced by 10 percent. If you had traded this system in place of the 20-day breakout, you might not have received a Christmas card from your broker\u2014less than one half the execution costs\u2014but your banker would have been happy.\n\nNow let's go back and retest System 1 with the _Last Trader Was a Loser Filter_ (LTLF) to see if it had any beneficial impact on the performance. Actual trades were only placed after a subsequent loss\u2014be it from an actual loss or a simulated loss. Losses were generated by the $2,000 money management stop or a trailing 10-day stop that resulted in a loss. Table 3.3 shows the results of System 1 with the LTLF in place.\n\n**Table 3.3** Turtle System 1 with LTLF for the Sample Portfolio\n\n**Summary** | **Value** | **Markets** | **PNL** \n---|---|---|--- \nTotal Return | $667,013.78 | @AD | $2,890.00 \nTotal Realized Return | $652,511.28 | @BP | ($6,031.25) \nGross Profit | $3,632,117.44 | @C | $5,912.50 \nGross Loss | \u2212$2,979,606.16 | @CC | ($19,900.00) \nOpen Trade P\/L | $14,502.50 | @CL | $107,830.00 \n| | @CT | $7,250.00 \nNumber of Trades | $3,301.00 | @DX | $20,110.00 \nNumber of Winning Trades | $1,125.00 | @EC | $83,300.00 \nNumber of Losing Trades | $2,175.00 | @ED | ($13,356.25) \n% Profitable | 34.08% | @EMD | ($30,180.00) \n| | @ES | ($23,475.00) \nAverage Trade | $197.67 | @FC | $4,300.00 \nAverage Trade (%) | 0.51% | @FV | ($1,917.18) \nStandard Deviation | $3,963.63 | @GC | $17,970.00 \nStandard Deviation Trade % | 26.13% | @HG | $114,037.50 \nLargest Winning Trade | $53,275.00 | @HO | $60,120.20 \nLargest Losing Trade | \u2212$7,925.00 | @KC | $18,531.25 \n| | @KW | $2,450.00 \nProfit Factor | 1.22 | @LC | ($18,630.00) \nAverage Win\/Average Loss | 2.36 | @LH | $28,620.00 \nSharpe Ratio | 0.15 | @NG | $64,760.00 \nK-Ratio | 0.22 | @OJ | $11,230.00 \nReturn Retracement Ratio | 1.10 | @PL | $88,465.00 \n| | @RB | $46,595.20 \nCompounded Annual Return | 14.96% | @S | $14,581.25 \nCompounded Monthly Return | 1.15% | @SB | $9,156.80 \n| | @SI | $169,050.00 \nAverage Annual Return | $44,467.59 | @TF | ($73,960.00) \nAverage Annual Return (%) | 19.54% | @TU | ($8,718.73) \nAverage Monthly Return | $3,789.85 | @TY | $1,725.00 \nAverage Monthly Return (%) | 1.59% | @US | ($10,581.25) \n| | @W | ($9,400.00) \nPercent Days Profitable | 50.69% | | \nPercent Months Profitable | 52.27% | | \nPercent Years Profitable | 73.33% | | \n| | | \nCommissions on Currencies | $165,375.00 | | \nCommissions on Futures | $0.00 | | \nCommissions on Equities | $0.00 | | \nTotal Commissions | $165,375.00 | |\n\nThe results agreed with my research from more than 10 years ago. In an article I wrote for _SFO_ magazine in 2004, I executed the exact same analysis utilizing another testing platform, Trading Blox Builder (www.tradingblox.com), and received similar results; the profit-to-drawdown ratio increased using the LTLF. The **Trading Blox** testing platform was built around the absolute complete Turtle algorithm (entry techniques, capital allocation, and position sizing models) by an original turtle and a very gifted programmer. As I mentioned in the Introduction, this is not one of the platforms included in this book, but it is well worth your time to investigate its capabilities. What this research is implying is that the prior trade may have an impact on the subsequent trade. In other words, it seems there does exist a higher probability of a winning trade after a losing trade has occurred at the macroscopic level on this particular algorithm. This autocorrelation could be a function of the volatility cycle. After a big run in commodity prices, it is not uncommon to see a congestive phase. In my opinion, this type of filter works better with shorter-term higher-frequency algorithms. If you think about it, this makes sense. A system that trades frequently can skip trades and still catch shorter-term trends. On the other hand, a system that trades infrequently needs every trade to add to the bottom line; skipping a single trade might keep you out of the market for a year. This is the reason the Turtles relied on the \"must-take\" 55-day breakout.\n\nLet's test if there is synergy by trading both systems simultaneously. Synergy occurs when the interaction of elements, when combined, produces a total effect that is greater than the sum of the individual elements. Synergy does not occur when combining the total profits of the two systems. Addition of total P & L follows the commutative law. The synergy that does occur when combining systems is revealed in the combined maximum drawdown metric. If two systems are somewhat non-correlated, then the overall maximum drawdown will not be equal to the sum of the two individual maximum drawdowns; it may be less. So, it logically follows that the synergy of combining multiple trading strategies is reflected in the increase of the overall profit to overall maximum drawdown ratio. The overall profit is a constant (sum of all total profits) and the overall maximum drawdown is variable. If drawdown decreases, then the ratio will increase and demonstrate a somewhat synergistic effect.\n\nThis combining of systems can be accomplished by trading the two systems independently of each other in separate accounts, or in a single account. A trader can also combine the rules into one complete strategy, and trade in a single account. Many of today's testing platforms offer both methods. The backtesting method where both systems are traded independently can be simulated simply by combining the daily equity streams for both systems. This is a valid method and does reveal a reduction in max drawdown, if one occurs. The second method requires additional programming but does help with eliminating the necessity of keeping track of multiple systems. If more than one system were to be traded simultaneously in separate accounts, then capital would need to be allocated to cover all open positions margins. Even if one system is long and the other short. If the systems are combined into one account, then the net position (Long + Short = Flat) is recorded, and therefore there is no margin requirement.\n\nTable 3.4 shows the performance of the Turtle system using both System 1 with the LTLF engaged and System 2 turned on.\n\n**Table 3.4** Tandem Performance of Turtle System 1 with LTLF and Turtle System 2 for the Sample Portfolio\n\n**Summary** | **Value** | **Markets** | **PNL** \n---|---|---|--- \nTotal Return | $587,797.03 | @AD | $14,260.00 \nTotal Realized Return | $556,674.53 | @BP | ($3,718.75) \nGross Profit | $4,380,499.89 | @C | ($5,712.50) \nGross Loss | \u2212$3,823,825.36 | @CC | ($39,040.00) \nOpen Trade P\/L | $31,122.50 | @CL | $113,720.00 \n| | @CT | $10,195.00 \nNumber of Trades | $4,048.00 | @DX | $45.00 \nNumber of Winning Trades | $1,334.00 | @EC | $77,087.50 \nNumber of Losing Trades | $2,711.00 | @ED | ($11,656.25) \n% Profitable | 32.95% | @EMD | ($47,440.00) \n| | @ES | ($36,700.00) \nAverage Trade | $137.52 | @FC | $26,025.00 \nAverage Trade (%) | \u22120.02% | @FV | ($10,285.93) \nStandard Deviation | $3,869.70 | @GC | ($4,420.00) \nStandard Deviation Trade % | 36.41% | @HG | $104,950.00 \nLargest Winning Trade | $53,275.00 | @HO | $97,538.00 \nLargest Losing Trade | \u2212$7,925.00 | @KC | ($4,225.00) \n| | @KW | ($2,412.50) \nProfit Factor | 1.15 | @LC | ($14,040.00) \nAverage Win\/Average Loss | 2.33 | @LH | $14,260.00 \nSharpe Ratio | 0.13 | @NG | $36,410.00 \nK-Ratio | 0.18 | @OJ | $2,547.50 \nReturn Retracement Ratio | 0.68 | @PL | $104,195.00 \n| | @RB | $59,458.80 \nCompounded Annual Return | 14.10% | @S | $46,856.25 \nCompounded Monthly Return | 1.09% | @SB | $15,202.40 \n| | @SI | $169,425.00 \nAverage Annual Return | $39,186.47 | @TF | ($94,540.00) \nAverage Annual Return (%) | 22.93% | @TU | ($9,118.73) \nAverage Monthly Return | $3,339.76 | @TY | $550.00 \nAverage Monthly Return (%) | 1.91% | @US | ($11,756.25) \n| | @W | ($6,000.00) \nPercent Days Profitable | 50.77% | | \nPercent Months Profitable | 52.27% | | \nPercent Years Profitable | 53.33% | | \n| | | \nCommissions on Currencies | $202,825.00 | | \nCommissions on Futures | $0.00 | | \nCommissions on Equities | $0.00 | | \nTotal Commissions | $202,825.00 | |\n\nThe results are better than the simple 20-day breakout but worse than the 20-day breakout with LTLF engaged, and much worse than the simple 55-day breakout. You would think the combination of the two systems would at least beat the System 1 component. In some markets, it did. The only explanation that I can come up with is: Let's say a trade is entered on 20-day breakout, and turns out to be a winner. The next 20-day breakout is ignored, but a subsequent 55-day breakout is taken in the same direction at a worse price and with probably higher risk\u2014a 20-day trailing stop versus a 10-day trailing stop. Following this line of thought, let's assume System 1 has a winner via a 20-day breakout, so the next 20-day breakout is skipped, but the market moves sufficiently in the same direction to trigger a System 2 trade. This trade occurs at a much worse price with an inherently higher level of risk. Still assuming, let's say the System 2 trade is stopped out for a large loss. The net between the two trades could theoretically be a loss, whereas if the trader had just traded System 1, she would have realized a winning situation. So there really isn't any synergy between the two components traded in this manner. Also due to the high correlation between the two components, combining them by trading them independently would probably still not provide any synergy. The clear winner here is the simple 55-day breakout.\n\n## Trend-Trading Battle Royale\n\nWe have reviewed a few trend-following trading algorithms and their results. Thus far, the results have shown some merit. Enough merit to continue research in this form of trading. There are many trend-following algorithms out there, but the perpetual question of which is the best has never really been _truly_ answered. Perry Kaufman has come very close in his _New Trading Systems and Methods_ books. Why hasn't this question ever been fully answered in an easy-to-interpret format? The main obstacle has always been the inability to compare apples to apples. However, with the tools I now have at my fingertips, maybe we can finally put this question to rest.\n\nThe following trend-following algorithms will be tested on the same data with the same commission\/slippage deduction, over the same time period and on a one-contract basis and on the same testing platform, and we have plenty of capital. The trend-following algorithms that will be tested will utilize their own entry-and-exit techniques. However, a maximum loss of $3,000 will be applied to each algorithm. I figure that most of the algorithms' exits will occur prior to this stop level, and most traders would feel more comfortable knowing that at this trading level, the risk of ruin should be sufficiently small to initiate one or more of the programs.\n\n##### Pause the Battle\u2014Let's Talk Risk of Ruin\n\nRisk of ruin is a very useful tool in determining the likelihood of a trader losing his entire bankroll or reducing it to a level that trading cannot continue. Calculating this risk (RoR) is quite simple; all you need is the amount of capital to be risked on any given trade and the probability of success, also known as the algorithm's trading advantage:\n\nwhere A is the algorithm's trading advantage and C is the number of units in your account. To calculate A, subtract the percent chance of loss from percent chance of win. So, if you expect to win 54% of your trades, the trading advantage would be 8% (54% \u2212 46% = 8%). To calculate C, simply divide 1 by the percent of capital you are willing to risk on each trade. So, if you are willing to risk 5% of any given trade, then you have 20 units. Plugging A and C into the formula you come up with ((1 \u2212 0.08) \/ (1 + 0.08)) ^ 20. The result turns out to be around 4%. The RoR for risking 5% of your capital on each trade with an algorithm that wins 54% of time is a relatively low 4%. If the percent of wins is 50% or less, the RoR is 100%. The base number that is being raised by unit size C decreases as the trading advantage increases. As long as the percent wins are greater than 50%, the base number will always be less than one. Unit size C decreases as risk per trade increases. Raising a number less than one by higher values decreases the result or in this case the RoR. In other words, the RoR is indirectly proportional to the risk.\n\nThis simple formula only works with algorithms that win more often than they lose and each win and loss is identical. If you plug in a winning percentage of 50% or less, the RoR is guaranteed. If you applied this very simple formula to the vast majority of trend-following systems, you would never take the first trade. When determining RoR you must look beyond percent wins and risk. Most trend-following systems win less than 40% of their trades. The key performance metrics in this case are the average win and average loss in dollars. You can still win with a sub-50% winning system as long as your average trade (average win \/ average loss) is sufficiently high enough. The formula for RoR for when wins and losses are not identical is unfortunately much more complex. I refer you to Ralph Vince's excellent book, _Portfolio Management Formulas_ (Wiley, New York, 1990) if you want to see the derivation of this formula. The formula is complicated but the algorithm is quite simple if you have the correct performance metrics of your algorithm. An Excel spreadsheet that utilizes this formula is available from this book's companion website. Here is an example of the worksheet and its computed RoR using performance metrics from a typical trend-following algorithm (see Figure 3.2.).\n\n**Figure 3.2** A three-dimensional contour chart of Bollinger performance across a subset of the parameters that were originally optimized.\n\nSource: AmiBroker\n\n**_Risk of Ruin Calculation_** \n--- \nAverage Win $ | $400 | \u226a--Input Here \nAverage Loss $ | $200 | \u226a--Input Here \nPercent Wins | 35.0% | \u226a--Input Here \nInitial Capital $ | $35,000 | \u226a--Input Here \nAmount of Pain % (% of Capital) | 50.0% | \u226a--Input Here \nPayoff Ratio | 2 | \nPercent Losers | 65.0% | \nAverage Win % | 1.1% | \nAverage Loss % | 0.6% | \nSum of Possible Events (SoPE) | 0.00029 | \nSq.Root of Sum of Squares of (SoPE) | 0.00818 | \n\" **P** \" | 0.517460757 | \nRoR | 1.39814% |\n\nThis trend-following system wins only 35% of the time but has a payoff ratio of 2 (Average Win$ \/ Average Loss$). If your pain threshold is 50% of your starting capital, then you run a risk of ruin of nearly 1.4%. With these algorithm performance metrics and RoR you shouldn't have a problem pulling the trigger on this system. Before you start trading be sure to check the risk of ruin and see if it fits your expectations. One more note before we resume the battle: Money management will not be utilized so that we can see the raw capabilities of each system.\n\n#### Resume the Battle\n\nThere will be a total of six popular trend-following algorithms tested, the Turtle system and the five shown in Box 3.3. Each test will consist of three subtests. The subtests will reflect three different parameter sets that will cause the algorithms to trade in a shorter-term, intermediate-term, and longer-term manner. For example, a simple moving average crossover algorithm will be tested utilizing moving average lengths of 19, 39, and 100. These parameters should cover the three time horizons\u2014short, intermediate, and long. The parameter lengths were chosen without the benefit of hindsight\u2014in other words, they were chosen based on my perceived applicability to obtain the three time horizons without looking at prior test results. This isn't really a true statement, because my experience through testing systems over the years does introduce a slight hindsight bias. All entries and exits will be executed on the closing price of the bar that generates the trade signal.\n\n* * *\n\n### Box 3.3 Battle Royale\u2014And the Competitors Are\n\n#### Single Simple Moving Average Crossover (SMA)\n\n 1. Buy when close crosses above moving average\n 2. Sell short when close crosses below moving average\n 3. Liquidate long if close < entryPrice \u2212 3000\/bigPointValue\n 4. Liquidate short if close > entryPrice + 3000\/bigPointValue\n 5. Utilize moving average lengths of 19, 39, and 100\n\n#### Double Simple Moving Average Crossover (DMA)\n\n 1. Buy when shorter moving average crosses above longer moving average\n 2. Sell short when short moving average crosses below longer moving average\n 3. Liquidate long if close < entryPrice \u2013 3000\/bigPointValue\n 4. Liquidate short if close > entryPrice + 3000\/bigPointValue\n 5. Utilize moving average lengths: \n 1. Short lengths: 9, 19, 49\n 2. Long lengths: 19 ,49, 99\n\n#### Triple Simple Moving Average Crossover (TMA)\n\nTriple moving averages require two criteria to be met before a trade entry:\n\n 1. Buy: \n 1. shortest moving average and intermediate moving average both must be greater than longer-term average\n 2. Buy when shortest moving average crosses above intermediate moving average\n 2. Sell short: \n 1. shortest moving average and intermediate moving average both must be less than longer-term average\n 2. Sell short when shortest moving average crosses below intermediate moving average\n 3. Liquidate long when shortest moving average crosses below intermediate moving average or if close < entryPrice \u2013 3000\/bigPointValue\n\nLiquidate short when shortest moving average crosses above intermediate moving average or if close > entryPrice + 3000\/bigPointValue\n\nUtilize the following moving average lengths:\n\n 1. Short lengths: 9, 19, 49\n 2. Intermediate lengths: 19, 49, 199\n 3. Long lengths: 49, 199, 399\n\n#### Donchian Channels (DC)\n\n 1. Buy on penetration of highest highs for past _N_ days\n 2. Sell short on penetration of lowest lows for past _N_ days\n 3. Liquidate long on penetration lowest lows for past _N_ \/ 2 days or if close < entryPrice \u2013 3000\/bigPointValue\n\nLiquidate short on penetration of highest highs for past _N_ \/ 2 days or if close > entryPrice + 3000\/bigPointValue\n\nUtilize the following channel lengths:\n\n 4. 1. Short lengths: 20 entry, 10 exit\n 2. Intermediate lengths: 40 entry, 20 exit\n 3. Long lengths: 100 entry, 50 exit\n\n#### Bollinger Bands (BB)\n\n 1. Buy on penetration of two standard deviations above _N_ -day moving average.\n 2. Sell short on penetration of two standard deviations below _N_ -day moving average.\n 3. Liquidate long on penetration of _N_ -day moving average or if close < entryPrice \u2013 3000\/bigPointValue.\n 4. Liquidate short on penetration of _N_ -day moving average or if close > entryPrice + 3000\/bigPointValue.\n\nUtilize the following moving average lengths of 20, 50, and 200.\n\nThe results are shown in Table 3.5.\n\n**Table 3.5** Single Moving Average (SMA) Crossover Algorithm\n\n**SMA** | **Simple Moving Average Crossover** | | | | | | \n---|---|---|---|---|---|---|--- \n**Length** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** \n19 | \u2212922061 | \u221215.08 | \u2212986733 | 0.91 | 48.53 | 15814 | \u221258.31 | 9.78 | 23.04 \n39 | \u221215191 | \u22120.1 | \u2212612726 | 1 | 16.1 | 11114 | \u22121.37 | 13.49 | 19.97 \n100 | 564180 | 2.91 | \u2212626574 | 1.11 | 13.92 | 6543 | 86.23 | 21.94 | 16.25 \n200 | 487626 | 2.58 | \u2212492640 | 1.13 | 14.95 | 4495 | 108.48 | 30.67 | 12.77\n\n* * *\n\nTable 3.5 starts the battle and sets the benchmark with the results of the SMA algorithm.\n\nLet's hope the other algorithms have better luck. Before moving on to the results of the other algorithms a clear explanation of performance metrics might be a good idea:\n\n * **Net Profit** \u2014summation of all profits or losses after deduction of execution costs.\n * **Sys Drawdown** \u2014the largest peak-to-valley decline experienced in the complete portfolio. This is a good metric to use in the calculation of how much capital to allocate to a trading algorithm. However, remember this is a onetime event and in many cases the **Start Trade Drawdown** analysis might be a better indicator for capitalization purposes. Start Trade Drawdown shows the different probabilities of the occurrence of different magnitudes of drawdown. This analysis will be detailed in Chapter 8 along with Monte Carlo simulation.\n * **Annual Return %** \u2014compounded annual return based on a cool million-dollar investment.\n * **Number of Trades** : number of trades.\n * **Profit\/Loss** \u2014(Profit of winners \/ Loss of losers) \/ Number of trades. This is also known as the expectancy in terms of dollars.\n * **Bars Held** \u2014the number of bars, on average, a trade is held. You can use this as a guide to align different parameters sets across different algorithms.\n * **Total Transaction Costs** \u2014summation of execution fees.\n * **Profit Factor** \u2014profit of winners divided by loss of losers.\n * **Ulcer Index** \u2014square root of sum of squared drawdowns divided by number of bars. It measures the volatility in the downward direction.\n * **Sharpe Ratio** \u2014indicator of consistency. Average return divided by the standard deviation of returns sampled on daily, monthly, or yearly basis. The higher the better.\n\nArmed with these performance metrics it is plain to see that the SMA as a complete trading algorithm is not that good. I hope you weren't surprised by this fact. Don't get me wrong; simple moving averages have their place in technical analysis, but not as a complete trading algorithm. Results might improve utilizing an exponential moving average, but not enough to consider it as your main trading tool. Notice how the long-term version handily outperformed its shorter and intermediate-term counterparts.\n\nIf a single moving average doesn't cut the mustard, then what about two? Table 3.6 shows the DMA utilizing three different lengths.\n\n**Table 3.6** Double Moving Average (DMA) Crossover Algorithm\n\n**DMA** | **Double Moving Average** | | | | | | | \n---|---|---|---|---|---|---|---|--- \n**Length** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** \n9,19 | \u221229879 | \u22120.19 | \u2212548958 | 1 | 20.2 | 8529 | \u22123.5 | 17.46 | 35.08 \n19,49 | 61910 | 0.39 | \u2212743755 | 1.01 | 21.29 | 3997 | 15.49 | 36.11 | 33.1 \n49,99 | 996693 | 4.53 | \u2212692714 | 1.24 | 11.39 | 2307 | 432.03 | 61.8 | 34.07\n\nA vast improvement. The short term and intermediate term still trail their big brother, but both improved. The DMA with lengths of 49 and 99 cranked out profits close to a million dollars. This feat was accomplished by trading just 2,307 times\u2014less than 100 times a year across 35 markets. Could the winner already be revealed? If the double moving average stood head and shoulders above the single moving average, where do you think the triple moving average will wind up? Table 3.7 gives the details.\n\n**Table 3.7** Triple Moving Average (TMA) Crossover Algorithm\n\n**TMA** | **Triple Moving Average** | | | | | | | \n---|---|---|---|---|---|---|---|--- \n**Length** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **percent of Winners** \n9,19,49 | \u221271434 | \u22120.47 | \u2212441997.88 | 0.99 | 14.68 | 5160 | \u221213.84 | 18.21 | 33.93 \n19,49,199 | 527917 | 2.75 | \u2212374103 | 1.22 | 9.41 | 1850 | 285.36 | 43.49 | 32.7 \n49,199,399 | 711878 | 3.5 | \u2212211493 | 1.77 | 6.09 | 528 | 1348.25 | 137.61 | 32.01\n\nThe trend continues. The longer-term triple crossover produced over $700K on just 528 trades. It made 70 percent of what the longer-term DMA produced but did it with a less than one-fourth the number of trades. It averaged $1,348 on every trade. Pretty impressive, but this is more like investing than trading. What if we changed the lengths of the parameters to try and match the number of trades from the longer-term DMA? Would that be curve-fitting? The parameter values that produced so few trades were initially chosen based on a preconceived notion that a certain number of trades and trade duration would be achieved. Tuning the parameters to get us into the ballpark of our objective, whatever that might be, is not over-curve-fitting. So far it looks like the longer-term versions of the DMA and TMA are producing somewhat comparable results. The next system up gets us out of the moving averages and back into Turtle mode. Table 3.8 shows the performance of three different Donchian lengths.\n\n**Table 3.8** Donchian Channel Breakout for Different Donchian Lengths\n\n**Donchian** | **Donchian Channel Breakout** | | | | | | \n---|---|---|---|---|---|---|--- \n**Length** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** \n20\/10 | 278329 | 1.59 | \u2212257735.79 | 1.05 | 9.61 | 6070 | 45.85 | 17.43 | 35.34 \n40\/20 | 754015 | 3.67 | \u2212361607 | 1.18 | 8.43 | 2963 | 254.48 | 35.45 | 36.85 \n100\/50 | 1114437 | 4.91 | \u2212367415 | 1.51 | 7.07 | 1366 | 815.84 | 68.65 | 32.01\n\nThe Turtle hit a home run! All three versions were profitable and the 100-day Donchian beat the longer-term DMA: $1.1 million on only 1366 trades. It's going to be hard to knock this system off of the podium. If any system can, it could be one based off of John Bollinger's world famous bands. Table 3.9 tells the tale of the tape.\n\n**Table 3.9** Bollinger Band Breakout\n\n**Bollinger** | **Bollinger Band Breakout** | | | | | | \n---|---|---|---|---|---|---|--- \n**Length** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **% of Winners** \n20-Day | \u221241360 | \u22120.27 | \u2212343007 | 0.99 | 13.83 | 4860 | \u22128.51 | 16.06 | 32.63 \n50-Day | 728097 | 3.57 | \u2212321144 | 1.24 | 8.03 | 2396 | 303.88 | 32.94 | 32.1 \n100-Day | 756849 | 3.68 | \u2212362325 | 1.37 | 8.33 | 1364 | 554.87 | 57.83 | 30.94\n\nWell that was a little bit of a disappointment. The trend did not continue as the longer-term version did not win the battle among the different Bollinger Band lengths. The intermediate-term version just barely nudged out the longer term with slightly less profit, but 10 percent less drawdown. The big news is the Bollinger Band algorithm came in third place when compared with the triple moving average and Donchian channel.\n\nSo the winner is... Hold on! We are getting some complaints out of the Bollinger Band camp. They are saying it's not a fair test. They want a rematch! They say that we held the number of standard deviations constant at two. Just changing the lengths of the moving averages and not the width of the bands (number of standard deviations) does not reflect the true capability of such a powerful algorithm. Now the other camps are complaining, too! What to do?\n\nWhy don't we have a grudge match between the four best algorithms: DMA, TMA, DC, and BB. But this time, let's let the computer choose the best parameter sets. AmiBroker has produced the results thus far, so let's lean on it a little bit and have it help us level the playing field. Let's optimize the living daylights out of each algorithm and see what parameter sets produce the best profit-to-drawdown ratio. Let's not stop at optimizing the lengths of the parameters but the protective stop as well. The Bollinger Band camp will be happy because not only will we optimize the parameter lengths, and the protective stop, but we will also optimize the width of the bands. Does this smell of over-curve-fitting? Sure it does, but we aren't developing a trading system here, we are just doing an analysis.\n\nNow that we have a plan, how can we use AmiBroker to carry it out? The algorithms are already programmed (source code will be graciously provided in the appendices), but how many optimizations are we talking about? Quickly doing the math in my head\u2014millions! Table 3.10 shows the exact number of permutations and the range that each parameter will be tested across.\n\n**Table 3.10** Comparison of Parameters for Algorithms Based on Different Strategies\n\n**Donchian** | **Start** | **Stop** | **Increment** | **# Iterations** \n---|---|---|---|--- \nEntry Len | 9 | 100 | 1 | 92 \nExit Len | 5 | 100 | 1 | 96 \nProtective Stop | 3000 | 6000 | 500 | 7 \nTotal | | | | 61824 \n**Bollinger** | **Start** | **Stop** | **Increment** | **# Iterations** \nAverage Length | 20 | 200 | 1 | 181 \n\n#Std. Deviations | 0.25 | 3 | 0.05 | 56 \nProtective Stop | 3000 | 6000 | 500 | 7 \nTotal | | | | 31752 \n**TMA** | **Start** | **Stop** | **Increment** | **# Iterations** \nShort Length | 9 | 100 | 1 | 92 \nIntermediate Length | 19 | 200 | 2 | 91 \nLong Length | 49 | 399 | 3 | 117 \nProtective Stop | 3000 | 6000 | 500 | 7 \nTotal | | | | 6856668 \n**DMA** | **Start** | **Stop** | **Increment** | **# Iterations** \nShort Length | 9 | 100 | 1 | 92 \nIntermediate Length | 19 | 200 | 2 | 91 \nProtective Stop | 3000 | 6000 | 500 | 7 \nTotal | | | | 58604\n\nThe number doesn't get really large until we move to the TMA optimization\u2014nearly seven million. This is due to the fact that we are optimizing four parameters. Well, it was a good idea. We will just have to go with what we have, because who has the time to do a multimillion-iterations optimization loop? Wait a minute\u2014this book is about algorithms\u2014right? This task is definitely not doable with a run-of-the-mill exhaustive search optimization engine. An exhaustive search optimization is where you use brute force and test every possible combination\u2014no stone is left unturned. Come to think of it, AmiBroker has access to three forms of genetic optimization. With the use of genetic optimization (GO) and artificial intelligence, we can accomplish the task and do it in just a few minutes. Not all iterations are executed, only those that fit a certain fitness. Imagine millions and millions of optimizations carried out in minutes instead of days or even months. Genetic optimization is an awesome tool, and this very topic will be discussed in Chapter 8. Right now, even if you don't understand artificial intelligence, just know it is the tool that we need to accomplish this task.\n\nAll optimizations will be carried out at the portfolio level. Individual market optimizations will not be conducted. This will cut down considerably on the total number of optimizations. Each set of parameters will be applied to each market in the portfolio, and only one set will be chosen to represent each algorithm. Also, like I said earlier, we are not trying to fit a system to data in an attempt to create a trading plan. We are just trying to cover all bases in this algorithm comparison. The winning parameter sets will be used for illustration purposes only.\n\nAmiBroker was able to complete the task in roughly 40 minutes. This time period covered all optimizations across the four algorithms. Pretty darn impressive! Table 3.11 shows the top 10 parameter sets for each algorithm and their associated profit\/loss, maximum drawdown, number of trades, average trade, profit factor, Ulcer index, and percent winners.\n\n**Table 3.11** Top 10 Parameter Sets for Each Algorithm\n\n**Algo Name** | **Net Profit** | **CAR** | **Max DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **%Winners** | **ShortLen** | **InterLen** | **StopDollars** \n---|---|---|---|---|---|---|---|---|---|---|---|--- \nDMA | 1338431.01 | 5.59 | \u2212491839.05 | 1.44 | 8.96 | 1991 | 672.24 | 71.42 | 25.62 | 9 | 162 | 6000 \nDMA | 1336531.01 | 5.59 | \u2212492539.05 | 1.44 | 8.97 | 2010 | 664.94 | 70.75 | 25.72 | 9 | 162 | 5500 \nDMA | 1333731.01 | 5.58 | \u2212493339.05 | 1.44 | 8.99 | 2038 | 654.43 | 69.79 | 25.66 | 9 | 162 | 5000 \nDMA | 1330531.01 | 5.57 | \u2212494639.05 | 1.43 | 9.01 | 2070 | 642.77 | 68.73 | 25.6 | 9 | 162 | 4500 \nDMA | 1325931.01 | 5.56 | \u2212495939.05 | 1.43 | 9.04 | 2116 | 626.62 | 67.26 | 25.14 | 9 | 162 | 4000 \nDMA | 1319431.01 | 5.54 | \u2212498839.05 | 1.42 | 9.09 | 2181 | 604.97 | 65.28 | 25.03 | 9 | 162 | 3500 \nDMA | 1310731.01 | 5.51 | \u2212501739.05 | 1.41 | 9.16 | 2268 | 577.92 | 62.82 | 25.04 | 9 | 162 | 3000 \nDMA | 1309059.66 | 5.51 | \u2212515389.7 | 1.43 | 9.15 | 1948 | 672 | 72.98 | 26.49 | 10 | 156 | 6000 \nDMA | 1308892.36 | 5.51 | \u2212522360.35 | 1.44 | 9.11 | 1941 | 674.34 | 73.23 | 25.66 | 9 | 164 | 6000 \nDMA | 1308303.31 | 5.5 | \u2212473577.53 | 1.43 | 8.96 | 2004 | 652.85 | 70.96 | 25.45 | 9 | 160 | 6000 \n**Algo Name** | **Net Profit** | **CAR** | **Max DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **%Winners** | **ShortLen** | **InterLen** | **StopDollars** \nTMA | 1124260.22 | 4.94 | \u2212179037.08 | 2.11 | 4.03 | 574 | 1958.64 | 143.68 | 35.89 | 49 | 194 | 309 \nTMA | 1100730.77 | 4.87 | \u2212167743.6 | 2.09 | 3.96 | 573 | 1921 | 143.33 | 34.73 | 49 | 194 | 312 \nTMA | 1071646.95 | 4.78 | \u2212168698.98 | 2.04 | 3.97 | 576 | 1860.5 | 142.43 | 34.55 | 49 | 194 | 306 \nTMA | 1088110.19 | 4.83 | \u2212181550.77 | 2.06 | 4.01 | 575 | 1892.37 | 143.43 | 35.13 | 48 | 194 | 309 \nTMA | 1049097.29 | 4.7 | \u2212171951.93 | 2.02 | 3.91 | 577 | 1818.19 | 142.48 | 35.7 | 47 | 194 | 309 \nTMA | 1069863.15 | 4.77 | \u2212169583.3 | 2.03 | 3.95 | 573 | 1867.13 | 143.02 | 34.38 | 48 | 194 | 312 \nTMA | 1023856.17 | 4.62 | \u2212163224.35 | 2 | 3.93 | 566 | 1808.93 | 143.04 | 35.34 | 49 | 192 | 315 \nTMA | 1005683.72 | 4.56 | \u2212160448.4 | 1.96 | 3.82 | 578 | 1739.94 | 141.37 | 34.95 | 47 | 194 | 306 \nTMA | 1040045.32 | 4.67 | \u2212168261.18 | 1.98 | 3.95 | 577 | 1802.5 | 142.02 | 34.14 | 48 | 194 | 306 \nTMA | 1083985.47 | 4.82 | \u2212195109.25 | 2.06 | 4.17 | 569 | 1905.07 | 144.76 | 36.03 | 49 | 192 | 309 \n**Algo Name** | **Net Profit** | **CAR** | **Max DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **%Winners** | **ShortLen** | **InterLen** | **StopDollars** \nBollinger | 1033937 | 4.65 | \u2212292963.4 | 1.63 | 6.09 | 1031 | 1002.85 | 67.16 | 36.28 | 101 | 2.25 | 3500 \nBollinger | 1020469 | 4.61 | \u2212296895 | 1.63 | 6.22 | 1012 | 1008.37 | 68.34 | 35.67 | 103 | 2.25 | 3500 \nBollinger | 885350 | 4.15 | \u2212238296.63 | 1.75 | 6.97 | 657 | 1347.56 | 87.76 | 38.05 | 129 | 2.5 | 4000 \nBollinger | 1024112 | 4.62 | \u2212296874.3 | 1.63 | 6.17 | 1022 | 1002.07 | 67.84 | 36.11 | 102 | 2.25 | 3500 \nBollinger | 1016747 | 4.6 | \u2212296905.3 | 1.61 | 6.3 | 1050 | 968.33 | 66.47 | 35.81 | 100 | 2.25 | 3500 \nBollinger | 877685 | 4.12 | \u2212249438.93 | 1.77 | 6.91 | 674 | 1302.2 | 82.73 | 36.65 | 123 | 2.5 | 3500 \nBollinger | 1182979 | 5.13 | \u2212384837.03 | 1.38 | 7.73 | 2086 | 567.1 | 51.44 | 31.4 | 89 | 1.25 | 5000 \nBollinger | 844532 | 4 | \u2212236280.73 | 1.77 | 6.95 | 628 | 1344.8 | 89.57 | 37.58 | 135 | 2.5 | 3500 \nBollinger | 1195823 | 5.17 | \u2212395271.98 | 1.39 | 7.71 | 2062 | 579.93 | 52 | 31.43 | 90 | 1.25 | 5000 \nBollinger | 863732 | 4.07 | \u2212238588.03 | 1.72 | 7.02 | 661 | 1306.71 | 86.3 | 37.52 | 126 | 2.5 | 4000 \n**Algo Name** | **Net Profit** | **CAR** | **Max DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg Profit\/Loss** | **Avg Bars Held** | **%Winners** | **ShortLen** | **InterLen** | **StopDollars** \nDonchian | 972653 | 4.45 | \u2212183567.7 | 1.4 | 4.93 | 0.9 | 2088 | 465.83 | 31.92 | 35.87 | 92 | 19 \nDonchian | 964178 | 4.42 | \u2212191985.6 | 1.39 | 4.98 | 0.89 | 2136 | 451.39 | 30.54 | 36.05 | 92 | 18 \nDonchian | 959512 | 4.4 | \u2212192721.65 | 1.39 | 5.08 | 0.87 | 2147 | 446.91 | 30.52 | 35.96 | 91 | 18 \nDonchian | 966614 | 4.43 | \u2212176310.85 | 1.39 | 4.98 | 0.89 | 2110 | 458.11 | 31.88 | 35.78 | 90 | 19 \nDonchian | 963078 | 4.42 | \u2212193489.13 | 1.4 | 5.1 | 0.87 | 2116 | 455.14 | 30.51 | 36.06 | 94 | 18 \nDonchian | 967138 | 4.43 | \u2212185009.95 | 1.39 | 5.03 | 0.88 | 2099 | 460.76 | 31.88 | 35.87 | 91 | 19 \nDonchian | 954784 | 4.39 | \u2212195440.55 | 1.39 | 5.15 | 0.85 | 2129 | 448.47 | 30.48 | 35.93 | 93 | 18 \nDonchian | 1038561 | 4.67 | \u2212214593.15 | 1.4 | 5.48 | 0.85 | 2049 | 506.86 | 37.22 | 34.75 | 81 | 23 \nDonchian | 959044 | 4.4 | \u2212184915.55 | 1.38 | 5.08 | 0.87 | 2168 | 442.36 | 31.83 | 35.56 | 85 | 19 \nDonchian | 954212 | 4.39 | \u2212175255.05 | 1.37 | 5.03 | 0.87 | 2183 | 437.11 | 31.8 | 35.41 | 84 | 19\n\nTable 3.12 shows the best parameters sets from each optimization.\n\n**Table 3.12** The Best Parameter Sets for Each Optimization\n\n**Best Parameter Sets** | | | **Money** | **Net** | **Max.** | **Profit to** | **#** \n---|---|---|---|---|---|---|--- \n**Algo Name** | **Param1** | **Param2** | **Param3** | **Mngmt. Stop** | **P \/ L** | **Drawdown** | **Drawdown** | **Trades** \nDMA | 9 | 162 | \u2212 | 3000 | 1310731 | \u2212501739 | 2.61 | 2268 \nTMA | 49 | 194 | 309 | 3000 | 1124260 | \u2212159761 | 7.04 | 574 \nDC | 92 | 19 | \u2212 | 3000 | 959512 | \u2212192721 | 4.98 | 829 \nBB | 101 | 2.25 | \u2212 | 3500 | 1033937 | \u2212292963 | 3.53 | 1031\n\nAnd the winner is\u2014triple moving average! The results show a unanimous champion, the triple moving average. The Donchian algorithm came in second with the Bollinger algorithm close behind in third. The winner produced a tremendous profit-to-drawdown ratio of 7.04. Quite a bit better than the second place Donchian Channels. The TMA accomplished this feat by trading only 574 times. Before discussing the winners let's discuss the also-rans.\n\nThe DMA algorithm came in last place. It looks like using the parameter sets revolving around an ultra-short length of 9, a long length of 160, and a $5,000 money management stop shows the best results. These numbers were derived from taking an average of the top 10 parameter sets. These numbers really don't make sense; the normal 1:2 and 1:3 ratio wasn't anywhere near the top. Basically, the parameters are telling us the nine-period moving average will eventually get on the trend, after going back and forth for a while, and hold onto it tenaciously.\n\nThe Bollinger Band algorithm came in third place, but with very respectable results. The parameter sets revolving around a 100-bar moving average length and 2.25 standard deviations and a $4,000 money management stop show the best results. One of the better parameter sets sticks out like a sore thumb (90, 1.25, 5000) due to the fact the surrounding parameters are so different, yet produce similar results. This set might be sitting on top of a peak. Figure 3.2 shows a three-dimensional contour chart of the Bollinger performance across a subset of the parameters that were originally optimized. The money management stop was held at a constant so that a three-dimensional representation could be generated. Notice where the 88 length and 1.25 width parameter lies on the chart. Almost smack-dab on a peak. This demonstrates a lack of robustness\u2014in other words, history would have to repeat itself almost exactly for this set to be productive into the future. A parameter set on a high but somewhat level plateau is a better choice.\n\nThe TMA looks to be the best by far; it nearly kicked the rest of the competitors off of the podium. The results are very impressive, with a very high profit-to-drawdown ratio. If you look at the top 10 parameter sets, you will see the almost exact performance for each. The only parameter that varied was the long-term length. The overall effectiveness of the algorithm was not affected by variations in this parameter. It just needs to be sufficiently large. This demonstrates a high level of robustness. Also notice the ratio of the short- and intermediate-term lengths to the long-term lengths: 1 to 4 and 1 to 6, respectively. This ratio is not one that is mainly prescribed when trading the TMA.\n\nThe Donchian algorithm looks to be nearly as good nearly as the TMA. It looks like using the parameter sets revolving around an entry length of 90, an exit length of 19, and a $3,000 money management stop shows the best results. I was a little surprised by the outcome; I was looking for an entry length around 55 and an exit length around 20\u2014the Turtle numbers. Or parameters that fit the _N_ bar entry and _N_ \/ 2 bar exit template. The mantra \"Hard to get in, easy to get out\" definitely fits these results. Even with such a short exit parameter, trades typically lasted 30 days. The results also demonstrated robustness among the parameter sets; results stayed somewhat constant throughout a good portion of the optimization. It's no wonder this algorithm is still being widely used.\n\nThere you have it! Four very tradable algorithms. You can't ask for much more than 60K to 70K annual return for the past 15 years, can you? On a million-dollar allocation, that works out to be 6 percent or 7 percent a year. Oh, yeah, you would have had to live through a 20 percent to 50 percent maximum drawdown. Hopefully that occurred after you had built up your equity. If it occurred right off the bat, then you would be in a heap of trouble\u2014most traders would jump ship at that point and never look back.\n\nSince most traders don't have a million dollars to allocate to trading, they can't afford to trade the 35-market portfolio we are currently testing. Even though this portfolio offers a tremendous amount of diversification, it is simply too large. The key to getting these systems into the realm of reality is to come up with a smaller yet diverse portfolio. Portfolio composition, especially to beginning traders, is as important as a trading algorithm. There are several steps to developing a complete algorithmic trading plan: algorithm selection, portfolio composition, proper optimization, and trade management. Position sizing is also an important component, but that will be covered later. In the next section, a smaller portfolio will be created by culling from the current large portfolio. After an algorithm has been developed and a portfolio selected, the next step is proper optimization. The final step is to develop trade management. So far, we have just used disaster stops in the development and testing of the algorithms. Are there better ways to manage a trade than waiting for a liquidation on a system-derived exit or a disaster stop? Also, is using a function of the market such as average true range better than a pure $ stop? Trade management is very important and it covers the concepts of dollar- or volatility-derived stops, profit objectives, and trailing stops. Trend-following mechanisms do not usually work with pure profit objectives unless they are sizable. You can't limit the upside, because the truly big winners don't occur all that often. Most trend-following algorithms have an inherent trailing stop mechanism built-into their logic. When the market moves up so does a moving average, a Bollinger band, and a Donchian channel. You can incorporate a more aggressive trailing stop, but again be aware that limiting the big winners will be counterproductive.\n\n## Portfolio Composition\n\nPicking a small but diverse portfolio isn't brain surgery. The key to a good portfolio is a selection of markets that are somewhat noncorrelated and cull from different market sectors. A good portfolio should have representation from at least five sectors: currencies, financials, energies, grains, and metals. You could just randomly pick one or two markets from each sector and be done with it, but more thought should be applied to the selection process. Why not just cherry-pick the very best markets from the backtested results and use these as the future portfolio? Unfortunately, this is curve fitting even though you are wanting a portfolio with high positive expectancy.\n\nA test on market correlation should be carried out prior to a selection of any portfolio component. Figure 3.3 shows a snapshot of a portion of the current portfolio correlation matrix. As you can see the diagonal is set to one. The diagonal represents the correlation of each market to itself.\n\n**Figure 3.3** A snapshot of a portion of the current portfolio correlation matrix.\n\nThe correlation coefficients range from +1 to \u22121. A coefficient of +1 represents a 100 percent correlation and a coefficient of \u22121 also represents a 100 percent correlation, but in the opposite direction. The AD (Australian dollar) is highly correlated to GC (gold), but not very much to the CU (Euro currency), and is highly anticorrelated to DX (dollar index). If you were picking two currencies, then you would probably want to go with the AD and CU. The BP is a little too noncorrelated for my taste. So let's pick the AD and CU to represent the currencies. Moving onto energies the crude is highly correlated to both the heating oil and natural gas. Unleaded is a different story; there is very little correlation there. CL and RB (unleaded) will take care of the energies sector. The grains consist of soybeans, corn, Kansas City wheat, Chicago wheat, corn, and a few other low-volume components. According to the correlation matrix, a good mix would be the corn and KC wheat. The financials are up next and are represented by 30-year Treasury bonds, 10-year notes, 5-year notes, 2-year notes, and Eurodollars. All these markets are highly correlated to each other, so there is no advantage\/diversification by trading one with another. Trading a Treasury bond with Treasury note is like trading two bonds. Bonds are very shock sensitive to news events such as Fed and employment situation reports. So the less volatile but still with some bang is the Treasury notes. The safest soft commodity is sugar (SB). It trends well and seems less sensitive to crop reports than coffee (KC) or cotton (CT). There is very little correlation among these three markets so any one of the three would probably suffice. All of the metals in the current portfolio, silver (SV), gold (GC), copper (HG), and platinum (PL), are, as you would assume, highly correlated, so like the financials only one should be chosen for this initial portfolio. Copper is the only nonprecious metal in the list and used extensively in manufacturing so let's pick it. The initial portfolio will consist of the following markets: AD, CU, CL, RB, TY, C, KW, SB, and HG. You will notice that the stock indices were left out. The indices are a totally different animal. In an interview with Richard Dennis by Arthur Collins, the King Turtle stated:\n\n> With the exception of the S&Ps, they're all the same. You have to treat them the same, for no reason other than sample size. You can optimize each system in each market individually or you can optimize them together. It's better to optimize them together.\n> \n> \u2014 ** _Technical Analysis of Stocks and Commodities_ , April 2005 Issue**\n\n### An Act of Futility?\n\nOkay, we now have a portfolio but on which algorithm should we risk our capital? Also should we use the best-optimized parameters for each algorithm that was derived from the global optimizations? Any of the four algorithms could be used\u2014they all showed positive expectancy. The \"optimal\" parameters that we previously derived were for illustration purposes only. These tests simply provided evidence that these algorithms have a technical edge. A new set of tests have to be set up with our new portfolio across the four best performing algorithms. Also, we need to come up with a set of parameters for each algorithm that will hopefully stand the test of time. The test of time can be accomplished by utilizing out-of-sample (OOS) data. OOS data is a segment of historical data that the algorithms did not see during their developmental periods. The algorithms can be optimized on in-sample data (IS) and the \"optimal\" parameter sets can then be applied to data that has not yet been seen. The ratio between OOS and IS is a subject of much debate. Some believe you should give the algorithm more data (IS) to be trained on in hopes that the parameters will reflect more diverse market conditions. Others feel that a longer walk-forward (OOS) test will demonstrate an algorithm's true robustness. I don't believe there is a universal answer to this conundrum, but experience has shown that a 1-to-3 ratio seems to work. The test period that we have been using is 15 years, so using this ratio we come up with roughly five years of OOS and roughly 10 years IS.\n\nBefore we carry out these tests the subject of individual market optimization needs to be brought up. I have never seen, in all my years of testing, a trading algorithm utilizing different parameters on a market-by-market basis survive the test of time. Even trading algorithms that just utilize different parameters on a sector-by-sector basis haven't been all that successful over the long run. All this optimizing simply leads to over-curve-fitting. The trading systems that have stood the test of time have one and only one parameter set for the entire portfolio. Now that that question has been answered, what about periodical portfolio reoptimization? This is the idea of optimizing an algorithm for the first five or so years and then carrying over for the next year or two. At the end of the carryforward period, the parameters are reoptimized over the new unseen data and then carried forward again. This form of optimization uses a sliding IS data window. The results from the OOS data are accurate, since the parameters were not trained on that data until after the fact. This form of optimization is discussed extensively in Chapter 8.\n\nStarting with the Donchian algorithm and our new portfolio, let's optimize the parameters from January 2000 through December 2009. Using the best parameters set from this test, the algorithm will be tested across the remaining data, January 2010 through August 2015, to evaluate the robustness of the selection.\n\nTable 3.13 shows the best results for the Donchian algorithm IS time period. The parameter set that I chose was 98, 25, and $4,000. This was a top echelon set that had a reasonable protective stop. In addition, the two length parameters were located on a plateau\u2014they were surrounded by similar values.\n\n**Table 3.13** The Best Results for the Donchian Algorithm for In-Sample Time Period\n\n**Name** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **%Winners** | **Entry** | **Exit** | **StopDollars** \n---|---|---|---|---|---|---|---|---|---|---|---|--- \nDonchian | 466438 | 3.9 | \u221257391 | 2.21 | 2.27 | 324 | 1439.62 | 46 | 40.74 | 64 | 26 | 5000 \nDonchian | 417508 | 3.55 | \u221255451 | 2.33 | 1.72 | 272 | 1534.96 | 45.46 | 40.07 | 95 | 28 | 3000 \nDonchian | 420843 | 3.57 | \u221256764 | 2.36 | 1.98 | 262 | 1606.27 | 46.6 | 43.13 | 99 | 26 | 4500 \nDonchian | 421760 | 3.58 | \u221256764 | 2.31 | 1.94 | 262 | 1609.77 | 47.39 | 43.51 | 97 | 26 | 5500 \nDonchian | 421849 | 3.58 | \u221256764 | 2.35 | 1.98 | 263 | 1603.99 | 46.61 | 42.97 | 98 | 26 | 4500 \nDonchian | 421762 | 3.58 | \u221256764 | 2.34 | 1.92 | 260 | 1622.16 | 47.47 | 43.85 | 98 | 26 | 5500 \nDonchian | 420241 | 3.57 | \u221256764 | 2.34 | 1.72 | 261 | 1610.12 | 48.18 | 41.76 | 96 | 28 | 4000\n\nNow the real test begins. A diversified portfolio has been chosen as well as a seemingly robust parameter set. Let's walk this algorithm forward and test it across the OOS time frame (January 2010 through August 2015). Table 3.14 exposes a seeming act of futility.\n\n**Table 3.14** Results for the Donchian Algorithm when Walked Forward across an Out-of-Sample (OOS) Time Period\n\n**Name** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **%Winners** \n---|---|---|---|---|---|---|---|---|--- \n | 25678 | 0.45 | \u2212166243 | 1.08 | 8.2 | 161 | 159.49 | 41.32 | 32 \nAD0_E0B | \u221216980 | \u22120.31 | \u221229050 | 0.61 | 1.83 | 20 | \u2212849 | 39 | 25 \nC20_E0B | \u221218413 | \u22120.33 | \u221235138 | 0.53 | 2.25 | 21 | \u2212876.79 | 39.14 | 33 \nCL20_E0B | 11230 | 0.2 | \u221239180 | 1.23 | 1.82 | 19 | 591.05 | 32 | 26 \nCU0_E0B | 37713 | 0.66 | \u221224450 | 2.99 | 1.14 | 13 | 2900.96 | 51.54 | 31 \nHG20_E0B | \u221216438 | \u22120.3 | \u221228638 | 0.62 | 1.87 | 19 | \u2212865.13 | 33.74 | 32 \nKW20_E0B | 1463 | 0.03 | \u221214725 | 1.07 | 0.54 | 19 | 76.97 | 41.95 | 32 \nRB0_E0B | \u22122927 | \u22120.05 | \u221260503 | 0.96 | 2.93 | 21 | \u2212139.4 | 29.9 | 14 \nSB20_E0B | 15918 | 0.28 | \u221212749 | 2.68 | 0.89 | 17 | 936.33 | 52.59 | 53 \nTY0_E0B | 14113 | 0.25 | \u22128084 | 2.54 | 0.37 | 12 | 1176.05 | 66.67 | 50\n\nWell, at least the system made some money. However, the drawdown is just way too great. What did we do wrong? We did all our homework\u2014picked a fairly diversified portfolio and a robust parameter set. How could we have been so far off? Out of pure sick curiosity, I optimized the algorithm across the OOS data to see how far off we missed the target. Table 3.15 has the best parameters sets for our small portfolio over the OOS timespan.\n\n**Table 3.15** The Best Parameters for the Portfolio over the Out-Of-Sample (OOS) Time Period\n\n**Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **%Winners** | **Entry** | **Exit** | **StopDollars** \n---|---|---|---|---|---|---|---|---|---|---|--- \n182607 | 3.04 | \u221295572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 5500 \n182607 | 3.04 | \u221295572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 4500 \n182607 | 3.04 | \u201395572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 4000 \n182607 | 3.04 | \u221295572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 3500 \n182607 | 3.04 | \u221295572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 3000 \n182607 | 3.04 | \u221295572 | 1.42 | 3.85 | 253 | 721.77 | 48.67 | 39.53 | 30 | 30 | 6000 \n182456 | 3.04 | \u221295583 | 1.42 | 3.85 | 253 | 721.17 | 48.67 | 39.53 | 30 | 42 | 3000 \n182412 | 3.04 | \u221295593 | 1.42 | 3.85 | 253 | 720.99 | 48.67 | 39.53 | 30 | 84 | 3000 \n182412 | 3.04 | \u221295593 | 1.42 | 3.85 | 253 | 720.99 | 48.67 | 39.53 | 30 | 100 | 5500\n\nBoy, were we way off! A couple of the best parameter sets had the exit length parameter greater than the entry length\u2014illogical, you say! In these situations, the system becomes a reversal system until it is stopped out with the money management stop. I am almost too scared to continue, but like looking at a car accident, let's continue in this same vein. Maybe the Donchian is just an inferior algorithm. Table 3.16 is the IS optimization of the Bollinger algorithm and Table 3.17 is the OOS results.\n\n**Table 3.16** The Optimization of the Bollinger Algorithm for the In-Sample (IS) Time Period\n\n**Name** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **%Winners** | **Len** | **Width** | **StopDollars** \n---|---|---|---|---|---|---|---|---|---|---|---|--- \nBollinger | 498208 | 4.13 | \u221259466 | 2.55 | 2.2 | 247 | 2017.04 | 66.91 | 37.65 | 103 | 1.5 | 5000 \nBollinger | 480108 | 4 | \u221266439 | 2.46 | 2.23 | 256 | 1875.42 | 63.79 | 38.28 | 98 | 1.5 | 5000 \nBollinger | 492573 | 4.09 | \u221259399 | 2.53 | 2.07 | 251 | 1962.44 | 65.7 | 38.25 | 102 | 1.5 | 4500 \nBollinger | 489796 | 4.07 | \u221259466 | 2.49 | 2.15 | 250 | 1959.18 | 65.93 | 37.2 | 103 | 1.5 | 4500 \nBollinger | 516639 | 4.25 | \u221263828 | 2.71 | 2.02 | 239 | 2161.67 | 68.67 | 38.49 | 105 | 1.5 | 6000 \nBollinger | 502931 | 4.16 | \u221261884 | 2.64 | 2.06 | 240 | 2095.54 | 68.08 | 38.33 | 108 | 1.5 | 4000 \nBollinger | 516685 | 4.25 | \u221264074 | 2.74 | 2.04 | 243 | 2126.27 | 66.91 | 37.86 | 105 | 1.5 | 4000 \nBollinger | 515383 | 4.24 | \u221263828 | 2.7 | 2.06 | 239 | 2156.42 | 69.05 | 38.08 | 106 | 1.5 | 6000 \nBollinger | 511872 | 4.22 | \u221263828 | 2.67 | 2.1 | 240 | 2132.8 | 68.34 | 38.33 | 105 | 1.5 | 5500 \nBollinger | 516735 | 4.25 | \u221265095 | 2.72 | 2.09 | 231 | 2236.95 | 71.45 | 38.53 | 110 | 1.5 | 5000\n\n**Table 3.17** Results for the Donchian Algorithm when Walked Forward across an Out-of-Sample (OOS) Time Period\n\n**Name** | **Net Profit** | **CAR** | **Max. Sys DD** | **Profit Factor** | **Ulcer Index** | **# Trades** | **Avg P\/L** | **Avg Bars Held** | **%Winners** \n---|---|---|---|---|---|---|---|---|--- \n | \u221231803 | \u22120.58 | \u2212222494.3 | 0.91 | 11.93 | 158 | \u2212201.28 | 56.15 | 30 \nAD0_E0B | \u22122570 | \u22120.05 | \u221226410 | 0.91 | 1.64 | 16 | \u2212160.62 | 64.56 | 38 \nC20_E0B | \u22128500 | \u22120.15 | \u221226325 | 0.71 | 1.73 | 20 | \u2212425 | 53.85 | 30 \nCL20_E0B | \u221214060 | \u22120.25 | \u221258490 | 0.78 | 3.36 | 21 | \u2212669.52 | 40.95 | 29 \nCU0_E0B | 16888 | 0.3 | \u221239763 | 1.62 | 2.17 | 14 | 1206.25 | 67.57 | 36 \nHG20_E0B | \u221225763 | \u22120.46 | \u221238750 | 0.56 | 2.47 | 19 | \u22121355.92 | 45.26 | 26 \nKW20_E0B | 8525 | 0.15 | \u221215063 | 1.4 | 0.59 | 17 | 501.47 | 65.71 | 41 \nRB0_E0B | \u221229267 | \u22120.53 | \u221279688 | 0.7 | 4.51 | 24 | \u22121219.48 | 36.63 | 13 \nSB20_E0B | 15185 | 0.27 | \u221219315 | 2.07 | 1.28 | 11 | 1380.44 | 94.27 | 36 \nTY0_E0B | 7760 | 0.14 | \u22129334 | 1.46 | 0.49 | 16 | 484.99 | 65.38 | 38\n\nOkay, looks good. I selected the parameter set [108, 1.5, 4000]. How did it do during the OOS timespan?\n\nI think I see a trend developing. I would show you the TMA and the DMA, but it would be just a waste of paper! I am talking reverse makeover. So what happened? Where do we place the blame? I went back and recreated a portfolio of the top nine markets based on IS performance and the OOS results were even worse than our small diversified portfolio. We did everything humanly possible to make these trend-following systems work: algorithm selection, optimization, and portfolio selection. What if we performed a more frequent periodic reoptimization? We saw the best parameter set shifting from just five years ago. This shift may be attributable to the disappearance of the pit session and the adoption of purely electronic markets. Who knows why, but the fact remains that the commodity markets have had a fundamental shift. Indicators such as the ones we have experimented with are adaptive by nature; they change based on market activity and\/or volatility. Theoretically, they should be able to keep up with the evolution of the markets. In practice, this was not the case.\n\nAmiBroker has a walk-forward backtesting capability\u2014meaning we can periodically reoptimize parameters throughout a historic backtest. I discuss this optimization method in great detail in Chapter 8. After this chapter, if you like, you can skip to Chapter 8 to help you understand exactly what is going on here. Figure 3.4 illustrates the basic concept of walk-forward testing. Basically it involves two primary steps:\n\n 1. Backtest and derive\u2014backtest and extract the best parameter set based on some criteria. It could be profit, drawdown, profit-to-drawdown ratio, etc.\n 2. Walk forward\u2014take the parameter sets and apply them forward in time on data not used in the backtest. Do this on a periodic basis.\n\n**Figure 3.4** Walk-forward testing begins with a backtest used to derive the desired parameter. Then, it applies that parameter going forward.\n\nSource: AmiBroker\n\nIn this example, the Bollinger Band algorithm will be reoptimized annually based on the best-performing parameters for the prior four years. Keep in mind that we are not cheating, as only the OOS (out-of-sample) data will be used to calculate performance metrics. Let's see if this method can turn around the trend of this trend-following method. Figure 3.4 shows the process of walking forward.\n\nAmiBroker's walk-forward optimizer (WFO) derived the best parameter set from January 1, 2006, to January 1, 2010, and then carried those parameters forward from January 1, 2010, to January 1, 2011. In this test, the algorithm netted $35,330 for 2010. It then included 2010 and backed up to January 1, 2007, and then carried those parameters forward through 2011. However, this time the algorithm lost a whopping \u2212$56,532. Keep stepping through the figure and you can see how the system performed through the present. What's really interesting is the shift in the parameter sets. You would think by adding just another year to the backtest during the periodic readjustment the parameters wouldn't shift that much. Take a look at Figures 3.5 and 3.6.\n\n**Figure 3.5** AmiBroker's walk-forward optimizer in action.\n\n**Figure 3.6** Parameters selected to carry forward for the following year.\n\nThe first year in our OOS window is 2010. The WFO picked the parameter set [72 day, 1.5 std. devs., 3000 stop] to apply to 2010 and the results looked great. Notice the wide shift in the parameters for 2011 [111, 0.25, 6000]. These parameters performed horribly, losing over $56,000. The parameters for 2012 shifted some more [143, 0.25, 3500]. These parameters didn't do much better. 2013 also shows a dramatic shift, [45, 3, 3500], but at least the algorithm made a little money. The parameter set stayed constant for 2014, and the algorithm really brought it home, with almost $72,000 in profit. The end result with periodic reoptimization beat the pants off of the static set with $45,000 in profit and a little more reasonable drawdown of $90,000. Figure 3.7 shows an equity curve of the walk-forward performance from 2006.\n\n**Figure 3.7** Performance of the WFO of the Bollinger Band system.\n\nSource: AmiBroker\n\nIs this the solution? Stick with your algorithm and readjust based on recent performance. That is a tough question to answer, and is best left up to what the trader truly believes when it comes to using optimization in the development of an algorithm's parameters. In today's trading environment, I think everything should be taken into consideration. Don't be afraid of new technology.\n\nAfter the second coming of trend following in 2008, the only bright spot has been the second half of 2014. And things are looking a little better here in 2015. It seems, for right now, that the commodity markets are behaving a little trendier. With prices in the tank trend followers are waiting for the eventuality of their springing back to life. They are limited resources, right? But how many trend followers will still be left out there? A lot more than you might think. Due to the nature of commodity price moves, you cannot simply abandon the trend-following methods. There is just way too much potential.\n\nSo what is the answer for a smaller account? In a similar fashion to diversifying through markets, a trader can diversify further through trading multiple algorithms. In a trader's perfect world, there would exist robust trend-following, short-term swing and day trading systems. Ones that were not closely correlated with the others. This perfect world doesn't exist due to the fact a robust short-term swing system is hard to find. The ones that seem to work on a somewhat consistent basis mostly work only on the stock indices. However, that's not a bad thing, because this is a very weak sector for trend followers. The best short-term algorithms that I have come across incorporate mean reversion or pattern recognition components. The marriage of trend following and these other types of algorithms might be one solution. This union brings together two different algorithms, as well as two noncorrelated portfolios.\n\n## Multi-Algorithm Strategy (MAS)\n\nMean reversion is a trading algorithm that trades in the direction of the trend but takes advantage of a temporary countertrend move.\n\nThe most recent performance of this algorithm looks very respectable. This algorithm utilizes the Bollinger B% indicator\/function (Box 3.4). Basically, it trades in the direction of the 200-day moving average but waits for a pullback for longs and rallies for shorts. The Bollinger B% function returns the location of the current close in relationship to the upper and lower Bollinger bands. If the function returns a small value, then the close is close to the lower band and vice-versa for a high value. This system is programmed in EasyLanguage and the source code will be revealed in the Chapter 7.\n\n* * *\n\n### Box 3.4 Mean Reversion (MR)\n\n 1. Calculate the 200-day moving average of closing prices\n 2. Calculate the 5-day Bollinger B% value\n 3. Calculate the 3-day moving average of the Bollinger B% value \n 1. If c > MAV(c,200) and MAV(BB%,3) < 0.25, then buy next bar at open\n 2. If c < MAV(c,200) and MAV(BB%,3) > 0.75, then sell short next bar at open\n 3. 1. Liquidate long MOC when BB% > .75 or close < entryPrice - 2000\/bigPointValue\n 2. Liquidate short MOC when BB% < 0.25 or close > entryPrice + 2000\/bigPointValue\n\n* * *\n\nTake a look at the equity curve in Figure 3.8. Here is a pattern system that trades the stock indices as well.\n\n**Figure 3.8** Equity curve that reflects a pattern system.\n\nThis system looks at the last day of the month, and if it closes down a certain amount from the prior day's close, it looks to buy if the first day of the month also closes below its open (Box 3.5). This is a reoccurring pattern, and it's based on the flip of the month.\n\n* * *\n\n### Box 3.5 LastBarOfMonth Pattern (LBM)\n\n 1. Calculate percentage change between yesterday's close and the prior day's close: %Chg = (close(1) \u2013 close(2)) \/ close(1) * 100\n 2. If today is the first trading day of the month and the %Chg < -0.2 and today's close < today's open, then buy MOC\n 3. If today is the first trading day of the month and the %Chg > 0.2 and today's close > today's open, then sell short MOC\n 4. Liquidate long at the open of the fifth day after entry day or on a stop @ entryPrice \u22122000\/bigPointValue\n 5. Liquidate short at the open of the fifth day after entry day or on a stop @ entryPrice + 2000\/bigPointValue\n\n* * *\n\nDay trading is a great complement to trend following as well. The equity curve in Figure 3.9 illustrates a mini-Russell day trading system that trades after a narrow range day and initially puts on two contracts and then pulls one off after a certain profit level and then lets the second contract run its course. It is out on the close no matter what. This algorithm incorporates trade management in the form of protective stop, breakeven stop, and trailing stop (Box 3.6).\n\n**Figure 3.9** Mini-Russell day trading system using a narrow range day. It initially puts on two contracts, pulling the first one off after a certain profit is reached and leaving the second to run its course.\n\n* * *\n\n### Box 3.6 Day trading the mini Russell\n\n 1. CanTrade = False\n 2. CanBuy = False\n 3. CanShort = False\n 4. If yesterday's True Range < MAV(TR,10), then CanTrade = True\n 5. If yesterday's close >= prior day's close, then CanBuy = True\n 6. If yesterday's close < prior day's close, then CanShort = True\n 7. If CanTrade, then \n 1. If CanBuy, then buy 2 units tomorrow at open +0.2 *MAV(TR,10) stop\n 2. If CanShort, then sell short 2 units tomorrow at open \u22120.2*MAV(TR,10) stop\n 8. If market position = long \n 1. If current size = 2 units, then\n\nIf H of 5 minute bar > entryPrice + 4.00, then\n\n 1. exitLong 1 unit at H of day \u2013 4.00 on a stop\n 2. If current size = 1 unit, then\n\nexitLong at entryPrice stop or MOC\n\n 9. If market position = short\n\nIf current size = 2 units, then\n\n 1. If L of 5 minute bar <= entryPrice \u2013 4.00, then\n\n 1. exitShort 1 unit at L of day + 4.00 on a stop\n 2. If current size = 1 unit, then\n\n 2. exitLong at entryPrice stop or MOC\n\n* * *\n\nHow about a system that lets the Commitment of Traders Report (COT) guide its directional trades\u2014one that only trades in the direction of the commercial interests? If the net commercial position is positive, then only take long positions, and vice versa. This type of trading system uses the COT as a sentiment indicator. Several trading platforms allow you to import the COT data. This system will be included on this books companion website and www.georgepruitt.com.\n\n## Summary\n\nThere are a lot of algorithms out there that are not correlated, so it might be best not to put all of your eggs in one basket. I think the best trend-following mechanism might even be a combination of a Donchian \/ Bollinger hybrid; use one indicator to confirm the other. I went back and redid all the testing on the four major trend-following candidates utilizing a multiple of an average true range (ATR) stop and the conclusions were exactly the same. A fixed-dollar stop is as good as an adaptive volatility stop. I will continue my search for that elusive combination of algorithms or a better trend-following mousetrap and report my findings on www.georgepruitt.com website. Chapter 4 starts the second section of this book, where different trading and testing platforms are discussed. This is where the real programming begins. Have fun!\n\n# Chapter 4 \nIntroduction to AmiBroker's AFL\n\nThis chapter starts the second part of the book that covers different programming languages and trading platforms. This second part discusses AmiBroker, Visual Basic (VBA) for Excel, Python, and TradeStation. The major goal of this particular chapter is to introduce AmiBroker and illustrate some of its very powerful capabilities. However, some very important building blocks of programming languages, reserved words, data types, operators and expressions, and precedence of operators, are quickly reviewed and used throughout the next three chapters. Even if you are not interested in AmiBroker, make sure you read the first part of this chapter to get a grasp on the universal usage of some key building blocks that are included in all programming languages.\n\n## Quick Start\n\nAmiBroker is a complete database management, charting, testing, trading, and optimizing program. So far we have covered many different trading algorithms and every one of them can be easily implemented in the AmiBroker Function Language (AFL). There are several features that make AmiBroker a serious contender as a go-to trading platform:\n\n * _Price_. The cost of the software ranges between $279 and $339 and once you purchase it, it is yours. There are no lease fees. You get free upgrades for one year after purchase and it's up to the purchaser to upgrader thereafter.\n * _Speed_. AmiBroker utilizes multithread processing, which means it can utilize multicore processors and carry out subprocesses or threads simultaneously. In other words, it is very fast.\n * _Power_. Portfolio-level backtesting is paramount when evaluating the robustness of a trading algorithm. If an algorithm works on multiple markets, it demonstrates a high level of robustness. Robustness and positive expectancy is all you can ask from a trading algorithm. AmiBroker provides Exhaustive Search and Genetic forms of parameter optimization.\n * _Data_. AmiBroker is compatible with many End Of Day(EOD) and Real-Time data feeds. It includes a very simple to use ASCII data importer.\n * _Broker Integration_. Several brokers can be linked with the software for automated order execution.\n * _Integrated Development Environment_. AmiBroker has two IDEs to help the user develop complete trading algorithms and technical analysis tools. The main IDE (AFL Editor) is a complete scripting tool and the AFL Code Wizard utilizes a drag-and-drop development paradigm. Both IDEs utilize the AmiBroker Function Language (AFL) as their programming\/scripting language and a vast library of strategies, functions, and indicators.\n * _Support_. Tomasz Janeczko, the founder and chief software architect of AmiBroker, holds PhD and MSc degrees in Computer Science and Telecommunications from Worclaw University of Technology. This developer really loves his software and stands behind it and provides much of the tech support. There is a devout, almost cultlike, following for AmiBroker, and many questions can be easily answered by searching the Internet and\/or joining the user groups.\n\nIf you have purchased my prior books, you know that I use TradeStation. I love its tightly integrated components and EasyLanguage. I will discuss TradeStation in Chapter 7. However, I felt I would be amiss if I didn't show off a little bit of AmiBroker. I was first introduced to the software through Howard Bandy's excellent book, _Quantitative Trading Systems_. I have included all of his books in \"George's List of Must-Own Trading Books\" in the appendix. The software that was described in Bandy's book really piqued my interest, so I contacted Dr. Janeczko for a review copy, and he more than graciously provided his complete software suite. I fell in love with the AFL Wizard and the speed of his backtester. Coming from a bar-by-bar algorithm development paradigm, I was really impressed and initially confused by Dr. Janeczko's array processing. Array processing is extremely fast versus bar-by-bar and in many cases is easier to learn. What is also very cool about AmiBroker is that you can flip from array to bar processing quite easily.\n\n### Things All Programmers Need to Know\n\nBefore I go into detail about array programming, let's go over a short introduction to some key concepts that all programming languages have in common, including AmiBrokers AFL: reserved words, remarks or comments, variables and variable naming conventions, data types, expressions and operators, and precedence of operators. Here is a quick synopsis:\n\n * _Reserved words_. Words that the computer language has set aside for a specific purpose. You can only use these words for their predefined purposes. Using these words for any other purpose may cause severe problems.\n * _Remarks or comments_. Words or statements that are completely ignored by the compiler. Remarks are placed in code to help the programmer, or other people who may reuse the code, understand what the program is designed to do. Double forward slashes \/\/ inform the AFL interpreter that anything that follows is a comment. The double forward slashes can be used anywhere within a line. The forward slash asterisk combination \/* and *\/ is used for multiline commentary. The \/* opens the remarks and *\/ closes the remarks block. Anything inside \/* --- *\/ is ignored by the computer.\n * _Variables_. User-defined words or letters that are used to store information. AFL is not a strongly typed language. You don't have to formally declare a variable name or its type prior to its use.\n * _Data types_. Different types of storage; variables are defined by their data types. AFL has three basic data types: numeric, boolean, and string. A variable that is assigned a numeric value, or stored as a number, would be of the numeric type. A variable that stores a true or false value would be of the boolean type. Finally, a variable that stores a list of characters would be of the string type.\n\n#### _Variables and Data Types_\n\nA programmer must understand how to use variables and their associated data types before they can program anything productive. Let's take a look at a snippet of code.\n\n mySum = 4 + 5 + 6;\n myAvg = mySum\/3;\n\nThe variables in this code are mySum and myAvg and they are of the numeric data type; they are storage places for numbers. AFL is liberal concerning variable names, but there are a few requirements (Table 4.1). A variable name cannot:\n\n * Start with a number or a period (.)\n * Be a number\n * Include punctuation\n\n**Correct** | **Incorrect** \n---|--- \nmyAvg | 1MyAvg \nmySum | .sum \nsum | val+11 \nval1 | the\/\/sum \nthe.sum | my?sum \nmy_val | 1234\n\nVariable naming is up to the style of the individual programmer. AFL is not case sensitive (you can use upper- or lowercase letters in the variable names). ( _Note_ : The following is my preference\u2014may not be everybody's.) Lowercase letters are preferred for names that only contain one syllable. For variable names that have more than one syllable, we begin the name with a lowercase letter, and then capitalize the beginning of each subsequent word in a multi-word identifier.\n\n sum, avg, total, totalSum, myAvg, avgValue, totalUpSum, totDnAvg\n\n#### Operators and Expressions\n\nIn programming, statements are made up of expressions. An expression consists of a combination of identifiers, functions, variables, and values, which result in a specific value. Operators are a form of built-in functions and come in two forms: unary and binary. A binary operator requires two operands, whereas a unary operator requires only one. AFL can handle both. Examples of unary operators are **++** and **\\--**. Some of the more popular binary ones are: + \u2212 \/ * < = > >= <= <> AND OR. These binary operators can be further classified into two more categories: arithmetic and logical.\n\nExpressions come in three forms: arithmetic, logical, and string. The type of operator used determines the type of expression. An arithmetic expression includes + \u2212 \/ *, whereas a logical or boolean expression includes < = > >= <= <> AND OR.\n\n**Arithmetic Expressions** | **Logical Expressions** \n---|--- \nmyValue = myValue + 1 | myCondition1 = sum > total \nmyValue = sum \u2212 total | myCondition1 = sum <> total \nmyResult = sum*total+20 | cond1 = cond1 AND cond2 \nmyCounter++ | cond1 = cond2 OR cond3\n\nArithmetic expressions always result in a number, and logical expressions always result in true or false. True is equivalent to 1, and false is equivalent to 0. String expressions deal with a string of characters. You can assign string values to string variables and compare them.\n\n myName1 = \"George\";\n myName2 = \"Pruitt\";\n cond1 = (myName1 <> myName2);\n myName3 = myName1 + \" \" + myName2;\n\nConcatenation occurs when two or more strings are added together. Basically, you create one new string from the two that are being added together.\n\n#### Precedence of Operators\n\nIt is important to understand the concept of precedence of operators. When more than one operator is in an expression, the operator with the higher precedence is evaluated first, and so on. This order of evaluation can be modified with the use of parentheses. Most programming languages' order of precedence is as follows:\n\n 1. Parentheses\n 2. Multiplication or division\n 3. Addition or subtraction\n 4. <, >, =, <=, >=, <>\n 5. AND\n 6. OR\n\nHere are some expressions and their results:\n\n* * *\n\n 20 - 15\/5 equals 17 not 1\n 20 - 3 division first, then subtraction\n 10 + 8\/2 equals 14 not 9\n 10 + 4 division first then addition\n 5 * 4\/2 equals 10\n 20\/2 division and multiplication are equal\n (20 - 15)\/5 equals 1\n 5\/5 parentheses overrides order\n (10 + 8)\/2 equals 9\n 18\/2 parentheses overrides order\n 6 + 2 > 3 true\n 8 > 3\n 2 > 1 + 10 false\n 2 < 11\n 2 + 2\/2 * 6 equals 8 not 18\n 2 + 1 * 6 division first\n 2 + 6 then multiplication\n 8 then addition\n\n* * *\n\nThese examples have all of the elements of numerical or logical expressions. They are to be evaluated, but they don't do anything. A statement informs the computer to do something. When you tell the computer to use an expression and then do something you have created a complete programming statement. When you assign the result of an expression to a variable, myVar = x + 2, then you have told the computer to do something. When you program, you create lines of statements.\n\n## Price Bar Interface\n\nA price chart consists of bars built from historical price data. Each individual bar is a graphical representation of the range of prices over a certain period of time. A five-minute bar would have the opening, high, low, and closing prices of an instrument over a five-minute time frame. A daily bar would graph the range of prices over a daily interval. Bar charts are most often graphed in an open, high, low, and close format. Sometimes the opening price is left off. A candlestick chart represents the same data, but in a different format. It provides an easier way to see the relationship between the opening and closing prices of a bar chart. Other bar data such as the date and time of the bar's close, volume, and open interest is also available for each bar. Since AFL works hand-in-hand with the charts that are created by AmiBroker, there are many built-in reserved words to interface with the data. These reserved words were derived from commonly used verbiage in the trading industry. You can interface with the data by using the following reserved words. ( _Note_ : Each word has an abbreviation and can be used as a substitute.)\n\n**Reserved Word** | **Abbreviation** | **Description** \n---|---|--- \nOpen | O | Open price of the bar. \nHigh | H | High price of the bar. \nLow | L | Low price of the bar. \nClose | C | Close price of the bar. \nVolume | V | Number of contracts\/shares traded. \nOpenInt | OI | Number of outstanding contracts.\n\nAFL uses functions **DateNum()** , **DateTime()** , **Hour()** , **Minute()** , **Second()** to retrieve the date and time of the price bar.\n\nArray programming or vector languages generalize operations on scalars to apply transparently to vectors, matrices (2d-array), and other higher-dimensional arrays. Sounds complicated, right? It really isn't. An array is simply a list of like data. In most testing platform scripting languages price data is held in arrays. When we code and use the word _high_ we are usually referring to an array or list of _high_ prices of the underlying instrument. When we use a subscript in the array, we are referring to that singular element in the list: High[6] is the _high_ price six bars ago. Most of the programming discussed thus far in this book has dealt with scalar programing in a pseudocode framework. The fundamental idea behind array programming is that operations apply at once to an entire set of data. An example will help clarify. How do we calculate a 20-day moving average of price bar's midpoint in a scalar (bar-by-bar) framework?\n\n* * *\n\n sum = 0\n for i = 1 to 20\n sum = sum + (high[i] + low[i]) \/ 2 #notice the subscript i\n next i\n avgMP = sum \/ 20\n\n* * *\n\nThis programming structure is known as a _for_ loop. The loop variable is the letter _**i**_ and the statement that is indented will be executed 20 times before the next line of code is processed. The _**sum**_ variable accumulates the high price over the past 20 bars. This moving average calculation requires five lines of code. Of course this code segment could be put into a function and in most testing languages or scripts it is. However, be it in a function module or inline, the code is executed on every given bar of data. Here's how it is done in an array-programming framework:\n\n* * *\n\n avgMP = MA((H + L)\/2,20)\n\n* * *\n\nA new array labeled **avgMP** is created and completely loaded with a 20-period moving average of the price bar's midpoint. **avgMP** is not a scalar or single value\u2014it is a full-blown array just like the **High** and **Low** arrays. Array processing eliminates the need for additional looping and this means much quicker execution. You might think a language like EasyLanguage is doing the same thing when it invokes the **average** function:\n\n* * *\n\n avgMP = average((H + L) \/ 2,20);\n\n* * *\n\nHowever, this is not the case. The code inside the **average** function consists of a loop and is called on each and every bar.\n\nIf you have a lot of experience with scalar programming (Java, C++, or EasyLanguage), then picking up AFL might require a little patience, but it will definitely be worth it. As you know, learning a new programming script\/language is best performed by working through examples. If you own AmiBroker, make sure you go to this link and download Howard Bandy's book: . This book will get you up and going very quickly. Bandy helps explain the sophisticated database management that you get with AmiBroker. Data is to a trading algorithm like gas is to an automobile.\n\n## AFL Array Programming\n\nHere is a simple moving average crossover system in AFL:\n\n* * *\n\n PositionSize = MarginDeposit = 1;\n avgLen = Optimize(\"Len\",20,10,100,1);\n avgLen = Param(\"Length\",81,10,100,1);\n Buy = C > MA(C,avgLen);\n Short = C < MA(C,avgLen);\n Sell = Short;\n Cover = Buy;\n\n* * *\n\nFor right now, ignore lines 2 and 3\u2014the ones starting with the word **avgLen**. If you are testing futures data, then don't forget the first line must be in every trading algorithm. This tells AmiBroker's backtester to only trade one contract and sets the margin deposit to one as well. The variable avgLen is the length of the moving average indicator the algorithm will utilize. Let's set it to 100.\n\n* * *\n\n Buy = C > MA(C,avgLen);\n\n* * *\n\nThis line of code tells AmiBroker to set the BUY array to true or 1 if the close is greater than the 100-day moving average of closes. If the test fails and the close is not greater than the moving average, then it is set to false or 0. Since we are array processing, this done all at one time. The BUY array is filled completely up with either 1s or 0s. The SHORT array does just the opposite\u2014true if the close is less than the 100-day moving average and false if it's not. This system simply flips back and forth between long and short positions\u2014it's always in the market. If you use **Buy** and **Short** arrays to initiate positions, then you must have values for the **Sell** and **Cover** arrays. If you only use **Buy** , then you only need a value for **Sell**. This applies to **Short** and **Cover** as well. If you are using a pure stop and reverse algorithm, you can set up your **Sell** and **Cover** arrays like this:\n\n* * *\n\n Sell = Short;\n Cover = Buy;\n\n* * *\n\nThese two lines tell the computer to cover long positions at the same price a short position is established and to cover short positions at the same price a long position is put on. Or you can do it like this:\n\n* * *\n\n Sell = 0;\n Cover = 0;\n\n* * *\n\nIf you don't take into consideration the arrays that get you out of a position, AmiBroker will give you a warning message, and will not execute the backtest. AmiBroker requires the **BUY** order and its corresponding **SELL** order to be defined prior to processing. The same goes for **SHORT** and **COVER**. In some platforms, you do not need to define **SELL** and **COVER** if the algorithm is always in the market long or short.\n\nThis little bit of code seems quite simple on the surface, but there is a lot going on behind the scenes. AFL has a plethora of built-in functions such as the **MA** function used in this simple program. So calculating the 100-day moving average is very simple; just call the function. The four arrays ( **BUY, SHORT, SELL, COVER** ) that instruct AmiBroker to establish and liquidate trades are instantly populated with 1s and 0s; it's a one-pass process. This process is extremely fast and efficient. Once this single pass is completed, the back tester is fed the necessary information to simulate the backtesting of the algorithm. As you can see, entry and exit prices are not defined, so they are defaulted to the close of the bar. This default can be changed using the settings dialog box.\n\nLet's give this simple algorithm a run. The next instructions assume you have worked with AmiBroker and know how to plot charts, apply indicators, and work with price databases.\n\nGo ahead and launch AmiBroker and load your database of choice. I imported an ASCII database of futures prices that I got from CSI data. The software is compatible with CSI and there are instructions in the online manual on how to create a database, and have it updated automatically. This may require an additional monthly data fee. Figure 4.1 shows how to get to the AFL editor from the main AmiBroker File menu.\n\n**Figure 4.1** Launching AmiBroker's AFL editor.\n\nOnce the editor launches you will see a window like the one in Figure 4.2.\n\n**Figure 4.2** The AmiBroker Editor window.\n\nThis is your tabula rasa\u2014blank slate. Anything you can dream up can be accomplished by typing in the right code. Go ahead and type in the code from the moving average example. The AFL Editor is one of the most powerful editors you will find in any trading or programming platform. It features outlining, collapsible, or text folding, function tips, and auto-completion. There's just a little bit of typing, so go ahead and just do it and I will highlight some of these key features along the way. Here it is again, so you won't have to flip back to the prior page.\n\n* * *\n\n PositionSize = MarginDeposit = 1;\n avgLen = Optimize(\"Len\",20,10,100,1);\n avgLen = Param(\"Length\",81,10,100,1);\n Buy = C > MA(C,avgLen);\n Short = C < MA(C,avgLen);\n Sell = Short;\n Cover = Buy;\n\n* * *\n\nAs you type the first line of code you will notice the words **PositionSize** and **MarginDeposit** turn bold. If you didn't capitalize the P or the S in the word **PositionSize** , the editor will automatically do so after you type the last letter in the word and hit the space bar. The editor is letting you know these are keywords or tokens. And that you can't use these for variable names. If you are looking for a keyword or a function name, and you type what you think it is and it doesn't turn bold or change colors, then you know you have not used the correct word. The editor can help you find the proper keyword or function name through its auto-completion feature. Later we will develop an algorithm based on Bollinger Bands, but for illustration purposes let's assume you want to calculate an upper Bollinger Band now, but don't know the exact words for the function. You probably think the function name starts with the letter \"b,\" so for now type the letter \"b\" after the first line and press the and . A list of keywords and functions starting with the letter \"b\" will appear in your editor window (see Figure 4.3).\n\n**Figure 4.3** The AFL Editor's auto-completion tool.\n\nIf you look down the list, you will see the name **BBandTop**. If you select and double-click on the name, the function call will be automatically inserted into your code. The more of the function name you type, the smaller the list of options will appear after pressing and . If you type **BBand** and hit the keyboard sequence, only two options will appear: **BBandBot** and **BBandTop**. If you still can't find the name of the keyword or function, then you will have to use the trial-and-error method and keep typing different words or take the time and look up the keyword in the AFL Language Reference under the Help menu. Delete whatever you typed as the second line and let's continue with the first algorithm. As you type the second line of code and type the keyword **Optimize** it will turn blue and right after you type the left parentheses a small box will open up right under your cursor (Figure 4.4).\n\n**Figure 4.4** AFL Editor function helper.\n\nThe box is helping you by providing a template of what the function **Optimize** is expecting (this is called the informal parameter list). If a word turns blue, the editor is letting you know the keyword is a built-in function. This line of code links the source code with the AmiBroker optimizer. This is how I was able to do all those cool optimizations in Chapter 3. The function Optimize wants you to provide a name inside quotes, a **default value** for the variable avgLen, a **min value** , a **max value** , and a **step value**. When you optimize the variable avgLen it will start out at the **min value** and increase each iteration by the **step value** until it reaches the **max value**. If you don't run the optimizer, the variable will assume the **default value**. The AFL editor has all these helpers or tips for all of the built-in functions. You will notice another helper window pop up as you type the keyword **Param**. The **Param** function acts similarly to the **Optimize** function. Instead of providing an interface to the optimizer, the **Param** function provides an interface to the user. Instead of having to retype different values for avgLen every time you want to test a different value, you can simply change it at the **Analysis** phase. I will show how easy this is a little later. Go ahead and finish typing in the rest of the code and go under the File menu and save it to your Desktop or a folder on the C drive as MyFirstAlgo. Now you need to check the syntax to make sure you have typed everything properly. Click on the AFL Check icon (see Figure 4.5).\n\n**Figure 4.5** The AFL Check icon.\n\nIf you type everything in correctly, then nothing will happen. If you mistyped a word, you might get something like Figure 4.6. If this happens, just make sure you have everything typed properly and then hit the icon again. After the syntax has been properly checked (compiled), click on the **Send To Analysis** window icon (see Figure 4.7).\n\n**Figure 4.6** An error warning.\n\n**Figure 4.7** The \"Send to Analysis\" window icon.\n\nThis will create an Analysis tab in the AmiBroker program. I have continuous crude oil data plotted in the first chart. If you don't have crude oil data, don't worry, just create a chart of something. I inform AmiBroker to apply MyFirstAlgo to the current data by using the dropdown menu in the top-left corner (Figure 4.8). Before we click on the BackTest icon, go ahead and click on the Parameters icon. It's the icon that looks like an old equalizer (Figure 4.9).\n\n**Figure 4.8** Apply the algorithm to the current data.\n\n**Figure 4.9** Set the parameters for the backtest.\n\nThis is where you can change the values of the avgLen parameter. Change it to 50 and click OK. I get the sense that AmiBroker was originally designed to trade equities only, so you have to set up the backtester to work with futures data by going into the **Settings** button in an Analysis sheet. Only do this if you are truly testing futures data. If you aren't, then just skip this paragraph. The Settings button has a small picture of wrench and screwdriver and is located directly to the left of the **Parameters** button. A dialog box like the one in Figure 4.10 should open. Click on the box beside the **Futures mode** option. It instructs AmiBroker's back-tester to use the margin deposit and point value that was set up when the database was created for its calculations.\n\n**Figure 4.10** Set Futures mode.\n\nNow click the **Backtest** button (five buttons to the left of the **Parameter** icon). This will apply the algorithm to the data and create a trade-by-trade report in the analysis window. If you have a database loaded as I do and you select the **Portfolio Backtest** , then the algorithm will be applied to all of the markets in the database. Don't be surprised if this only takes a few seconds. AmiBroker is really applying the algorithm to every single bar of data in the portfolio. Figure 4.11 and Figure 4.12 provide a snapshot of the trade-by-trade report on the crude oil and the portfolio results on the entire database.\n\n**Figure 4.11** The trade-by-trade report.\n\n**Figure 4.12** The portfolio results.\n\nThe results don't look that great, so let's test a double moving average crossover system. Work your way back over to the AFL Editor\u2014it should still be open. Go under the File menu and create a new formula by clicking on New. Once a blank Editor window opens, type in the following exactly:\n\n* * *\n\n Filter = 1;\n PositionSize = MarginDeposit = 1;\n avgLen1 = Optimize(\"Len1\",9,9,49,1);\n avgLen2 = Optimize(\"Len2\",19,19,99,1);\n shortMav = MA(C,avgLen1);\n longMav = MA(C,avgLen2);\n Buy = Cross(shortMav,longMav);\n Short = Cross(longMav,shortMav);\n Sell = Short;\n Cover = Buy;\n\n* * *\n\nTo save some typing, I copied the code from MyFirstAlgo and made the necessary changes. This is the code for a double moving average system where you buy when the short (fast) moving average crosses above long (slow) moving average and you short when the fast moving average crosses below the slow moving average. The beauty of AmiBroker's AFL is it reads almost like English. After you check the AFL and send it to an **Analysis** window, go back to AmiBroker. Instead of clicking on the **Backtest** button, click the **Optimize** button. AmiBroker will now optimize the fast length from 9 to 49 and the slow length from 19 to 99 and report the results from each iteration. This might take a few seconds. When the optimization has completed, click on the down arrow beside the **Optimize** button and select **3D Optimization chart**. A chart like the one in Figure 4.13 will appear on your screen.\n\n**Figure 4.13** A 3D optimization chart.\n\nSource: AmiBroker\n\nThis is the result of the optimization where the _x_ -axis and _y_ -axis are the varying lengths of the moving averages and the _z_ -axis is the net profit. You can also see the water level; this represents where the profit is equal to zero. Hopefully, most of your mountains are above this level. This 3D chart only works on a two-parameter optimization.\n\nYou may want to play around with some of the other icons and familiarize yourself with their functions. AmiBroker is very sophisticated, and it took me several hours to become somewhat comfortable with the charting, reports, and applying trading and indicator algorithms. Again, I refer you to the excellent online manual, the AmiBroker forums, and of course, Bandy's book.\n\n## Syntax\n\nThe AmiBroker Function Language is very powerful, and, once you grasp the array-processing paradigm, quite easy to use. In some programming languages you have to declare variables and sometimes their types before you can use them. This is not so for the AFL. However, when you create a variable know that it is an array or list and not just a single memory location. Because of this, you can't do this:\n\n* * *\n\n myValue = (H + L)\/2;\n if (C > myValue){\n Buy = 1;\n }\n\n* * *\n\nIf you type this and check the syntax, you will receive the following message:\n\n Condition in IF, WHILE, FOR statements has to be Numeric or Boolean type.\n\nBasically, you are asking AmiBroker to compare the **close** array with **myValue** array. You were probably thinking you were comparing the current close price to the current value in **myValue** , but you weren't. Forget about using **if's** in your code. This is a very difficult thing to do if you are used to working in a bar-by-bar paradigm. Instead, use something like this:\n\n* * *\n\n myValue = (H + L)\/2;\n Buy = C > myValue;\n\n* * *\n\nTomasz Janeczko has provided this type of array processing functionality in his software. This accomplishes the same thing as the previous **if** statement. How do you think you compare today's close with the prior day's close? You can't use an **if** statement, so could you do it like this?\n\n* * *\n\n cond1 = C > C[1];\n cond2 = C < C[1];\n Buy= cond1;\n Short = cond2;\n\n* * *\n\nIf you type this in and check the syntax, it will pass. You will also be able to send it to an **Analysis** window, and backtest it. However, it will not work. The computer doesn't come out and say, \"I'm sorry, Dave, I'm afraid I can't do that.\" It just won't generate the correct trades. These statements are syntactically correct, but they are logically incorrect. You are comparing the first element of the close array with the close array. In other words, you are comparing an element in the list with the list. This is how you do it in AFL:\n\n* * *\n\n cond1 = C > Ref(C,-1);\n cond2 = C < Ref(C,-1);\n Buy= cond1;\n Short = cond2;\n\n* * *\n\nThe **Ref(C,-1)** function returns the prior close price in the close array. The function processes the array and allows you to compare today's closing price with yesterday's closing price. You can use any negative number to reference previous values of any array. You can do this as well:\n\n* * *\n\n myValue = (H + L)\/2;\n cond1 = myValue > Ref(myValue,-1);\n\n* * *\n\nAnd you have probably noticed that all lines end with a semicolon (;). This tells the parser that the line of code has terminated and to go onto the next line. What do you think the next bit of code does?\n\n* * *\n\n sl = Param(\"ShortLen\",9,9,100);\n il = Param(\"InterLen\",19,19,200);\n mmStop = Param(\"StopDollars\",3000,3000,6000);\n Buy = MA(C,sl) > MA(C,il) ;\n Short = MA(C,sl)< MA(C,il);\n Sell = short;\n Cover = buy;\n ApplyStop(stopTypeLoss,stopModePoint,mmStop\/PointValue,0);\n\n* * *\n\nThe variables **sl** and **il** are defaulted to 9 and 19, respectively. The **Param** function allows the user to change the variables to values between 9 and 100 and 19 and 200, respectively. The variable **mmStop** defaults to 3000 but can be changed to values ranging from 3000 to 6000. The array **Buy** is filled with 1s when the moving average of **sl** (shortLength) is greater than the moving average of **il** (intermediateLength). The **Short** array is filled when the opposite happens. This is a very simple double moving average crossover system. The **ApplyStop** function tells AmiBroker to stop out on the close any time the current position reaches a loss of $3,000. The close is checked in this particular case. The **ApplyStop** function has many different ways of exiting a position: stop loss, trailing stop, or a profit objective. Here are three examples:\n\n* * *\n\n ApplyStop( **stopTypeLoss** , **stopModePercent** ,2, **True** );\n \/* single-line implementation of Chandelier exit *\/\n ApplyStop( **stopTypeTrailing** , **stopModePoint** , 3*ATR(14), **True** , **True** );\n \/* N-bar stop *\/ ApplyStop( **stopTypeNBar** , **stopModeBars** , 5 );\n\n* * *\n\nThis is a very powerful function and can fulfill almost every possible criterion to exit an existing position with a stop.\n\nReferring back to **MySecondAlgo** , you might have noticed these two lines of code:\n\n* * *\n\n Buy = Cross(shortMav,longMav);\n Short = Cross(longMav,shortMav);\n\n* * *\n\nThe keyword **Cross** is actually a function call. The function gives a \"1\" or true on the day that the **shortMav** crosses above the **longMav**. Otherwise, the result is false or zero. To find out when shortMav crosses below longMav, simply reverse the order of the arrays. I admit this took me a few minutes to understand, but like the rest the AFL functions, it makes perfect sense. The opposite of the short-term moving average crossing above the long-term average is the long-term average crossing above the short-term average.\n\nCoding like this might not be your cup of tea\u2014having to remember the function calls and how the **Cross** function works and all the business about arrays. If you want to test with AmiBroker, but don't want to work with the full-blown AFL editor, you can still do this. The next part of this chapter introduces the AmiBroker AFL wizard.\n\n## AFL Wizard\n\nImagine creating trading algorithms with point-and-click ease and minimal typing. Enter the AmiBroker AFL Wizard. Instead of typing MySecondAlgo into the AFL Editor, let's create it in the AFL Wizard. Get back to AmiBroker and click on the **AFL Wizard** button (Figure 4.14). Once you click on the button a window like the one in Figure 4.15 will pop up.\n\n**Figure 4.14** The AFL Code Wizard button.\n\n**Figure 4.15** A new AFL Code Wizard window.\n\nThis is the **AFL Code Wizard** , and it's a really cool way to create a trading algorithm without having to create it from scratch. The interface is really quite simple, so let's start by first adding a long entry rule. Click on the words **Enter Long when...** and then click on the pencil icon labeled **Add Item** (Figure 4.16). This will put the following code in the **Edit Rule** section and also below **the Enter Long When...**.\n\n**Figure 4.16** Add item in AFL Code Wizard.\n\n* * *\n\n **Value of** Close (now) is greater than 10\n\n* * *\n\nNow this is where things get really cool. You can click on the individual words in the code and change them. Remember **MySecondAlgo** was a dual moving average crossover. Click on the words **Value of**. A list of different functions will appear in the pane below the **Edit Rule** pane. Figure 4.17 shows where the list is located.\n\n**Figure 4.17** The AFL Code Wizard \"Edit Rule\" dropdown list.\n\nClick in the pane and select **MA - Simple Moving Average**. The words **15-bar moving average of** will take place of **Value of**.\n\n* * *\n\n **15-bar moving average of** Close (now) is greater than 10\n\n* * *\n\nNow click on the number **10** and go back down to the same pane we selected the first MA and select MA again. The code will change to:\n\n* * *\n\n 15-bar moving average of Close (now) is greater than **15-bar moving average of** Close now\n\n* * *\n\nWell, this won't do. The 15-bar moving average of Close will never be greater than the 15-bar moving average of Close. Click on the number 15 in the second moving average phrase and slide down to the pane right beside the pane with the list of functions (see Figure 4.18). Change the period from 15 to 30. The code in the Edit Rule should now read:\n\n**Figure 4.18** Changing the parameters in the \"Edit Rule\" pane.\n\n* * *\n\n 15 -bar moving average of Close (now) is greater than **30 -bar moving average of** Close now\n\n* * *\n\nSo the rules for entering a long position are now defined. Buy when the 15-bar moving average (fast) is greater than 30-bar moving average (slow). As you point and click the AFL code equivalent is created simultaneously. The AFL code equivalent thus far is:\n\n* * *\n\n MA( Close , 15 ) **>** MA( Close , 30 )\n\n* * *\n\nIf you want to see what is going to be ported in the **AFL Editor** , click on the tab labeled **Auto-generated Formula**. The tab is to the right of the **Design View** that we are currently located within. When you click on it you will see the following code.\n\n* * *\n\n Buy = MA( Close , 15 ) > MA( Close , 30 );\n Sell = 0;\n Short = 0;\n Cover = 0;\n\n* * *\n\nThis should look familiar. The **AFL Wizard** has auto-generated the rules for the four trading arrays: **Buy** , **Sell** , **Short** , and **Cover**. The Buy array is turned on when the **MA( Close , 15)** is greater than **MA( Close , 30)**. Click back on the **Design View** tab and let's point-and-click our way to a short entry rule. Click on **Enter Short when...** and then the **Add Item (Pencil** ) icon. You will once again see the following code:\n\n* * *\n\n **Value of** Close (now) is greater than 10\n\n* * *\n\nFollowing the same steps we did for the long entry rules:\n\n * Click **Value of** and slide down to the function pane and select **MA**.\n * This time click on **is greater than** and slide down to the function pane. You will notice that the list of functions has now changed to just three options: \n 1. **Is greater than**\n 2. **Is less than**\n 3. **Is equal to**\n * Select **is less than**.\n * Click on the number **10** and slide down again to the function pane and select **MA\u2014Simple Moving Average**.\n * Click on **15-bar moving average of** and change the period to **30**.\n\nIf you click on the **Auto-generated Formula** tab, you should now see the following code:\n\n* * *\n\n Buy = MA( Close , 15 ) > MA( Close , 30 );\n Sell = 0;\n Short = MA( Close , 15 ) < MA( Close , 30 );\n Cover = 0;\n\n* * *\n\nNow if you are testing a stock, you can send this directly to AmiBroker and have it **Backtest** or **Scan**. Before we test it, go ahead and save it somewhere as **MySecondAlgoWizard**. Assuming a stock database is loaded in AmiBroker, click on the **Exclamation** mark to send it to AmiBroker (see Figure 4.19).\n\n**Figure 4.19** Click the exclamation point to send your request to AmiBroker.\n\nIf you switch back to AmiBroker, you will be presented the **Automatic Analysis** dialog with your newly designed formula loaded. This dialog looks like the one in Figure 4.20.\n\n**Figure 4.20** Automatic Analysis dialog box.\n\nFrom here, you can click on **Back Test, Scan, Optimize, Explore** , etc. If you are testing a futures market, it is better to click on the icon that is right beside the **Exclamation** mark. This will build the formula and export it with a \".afl\"extension. You can then open it with **AFL Editor** and add the necessary code for testing a futures contract:\n\n* * *\n\n PositionSize = MarginDeposit = 1;\n\n* * *\n\nFor practice, go ahead and click on the **Build and Export a formula** icon and save it somewhere on your desktop or in a folder in your C: drive. You then can go to the **AFL Editor** and open it and add the line of code above. I did just that and my **AFL Wizard** designed code looks like this:\n\n* * *\n\n PositionSize = MarginDeposit = 1;\n Buy = MA( Close , 15 ) > MA( Close , 30 );\n Sell = 0;\n Short = MA( Close , 15 ) < MA( Close , 30 );\n Cover = 0;\n\n* * *\n\nThis should look very similar to the code we originally typed in for **MySecondAlgo**. The AFL Wizard can get you up and running very quickly and can also be used as a learning tool. It automatically builds the AFL code so you can start your design with the **Wizard** and have it generate the framework and then move onto the **AFL Editor** and complete your coding of your algorithm there.\n\n## AmiBroker Loop Programming\n\nAs powerful as AmiBroker's array programming is, there are times when you want to program on a bar-by-bar basis. Dr. Janeczko has built this capability into his software as well. With this feature you can program with your precious **If** constructs. Here is a familiar algorithm utilizing loops:\n\n* * *\n\n PositionSize = MarginDeposit = 1;\n mav = MA(C,20);\n for( i = 0; i < BarCount; i++ ){\n if (C[i] >= mav[i]) {\n Buy[i] = 1;\n }\n if (C[i] <= mav[i]) {\n Sell[i] = 1;\n }\n }\n\n* * *\n\nThis is the simple price crossing moving average reversal algorithm. The **mav** array is set to a 20-day simple moving average of closes. This line of code is still utilizing array programming. A **for loop** is then set up so that individual elements of the different arrays can be examined. The **for loop** construct in AFL is very similar to one in the C language. The loop variables are controlled by what is inside the parentheses.\n\n 1. ( i = 0; i < BarCount; i++ )\n\nHere the loop will start at zero and stop at **BarCount** and the loop variable **i** will increment by one each time **i++**. The **i++** is the same as **i = i + 1** ; since we are not processing arrays, we can now use **if** constructs. Notice how the comparison of the **C[i]** element and the **mav[i]** element is enclosed in parentheses. If the close is greater than the 20-bar moving average, then the following code is executed: Buy[i] = 1; This sets the **ith** element in the **Buy** array to one. Also, notice how the curly brackets **{ }** are used in the code. The curly brackets inform the computer and the programmer that certain lines are controlled by a loop or if construct. All the code involved with the **for loop** is surrounded by curly brackets. The code controlled by the **if** statement is surrounded by nested curly brackets. By matching an opening left curly bracket with a closing curly right bracket, the programmer can easily see what code goes with the **for loop** or the **if** statement. The left curly bracket right after the loop definition opens up the block of code consisting of six lines. The last-right curly bracket closes the loop and the block of code.\n\nIn addition to having to use the curly brackets to tell the computer which lines of code go inside the **loop** or the **if** construct, it's good practice to also indent the lines of code enclosed within brackets. This is not a necessity, but it makes the readability of the code so much easier. Now that we are using loops and ifs, we can highlight the collapsible or folding text feature of the editor. Look at the code in Figure 4.21.\n\n**Figure 4.21** Sample loop programming code.\n\nNotice where the arrows for the opening curly brackets are pointing. Now look at the small boxes with a dash inside that correspond to the curly brackets. If you click on the first box, the code controlled by the corresponding line of code will collapse or hide. Go ahead and do it\u2014see for yourself. If you click on the very first box, all the code disappears except the **for loop** definition. The second box collapses the code that goes with the first **if**. This is a neat feature if you want to streamline the look of your code, or if you want to hide it and send a screenshot to someone else. The combination of array and loop programming capabilities in AmiBroker should facilitate any programming needs you come across.\n\n## Summary\n\nAll programming languages are built on expressions and operators and the precedence of those operators. A solid understanding of these concepts is absolutely necessary before a single line of code is typed. We have just skimmed the surface of the capabilities of AmiBroker. It is a very powerful and easy-to-use tool. I learned AFL while writing this book, and used it for most of the testing in Chapters 2 and . Once you get your futures data into a database and create different portfolios, testing across the entire portfolio is as simple as clicking on a single button. The optimization capabilities of AmiBroker are simply mindblowing. You can use a genetic optimizer to optimize not only a single market but an entire portfolio\u2014just like I did in Chapter 3. The best way to learn AFL is through examples. Also the online community is absolutely terrific! I found answers to all my questions online and I didn't have to search very far.\n\nHere are some of the codes for the various systems I tested in Chapters 2 and :\n\n### Code Samples\n\n* * *\n\n \/\/ Chapter 2 Double Moving Average Cross Over\n \/\/ with Dollar Stop\n Filter = 1;\n PositionSize = MarginDeposit = 1;\n sl = Param(\"ShortLen\",9,9,100);\n il = Param(\"InterLen\",19,19,200);\n mmStop = Param(\"StopDollars\",3000,3000,6000);\n OptimizerSetEngine(\"cmae\");\n Buy = MA(C,sl) > MA(C,il) ;\n Short = MA(C,sl)< MA(C,il);\n Sell = short;\n Cover = buy;\n ApplyStop(stopTypeLoss,stopModePoint,mmStop\/PointValue,1);\n \/\/ Chapter 2 Bollinger Band Algorithm\n PositionSize = MarginDeposit = 1;\n len = Optimize(\"Len\",60,10,80,2);\n width = Optimize(\"Width\",2,0.25,3,.25);\n Buy = Cross(C,BBandTop(C,len,width));\n Short = Cross(BBandBot(C,len,width),C);\n Sell = Cross(MA(C,len),C);\n Cover = Cross(C,MA(C,len));\n \/\/Chapter 2 Bollinger Band using\n \/\/RISK filtering\n PositionSize = MarginDeposit = 1;\n riskAmt = (BBandTop(C,60,2) - MA(C,60)) * pointValue;\n COND1 = riskAmt <= 2000;\n Buy = Cross(C,BBandTop(C,60,2)) AND COND1;\n Short = Cross(BBandBot(C,60,2),C) AND COND1;\n Sell = Cross(MA(C,60),C);\n Cover = Cross(C,MA(C,60));\n \/\/Chapter 2 MACD utilizing AMIBROKERS\n \/\/Exploration Feature\n \/\/Refer to the AMIBROKER Appendix for\n \/\/further explanation\n Filter = 1;\n PositionSize = MarginDeposit = 1;\n myMACD = MACD(fast=12,slow =26);\n myMACDAvg = MA(myMACD,9);\n myMACDDiff = myMACD - MYMACDAvg;\n leftBar2 = Ref(myMACDDiff,-4);\n leftBar1 = Ref(myMACDDiff,-3);\n centerBar = Ref(myMACDDiff,-2);\n rightBar1 = Ref(myMACDDiff,-1);\n rightBar2 = Ref(myMACDDiff,0);\n COND3 = C > MA(C,100);\n COND1 = centerBar < 0 AND centerBar < Min(leftBar2, leftBar1) AND centerBar < Min(rightBar1,rightBar2);\n COND2 = centerBar > 0 AND centerBar > Max(leftBar2, leftBar1) AND centerBar > Max(rightBar1,rightBar2);\n Buy = COND1 AND COND3;\n Short = COND2 AND NOT(COND3);\n BuyPrice = C;\n ShortPrice = C;\n longEntryPrice=ValueWhen(Buy,BuyPrice,1);\n shortEntryPrice = ValueWhen(Short,ShortPrice,1);\n Sell = Cross(C, longEntryPrice - 3 * ATR(10));\n Cover = Cross(ShortEntryPrice + 3 *ATR(10),C); ;\n AddColumn(longEntryPrice,\"BuyPrice\");\n AddColumn(longEntryPrice - 3 * ATR(10),\"longStop\");\n AddColumn(Sell,\"Sell ?\");\n\n* * *\n\nThis last algorithm introduces the **AddColumn** and **ValueWhen** functionality. The **AddColumn** is useful for many purposes, but is probably used more as a debugging tool. Basically, this prints information out to the spreadsheet in **Exploration** mode. The **ValueWhen** function, in this example, returns the element of the **BuyPrice** array when the first value of 1 occurs in the **BUY** array. In other words, it is the long entry price. This code is somewhat sophisticated, as it introduces methods of debugging and gathering the last entry price. This code is fully explained along with utilizing AmiBroker's Exploration feature in the AmiBroker appendix.\n\n# Chapter 5 \nUsing Microsoft Excel to Backtest Your Algorithm\n\nThe majority of the testing that has been performed thus far in the book was carried out using either AmiBroker or TradeStation. These are complete trading solutions and should be able to fulfill all the needs of a trader. However, some traders would like to use software that they already have on their computer. Microsoft Excel has been a major player in the trading algorithm arena since the beginning. Spreadsheets combine data with formulas, and as we have seen these are the major ingredients to trading algorithms. Several years ago, I developed a very simple spreadsheet to help a client generate his trading signals for the next day. The system incorporated several indicators across several different markets. The Excel workbook turned out to be quite large and required the user to type in the daily data after the close each day. Excel spreadsheets are very powerful but when it comes to calculating indicators and trade signals they can become very cumbersome.\n\nThis is where VBA (Visual Basic for Applications) comes in very handy. VBA combines the power of the BASIC programming language with the power of spreadsheets. I have created a simple single-market algorithm-testing platform for those who wanted to use Excel and VBA. I call it the Excel System Backtester, ESB for short. Here is a version of the Bollinger Band algorithm that has been evaluated in the previous chapters programmed in our ESB platform.\n\n* * *\n\n '****************************************************************\n '**** This is a good place to put all of your function calls ****\n '**** and system calculations. ****\n '****************************************************************\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n simpleAvg = Average(myClose, 10, i, 1)\n rsiVal = RSI(myClose, 14, i, 1)\n Call Stochastic(3, 4, 7, stoK, stoD, slowD, i, 1)\n '****************************************************************\n '**** Put All Of Your Orders Here ****\n '****************************************************************\n prevMarketPosition = marketPosition\n If marketPosition <> 1 Then\n Call Trade(Buy, \"BB-Buy\", upBand, stp, i)\n End If\n If marketPosition <> -1 Then\n Call Trade(Sell, \"BB-Sell\", dnBand, stp, i)\n End If\n If marketPosition = -1 Then\n Call Trade(ExitShort, \"ExitShortStop\", entryPrice + 2000 \/ myTickValue, stp, i)\n If barsShort > 10 And myClose(i) > entryPrice Then\n Call Trade(ExitShort, \"10dayShOut\", myClose(i), moc, i)\n End If\n End If\n If marketPosition = 1 Then\n Call Trade(ExitLong, \"ExitLongStop\", entryPrice - 2000 \/ myTickValue, stp, i)\n If barsLong > 10 And myClose(i) < entryPrice Then\n Call Trade(ExitLong, \"10dayLgOut\", myClose(i), moc, i)\n End If\n End If\n '****************************************************************\n '**** End of Main Traiding Loop ****\n '**** No orders allowed below this point ****\n '****************************************************************\n\n* * *\n\nThis system buys\/sells short on the penetration of 60-day two-standard-deviations Bollinger Bands, then risks $2,000 per trade and exits if the trade is not profitable after 10 days. The code is Visual Basic, so it follows that syntax. In developing this testing software my overall objective was simplicity\u2014I wanted a very easy sloping learning curve. You don't need to know VBA to invoke the indicator or trading functions. You will just need to follow the included templates.\n\nIf you are interested in learning some VBA and want to see under the hood, a discussion of the source code is included in the ESB appendix. First off, let's learn how to use the software and its indicator and trading functions. The VBA tester is based on one large loop. The software loops through each and every bar of data and allows the user to create indicators and analyze patterns and make trading decisions on each and every bar. Conceptually, it works like AmiBroker and TradeStation, but doesn't have all the bells and whistles. It can only test one market at a time, and has limited performance metrics. However, it is sufficient to get your feet wet, and since the source code is open, you can take it and do as you want.\n\n## VBA Functions and Subroutines\n\nThe heart of this algorithm is a 60-day Bollinger Band, and just like AmiBroker, you get access to this indicator by calling a function:\n\n* * *\n\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n\n* * *\n\nSome indicators return a single value and some return several. This function call is actually a subroutine that returns three parts of the Bollinger Band indicator: the moving average, the top band, and the lower band. The subroutine needs five inputs or arguments to calculate the bands: price (myClose), length (60), number of deviations (2), the current bar we are on (i), and the offset (1). Don't worry about the difference between a subroutine and function because in this application they do the same thing, return indicator values. The only difference is in the way you call the indicator and how the indicator values are assigned. Notice the difference between a pure function call and our BollingerBand subroutine call:\n\n* * *\n\n myHH = Highest(myHigh, 20, i, 1)\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n\n* * *\n\nThe function **Highest** returns a single value and that value is assigned to the variable myHH. The subroutine **BollingerBand** is invoked by preceding the name of the subroutine with the keyword **Call**. The values that are used for trading decisions are included in the list of arguments that are passed into and out of the subroutine. The information that is passed to a function is only used by the function internally and is not passed back. The variable in our function call, **myHH** , holds the output off the function. In this case, it will be the highest high of the past 20 days starting from yesterday. A neat feature of VBA is that once you define functions or subroutines, the editor will help you fill out the argument list just like AmiBroker. (see figure 5.1.)\n\n**Figure 5.1** Once you define the Bollinger Band routine, you can easily incorporate it into trading.\n\nIf you are trying to invoke a function or subroutine and this helper box doesn't appear, then you probably do not have the function\/subroutine spelled correctly or it doesn't exist. All functions and subroutines in the ExcelSystemTester will be listed and explained in the appendix. All functions and subroutines require two bits of information: (1) the current bar and (2) how many days back to start the calculations. In the case of the **Highest** function, the current bar is **i** and the offset is **1**. An offset of two starts the calculations the day before yesterday. Remember, we are working in one big loop and each bar is examined by incrementing the variable _i_.\n\n## Data\n\nAccessing the date, price, volume, or open interest data is accomplished by using seven different arrays: **myDate** , **myOpen** , **myHigh** , **myLow** , **myClose** , **myVol** , and **myOpInt**. Two more arrays provide access to daily range and true range: **myRange** and **myTrueRange**. Unlike AmiBroker's array processing, you must index these arrays to get the data for a particular bar. **myOpen(10)** is the tenth bar's open from the very beginning of the data. **myDate(10)** is the date of the bar with **myOpen(10)** opening price. The arrays are synchronized. All data arrays are preceded with **my\u2014** so don't forget this. Let's say you want to see if yesterday was a high pivot of strength one. This is how you would test for this occurrence:\n\n* * *\n\n If myHigh(i-1) > myHigh(i) and myHigh(i-1) > myHigh(i-2) then\n myHighPivot = 1\n End if\n\n* * *\n\nRemember, **i** is the current bar in the loop. So by subtracting 1 you get yesterday's bar and subtracting 2 gets the day before yesterday's bar. If you add 1, then you will have tomorrow's data today and you can make a killer trading system. With this information, you will finally have the Holy Grail in your grasp. On the other hand, save yourself a lot of time and heartache by not adding\u2014just subtracting. I can't tell you how many times a client has come to me with a 90% winning trading idea and I burst their bubble once they discover they are taking advantage of _future leak_. Here is the best example of future leak: Buy tomorrow's open if the high is greater than the open. This obviously is a mistake, but other forms of future leak are more esoteric. If high of tomorrow is greater than the buy stop, then buy price = buy stop. This one makes sense, where is the future leak; the price moved above the buy stop so the stop was filled at the specified price. If you test using this exact logic in the ESB, then you will hyperinflate your algorithm's performance. The error is hard to see, but it's there. What if the high is equal to your buy stop? Using this logic, the trade will not be executed and you will skip a trade that buys the absolute high price of the day. Skipping these trades will, without a doubt, increase your bottom line. Most system-testing platforms go out of their way to prevent future leak. TradeStation's EasyLanguage only lets you peek at the next bar's open. You can use it as a price to execute a trade or as a base price in a calculation of stop or limit orders. You can say buy next bar at open of next bar + 1\/2 ATR(10) on a stop or buy next bar at open \u2013 1\/2 ATR(10) on a limit. This makes future leak impossible and that should be a good thing. In most cases, this is true. However, this safety feature can make things a lot more difficult, too. Let's say you are placing multiple orders for the next bar, and one of them is filled, and you need to know exactly which order was executed. Some platforms simply execute the trade and don't let you know which order generated the trade. You might have different trade management algorithms for each order. In the ESB, I give the user complete power and therefore unlimited creativity. However, as you know, with great power comes great responsibility. Just be careful.\n\n## Software Structure\n\nFigure 5.2 shows a simplified structure of how the software works. There's a lot more going on behind the scenes, but this diagram gives a good overview of how the software in general works.\n\n**Figure 5.2** The structure of the backtesting software.\n\nThere are just two major components in the ESB, as you can see from the diagram. The two components are actuated by two simple buttons on the Data worksheet in the workbook. The **GetData** component forms the top of the diagram. This is where the programs asks for and then processes the data and puts the data into a digestible format. The second component, **TestSystem** , makes up the rest of the diagram and the rest of the software. Here is a breakdown of each component:\n\n * **GetData** \u2014this button first asks you to locate a comma-delimited file (CSV) through an Open File dialog box. Once the file is opened it is cross-referenced with the data in the DataMaster to determine the **Tick Value** and **Min Tick** properties. The first two letters of the file names are used as the search key. If the file name is CLXXX.CSV, then the CL will be used to determine what market data is being utilized. In most cases CL is crude oil. If the symbol is not located in the DataMaster, then the software assumes it is a stock and defaults the **Tick Value** to one dollar and the **Min Tick** to a penny.\n * **TestSystem** \u2014this button reads the data that was dumped into the **Data** worksheet and puts it into the seven data arrays. The program then starts looping through each bar and flows through the user-defined entry and exit logic. If the consequence of the user-defined logic results in a trade entry or exit, the software makes a note and processes the order as if it was actually executed. At the termination of the data loop, all trades are processed and an equity stream of closed trade profits and open trade equity is dumped out into the **EquityStream** worksheet.\n\nKeep in mind this is a very simple program and can only work on one market one system at a time. Figure 5.3 shows a typical layout of the Data worksheet.\n\n**Figure 5.3** A typical Excel data worksheet.\n\nThe **GetData** component was previously actuated by simply clicking the button and as you can see the different cells, **open** , **high** , **low** , **close** , **volume** , and **open interest** , were then populated. Also, the **Tick Value** and **Min Tick** values were cross-referenced in the DataMaster and their respective cells were filled in as well. The DataMaster worksheet contains the symbols and their properties in the current data universe. As you can see, stocks are not listed, but that doesn't mean you can't test them. Commodities and futures contracts have different sizes and values. These values must be stored somewhere so the software can gain access to them during the testing process. Originally, the software simply asked the user to input this information, but I quickly discovered this was way too cumbersome and decided to create the DataMaster worksheet (see Figure 5.4).\n\n**Figure 5.4** The DataMaster worksheet can help you store the values of your commodities and futures contracts.\n\nThese data properties were derived directly from the underlying data. If you don't get these values right, then your results will be completely wrong. Most data vendors will provide this information when you purchase their end-of-date (EOD) historic database. I use two data vendors, CSI and Pinnacle, for commodity and futures price quotes. You can buy deep historic databases from either of these vendors for a very reasonable price. If you purchase data through a reliable vendor, then you know you are getting quality data. You can cobble data together from various free services on the Internet, but remember GIGO (garbage in garbage out). For the ExcelSystemBackTester, I utilize data provided by CSI, but you can utilize any data as long as it is in ASCII and delimited by commas. The DataMaster can be used as a template and is fully editable. Some vendors use different decimal locations for the same market. If this is the case, you have got to make sure your DataMaster reflects the correct **Tick Value** and **Min Tick**.\n\nThe **Results** worksheet is the repository of all your trades and performance metrics. Every trade covers two rows, one for entry and one for exit. A profit or loss is calculated when a trade is exited and the cumulative profit or loss is updated as well. Figure 5.5 is an example of the **Results** worksheet where several trades and the performance metrics associated with them are listed.\n\n**Figure 5.5** The Results worksheet lists multiple trades and their associated performance metrics.\n\nThe date, name of entry\/exit signal, price of entry\/exit, and the results of the trade are listed chronologically. Currently there are only four major performance metrics included in the worksheet: (1) **Total Profit** , (2) **Maximum DD** , (3) **Number of Trades** , and (4) **Percent Wins**. By the time this book is published, I should have a few more calculated, such as: **Average Trade** , **Average Win** , **Average Loss** , and **Profit Factor**.\n\nThe last worksheet in the ESB is labeled **EquityStream** and stores the daily equity of the trading system. There is a **Create Equity Curve** button that launches a simple macro that creates a chart (see Figure 5.6) and plots the cumulative daily equity and drawdown. This chart gives a very quick snapshot of the overall performance of the trading system. There is enough information provided to help determine if your particular algorithm is good enough for either trading or further research. As you can see, the interface is simple enough\u2014load data, test system, plot equity. The hard stuff is getting into the VBA and creating a trading algorithm with the tools at hand.\n\n**Figure 5.6** The EquityStream worksheet has a button that launches a macro to create a chart that plots the cumulative daily equity and drawdown.\n\n## Programming Environment\n\nThe BASIC (an acronym for **Beginner's All-purpose Symbolic Instruction Code** ) programming language was introduced in the 1960s but became popular in the mid-1970s. BASIC quickly became the most popular interpreted language for beginners. Over the years, compiler companies have extended BASIC into professional software development. Microsoft has been using BASIC derivatives for decades and it is at the heart of VBA. When you code your trading algorithm in to the ESB, you will be programming in pure BASIC. You will see a lot of lines of code (I wish I could hide them, but the VBA Editor doesn't allow for collapsible text regions) that you will not need to understand (unless you want to). There are just three major sections with which you will need to concern yourself. But before we get into all that, launch your Microsoft Excel and make sure you see the **Developer** tab in the Ribbon. If you don't see it, then you will need to turn it on. You can do this by simply clicking the **File** menu and then selecting **Options**. After Excel Options dialog opens scroll down to **Customize Ribbon** and click on it. Figure 5.7 shows the **Customize Ribbon** dialog and where to click to get the **Developer** Tab to show up in the Ribbon.\n\n**Figure 5.7** Customize your Excel ribbon. Make sure you check the box next to the Developer tab option.\n\nOnce you return to a blank worksheet, the Developer tab should now be visible. Now go to the www.wiley.com\/go\/ultimatealgotoolbox and download the ExcelSystemBackTester.zip file to your C: drive and unzip it. The zip file contains two folders: Algorithms and Data. Get to the Algorithms folder and open the BollingerDX spreadsheet. The spreadsheet that opens should look similar to Figure 5.3. Now click on the **Developer** tab and the Ribbon should take on this appearance (see Figure 5.8).\n\n**Figure 5.8** The Developer tab in Microsoft Excel.\n\nThe only icon that we are concerned with is to the far left of the Ribbon, **Visual Basic**. Click on the icon\/button and the **Visual Basic Editor** (VBE) will launch. Make sure your VBE looks like the one in Figure 5.9.\n\n**Figure 5.9** The Visual Basic Editor (VBE) in Microsoft Excel.\n\nThere's a lot of stuff here. But we are just interested in the modules that are inside the red oval from Figure 5.9. You don't need to mess with anything else if you are just interested in using the ESB to test your trading ideas. The window that contains the modules is called the **Project Explorer**. It simply groups all the files in the project together for convenience.\n\n### The ESB VBA Code\n\nThe modules are individual files that contain the source code to carry out the various chores necessary to test a trading system. The most import module ( **Main** ) is the one we will spend most of our time in. Go ahead and double-click **Main** \u2014the source code inside the module will open in a separate window (see Figure 5.10). Inside this module are five submodules or subroutines: **declarations** , **fillTradeInfo** , **GetData** , **SystemTester** , and **main**. Most of our work will take place in the **SystemTester** module. Go ahead and scroll up and down in this window. It's going to look daunting without a doubt, but you need not concern yourself with 80 percent of the source code. Scroll to the very top of the window and you will see a lot of text in green. In VB, everything green is considered a comment. This information is just there for the benefit of the person reading the code\u2014it is hidden from the computer. Notice the first character in each line that is green. It is a single quote ('). A single quote at the beginning of a line of VBA code tells the computer to ignore the line. Just like the double forward slashes \"\/\/\" in AmiBroker. This area of the source code lets the reader know the title, version, subversion of the software, and any notes pertaining to revisions and necessary information a user may need to know. If you scrolled through the source, you will see multiple lines of comments. I did this to modularize the code and explain what the individual sections were doing. Breaking down a large program into sections helps explain the code in block-by-block fashion. Source code read as a whole is very difficult to understand, but if you can break the code into individual blocks, it will help make things much clearer.\n\n**Figure 5.10** Comment text in VBA code is written in gray. It is also indicated by the single quote at the beginning of each line.\n\nYou will notice several banners or blocks of green text embedded in the source code. Figure 5.10 is an example of one of these blocks.\n\nThese comments, in this format, help break up the code and also explain what's happening in the next few lines of code. This commentary explains how the data contained in the cells of the Data worksheet will be imported into the individual data arrays. Column 1 holds the Dates of each individual daily bar. The first row of data (row 3 in our case) holds the date, open, high, low, close, volume, and open interest for one day of data. Think of the data as just in one big table consisting of rows and columns. If you want the data of the very first bar, you would access it using the following notation: Cells (3, 1). In Excel, _cells_ refer to the entire table and the first index value inside the parentheses refers to the row number and the second index value is the column number. Cells (3, 2) refer to the open price of the very first bar. A newcomer to VBA might not know this nomenclature so it is included in this comment block. Since all of the data is being read into individual arrays you do not need to concern yourself with notion of cells, unless you want to.\n\nScroll down in the code until you find a comment block that looks like the one in Figure 5.11.\n\n**Figure 5.11** This is where the VBA comments end and the actual source code begins.\n\nAll the code that you scrolled through until you got to this point can be ignored. This area of the source code is used to set up any system-specific variables. The two lines of code following the comment block set **rampUp** to 100 and **commsn** to 100. Notice there are lines of comments to the right of each variable assignment. These are inline comments to let you know what that exact line of code is doing. You will again see the single quote (') preceding the comment. Whatever follows the single quote is ignored by the computer, be it at the beginning of a line of code or right in the middle. The **rampUp** variable informs the computer that the trading algorithm needs 100 days of data for calculation purposes before it can initiate trading. If you want to test a 100-day simple moving average algorithm, you would need to tell the ESB to skip the first 100 days of data so that the moving average can be properly calculated. You must be careful and make sure you provide enough ramp-up data for your algorithm. If you don't, the computer will halt and provide an error message like the one in Figure 5.12.\n\n**Figure 5.12** This error message appears if your algorithm does not have enough ramp-up data.\n\nThis looks like a scary error message but it's simply telling you that you are trying to go back further in time than you have specified. The **commsn** variable is what the computer will deduct from each round-turn trade. In this example it is set to 100; you can change this to any value you think might be appropriate. This is also a good area to set up any user-defined variables that you might need to use later in your code. Let's say you have a special calculation that uses a constant value, like a profit objective. You could set this up by using the following code:\n\n* * *\n\n rampUp = 5 ' how many days needed in calculations before trading\n commsn = 100 ' commission per round turn trade\n **myProfitTarg = 0.02 ' I just put this line of code in**\n\n* * *\n\nLater on, in the source code you can use **myProfitTarg** to help calculate where a profit might be taken. This is a very good time to mention that VBA, in most cases, is case insensitive. This means the two variable names, **myDayCount** and **mydaycount** , are one and the same. Ignoring case can cause sloppy-looking code and difficult readability. It's good programming etiquette to use the same case throughout a program. As I have mentioned in a previous chapter, I personally like using a capital letter in a variable name where a new word begins, but not the first letter of the variable name. Here are some examples you can use as a template for your variable names: **myProfitTarg** , **longDayCount** , **myStopAmt**. You have also got to be careful not to step on one of the keywords that is used by the ESB. Unlike AmiBroker or TradeStation, VBA will not tell you ahead of time that you are reassigning a variable that is already used elsewhere in the source code. A list of keywords is provided in the appendix to help prevent this from happening.\n\nLet's get to the heart of the ESB by scrolling down to the main trading loop. You can find it by looking for the comment block that says, \"Main Trading Loop.\" The entire Main Trading Loop is shown below. This includes some of the code we have already discussed and some code that you can simply ignore.\n\n* * *\n\n '****************************************************************\n '**** Main Trading Loop ****\n '****************************************************************\n Do While i <= numRecords\n tradeDays = tradeDays + 1\n IncrementalProgress.Show\n i = i + 1 'Dont touch\n sPercentage = (i \/ numRecords) * 100\n sStatus = \"Checking \" & i & \" of \" & numRecords & \" paragraphs\"\n IncrementalProgress.Increment sPercentage, sStatus\n intraDayTrdCnt = 0 'Leave in.\n If barsLong <> 0 Then barsLong = barsLong + 1 'Leave in.\n If barsShort <> 0 Then barsShort = barsShort + 1 'Leave in.\n '****************************************************************\n '**** This is a good place to put all of your function calls ****\n '**** and system calculations. ****\n '****************************************************************\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n simpleAvg = Average(myClose, 10, i, 1)\n rsiVal = RSI(myClose, 14, i, 1)\n Call Stochastic(3, 4, 7, stoK, stoD, slowD, i, 1)\n '****************************************************************\n '**** Put All Of Your Orders Here ****\n '****************************************************************\n prevMarketPosition = marketPosition\n If marketPosition <> 1 Then\n Call Trade(Buy, \"BB-Buy\", upBand, stp, i)\n End If\n If marketPosition <> -1 Then\n Call Trade(Sell, \"BB-Short\", dnBand, stp, i)\n End If\n If marketPosition = -1 Then\n Call Trade(ExitShort, \"ExitShortStop\", entryPrice + 2000 \/ myTickValue, stp, i)\n If barsShort > 10 And myClose(i) > entryPrice Then\n Call Trade(ExitShort, \"10dayShOut\", myClose(i), moc, i)\n End If\n End If\n If marketPosition = 1 Then\n Call Trade(ExitLong, \"ExitLongStop\", entryPrice - 2000 \/ myTickValue, stp, i)\n If barsLong > 10 And myClose(i) < entryPrice Then\n Call Trade(ExitLong, \"10dayLgOut\", myClose(i), moc, i)\n End If\n End If\n '****************************************************************\n '**** End of Main Traiding Loop ****\n '**** No orders allowed below this point ****\n '****************************************************************\n\n* * *\n\nThis is the complete listing for this simple Bollinger Band system. Don't worry about any of the source code _above_ the Main Trading Loop comment block:\n\n* * *\n\n '****************************************************************\n '**** This is a good place to put all of your function calls ****\n '**** and system calculations. ****\n '****************************************************************\n\n* * *\n\nAll of your programming will take place below these comments. For illustration purposes, I immediately call four indicator functions\/subroutines.\n\n* * *\n\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n simpleAvg = Average(myClose, 10, i, 1)\n rsiVal = RSI(myClose, 14, i, 1)\n Call Stochastic(3, 4, 7, stoK, stoD, slowD, i, 1)\n\n* * *\n\nThis algorithm will just use the values modified in the **BollingerBand** subroutine: **avg** , **upBand** , **dnBand**. Let's look at the other function calls in the program:\n\n * _Average_. This function returns a moving average value for the past 10 days. Its first argument is the data array that is to be averaged, and the second argument is the length of the calculation. You will again notice the last two arguments are the same for all of the function calls: **i** and **1**. The **i** will never change but you can change the last argument. If you were to use **2** , then the indicator calculation would be offset by two days. Instead of starting yesterday and going back 10 days, it would start the day before yesterday and go back 10 days.\n * _RSI_. This function returns the Relative Strength Index from the last 14 days of data. This function requires the data array and the length of the RSI calculation. As it is programmed in this example, it is utilizing the closing prices for its calculations. You can pass it high or low or volume data\u2014it doesn't matter.\n * _Stochastic_. This subroutine returns K, D, and Slow D. Here is another example of using a subroutine in place of a function. Just like the BollingerBand subroutine, this subroutine returns three values. It requires the length of the K calculation and the two additional smoothing lengths for the D and Slow D.\n\nExamples of all the indicator functions and subroutines are included in Appendix B.\n\nAfter you get your indicator values, the real fun begins. The most important code in the ESB can be found in the **Trade** subroutine. This subroutine determines if a trade takes place and then stores the information for later use. The subroutine requires five arguments (see Figure 5.13).\n\n**Figure 5.13** This tiny snippet of code contains five arguments, which are all necessary for the Trade subroutine.\n\nThe first argument informs the subroutine what you are trying to do and can take on four different values: **Buy** , **Sell** , **ExitLong** , **ExitShort**. The second argument is the name of the signal that will show up in the trade listing. It is a string so it needs to be included in quotes. In this example, the signal name is \" **BB-Buy**.\" It can be anything you want. The third argument is the price you would like to execute the order. Here we are trying to **Buy** on the penetration of the Upper Bollinger Band. The fourth argument informs the subroutine what type of order is being placed. It can take on four types of orders:\n\n * **stp\u2014Stop order**. The price of the order must be above the market for Buy and ExitShort or below the market for Sell and ExitLong.\n * **lmt\u2014Limit order**. The price of the order must be below the market for Buy and ExitShort or above the market for Sell and ExitLong.\n * **moc\u2014Market On Close order**. Execute the order at the closing price of the bar. Specify myClose(i) as the trade price.\n * **mkt\u2014Market order**. Executes at the opening of the bar. Specify **myOpen(i)** as the trade price.\n\nThe final argument is always the letter **i** , the current bar in the loop.\n\n* * *\n\n If marketPosition <> 1 Then\n Call Trade(Buy, \"BB-Buy\", upBand, stp, i)\n End If\n\n* * *\n\nThis order is only placed if the current **marketPosition** is not equal to 1 or long. In other words, don't place a **Buy** order if you are already long. Unfortunately, this version of the ESB doesn't allow pyramiding; however, future versions will have this capability. Entering a short position uses the same subroutine but the arguments are different:\n\n* * *\n\n If marketPosition <> -1 Then\n Call Trade(Sell, \"BB-Short\", dnBand, stp, i)\n End If\n\n* * *\n\nHere we are trying to **Sell** short at the lower Bollinger Band on a stop. That's it for the trade entries. Simple, thus far? Once you get into a trade, this algorithm has three different ways to exit:\n\n * A $2,000 money management stop\u2014any time the market moves $2,000 against the position it is exited.\n * Time-based market order (MOC)\u2014if the position is not profitable after 10 bars, the trade is exited on the close.\n * Reversal if the opposite side of the Bollinger Bands is penetrated before an exit is executed.\n\n* * *\n\n If marketPosition = 1 Then\n Call Trade(ExitLong, \"ExitLongStop\", entryPrice - 2000 \/ myTickValue, stp, i)\n If barsLong > 10 And myClose(i) < entryPrice Then\n Call Trade(ExitLong, \"10dayLgOut\", myClose(i), moc, i)\n End If\n End If\n\n* * *\n\nThe money management order is placed by calling the Trade subroutine with the following parameters: **ExitLong** , \" **ExitLongStop** ,\" **entryPrice \u2212 2000\/ myTickValue** , **stp** , **i**. Here we are informing the Trade subroutine to liquidate our long position on a stop at a price equivalent to the **entryPrice** \u2212 $2,000. The trade price can be represented by a single variable name or it can be a mathematical expression. In this case, we convert $2,000 to points by dividing 2,000 by **myTickValue**. Remember, you have got to make sure your units are compatible. If you are working with prices, then you must convert dollars to a price level. It would be a mistake in this case to forget to divide by **myTickValue**. Let's say you entered a trade in the DX at 129.050 and wanted to risk $2,000. If you didn't convert to points, then the exit price would be 129.050 \u2013 2000. This doesn't make sense. Just remember to convert all dollar figures to points.\n\nThe time-based order is placed after the long position has been in a trade for more than 10 days and is in a losing position. The variables **barsLong** and **entryPrice** are keywords so don't use them in an assignment statement\u2014just look, don't touch.\n\n**If barsLong > 10** tells the computer to ignore the **ExitLong** order until the trade has been on for at least 10 days and the **and myClose(i) < entryPrice** tells the computer to ignore the order if the position is in the profit. The orders to exit a short position use the keyword **barsShort** , and the logic **myClose(i) > entryPrice**.\n\n* * *\n\n If marketPosition = -1 Then\n Call Trade(ExitShort, \"ExitShortStop\", entryPrice + 2000 \/ myTickValue, stp, i)\n If barsShort > 10 And myClose(i) > entryPrice Then\n Call Trade(ExitShort, \"10dayShOut\", myClose(i), moc, i)\n End If\n End If\n\n* * *\n\nOnce you type in your trading logic, simply return to Excel and go to the **Data** worksheet and click on the **Run System** button.\n\n## Summary\n\nAll the tools that you need to calculate indicators, analyze price bar relations, manage open trades, and execute them are all built into the ESB. The best way to learn how to program your trading algorithms using VBA is by following along as many examples as you can. The end of this chapter has a couple more simple examples that you should be able to build upon.\n\n#### _Simple Moving Average Crossover using 3 X ATR stop_\n\n* * *\n\n '****************************************************************\n '**** This is a good place to put all of your function calls ****\n '**** and system calculations. A simple moving average ****\n '**** crossover system using a 3 ATR protective stop. ****\n '****************************************************************\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n simpleAvg = Average(myClose, 19, i, 1)\n atr = Average(myTrueRange, 20, i, 1)\n rsiVal = RSI(myClose, 14, i, 1)\n Call Stochastic(3, 4, 7, stoK, stoD, slowD, i, 1)\n '****************************************************************\n '**** Put All Of Your Orders Here ****\n '****************************************************************\n prevMarketPosition = marketPosition\n If marketPosition <> 1 And myClose(i) > simpleAvg Then\n Call Trade(Buy, \"CrossBuy\", myClose(i), moc, i)\n End If\n If marketPosition <> -1 And myClose(i) < simpleAvg Then\n Call Trade(Sell, \"CrossSell\", myClose(i), moc, i)\n End If\n If marketPosition = 1 And myClose(i) < entryPrice - 3 * atr Then\n Call Trade(ExitLong, \"L-ATR Stop\", myClose(i), moc, i)\n End If\n If marketPosition = -1 And myClose(i) > entryPrice + 3 * atr Then\n Call Trade(ExitShort, \"S-ATR Stop\", myClose(i), moc, i)\n End If\n '****************************************************************\n '**** End of Main Traiding Loop ****\n '**** No orders allowed below this point ****\n '****************************************************************\n\n* * *\n\n#### _Simple RSI system using 3 X ATR stop and 5 X ATR profit objective_\n\n* * *\n\n '****************************************************************\n '**** This is a good place to put all of your function calls ****\n '**** and system calculations. A simple RSI system ****\n '**** that buys when RSI < 20 and sells when RSI > 80. ****\n '**** Utilizes a 5 ATR Profit and a 3 ATR Protective Stop ****\n '****************************************************************\n Call BollingerBand(myClose, 60, 2, avg, upBand, dnBand, i, 1)\n simpleAvg = Average(myClose, 19, i, 1)\n atr = Average(myTrueRange, 20, i, 1)\n rsiVal = RSI(myClose, 14, i, 0)\n Call Stochastic(3, 4, 7, stoK, stoD, slowD, i, 1)\n '****************************************************************\n '**** Put All Of Your Orders Here ****\n '****************************************************************\n prevMarketPosition = marketPosition\n If marketPosition <> 1 And rsiVal < 20 Then\n Call Trade(Buy, \"RSIBuy\", myClose(i), moc, i)\n End If\n If marketPosition <> -1 And rsiVal > 80 Then\n Call Trade(Sell, \"RSISell\", myClose(i), moc, i)\n End If\n If marketPosition = 1 Then\n If myClose(i) < entryPrice - 3 * atr Then\n Call Trade(ExitLong, \"L-ATR Stop\", myClose(i), moc, i)\n End If\n If myClose(i) > entryPrice + 5 * atr Then\n Call Trade(ExitLong, \"L-ATR Prof\", myClose(i), moc, i)\n End If\n End If\n If marketPosition = -1 Then\n If myClose(i) > entryPrice + 3 * atr Then\n Call Trade(ExitShort, \"S-ATR Stop\", myClose(i), moc, i)\n End If\n If myClose(i) < entryPrice - 5 * atr Then\n Call Trade(ExitShort, \"S-ATR Prof\", myClose(i), moc, i)\n End If\n End If\n '****************************************************************\n '**** End of Main Trading Loop ****\n '**** No orders allowed below this point ****\n '****************************************************************\n\n* * *\n\n# Chapter 6 \nUsing Python to Backtest Your Algorithm\n\n## Why Python?\n\nAround the same time I started to write this book, I was teaching myself the Python programming language. If you have spent time roaming around the Internet looking for the next quant language, you have seen Python mentioned many times. The usage of this language has grown tremendously over the past few years in the quant universe. This doesn't mean Python is only found in this arena, nor does it mean it is only used by mathematicians, economists, or scientists. There are languages, such as R, that are specifically designed for mathematicians, but Python has universal usage. As I have mentioned many times in the previous chapters, most algorithmic traders do not come from a programming background. The introduction to AmiBroker and the Excel VBA\u2013based backtester has shown that a computer science degree is not necessary to get your algorithms tested on historic data. Most algorithmic traders learn just enough of a language to get the job done. In doing so, they use a very small subset of a platforms tools\u2014barely touching the tip of the iceberg. Imagine, though, how much more powerful their algorithm backtesting and development skills could become through learning as much as they can about programming. If I was a newbie and wanted to learn as much about programming as quickly as possible, I would learn Python. This is coming from a programmer who is deeply devoted to FORTRAN and C. The skillset that you would acquire would only enhance your abilities in other languages and testing\/trading platforms.\n\nPython has caught on for many reasons, but the biggest is ease of learning. Plus, you are exposed to the two predominant programming paradigms: object oriented and procedural. If you were formally educated in computer science in the 1970s and 1980s, you probably come from the procedural school of thought. I have a programmer friend who worked at Bell Laboratories in the 1970s, and he doesn't even want to talk about \"objects.\" Today's programmers, or should I say constructors, can build a rich graphical user interface (GUI) in a matter of minutes\u2014something that took me a week to do back in the 1980s. A really good programmer can use both objects and procedures.\n\nThis chapter introduces ideas from both schools of thought. However, this chapter is only a small introduction to the Python language. If you want to learn more about Python and computer science in general, I highly recommend John Zelle's _Python Programming: An Introduction to Computer Science_. This book provides a solid foundation not only in Python but also in some of the most useful topics in computer science\u2014knowledge that can be carried over into the trading arena.\n\nIn this new world of touchscreens, the usage of typing in a command line is disappearing. Well, that is if you are not from a Unix background. Python programmers become very comfortable with the command line, because it is so powerful. In many cases, a sophisticated user interface isn't necessary and this backtesting application is one of those cases. There isn't any exposure to developing a GUI because it wasn't necessary. Time was spent on topics that provided exposure on file manipulation, simple input\/output, objects, and functions. Before we start discussing the Python system backtester (PSB), here is a list of why Python was the language of choice:\n\n * _Python is an interpreted language_. The user doesn't need to go through an additional compilation step. Once you type the program into the editor, all you need to do is run it. If there is a syntax or runtime error, the Python shell will let you know about it.\n * _Python has a shell_. This interactive command line interpreter can be used for testing small bits of code, as the output window for printing out information from your programs, or as a very cool calculator. The PSB uses this window exclusively in this tutorial. This window also alerts you to syntax and runtime errors.\n * _Python is dynamically typed_. A user can create a variable name on the fly without having to declare\/size it before using it. This is similar to AFL and VBA. This helps the creative flow process. In other languages, when you create a variable you have to go back to the top of the code and declare it. By the time you get back to using it, you might have forgotten what you were planning on doing. Well, this is a problem I suffer; you might not. There are both advantages and disadvantages to dynamic typing and this is a subject of much controversy in the programming arena.\n * _Python is free and has a very large user's group_. The code is open source and free to use in commercial and personal applications as long as the copyright information is prominently displayed. Almost any question about how to do something in Python can be answered by simply Googling it.\n * _Python is perfect for our purposes_. All the trading system tracking\/bookkeeping\/analysis has already been programmed. All you need to do is use Python language and the PSB tools to create the perfect mousetrap.\n * _Python has no foo bar_. Most other languages use the words **foo** and **bar** as variable names in example code snippets. Their origination is from the military acronym **fubar** and was probably first used at MIT. Python uses the words **spam** and **eggs** instead. The creators of Python wanted it to be fun, so they named the language after _Monty Python_ , the British comedy group. Most people wouldn't put the words \"fun\" and \"programming\" together, but some of us would. **Spam** and **eggs** come from _Monty Python's Flying Circus_.\n\n## Python Installation\n\nYou will need to install Python on your computer before we can do anything. This is another benefit of Python\u2014it is very easy to install. Go to the website www.python.org and click on **Downloads**. You will be provided links for different operating systems. As of the writing of this chapter the latest version was 3.5. The PSB was written in 3.4 and is upwardly compatible. Download the installer and run it. Just click through the prompts\u2014the default values will be fine. This installer should install both IDLE (Python GUI) and Python (command line). If you are using a Windows operating system, a folder with the Python programs and manuals will be installed in your **Apps** screen. I use **Classic Shell** on my Windows 8 machine and both applications flow to the Start menu. Of course, if you are using Windows 7, it goes without saying you will find Python on the Start menu.\n\n## PSB Installation\n\nDownload the PSB.zip file from this book's companion website (www.wiley.com\/go\/ultimatealgotoolbox). Unzip it to your C: drive or to another convenient location.\n\n### IDLE\n\nThe PSB was programmed exclusively with **IDLE** , the standard Python development environment. Its name is an acronym of \"Integrated DeveLopment Environment.\" It works well on both Unix and Windows platforms. It includes a Python shell window, which gives you access to the Python interactive mode. Before we can start looking at the PSB, we need to learn a little bit about IDLE. So go ahead and launch it through your Apps screen or Start menu. The Python Shell should now be in front of you. Doesn't look that special; it's barebones in fact. This is by design to keep the Python learning curve as a gradual incline.\n\nA prompt, preceded by >>>, should now be blinking at you. Currently, the Shell is in interactive mode\u2014meaning that it wants you to give it a command. Type **4 + 6** and hit enter. The prompt now comes back with the answer\u2014 **10**. Now type **print(\"Hello World\")** and hit enter. The prompt comes back with **Hello World**. Now type **100 ** 0.5** and hit enter. You should get the number **10**. Now type **import this** and hit enter. Your screen should be filled with the following:\n\n**The Zen of Python, by Tim Peters**\n\nBeautiful is better than ugly.\n\nExplicit is better than implicit.\n\nSimple is better than complex.\n\nComplex is better than complicated.\n\nFlat is better than nested.\n\nSparse is better than dense.\n\nReadability counts.\n\nSpecial cases aren't special enough to break the rules.\n\nAlthough practicality beats purity.\n\nErrors should never pass silently.\n\nUnless explicitly silenced.\n\nIn the face of ambiguity, refuse the temptation to guess.\n\nThere should be one\u2014and preferably only one\u2014obvious way to do it.\n\nAlthough that way may not be obvious at first unless you're Dutch.\n\nNow is better than never.\n\nAlthough never is often better than *right* now.\n\nIf the implementation is hard to explain, it's a bad idea.\n\nIf the implementation is easy to explain, it may be a good idea.\n\nNamespaces are one honking great idea\u2014let's do more of those!\n\nThis is an \"Easter egg\" of a poem created by Python pioneer Tim Peters. Pretty cool, huh? Some people live, eat, and breathe Python. You don't need to go overboard to get the benefits of learning a programming language such as Python.\n\nYou can now see why they call it an \"interactive\" shell. Let's switch gears and use IDLE as an IDE. Go under the **File** menu and select **Open...** and then navigate your way to the PSB folder and open **PSBBollinger**. The file that opens is a trading algorithm based once again on Bollinger Bands.\n\n## PSB Structure\n\nThe PSB consists of a collection of files or modules. The main module is this one\u2014it pulls or calls all the other modules to facilitate the loading of data, looping through each and every bar, accounting for all of the trades and input\/output. If you want to create another trading algorithm, you start with an existing one and simply save it as a different name. There aren't separate submodules that simply include trading logic. This is just like the VBA-based ESB. This is unlike AmiBroker and TradeStation. In these softwares, trading rules, functions, and indicators are stored in a library.\n\nEverything you program will take place in this module or the indicators.py module. All Python source code files have the .py extension. The PSB is very simple\u2014type in your trading logic, which hopefully you have derived from a flowchart or a finite state machine, and then **Check Module** under the **Run** menu. If it passes, then you simply **Run** it by going under the **Run** menu and selecting **Run Module**.\n\nLet's run this PSBBollinger module by selecting **Run Module** from the **Run** menu. After you select **Run Module** , a File Browser window titled **Select Markets To Test** will open. The PSB is asking you to select a .CSV file or files that in can read into memory to which it will apply the Bollinger algorithm. Navigate to the Commodity Data folder and select the file that starts with CL (crude oil). Once you select the file and click OK, data and results generated by the algorithm will flow to the Python Shell and be displayed there. The results are presented in the following order:\n\n * _Combined results_. The PSB will combine the results of a multimarket selection. If only one market is selected, then it will just be the results from the single market.\n * _Combined monthly results_. The monthly results in $ are shown for all markets selected.\n * _Individual market results_. Performance metrics for each market are displayed.\n * _Trade-by-trade results_. A list of entries and exits and the $P\/L derived from each trade are shown.\n\nThat's it. There aren't any fancy charts involved\u2014everything is presented in a tabular format. If you want to see indicator values, you simply print them out to the Shell. The PSB structure, just like IDLE, was kept as simple as possible. Let's learn some Python by looking at the different PSB modules.\n\n### Indicator.py\n\nThis module contains all of the indicators that are utilized in the PSB. Go under the **File** menu in the Shell and open **indicators.py**. Keep the Python Shell open and quickly accessible. There are two types of indicators in this file. Some are just simple function modules and some are a little more sophisticated and are programmed as a class structure. I said you would be exposed to procedural (functions) and object-oriented (classes) programming. Let's start slowly with a simple indicator function.\n\n#### sAverage\n\n* * *\n\n def sAverage(prices,lookBack,curBar,offset):\n result = 0.0\n for index in range((curBar - offset) - (lookBack-1),curBar - offset +1):\n result = result + prices[index]\n result = result\/float(lookBack)\n return result\n\n* * *\n\nThis looks pretty palatable! All functions or, if you like, subprograms, use the key word **def** to let the interpreter know a function is about to be defined. The function has to have a name, and in this case it is **sAverage** (simple moving average). Remember how we called functions in AFL and VBA? You do it exactly the same way in Python. The list of arguments or parameters that are included in the parentheses after the function name are known as the formal argument list. These parameters are called formal because they're included in the function definition. Since we are using Python you don't need to employ function prototyping or forward declaration. In other words, you don't need to tell the interpreter the types of the arguments before-hand. The **sAverage** function requires four parameters:\n\n * **prices**. This is a list of price data (open, high, low, close, volume, or open interest). In this application of Python, we will be using the word _list_ instead of **array** , but know they mean basically the same thing. The Python **list** structure is very powerful as you will find out.\n * **lookback**. The number of days in the calculation of the indicator. This would equate to 20 in a 20-day moving average.\n * **curBar**. Simply the historic bar being evaluated.\n * **offset**. Just like the ESB, this number will usually be set to one. The indicator value from the prior day. You can go offset with a more positive number. If you use two, then it will return the indicator value form two days prior.\n\nNotice the colon (:) at the end of the function definition. The colon tells the interpreter that the indented code (four spaces) below is controlled by the current line. So everything that is indented below the function definition header is included in the function. Indentation is _very important_ in Python. Don't use tabs to indent; simply hit the spacebar four times. Don't forget this\u2014spacebar four times. Things will become much clearer very quickly.\n\nIn Python variables are assigned values with the equal sign ( **=** ). Equality between two variables is verified by using a double equal sign ( **==** ). Jump over to the Python Shell really quick. I hope you still have it close at hand. There might be a bunch of stuff in the window, so just scroll down to the very bottom until you find the >>> prompt. Once there type **a = 5** and hit enter. Type **a** and hit enter. The number 5 should appear at the prompt. You have basically assigned 5 to the variable **a**. Now type **b = 5** and hit enter. Type **a==b** and hit enter. The prompt should return with **True**. In this case **a** equals **b**. Type **a != b** and hit enter. The prompt will return with **False** , because **a** does equal **b**. You are asking if **a** doesn't equal **b** and the answer is **False** because it does. Remember to use **==** to test for equality and **!=** for inequality.\n\nThe next line of code is very important because you will see it often.\n\n* * *\n\n for index in range((curBar - offset) - (lookBack-1), curBar - offset +1):\n\n* * *\n\nThis is an example of a definite loop; the number of repetitions is known ahead of time. This **for-loop** will iterate across the number of items in the range from ((curBar \u2212 offset) \u2212 (lookBack\u22121) to curBar \u2212 offset +1). This only looks complicated because of the variables in the **range** function. Here is a more simplified version of the Python for loop:\n\n* * *\n\n myList = list()\n myList = [1,2,3,4]\n for index in range(0,3):\n print(myList[index])\n\n* * *\n\nThe output of this code will print only the first three elements in the list named **myList**. The function Range(0,3) returns 0, 1, and 2. The upper bound in the **Range** function is not inclusive. So to print out **myList** in its entirety, you must use Range(0,4). Referring back to the original bounds in our **Range** function, let's simplify by substituting some numbers for the values. Assume:\n\n 1. curBar = 500\n 2. offset = 1\n 3. lookback = 20\n\nSo, range ((500 \u2212 1) \u2212 (20 \u22121), 500 \u2212 1 + 1) equals range (499 \u2212 19, 500). The loop will iterate from 480 to 499 because 500 isn't included. Since 480 is inclusive, the number of iterations turns out to be 20. Count on your fingers if you want to prove this starting at 480 and going to 499. The loop will start at yesterday if the offset is one and go back 20 days and sum up whatever data is in the list that is passed to the function. Once the loop completes, the summation is divided by the number of days in the calculation\u2014the average of lookback days. This value is then returned to the calling program. That's all there is to this function. Sum up all requested values and divide by the number of requested values. The complicated part was deciphering the values in the **Range** function. Notice how the only line that was indented was **result = result + prices[index]**. This was because the **for-loop** was only controlling this one line of code. The rest of the lines were not under the influence of the **for-loop**. They were still indented in relationship to the **def** keyword and this was because the lines were encapsulated in the function body. Can you tell what these other functions are doing?\n\n* * *\n\n def highest(prices,lookBack,curBar,offset):\n result = 0.0\n maxVal = 0.00\n for index in range((curBar - offset) - (lookBack-1),curBar - offset + 1):\n if prices[index] > maxVal:\n maxVal = prices[index]\n result = maxVal\n return result\n def lowest(prices,lookBack,curBar,offset):\n result = 0.0\n minVal = 9999999.0\n for index in range((curBar - offset) - (lookBack-1),curBar - offset + 1):\n if prices[index] < minVal:\n minVal = prices[index]\n result = minVal\n return result\n\n* * *\n\nIf you guessed calculate the highest high and lowest low of lookback days, then give yourself a gold star. If not, just go back over the code until you get it. Notice the indentations and the use of the colon.\n\n#### rsiClass\n\nThat wasn't too bad now, was it? Are you ready to attack the indicators that are defined as a **class**? Let's take a close look at the RSI indicator:\n\n* * *\n\n class rsiClass(object):\n oldDelta1 = 0\n def __init__(self):\n self.delta1 = 0\n self.delta2 = 0\n self.rsi = 0\n self.seed = 0\n def calcRsi(self,prices,lookBack,curBar,offset):\n upSum = 0.0\n dnSum = 0.0\n if self.seed == 0:\n self.seed = 1\n for i in range((curBar - offset) - (lookBack-1),curBar - offset):\n if prices[i] > prices[i-1]:\n diff1 = prices[i] - prices[i-1]\n upSum += diff1\n if prices[i] < prices[i-1]:\n diff2 = prices[i-1] - prices[i]\n dnSum += diff2\n self.delta1 = upSum\/lookBack\n self.delta2 = dnSum\/lookBack\n else:\n if prices[curBar - offset] > prices[curBar - 1 - offset]:\n diff1 = prices[curBar - offset] - prices[curBar - 1 - offset]\n upSum += diff1\n if prices[curBar - offset] < prices[curBar - 1 - offset]:\n diff2 = prices[curBar - 1 - offset] - prices[curBar - offset]\n dnSum += diff2\n self.delta1 = (self.delta1 * (lookBack -1) + upSum) \/ lookBack\n self.delta2 = (self.delta2 * (lookBack -1) + dnSum) \/ lookBack\n if self.delta1 + self.delta2 != 0:\n self.rsi = (100.0 * self.delta1) \/ (self.delta1 + self.delta2)\n else:\n self.rsi = 0.0\n return (self.rsi)\n\n* * *\n\nThis indicator is programmed as a **class** object. We have ventured over into the land of objected-oriented programming, but don't worry; we are just going to work in an introductory mode to get the job done. You are probably asking yourself, why didn't he just program the RSI as a function module? The quick answer is I wanted to encapsulate the data and functions in one block of code so I could cut down on using global variables.\n\nThe first time an RSI indicator is called, it uses a special calculation to seed the indicator value. Subsequent calls to the indicator utilize the seed value and a different set of calculations. So I had to know, within the indicator code, if it was the first time it was being called. Also, I needed to store the seed and prior values in the class for subsequent calculations.\n\nBy preceding the name of the class object with the keyword **class** , you are informing the interpreter that a class definition is about to be defined with the name that follows the _**class**_ keyword. In this example, we are defining a class named **rsiClass**. The keyword **object** within parentheses follows the name of the class. This would be a great time to explain the difference between a class and an object. A class is a template and an object is an actual thing that reflects the class template. Think of it like this: A class is blueprint and an object is the house that is instantiated or created with the use of the blueprint. One blueprint can be used to create many houses. The following snippet of code informs the interpreter about data to be stored in the class:\n\n* * *\n\n def __init__(self):\n self.delta1 = 0\n self.delta2 = 0\n self.rsi = 0\n self.seed = 0\n\n* * *\n\nThe bit of code, **def __init__(self)** :, is the function name the object itself calls to set the initial values of the data variables (class members) when the class is instantiated. The key word **self** refers to the class itself. The keyword **init** must be preceded by two underscores and followed by two underscores. The keyword **self** must be followed by a period to access the different data encapsulated in the class. As you can see from the code, the variables **self.delta1** , **self.delta2** , **self.rsi** , and **self.seed** are all initially set to zero.\n\nThe next line of code should look familiar\u2014it looks like the functions we discussed earlier in the chapter.\n\n* * *\n\n def calcRsi(self,prices,lookBack,curBar,offset):\n\n* * *\n\nThe only difference in this function header is the word **self** in the argument list. Basically, when the function **calcRsi** is called, the first argument or parameter is going to be the class structure itself. The other arguments are: the data to be used in the calculations, the lookback period, the current bar, and the offset.\n\nTake a close look at the following code snippet:\n\n* * *\n\n upSum = 0.0\n dnSum = 0.0\n if self.seed == 0:\n self.seed = 1\n for i in range((curBar - offset) - (lookBack-1),curBar - offset):\n if prices[i] > prices[i-1]:\n diff1 = prices[i] - prices[i-1]\n upSum += diff1\n if prices[i] < prices[i-1]:\n diff2 = prices[i-1] - prices[i]\n dnSum += diff2\n self.delta1 = upSum\/lookBack\n self.delta2 = dnSum\/lookBack\n else:\n\n* * *\n\nThe function starts out by setting the variables **upSum** and **dnSum** to zero. The next line of code utilizes the keyword **self** and accesses the value of seed through the dot (.) notation. If **self.seed** is equal to zero, then all the indented code below the **if** construct will be executed. If **self.seed** is equal to zero, the very first line of code sets **self.seed** to one. In doing so, these lines of code will only be executed the very first time the function is called. Notice the variables **upSum** and **dnSum** do not use the dot notation. These variables are not members of the class and are temporary. They do not need to be remembered from one function call to the next. By using the dot notation, you are setting the data member to a value that will be remembered from one call to the next. By the way, a function inside a class is called a method. This function\/method calculates the initial RSI value by looping back in time and calculating, accumulating, and averaging the up and down sums. The **upSum** and **dnSum** averages are stored in the class data members, **self.delta1** and **self.delta2** , respectively. The next time this function is called, this portion of the function will be bypassed, but the data stored in the data members will be available for future use. The second part of the function:\n\n* * *\n\n else:\n if prices[curBar - offset] > prices[curBar - 1 - offset]:\n diff1 = prices[curBar - offset] - prices[curBar - 1 - offset]\n upSum += diff1\n if prices[curBar - offset] < prices[curBar - 1 - offset]:\n diff2 = prices[curBar - 1 - offset] - prices[curBar - offset]\n dnSum += diff2\n self.delta1 = (self.delta1 * (lookBack -1) + upSum) \/ lookBack\n self.delta2 = (self.delta2 * (lookBack -1) + dnSum) \/ lookBack\n\n* * *\n\nwill be executed every time. **Self.delta1** and **self.delta2** are used and reassigned each time the function is called. You might be able to see that the Wilder's averaging method is being used to calculate the current RSI components:\n\nThe final snippet of code is executed every time and returns the RSI calculation.\n\n* * *\n\n if self.delta1 + self.delta2 != 0:\n self.rsi = (100.0 * self.delta1) \/ (self.delta1 + self.delta2)\n else:\n self.rsi = 0.0\n return (self.rsi)\n\n* * *\n\nSince the design of this class-based indicator is a little more involved than a regular run-of-the-mill function, you would expect the call routine to be more involved as well. This is the case, but it only requires one additional line of code. In the case of this RSI indicator, all you need to do is add the line of code to your program: **rsiStudy = rsiClass()**. You can instantiate the **rsiClass** by calling it like a function. Instantiation is the creation of a shell that follows the class template\/plan. In this case, the class object is assigned to the **rsiStudy** variable. Once the class is assigned to a variable, you can access the data and methods of that class by using the name of the variable (object) and dot notation. Here is how you call the **calcRsi** method through the **rsiStudy** variable name: **rsiVal = rsiStudy.calcRsi (myClose, 10, curBar, i)**. That's all there is to using the RSI indicator.\n\nScroll through the rest of the indicators in **indicator.py** and familiarize yourself with them. You can add you own indicators by using one of the existing functions or indicator classes as a template. Just include the code in this file and import the name of the indicator in the main trading program.\n\n#### SystemTester.py\n\nThe main module that calls all the other modules is **SystemTester.py**. As I explained prior, you use this as a template to develop other trading algorithms. I usually open **SystemTester.py** and _save as_ immediately. If I am working on a Donchian type of algorithm, I will use a name like **DonchianSys1.py**. Instead of listing the program in its entirety, let's break it up section by section.\n\n##### Import Section\n\n* * *\n\n #------------------------------------------------------------\n #Import section - inlcude functions, classes, variabels\n #form externam modules\n #------------------------------------------------------------\n import csv\n import tkinter as tk\n import os.path\n from getData import getData\n from dataLists import myDate,myTime,myOpen,myHigh,myLow,myClose\n from tradeClass import tradeInfo\n from equityDataClass import equityClass\n from trade import trade\n from systemMarket import systemMarketClass\n from portfolio import portfolioClass\n from indicators import highest,lowest,rsiClass,stochClass,sAverage,bollingerBands\n from systemAnalytics import calcSystemResults\n from tkinter.filedialog import askopenfilenames\n\n* * *\n\nThe hash sign (#) at the beginning of any text informs the interpreter to ignore whatever follows up to the end of the line. Use this symbol for comments in your Python code\u2014just like we did with the single quote (') in VBA. You can also use it to temporarily hide a line of code from the interpreter. All of the external files and functions\/classes are pulled into the main program by using the keywords **from** and **import**. This is similar to C's **include** statement **\u2014** on the surface, anyway. For all intents and purposes, we will use it simply to import external code. The name of the external module follows **from** and the function\/class name follows the **import** keyword. Look at the line that starts, **from indicators import...** You will see a good portion of the indicator functions and classes that were defined in **indicator.py**.\n\nSome of the imports are strictly Python related:\n\n* * *\n\n import csv\n import tkinter as tk\n import os.path\n from tkinter.filedialog import askopenfilenames\n\n* * *\n\nAll these files deal with opening and reading a comma-delimited file. The rest of the imported files all deal with the PSB.\n\n##### Helper Functions for the PSB\n\nThese functions help parse the **.csv** file into the individual **myDate** , **myHigh** , **myLow** , **myClose** , **myVol** , and **myOpInt** lists. The attributes of each data file, symbol, **pointValue** , and **minMove** are collected here as well. A function that calculates the results of exiting a trade is also located here. I won't bore you with the details of these functions right now, but I want to bring to your attention another really cool thing about Python. A Python function can return multiple values. The **exitPos** function returns three values: **profit** , **trades** , and **curShares**. When you call a multiple return function, make sure you have the correct number of variables on the left side of the assignment:\n\n* * *\n\n myProfit, myTrades, myCurShares = exitPos(price,myDate[i],\"RevLongLiq\",curShares)\n\n* * *\n\nThe larger **exitPos** function was put here because it uses several global variables. These variables are shared among most of the functions in this file module. I didn't want to have to pass these variables back and forth within different function calls. I was slightly lazy in doing this, but it does help improve readability by reducing the number of different parameters included in the argument list.\n\n* * *\n\n #------------------------------------------------------------\n #Helper Functions local to this module\n #------------------------------------------------------------\n def getDataAtribs(dClass):\n return(dClass.bigPtVal,dClass.symbol,dClass.minMove)\n def getDataLists(dClass):\n return(dClass.date,dClass.open,dClass.high,dClass.low,dClass.close)\n def calcTodaysOTE(mp,myClose,entryPrice,entryQuant,myBPV):\n todaysOTE = 0\n for entries in range(0,len(entryPrice)):\n if mp >= 1:\n todaysOTE += (myClose - entryPrice[entries])*myBPV*entryQuant[entries]\n if mp <= -1:\n todaysOTE += (entryPrice[entries] - myClose)*myBPV*entryQuant[entries]\n return(todaysOTE)\n def exitPos(myExitPrice,myExitDate,tempName,myCurShares):\n global mp,commission\n global tradeName,entryPrice,entryQuant,exitPrice,numShares,myBPV,cumuProfit\n if mp < 0:\n trades = tradeInfo('liqShort',myExitDate,tempName,myExitPrice,myCurShares,0)\n profit = trades.calcTradeProfit('liqShort',mp,\n entryPrice,myExitPrice,entryQuant,myCurShares) * myBPV\n profit = profit - myCurShares *commission\n trades.tradeProfit = profit\n cumuProfit += profit\n trades.cumuProfit = cumuProfit\n if mp > 0:\n trades = tradeInfo('liqLong',myExitDate,tempName,myExitPrice,myCurShares,0)\n profit = trades.calcTradeProfit('liqLong',mp,\n entryPrice,myExitPrice,entryQuant,myCurShares) * myBPV\n trades.tradeProfit = profit\n profit = profit - myCurShares * commission\n cumuProfit += profit\n trades.cumuProfit = cumuProfit\n curShares = 0\n for remShares in range(0,len(entryQuant)):\n curShares += entryQuant[remShares]\n return (profit,trades,curShares)\n #------------------------------------------------------------\n #End of functions\n #------------------------------------------------------------\n\n* * *\n\n##### Lists and Variables Initiation\n\nYou can use this section to initialize your own lists and variables. These lines of code are pretty cool.\n\n* * *\n\n #------------------------------------------------------------\n #Lists and variables are defined and initialized here\n #------------------------------------------------------------\n alist, blist, clist, dlist, elist = ([] for i in range(5))\n marketPosition,listOfTrades,trueRanges,ranges = ([] for i in range(4))\n dataClassList,systemMarketList,equityDataList = ([] for i in range(3))\n entryPrice,fileList,entryPrice,entryQuant,exitQuant = ([] for i in range(5))\n #exitPrice = list()\n currentPrice,totComms,barsSinceEntry = 0\n numRuns,myBPV,allowPyra,curShares = 0\n #------------------------------------------------------------\n #End of Lists and Variables\n #------------------------------------------------------------\n\n* * *\n\n alist, blist, clist, dlist, elist = ([] for i in range(5))\n\nThe first line of code creates five different lists using an implicit **for loop** , a one-liner **for loop**. You are probably starting to see the magic of Python.\n\n##### Data Import and Configuration and Portfolio Setup\n\nThe list of data class objects are assigned whatever is returned by the function **getData()**. When the PSB is launched, one of the first things it asks the user is to pick some data (commodity, equities, or index prices). The **getData** function handles the creation of an **Open File** dialog, the selection of data files, and determining the market specifications for each file selected. The following is the complete listing of the function's source broken down into easily explainable components.\n\n* * *\n\n #------------------------------------------------------------\n #Get the raw data and its associated attributes [pointvalue,symbol,tickvalue]\n #Read a csv file that has at least D,O,H,L,C - V and OpInt are optional\n #Set up a portfolio of multiple markets\n #------------------------------------------------------------\n dataClassList = getData()\n numMarkets = len(dataClassList)\n portfolio = portfolioClass()\n import csv\n import tkinter as tk\n import os.path\n from marketDataClass import marketDataClass\n from dataMasterLists import commName, bigPtVal, minMove\n from tkinter.filedialog import askopenfilenames\n from equityDataClass import equityClassdataClassList = list()\n fileName = \"c:\\PBS\\dataMaster.csv\"\n def getData():\n totComms = 0\n with open(fileName) as f:\n f_csv = csv.reader(f)\n for row in f_csv:\n commName.append(row[0])\n bigPtVal.append(float(row[1]))\n minMove.append(float(row[2]))\n totComms = totComms + 1\n f.close\n\n* * *\n\nThe function starts out by opening the file C:\\PBS\\dataMaster.csv and reading its contents into three different lists: **commName** , **bigPtVal** , and **minMove**. Here is a quick snapshot of the contents of this file:\n\n \"AD\",100000,0.0001\n \"BP\",125000,0.0001\n \"CL\",1000,0.01\n \"C2\",50,0.25\n \"CC\",10,1\n \"CD\",100000,0.0001\n \"CL\",1000,0.01\n \"CT\",500,0.01\n \"CU\",125000,0.0001\n \"DX\",1000,0.005\n \"ED\",2500,0.005\n \"EM\",100,0.1\n \"FC\",500,0.025\n \"FV\",1000,0.0078\n \"GC\",100,0.1\n \"HG\",250,0.05\n \"HO\",42000,0.0001\n \"JY\",125000,0.00005\n\nAs you can see, the data are separated by commas, and there are three data values per line. The first data value is the string (enclosed in quotes) that will be assigned to **commName**. The second is the value of a big point move (a single increment of the number right before the decimal point (British pound is quoted as 1.5631, so a move from 1.5631 to 2.5631 would equate to $125,000), and the third is the minimum move of the market. The minimum move in stocks is 0.01 or one penny. In the British pound, it is 0.0001. Just like the ESB, the PSB needs to know this information ahead of time so it can properly calculate price-based values and perform accurate trade accounting. This file is easily editable and you can customize it to fit your own data and its format.\n\nPython has a ton of reusable code and helper modules. This little bit of code relies on the built-in **csv.Reader**. If you noticed the dot notation, then you realize that **csv** is class and **.Reader** is a method from that class. Before using the csv class, it had to be imported. If you look back at the source code, you will see it is the first module to be imported. After the file is opened using `with open(fileName) as f: ,` the file pointer (f) is passed to the **csv.Reader** method. The **f_csv** is then utilized to read each row of data in the file. The columns in each row are demarked by using a subscript. So row[0] is the commName, row[1] is the big point value, and row[2] is the minimum move. Since we are inside a definite **for loop** , the loops ends when the last row of data is read. Once the loop has terminated, the file is closed. These six or seven lines of code open the file, loop through each row of data, read the data into predefined lists, and then close the file. Pretty simple and concise!\n\nThis next snippet of code does a lot and is a little more sophisticated, so only the most important parts will be discussed.\n\n* * *\n\n root = tk.Tk()\n root.withdraw()\n cnt = 0\n files = askopenfilenames(filetypes=(('CSV files', '*.txt'),\n ('All files', '*.*')),\n title='Select Markets To Test')\n fileList = root.tk.splitlist(files)\n fileListLen = len(fileList)\n for marketCnt in range(0,fileListLen):\n head,tail = os.path.split(fileList[marketCnt])\n tempStr = tail[0:2]\n for i in range(totComms):\n if tempStr == commName[i]:\n commIndex = i\n newDataClass = marketDataClass()\n newDataClass.setDataAttributes(commName[commIndex],\n bigPtVal[commIndex],minMove[commIndex])\n with open(fileList[marketCnt]) as f:\n f_csv = csv.reader(f)\n for row in f_csv:\n newDataClass.readData(int(row[0]),float(row[1]),\n float(row[2]),float(row[3]), float(row[4]),0.0,0.0)\n cnt = cnt + 1\n dataClassList.append(newDataClass)\n f.close\n return(dataClassList)\n\n* * *\n\nThe single line of code:\n\n* * *\n\n files = askopenfilenames(filetypes=(('CSV files', '*.txt'),\n ('All files', '*.*')),\n title='Select Markets To Test')\n\n* * *\n\nopens an OS-independent **File Open Dialog** labeled **Select Markets To Test** and asks the operating system to list all files with a .CSV extension in that particular location. Once the user selects one or more files, the selection is passed back and stored in the variable **files**.\n\n* * *\n\n fileList = root.tk.splitlist(files)\n\n* * *\n\nThe files are then listed separately and stored in a list named **fileList**. This is all handled with the built-in method **root.tk.splitlist(files)**. This method takes all of the files the user selected and then splits them apart and stores the individual file names in a list.\n\n* * *\n\n head,tail = os.path.split(fileList[marketCnt])\n tempStr = tail[0:2]\n for i in range(totComms):\n if tempStr == commName[i]:\n commIndex = i\n\n* * *\n\nAnother OS method **os.path.split** takes the name of each individual file and splits the path name ( **C:\\myPath\\Data\\** ) and the actual filename apart ( **BP.CSV** ). The **head** variable is assigned the pathname and the **tail** variable the filename. Once the filename is separated the first two letters in the filename can be accessed by simply indexing into the string: **tempStr = tail[0:2]**. The first two characters in the filename represent the **symbol** that was selected. From this the **symbol** can be cross-referenced in the **DataMaster** and the market name, big point value, and minimum move can be attached to the symbol.\n\n* * *\n\n newDataClass = marketDataClass()\n newDataClass.setDataAttributes(commName[commIndex],bigPtVal[commIndex],minMove[commIndex])\n\n* * *\n\nAs soon as the filename is cross referenced with **DataMaster** , a **marketDataClass** object with the variable name **newDataClass** is instantiated by calling the **marketDataClass()** method. The **marketDataClass** class looks like this:\n\n* * *\n\n class marketDataClass(object):\n def __init__(self):\n self.symbol = \"\"\n self.minMove = 0\n self.bigPtVal = 0\n self.seed = 0\n self.date = list()\n self.open = list()\n self.high = list()\n self.low = list()\n self.close = list()\n self.volume = list()\n self.opInt = list()\n self.dataPoints = 0\n def setDataAttributes(self,symbol,bigPtVal,minMove):\n self.symbol = symbol\n self.minMove = minMove\n self.bigPtVal = bigPtVal\n def readData(self,date,open,high,low,close,volume,opInt):\n self.date.append(date)\n self.open.append(open)\n self.high.append(high)\n self.low.append(low)\n self.close.append(close)\n self.volume.append(volume)\n self.opInt.append(opInt)\n self.dataPoints += 1\n\n* * *\n\nThis class acts like a container that holds all of the price data and market attributes for each file selected by the user. It also contains the methods for gathering that data. The **init** method creates all of the storage needed to handle years and years of data. Other than the single variables **self.symbol** , **self.minMove** , **self.bigPtVal** , the rest of the data holders are lists. Each list is capable of holding tremendous amounts of data. The other two methods, **setDataAttributes** and **readData** , are used to set the market specifications and fill up the lists with price data. Notice Python uses the **.append** method to add values to an existing list. Lists act like arrays, but are much more powerful due to their associated methods. If I want to know the number of elements in a list, all I have to do is: **listLen = len(myList)**. **Len()** is simply a method of the **list** class.\n\nNow keep in mind all of this code is inside a **for loop**. The number of loops is determined by the number of markets selected by the user. If the user selected five files, then this loop would be performed five times. You would have five instantiations of the **marketDataClass** objects, and each would be used to set the market specifications for the five markets and read in the different price data from the five different files. A total of five different objects would be spawned to handle all of the data. The best way to keep these classe objects together would be to put them in a **list**. I bet you knew a **list** can contain primitive data types like numbers, strings, letters, and Booleans. But, I bet you didn't know a list can contain complex data structures like our **marketDataClass**. Jump over the Python Shell and type the following:\n\n >>> a = list()\n >>> a = [\"apple\",\"banana\",\"strawberry\"]\n >>> a\n\nWhen you hit enter after the last line, the Shell will display:\n\n 1. ['apple', 'banana', 'strawberry']\n\nNo surprise here, it basically repeated what we put into the list. Now type this:\n\n >>>b = list()\n >>> b = [\"pineapple\",\"coconut\",\"mango\"]\n c = list()\n >>> c.append(a)\n >>> c.append(b)\n >>> c\n\nand hit return. The Shell shows:\n\n 1. [['apple', 'banana', 'strawberry'], ['pineapple', 'coconut', 'mango']]\n\nYou have a list that contains two other lists. Notice the grouping? ['apple', 'banana', 'strawberry'] is the **a** list and ['pineapple', 'coconut', 'mango'] is the **b** list.\n\nThis line of code, `dataClassList.append(newDataClass)` inserts the individual **marketDataClasse object** in the **dataClassList list**. This list will be accessible to the rest of the program later on.\n\nGetting back to:\n\n* * *\n\n dataClassList = getData()\n numMarkets = len(dataClassList)\n portfolio = portfolioClass()\n\n* * *\n\nThe first simple line of code does quite a bit. The next line starting with numMarkets gets the length of the list that contains all the **marketDataClass** objects. In other words, it returns the number of **marketDataClass** objects, which is the number of markets selected by the user. The next line of code instantiates a **portfolioClass** objectd labeled **portfolio**. The **portfolioClass** is quite large, so I won't regurgitate it here. I will in the appendices. There are some very important and cool things going on in this class, so I want to highlight those very quickly. But before we do, that there are two important class structures that are a prerequisite to the **portfolioClass**. These classes are named **equityClass** and **marketSystemClass**. The **equityClass** is used to store the daily equity for each individual market. A new **equityClass** object is instantiated for each different market in the market list. Here's what the data containers in the **equityClass** class look like:\n\n* * *\n\n def __init__(self):\n self.equityDate = list()\n self.equityItm = list()\n self.clsTrdEquity = list()\n self.openTrdEquity = list()\n self.cumuClsEquity = 0\n self.dailyEquityVal = list()\n self.peakEquity = 0\n self.minEquity = 0\n self.maxDD = 0\n\n* * *\n\nAfter you open a trading account and start trading something happens every day to your account. It either stays flat, goes up, or goes down. These daily fluctuations are caused by the P\/L from a closed trade or the change in market value of an open trade. Cumulative equity reflects the growth of your account. This **equityClass** keeps track of P\/L from closed trades, change in daily open trade equity, and the cumulative equity for any given time period. If you buy Apple today at $100 a share and buy just one share, then today's equity simply reflects the difference between the closing price and $100. Let's pretend Apple closed at $105, so your closed trade equity is equal to zero, but your open trade equity (OTE) is $5. Today's equity in your account is $5. Let's pretend a little further and say Apple moves up to $110, and you decide to cover your long position. Today's equity is derived from a closed trade profit of $10. Since there is no open position, then there is no OTE. Tracking your two-day performance, you show daily equity of $5 for yesterday and $10 for today. Your cumulative equity stands at $10. Feeling a little more bullish, you buy Apple again on the third day at $112, but unfortunately, some bad news comes out of China and the stock drops back to $105. So today's equity reflects the cumulative closed out equity $10 and today's OTE that stands at \u2212$7. Your cumulative equity drops by $7 and now stands at $3. The next day Apple drops further and you start feeling bearish so you sell short at $100. Unfortunately, China states their GDP is growing a little faster than the analysts predicted and Apple rebounds and closes at $110. What is your cumulative equity now?\n\n 1. Day 1 : Cum.E ($5) = Cum.Cls.TE (0) + OpenTE (5)\n 2. Day 2 : Cum.E ($10) = Cum.Cls.TE (10) + OpenTE (0)\n 3. Day 3 : Cum.E ($3) = Cum.Cls.TE(10) + OpenTE(\u22127)\n 4. Day 4 : Cum.E (\u2212$12) = Cum.Cls.TE(\u22122) + OpenTE(\u221210)\n\nThe one trade that you took on Day 4 was a disaster. First off, you closed out a $12 loser ($112 \u2212 $100), and to add insult to injury your OTE is \u2212$10 ($100 \u2212 $110). You real cumulative losses stand at \u2212$2 and your paper loss stands at \u2212$10. All these values are needed to calculate a daily equity stream and that is why we have: **self.clsTrdEquity** , **self.openTrdEquity** , **self.cumuClsEquity**. The rest of the module keeps track of the daily equity stream as well as the maximum equity peak, and the subsequent equity valley. From these values the worst-case drawdown can be derived.\n\n* * *\n\n def setEquityInfo(self,equityDate,equityItm,clsTrdEquity,openTrdEquity):\n self.equityDate.append(equityDate)\n self.equityItm.append(equityItm)\n self.cumuClsEquity += clsTrdEquity\n tempEqu =self.cumuClsEquity+openTrdEquity\n self.dailyEquityVal.append(tempEqu)\n self.peakEquity = max(self.peakEquity,tempEqu)\n maxEqu = self.peakEquity\n self.minEquity = min(self.minEquity,tempEqu)\n minEqu = self.minEquity\n self.maxDD = max(self.maxDD,maxEqu-tempEqu)\n maxDD = self.maxDD\n maxDD = maxDD\n\n* * *\n\nThe next class, **systemMarketClass** , is used to keep track of each system on each individual market. I did this in case a future version of PSB might combine multiple markets on multiple systems. You could have a bunch of these **systemMarketClass** objects reflecting the performance on several system\/markets; you then could combine certain ones to produce a very efficient equity curve. For right now, though, these class objects contain the following data:\n\n* * *\n\n def __init__(self):\n self.systemName = \"\"\n self.symbol = \"\"\n self.tradesList =list()\n self.equity = equityClass\n self.avgWin = 0\n self.avgLoss = 0\n self.avgTrade = 0\n self.profitLoss = 0\n self.numTrades = 0\n self.maxxDD = 0\n self.perWins = 0\n\n* * *\n\nEach **systemMarketClass** contains the name of the system and the symbol. In addition, it stores a list of trades, the equity stream, the average win, loss, and trade, percent wins, number of trades, and maximum drawdown. The methods in this class set the pertinent data, such as system name and symbol, and calculate all the performance metrics.\n\n* * *\n\n def setSysMarkInfo(self,sysName,symbol,trades,equity):\n self.systemName = sysName\n self.symbol = symbol\n self.tradesList = list(trades)\n self.equity = equity\n temp1 = 0\n temp2 = 0\n temp3 = 0\n temp4 = 0\n temp5 = 0\n temp6 = 0\n temp7 = 0\n numTrades = 0\n for i in range(0,len(self.equity.dailyEquityVal)):\n temp5 = self.equity.dailyEquityVal[i]\n temp6 = max(temp6,temp5)\n temp7 = max(temp7,temp6-temp5)\n self.maxxDD = temp7\n for i in range(0,len(self.tradesList)):\n if self.tradesList[i].entryOrExit == 1:\n numTrades += 1\n if self.tradesList[i].tradeProfit > 0:\n temp1 += self.tradesList[i].tradeProfit\n temp2 += 1\n if self.tradesList[i].tradeProfit < 0:\n temp3 += self.tradesList[i].tradeProfit\n temp4 += 1\n if temp2 != 0: self.avgWin = temp1\/temp2\n if temp4 != 0: self.avgLoss = temp3\/temp4\n if numTrades != 0: self.avgTrade = temp5\/numTrades\n self.numTrades = numTrades\n self.profitLoss = temp5\n if numTrades != 0: self.perWins = temp2 \/ numTrades\n\n* * *\n\nThe **setSysMarkInfo** method is the only method in this class, but it does a bunch of work. Notice about halfway through the variables with **temp** in their name; these are temporary holders for data that is not stored in the class. They are born when the method is called and die when the method exits. They are not members of the class. The **portfolio** class is similar to the **systemMarketClass** , but is much more macroscopic in nature. Basically, it sits on top of **systemMarketClass** and stores aggregate information concerning the multiple markets in the portfolio.\n\n* * *\n\n class portfolioClass(object):\n def __init__(self):\n self.portfolioName = \"\"\n self.systemMarkets = list()\n self.portEquityDate = list()\n self.portEquityVal = list()\n self.portclsTrdEquity = list()\n self.portDailyEquityVal = list()\n self.portPeakEquity = 0\n self.portMinEquity = 0\n self.portMaxDD = 0\n tempEqu = 0\n cumEqu = 0\n maxEqu = -999999999\n minEqu = 999999999\n maxDD = 0\n\n* * *\n\nAs you know, a portfolio is simply a collection of different markets. A portfolio has to have a name, a list of the different **systemMarkets** or just markets, and lists that make up **equityDate** , **equityVal** , **clsTrdEquity** , and **dailyEquity** at the portfolio level. The methods involved with this class are rather long and for brevity's sake will not be displayed here. All classes including their methods will be listed in the appendix. There are a couple of Pythonesque list features I would like to discuss, because they are so cool. If you have traded commodities or futures, you know some days one market is open and another closed. Creating a master date list to contain the daily portfolio equity had to take this into consideration. The use of Python's lists made creating a master date list that included all the dates of the entire portfolio very easy. I simply concatenated (added together) all of the different date, not data, streams from each **systemMarket**.\n\n* * *\n\n for i in range(0,len(self.systemMarkets)):\n masterDateList += self.systemMarkets[i].equity.equityDate\n\n* * *\n\nThis loop starts at 0 and loops through all the **systemMarkets**. If you have five markets in your portfolio, then the loop would start at 0 and end at 4. You will notice the **+=** operand after **masterDateList** in the code. This is a shortcut like **a = a + 1**. Using this operand eliminates repeating the variable name after the equal sign. If you want to see how this works, jump over to the Python Shell and type this:\n\n >>> a = list()\n >>> a = [1,2,3,4,6,7,8,9]\n >>> b = list()\n >>> b = [1,2,3,4,5,6,7,8,10]\n >>> c = a + b\n >>> c\n\nAfter you hit enter following the last c you will be presented with this:\n\n 1. [1, 2, 3, 4, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10]\n\nThis is simply a concatenation of the two lists. It includes all values from both lists. Now type this:\n\n >>> c.sort()\n >>> c\n\nHit enter after the last c, and the list is now sorted and stored back in the original list.\n\n 1. [1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 10]\n\nThis is how I created a master data list that included all the dates in the different equity streams from each market. I then used a **removeDuplicates** function to remove the duplicate list entries. The other cool thing in this class is this snippet of code:\n\n* * *\n\n def createMonthList(li):\n myMonthList = list()\n for i in range(0,len(li)):\n if i != 0:\n tempa = int(li[i]\/100)\n pMonth = int(li[i-1]\/100) % 100\n month = int(li[i]\/100) % 100\n if pMonth != month:\n myMonthList.append(li[i-1])\n if i == len(li)-1:\n myMonthList.append(li[i])\n return myMonthList\n\n* * *\n\nThis code takes a large list of dates and extracts the beginning date of each month in that list, and then creates a list with just the different months. This is how I was able to create a monthly breakdown of the time period used in the testing of the system.\n\n* * *\n\n 20110930 2249 2249\n 20111031 -2545 -296\n 20111130 0 -296\n 20111230 -913 -1209\n 20120131 0 -1209\n 20120229 0 -1209\n 20120330 0 -1209\n 20120430 -120 -1329\n 20120531 921 -408\n 20120629 -1735 -2143\n 20120731 955 -1188\n\n* * *\n\nOne last bit of code that shows off the power of Python follows. After this, I will demonstrate how to pull all this together and test a trading algorithm.\n\n* * *\n\n for i in range(0,len(masterDateList)):\n cumuVal = 0\n for j in range(0,len(self.systemMarkets)):\n skipDay = 0\n try:\n idx = self.systemMarkets[j].equity.equityDate.index(masterDateList[i])\n except ValueError:\n skipDay = 1\n if skipDay == 0:\n cumuVal += self.systemMarkets[j].equity.dailyEquityVal[idx]\n combinedEquity.append(cumuVal)\n\n* * *\n\nThis snippet of code is important because two very important concepts are covered. If you review the code, you will see the keyword **try** : The code controlled by **try** is simply finding if and where the last day of a month is located in a **systemMarket's equityDate** stream. Let's say we are trying to see if July 31, 2012, is in an **equityDate** list. If it is, then the variable **idx** returns the location in the list. If it's not located in the list, then an error is returned. This is where **except** comes into play. The code controlled by **except** is only executed if the method **index** returns an error. Back to the Python Shell!\n\nType the following and hit enter after the last line:\n\n >>> a = list()\n >>> a = [100,300,200,800]\n >>> a.index(300)\n 1\n\nThis example returns the location of the number 300 in the **a** list. Remember Python is zero based. The first element is number 0.\n\n## Getting Down to Business\n\nOkay, we now have somewhat of an understanding of how the PSB works. I designed it to be like one of those calculators or watches that is encased in see-through plastic. Everything is there if you just look for it. However, just like the watch or calculator, you don't need to know exactly how one works to use it. This software allows the users to do whatever they want, including looking into the future, so be careful. Our first test is going to be the ol' Bollinger Band algorithm.\n\n* * *\n\n for i in range(len(myDate) - numBarsToGoBack,len(myDate)):\n equItm += 1\n tempDate = myDate[i]\n todaysCTE = todaysOTE = todaysEquity = 0\n marketPosition[i] = marketPosition[i-1]\n mp = marketPosition[i]\n buyLevel,shortLevel,exitLevel = bollingerBands(myDate,myClose,60,2,i,1)\n print(tempDate,\" avg \",exitLevel,\" \",buyLevel - exitLevel)\n atrVal = sAverage(trueRanges,10,i,0)\n rsiVal = rsiStudy.calcRsi(myClose,10,i,0)\n stopAmt = 3000\/myBPV\n # print(myDate[i],\"rsi \",rsiVal,\" atrVal \",atrVal*myBPV,\" \",myBPV)\n # fastKVal,fastDVal,slowDVal = stochStudy.\n # calcStochastic(3,9,9,myHigh,myLow,myClose,i,1)\n # if (mp > 0 and maxPositionL < 3) : maxPositionL = mp\n # if (mp < 0 and maxPositionS < 3) : maxPositionS = mp\n #Long Entry Logic - Bolloinger\n if (mp == 0 or mp == -1) and myHigh[i] >= buyLevel:\n profit = 0\n price = max(myOpen[i],buyLevel)\n if mp <= -1:\n profit,trades,curShares = exitPos(price,myDate[i],\"RevShrtLiq\",curShares)\n listOfTrades.append(trades)\n mp = 0\n todaysCTE = profit\n tradeName = \"Boll Buy\"\n mp += 1\n marketPosition[i] = mp\n numShares = 1\n entryPrice.append(price)\n entryQuant.append(numShares)\n curShares = curShares + numShares\n trades = tradeInfo('buy',myDate[i],tradeName,entryPrice[-1],numShares,1)\n barsSinceEntry = 1\n totProfit += profit\n listOfTrades.append(trades)\n #Long Exit - Loss\n if mp >= 1 and myLow[i] <= entryPrice[-1] - stopAmt and barsSinceEntry > 1:\n price = min(myOpen[i],entryPrice[-1] - stopAmt)\n tradeName = \"L-MMLoss\"\n exitDate =myDate[i]\n numShares = curShares\n exitQuant.append(numShares)\n profit,trades,curShares = exitPos(price,myDate[i],tradeName,numShares)\n if curShares == 0 : mp = marketPosition[i] = 0\n totProfit += profit\n todaysCTE = profit\n listOfTrades.append(trades)\n maxPositionL = maxPositionL - 1\n # Long Exit - Bollinger Based\n if mp >= 1 and myLow[i] <= exitLevel:\n price = min(myOpen[i],exitLevel)\n tradeName = \"L-BollExit\"\n numShares = curShares\n exitQuant.append(numShares)\n profit,trades,curShares = exitPos(price,myDate[i],tradeName,numShares)\n if curShares == 0 : mp = marketPosition[i] = 0\n totProfit += profit\n todaysCTE = profit\n listOfTrades.append(trades)\n maxPositionL = maxPositionL -1\n\n* * *\n\nThis is just the code for long entries and exits, and I must admit it looks a little bit ugly. Like I mentioned earlier, everything is exposed and the user has to do a little more of the programming that is taken care of behind the scenes with software such as AmiBroker and TradeStation. However, if you can program in the PSB, you can program anywhere.\n\nThe first thing we need to calculate is the Bollinger Bands. We are going to buy on a stop when the high of the day exceeds a 60-day two-deviation upper band. Shorting occurs when the low of the day exceeds a 60-day two-deviation lower band. This line of code provides exactly what we need.\n\n* * *\n\n buyLevel,shortLevel,exitLevel = bollingerBands(myDate,myClose,60,2,i,1)\n\n* * *\n\nPrior to actually programming your algorithm, it is important to know how your algorithm enters trades: on a stop, market, or on a limit. Unlike AmiBroker, the ESB, or TradeStation, it is up to the user to program the different **if** constructs that pertain to the different types of orders. Don't worry; it's not nearly as complicated as it sounds. The **buyLevel** , **shortLevel** , and **exitLevel** are all calculated by the **BollingerBands** function. This algorithm also utilizes a $3,000 protective stop. Prepared with this information we are now ready to enter battle. With the PSB you must determine if the daily market action met the requirements for trade entry and\/or exit. In other words, you have to test the bar's extreme prices to see if an entry or exit level was exceeded. You might want to follow along in the code box as you read the following instructions. First, I have to make sure I am not already in a long position ( **mp** \u2014market position not equal to 1), and then I look at today's high; I am peeking into the future here, to see if the market would have exceeded or equaled the **buyLevel**. If it did, then I know I should have entered a long position. With this method of backtesting, you tell the computer a trade has taken place. In other platforms, the computer tells you a trade has taken place. Once you determine a trade should have been executed, you only need to change a little bit of code in the Long Entry Logic. The code that needs to be changed is bolded in the following code listing.\n\n* * *\n\n if (mp != 1) and myHigh[i] >= **buyLevel** :\n profit = 0\n price = max(myOpen[i], **buyLevel** )\n if mp <= -1:\n profit,trades,curShares = exitPos(price,myDate[i],\"RevShrtLiq\",curShares)\n listOfTrades.append(trades)\n mp = 0\n todaysCTE = profit\n tradeName = \" **Boll Buy** \"\n mp += 1\n marketPosition[i] = mp\n numShares = 1\n entryPrice.append(price)\n entryQuant.append(numShares)\n curShares = curShares + numShares\n trades = tradeInfo('buy',myDate[i],tradeName,entryPrice[-1],numShares,1)\n barsSinceEntry = 1\n totProfit += profit\n listOfTrades.append(trades)\n\n* * *\n\nThat's all the code you have to concern yourself with. There is a lot of code, but most off it stays the same from one algorithm to the next.\n\nIn the case of this system, all entries and exits are executed as stop orders. Since we are dealing with stops, we must test the **myHigh[i] (today's high)** against the **buyLevel**. If the high of the day is greater than or equal to our buy stop, then we can safely assume the order was filled. Did the market gap above our buyLevel\u2014you must test for this as well. The code is already in place: **price = max(myOpen[i], buyLevel)**. If the market did indeed gap above our **buyLevel** , then the fill price is moved to the open of the day. This line of code is only necessary if a gap open could impact the fill price on a stop order. The only other thing you need to change is the **tradeName** variable. In this case, we change the name inside the quotes to **Boll Buy**. That's all you have to change in the code. The rest of the code is for internal use only. If IDLE had a collapsible text feature, I would just collapse this down so you wouldn't have to see it. You can edit your Python code in a more sophisticated text editor such as NotePad ++ (). Figure 6.1 demonstrates the collapsible text feature.\n\n**Figure 6.1** NotePad++'s collapsible text feature.\n\nWe would all agree this is a much cleaner interface. NotePad ++ is available for download for a small donation. The reason I didn't use NotePad++ in this book is because it is not exactly easy to integrate into IDLE and I wanted to keep things as simple as possible.\n\nThat was the long entry logic only and now we must program the two exits associated with this algorithm: a money management stop and a moving average stop. Here is the money management stop logic:\n\n* * *\n\n if mp >= 1 and myLow[i] <= **entryPrice[-1] - stopAmt** and barsSinceEntry > 1:\n price = min(myOpen[i], **entryPrice[-1] - stopAmt** )\n tradeName = \" **L-MMLoss** \"\n exitDate =myDate[i]\n numShares = curShares\n exitQuant.append(numShares)\n profit,trades,curShares = exitPos(price,myDate[i],tradeName,numShares)\n if curShares == 0 : mp = marketPosition[i] = 0\n totProfit += profit\n todaysCTE = profit\n listOfTrades.append(trades)\n maxPositionL = maxPositionL - 1\n\n* * *\n\nIf **mp >=** 1, then the algorithm's current position is long. You could state **if mp** == 1, but this software has the capability of pyramiding and scaling in and out. So just always use >= to test for a long or short position. Since we are exiting on stops, the low of the day is tested against the **entryPrice - stopAmt** ($3,000). In Python the last element in a **list** can be easily accessed by using a **-1** inside the brackets. **EntryPrice[-1]** simply refers to the last price in the **entryPrice** list, which turns out to be the price at which the algorithm assumed a long position. I have put a small **i** in the **entryPrice** list more times than I would like to admit, and this definitely will throw a monkey wrench into the works. So don't do it. If the low of the day is less than or equal to **entryPrice - stopAmt** , then an exit has taken place and all you need to do is set the **price** and the **tradeName**. The rest of the code in the block runs in the background. **BarsSinceEntry** is an internal variable that keeps track of the number of bars since the last entry, and is used in this logic to make sure an entry and an exit doesn't occur on the same bar. This version of the PSB doesn't allow more than one entry per bar. Getting out on a stop at the midpoint between the upper and lower bands is handled in the same manner. The only difference is the **price** and the **tradeName** variables.\n\n* * *\n\n if mp >= 1 and myLow[i] <= **exitLevel** :\n price = min(myOpen[i], **exitLevel** )\n tradeName = \" **L-BollExit** \"\n numShares = curShares\n exitQuant.append(numShares)\n profit,trades,curShares = exitPos(price,myDate[i],tradeName,numShares)\n if curShares == 0 : mp = marketPosition[i] = 0\n totProfit += profit\n todaysCTE = profit\n listOfTrades.append(trades)\n maxPositionL = maxPositionL -1\n\n* * *\n\nUnless you are adding a new indicator to the indicator.py file, this is the only file you will ever need to modify. Once you make your changes, all you need to do to run your algorithm is go under the **Run** menu and select **Check Module**. If everything checks out, then you go under the **Run** menu once again and select **Run Module**.\n\nI guarantee that you will get some type of syntax error or run-time error every time you create a new trading algorithm module. This is a good learning experience, as IDLE will point out the offending line of code. Figure 6.2 is an example of a syntax error message dialog and Figure 6.3 shows the offending line. You will see this until you stop forgetting the difference between the assignment operator ( **=** ) and the comparison operator ( **==** ).\n\n**Figure 6.2** A Python syntax error message.\n\n**Figure 6.3** In this case, the syntax error was the result of confusion between the assignment operator (=) and the comparison operator (==). Python highlights the problematic code.\n\nAnother easy thing to forget is using parentheses ( ) when you really want to use square brackets [ ]. If you do make this mistake you will see the error message shown in Figure 6.4.\n\n**Figure 6.4** A Python run-time error resulting from using parentheses instead of square brackets.\n\nThis is a run-time error because it will pass the **Check Module**. However, when you run the module, it will pop this error message into the Python Shell. The good thing is it tells the offending module and line number. Unfortunately, Python doesn't use line numbers, but if you go up under the **Edit** menu in the offending module and select **Go To Line** , a small dialog will open and you can plug in the line number and it will take you to the offending line.\n\nSimilar to any testing platform or programming language, the more you use it, the better you will become. Here are a couple more algorithms in the PSB that utilize market and limit orders.\n\nIf you are entering on the close, then you do not need to use a 1 offset in your indicator calculations. Basically, you are calculating the indicator at the close and executing at the close\u2014in real time this is somewhat difficult, but if you want to test it, you can. Here is a dual moving average crossover algorithm in the PSB. For brevity's sake, only the important code snippets were included.\n\n* * *\n\n avg1 = sAverage(myClose,19,i,0)\n avg2 = sAverage(myClose,39,i,0)\n print(myDate[i],\"avg1 \",avg1,\" avg2 \",avg2)\n\n* * *\n\nNotice how a 0 is used as the offset\u2014I want to use today's data in the calculation. Since we don't have graphing capabilities, you can print right out to the Python Shell using the keyword print. Basically, put everything you want printed out in a list separated by a string or a space enclosed in quotation marks and a comma. This print statement will print out the date, the word avg1, the value of avg1, the word avg2, and the value of valu2. Here's what the printout looks like.\n\n* * *\n\n 20150429 avg1 57.15842105263158 avg2 54.38384615384615\n\n* * *\n\n* * *\n\n #Long Entry Logic\n if (mp != 1) and avg1 > avg2:\n profit = 0\n price = myClose[i]\n ----------------\n ----------------\n #Long Exit - Loss\n if mp >= 1 and myClose[i] < entryPrice[-1] - stopAmt and barsSinceEntry > 1:\n price = myClose[i]\n # Short Logic\n if (mp !=-1) and avg1 < avg2:\n profit = 0\n price = myClose[i]\n ----------------\n ----------------\n # Short Exit Loss\n if mp <= -1 and myClose[i] >= entryPrice[-1] + stopAmt and barsSinceEntry > 1:\n price = myClose[i]\n\n* * *\n\nThe only problem with this logic is that the system gets right back in the next bar after a money management exit if the moving averages are still aligned. Other testing software might get right back in at the same price it exits if the software allows multiple entries on a single bar. If you want to force a new crossover, then just add these lines:\n\n* * *\n\n prevAvg1 = sAverage(myClose,19,i,1)\n prevAvg2 = sAverage(myClose,39,i,1)\n avg1 = sAverage(myClose,19,i,0)\n avg2 = sAverage(myClose,39,i,0)\n\n* * *\n\nYou create two new variables and assign them the moving average values using an offset of 1. **PrevAvg1** and **prevAvg2** are the moving averages from yesterday. Your long and short entries should look something like this:\n\n* * *\n\n #Long Entry\n if (mp != 1) and avg1 > avg2 and prevAvg1 < prevAvg2:\n price = myClose[i]\n #Short Entry\n if (mp !=-1) and avg1 < avg2 and prevAvg1 > prevAvg2:\n price = myClose[i]\n\n* * *\n\nNotice how the comparison of the prior day's moving average values is incorporated in the logic. Yesterday's **prevAvg1** must be less than yesterday's **prevAvg2** and today's **avg1** must be greater than today's **avg2** \u2014a crossover. There are a few different ways you could accomplish this, but until you become more comfortable with Python, the PSB, and lists, I would suggest simply offsetting the indicators to get the values you need. This is highly inefficient, but I don't think, unless you are doing it a lot, you will see a degradation in performance.\n\nIf you are using limit orders, just make sure you test the worst-case scenario. Most limit orders are not executed unless the price penetrates and trades one tick through the limit price. So you know how it important it is to use **> =** and **< =** in your price comparisons for stop orders. In limit orders forget the **=** sign. Like this:\n\n* * *\n\n #Long Exit - Profit\n if mp >= 1 and myHigh[i] > entryPrice + profAmt and barsSinceEntry > 1:\n price = max(myOpen[i],entryPrice + profAmt)\n tradeName = \"L-Prof\"\n\n* * *\n\nUsing just the > sign informs the PSB to make sure the market action penetrates the **entryPrice + profAmt**. In reality, there is a chance that a limit order will be filled if the order is touched. But we always want worst-case scenario when developing a trading algorithm. There is a bunch more Python code in the appendix and a few tutorials on the website. This version of the PSB is really in its infancy. I will continue to enhance it into the future by including some basic graphing utilities and loading it into a more sophisticated IDE.\n\n## Summary\n\nI love Python, and it really is a great language for quants and quant wannabes. It is the language to learn if you are new to programming. You will hear things out there about how it is inferior to C# and other faster languages. Unless you are an HFT trader, don't take these criticisms seriously. Others may complain that Python is not a purely objective language due to its deviations from the philosophy of \"OO.\" I look at Python as means of getting something done quickly and accurately. Traders need to concern themselves with trading concepts more so than programming theory.\n\n# Chapter 7 \nAn Introduction to EasyLanguage\n\nTradeStation has come a long ways from its early days, when it was known as SystemWriter. TradeStation, just like AmiBroker, is a complete testing and trading platform. The main difference between the two is you must use TradeStation's data servers and TradeStation's clearing services if you want to automate your trading algorithm. TradeStation is one of the most used trading platforms currently. You will find it in large hedge funds and CTAs as well as on the computers of smaller retail traders. Most system vendors have a TradeStation-compatible version of their software, because of its far reach. You don't have to trade through TradeStation's clearing services to use TradeStation. Many TradeStation users lease the software and data and then execute through their own broker. The beauty of trading through TradeStation is you can get the platform for free if you trade enough to meet a certain threshold. Else you will need to lease the TradeStation software for $249 per month. The supplementary products **RadarScreen** and **Portfolio Maestro** require additional fees.\n\nI have used TradeStation for the last 25 years and have written a book on using it to develop trading systems ( _Building Winning Trading Systems with TradeStation_ ). The latest version is 9.5, the culmination of three decades of hard work. The online community, just like AmiBroker's, is extremely large and many programming questions can usually be found with a quick Google search. In this chapter I will discuss TradeStation's development environment (TDE) and **EasyLanguage**.\n\n## TradeStation IDE\n\nTradeStation has beautiful charts and a huge library of indicators and drawing tools. Technicians love this interface. Chart creation is very simple and since TradeStation uses its own data servers, database management is not an issue. You log on, log in, and the data is but a few keystrokes away. This tight integration is one of the things that make TradeStation so popular. The other thing that makes TradeStation so good is EasyLanguage (EL). EL is similar in concept to AmiBroker's AFL and the code that makes up the Exel and Python backtesters that we have discussed.\n\nThe **TradeStation Development Environment** (TDE) can run independent of TradeStation 9.5 and you can launch it by finding it under the start menu or double-clicking its icon. This is helpful sometimes when you simply want to modify some code or start a new strategy or analysis technique and don't need to see the results of your work. However, if you do want to see the results of your coding instantaneously, then you should have both running. If you have TradeStation, you can follow along with this tutorial. If not, you can still follow along to see if TradeStation and EasyLanguage might fit your testing\/trading needs. Let's launch TradeStation 9.5. For this exercise, let's go ahead and log on by typing in your UserName and Password. Your screen should look somewhat similar to Figure 7.1.\n\n**Figure 7.1** The TradeStation home screen.\n\nInside this figure you should see a small tab labeled **TradingApps**. Click on the tab and another window like the one in Figure 7.2 will open up.\n\n**Figure 7.2** TradeStation's trading apps.\n\nSource: TradeStation\n\nThis window shows all the additional trading tools that have been turned on in your TradeStation platform. The one we are interested in right now is the button labeled **EasyLanguage**. Click it and you should be transferred over to the TDE. Check to make sure your screen looks like Figure 7.3.\n\n**Figure 7.3** The initial screen of the TradeStation Development Environment.\n\nWith version 8.8, TradeStation finally developed a powerful IDE. It is now similar in capabilities to other professional program authoring tools. If you went through Chapter 4, you will also notice a very close similarity to the AFL editor. Here is a quick tutorial on the editor.\n\nAn impressive feature of this editor is the ability to quickly and easily move from the source code of one program to another. When you open to edit more than one analysis technique, each program or file is opened underneath its own tab very similar to the way Microsoft Excel uses tabs for different worksheets. This is a nice feature because it makes copying existing code from one **Strategy** , **Function** , **Indicator** , or **Paintbar** to another very easy. As you have seen thus far in the book, building trading algorithms is done by extending existing code. After programming for a while, you will develop a library of ideas that you use and reuse again and again. So it's nice to be able to program a new idea with bits and pieces of old ideas. The multiple-tab concept makes this much simpler.\n\nThe TDE also incorporates the idea of **Outlining**. We touched on this in Chapter 4 on AmiBroker very briefly when we switched to **loop programming** mode. If you skipped that chapter or want a refresher, just follow along. **Outlining** is a feature where blocks of source code can be grouped together to make readability much easier. This also helps make programs much more modular. Let's play around with the EL Editor a bit. If you haven't downloaded the companion EL code for this book, it would be advisable to do so now. If you need help, go to the TradeStation appendix and follow the instructions. The EL Editor should still be open from our previous exercise. If not, then go ahead and launch it. From the **File** menu, select **Open** and when the **Open Easy Language Document** dialog box appears select **Strategy** in the **Select Analysis Type** drop-down menu. Your screen should look like the one in Figure 7.4.\n\n**Figure 7.4** The EasyLanguage editor in the TradeStation Development Environment.\n\nIf you have imported the companion code properly, select **MyMeanReversion1** strategy and click **OK**. The following code listing should now be on your screen.\n\n* * *\n\n {This algorithm trades in the direction of\n the longer term trend but buys\/shorts on dips\n and rallies. The indicator BollingerB returns\n the location of the current bars close in relation\n to the 5-bar Bollinger Band. If the trend\n is up and the current close is near the bottom\n BBand it will buy. If the trend is down and the\n close is near the upper BBand it will Short.}\n Inputs:Length(5),mmStop(2000),triggerVal(0.25),triggerSmooth(3);\n Vars: myBollingerB(0);\n myBollingerB = BollingerB(c,5,1,-1);\n If MarketPosition = 0 and close > average (close,200) and\n average(myBollingerB,triggerSmooth) < triggerVal then buy(\"LongReversion\") next bar at market;\n If MarketPosition = 0 and close < average (close,200) and\n average(myBollingerB,triggerSmooth) > 1 - triggerVal then sellShort(\"ShortReversion\") next bar at market;\n If marketposition = 1 then\n begin\n If myBollingerB > 1 - triggerVal then sell(\"L-Exit\") next bar at market;\n If c <= entryPrice - mmStop\/BigPointValue then sell(\"MML-Exit\") next bar at market;\n end;\n If marketposition = -1 then\n begin\n if myBollingerB < triggerVal then buyToCover(\"S-Exit\") next bar at market;\n if c >= entryPrice + mmStop\/BigPointValue then buyToCover(\"MMS-Exit\") next bar at market;\n end;\n\n* * *\n\nA portion of the strategy or algorithm is shown in Figure 7.5.\n\n**Figure 7.5** The algorithm with a single, complete portion of the strategy marked.\n\nYou can easily see how the blocks of code are outlined. There's a small box with a \"-\" symbol and a vertical line connecting the related block of code together. Outlining also allows you to hide the blocks of code if you wish to do so, again adding to the readability of the code. You can hide the block of code that is being outlined by simply clicking on the small box with the dash in it. This is a feature I would love to have in VBA and Python's IDLE.\n\nEL has a huge library of reserved words, and it is very difficult if not impossible to remember them all. The EL Editor has a really cool feature called _autocompleting_. Let's say you want to code an idea that incorporates an average true range calculation and you can't remember the name of the function that does the calculation. You could, of course, stop what you are doing and go to HELP and look up the function. However, this is time consuming, so the EL Editor monitors what you are typing and provides all the possible reserved words that might match what has thus been typed. In the case of our example, all you need to do is type what you might think is the name of the function and the list appears. By typing \"av\" the list pops up and places you at the word _average_. You can simply scroll down to find the function **AvgTrueRange**. Let's practice this. Go to the EL Editor and new line of code at the very bottom of the **MyMeanReversion1** strategy. Start typing \"av\" and see what happens. You should see something very similar to what is in Figure 7.6.\n\n**Figure 7.6** The EasyLanguage editor monitors what you are typing and provides likely functions.\n\nScroll down and select **AvgTrueRange** and it will be inserted into your code. Now go back and delete it. Keep the EL Editor open; we will be back with it shortly.\n\n## Syntax\n\nThe syntax of EasyLanguage is very similar to other programming languages, but there are a couple of differences in how remarks are demarked and the use of SKIP words:\n\n * _Remarks or comments_. Words or statements that are completely ignored by the compiler. Remarks are placed in code to help the programmer, or other people who may reuse the code, understand what the program is designed to do. Double forward slashes \/\/ informs the EasyLanguage compiler that anything that follows is a comment. The double forward slashes can be used anywhere within a line. The curly left bracket { and curly right bracket } are used for multiline commentary. The { opens the remarks and } closes the remarks block. Anything inside { --- } is ignored by the computer.\n * _SKIP words_. Words used to help EasyLanguage look more like English than a programming language. Here is a list: **an** , **at** , **by** , **does** , **is** , **of** , **on** , **than** , **the** , and **was**.\n\nEasyLanguage is the medium used by traders to convert a trading idea into a form that a computer can understand. Fortunately for nonprogrammers, EasyLanguage is an extremely high-level language; it looks like the written English language. It is a compiled language; programs are converted to computer code when the programmer deems necessary. This is different from VBA and Python. The compiler then checks for syntactical correctness and translates your source code into a program that the computer can understand. If there is a problem, the compiler alerts the programmer and sometimes offers advice on how to fix it. This is different from a translated language, which evaluates every line as it is typed.\n\nUnlike AmiBroker's AFL, VBA, and Python, EL requires all variables names to be declared\/defined prior to use. The declaration statement defines the initial value and data type of the variable. In a compiled language, the compiler needs to know how much space to reserve in memory for all variables. The following code is a complete EasyLanguage program.\n\n Vars: mySum(0),myAvg(0);\n mySum = High + Low + Close;\n myAvg = mySum\/3 ;\n\nThe **Vars** : (or **Variables** :) statement tells the computer what variables are being declared and initialized. We declare the variables by rsimply listing them in the **Vars** statement and initialize them by placing an initial value in parentheses following the variable name. In this case, **mySum** and **myAvg** are to be equal to zero. EasyLanguage is smart enough to realize that these variables should be of the numeric data type, since we initialized them with numbers. Variable names should be self-descriptive and long enough to be meaningful. Which of the following is more self-explanatory?\n\n mySum = High+Low+Close; or k = High + Low + Close;\n myAvg = mySum\/3; or j = k\/3;\n BuyPt = Close + myAvg; or l = Close+j;\n\nVariables of Boolean and string types are declared in a similar fashion.\n\n Vars: myCondition(false),myString(\"abcdefgh\");\n\nThe variable **myCondition** was initialized to **false**. The word _false_ is a reserved word that has the value of zero. This word cannot be used for any other purpose. The variable **myString** was initialized to \"abcdefgh.\" Sometimes you will need to use a variable for temporary purposes, and it is difficult to declare and initialize all of your variables ahead of time. In the case of a temporary variable (one that holds a value for a short period of time), EasyLanguage has already declared and initialized several variables for your use; **value0** through **value99** have been predefined and initialized to zero and are ready for usage in your programs. The following is a complete EasyLanguage program as well:\n\n value1 = High + Low + Close;\n value2 = (High + Low)\/2.0;\n\nNotice that there isn't a **Vars** statement. Since **value1** and **value2** are predefined, the statement isn't needed. You have probably noticed the semicolon (;) at the end of each line of code. The semicolon tells the compiler that we are done with this particular instruction. Another similarity with **AFL**. In programming jargon, instructions are known as statements. Statements are made up of expressions, which are made up of constants, variables, operators, functions, and parentheses. Some languages need a termination symbol and others do not. **EL** and **AFL** need the statement termination symbol. Remember to put a semicolon at the end of each line to prevent a syntax error.\n\n**Inputs** are similar to variables. They follow the same naming protocol and are declared and initialized, too. However, an input variable remains constant throughout an analysis technique\u2014it cannot be changed. An input cannot start a statement (a line of instruction) and cannot be modified within the body of the code. One of the main reasons for using inputs is that you can change input values of applied analysis techniques without having to edit the actual EasyLanguage code. Input variables are the interface between the algorithm and user. Inputs would be perfect for a moving average indicator. When you plot this indicator on a chart, you simply type in the length of the moving average into the input box of the dialog. You don't want to have to go back to the moving average source code and change it and then verify it. **Inputs** are the same as **Param** in AFL, by the way. Also, when used in trading strategies, inputs allow you to optimize your strategies. Optimization was touched upon in the AmiBroker chapter and will be thoroughly discussed in Chapter 8. EL inputs serve two purposes: user and optimization interface.\n\nNotice how inputs and variables are declared in similar style.\n\n Inputs: length1(10),length2(20),flag(false);\n Vars: myLength1(10),myAvgVal(30);\n\nHowever, notice how they are used differently in coding.\n\n* * *\n\n _Variables_\n\n* * *\n\n myLength1 = myAvgVal + myLength1; {Correct}\n\n* * *\n\n _Inputs_\n\n* * *\n\n length1 = myAvgVal + length1; {Incorrect}\n myLength1 = length1*2; {Correct}\n\nVariables can start a statement and can be assigned another value. Since inputs are constants and cannot be assigned new values, they cannot start a statement.\n\nIn a strongly typed language, such as C, Pascal, or C++, if you assign a real value such as 3.1456 to an integer typed variable, the decimal portion is truncated and you end up with the number 3. As we all know, precision is important when it comes to trading, so EasyLanguage includes only one Numeric type. All numbers are stored with a whole and a fractional part. In the old days when CPUs were slow, noninteger arithmetic took too much time and it was advised to use integer variables whenever possible.\n\nLike AFL, the overall purpose of EasyLanguage is to translate an idea and perform an analysis on a price data series over a specific time period. You can access the different data elements by using the keywords shown in Table 7.1.\n\n**Table 7.1** EasyLanguage Keywords and Abbreviations\n\n**Reserved Word** | **Abbreviation** | **Description** \n---|---|--- \nDate | D | Date of the close of the bar. \nTime | T | Time as of the close of the bar. \nOpen | O | Open price of the bar. \nHigh | H | High price of the bar. \nLow | L | Low price of the bar. \nClose | C | Close price of the bar. \nVolume | V | Number of contracts\/shares traded. \nOpenInt | OI | Number of outstanding contracts.\n\nIf you wanted to determine that the closing price of a particular instrument was greater than its opening price, you would simply type: **Close** > **Open** , or **C** > **O**. The beauty of any trading platform's scripting languages is their ability to have all of the data of an instrument at your fingertips. The reserved words that we use to access the different prices of the current bar are also used to access historical data. You do this by adding an index to the reserved word. The closing price of yesterday would be: **Close** [1]. The closing price two days ago would be: **Close** [2], and so on. The number inside the bracket determines the number of bars to look back. The larger the number, the further you go back in history. If you wanted to compare today's closing price with the closing price 10 days prior, you would type: **Close** > **Close** [10].\n\nBefore we move on, we should discuss how TradeStation stores dates and times. January 1, 2001, is stored as 1010101 instead of 20010101 or 010101. When the millennium changed, instead of incorporating the century into the date, TradeStation simply added a single digit to the year. The day after 991231 was 1000101 according to TradeStation. Time is stored as military time. For example, one o'clock in the afternoon is 1300 and one o'clock in the morning is 100.\n\nAfter that brief introduction to the EasyLanguage, let's return to the EL Editor and take a look at **myMeanRev1** algorithm.\n\nStart off by reading the first few lines of code. You will notice that these lines are comments because the comments are preceded and followed by the left and right curly brackets, {}. This is your typical mean reversion system and is designed to trade those markets that demonstrate a mean reversion propensity. All markets demonstrate mean reversion characteristics at some time or another, but the stock indices seem to revert to the mean more frequently than the others.\n\nThe next lines are the **Inputs** and **Variables** used in the algorithm. The user can change the input values through the **Format Analysis Techniques and Strategies** dialog window. This window is brought up once you have applied the **Strategy** to a chart. If you like, go ahead and create a **Chart Analysis** of daily **ES** (emini-S&P) going back 10 years. Once the chart has been populated with data, go up under the **Insert** menu and select **Strategy** (see Figure 7.7).\n\n**Figure 7.7** How to apply a strategy to your chart.\n\nSource: TradeStation\n\nAfter selecting **MyMeanReversion1** from the list of **Strategies** , your chart window should contain some trades like the ones shown in Figure 7.8. Now we can access the **Inputs** and change them if we like by right-clicking the chart and selecting **Format Strategies**. A dialog similar to Figure 7.9 will open.\n\n**Figure 7.8** A reversion analysis strategy shown on a chart.\n\nSource: TradeStation\n\n**Figure 7.9** How to change the inputs and adjust your strategy.\n\nAnother dialog will follow once you select **Format** (Figure 7.10.). Here you can select any of the four **input** variables. Go ahead and select **mmStop** and change it to 3000. Then click **OK** and then **Close**. That's all there is to changing the **inputs** from the user's interface. You can always change them programmatically from the EL Editor. The next line is where you must define any variables you may use later in your code. If you have properly converted your trading idea into either a FC or FSM diagram and then into pseudocode, then you will know ahead of time the number and names of your variables. It doesn't matter how well thought out your pseudocode is; you will almost always come across the need for additional variables. Don't worry; you can always go back to the **Vars** or **Inputs** and add more variable names. Here the only variable name that will be used is **myBollingerB** , and it will be initially set to zero.\n\n**Figure 7.10** The four input variables to adjust the mean reversion strategy.\n\nContinuing on through the code, the first order of business is the assignment of **myBollingerB**. **myBollingerB** is assigned the output of the function **BollingerB**. This function requires four parameters or arguments: price data array, lookback period, the number of **+** standard deviations, and the number of negative standard deviations. In our example, we are using the closing prices, a five-bar lookback, and positive one and negative one standard deviations.\n\n* * *\n\n myBollingerB = BollingerB(c,5,1,-1);\n\n* * *\n\nThe **BollingerB** function returns a value between a negative value and a positive value and 1.00 which indicates the location of the current bar's close in relation to the upper and lower Bollinger Bands. The lower the value, the closer it is to the lower band. The higher the value, the closer it is to the upper band.\n\n* * *\n\n If MarketPosition = 0 and\n close > average (close,200) and\n average(myBollingerB,triggerSmooth) < triggerVal then\n buy(\"LongReversion\") next bar at market;\n If MarketPosition = 0 and\n close < average (close,200) and\n average(myBollingerB,triggerSmooth) > 1 - triggerVal then\n sellShort(\"ShortReversion\") next bar at market;\n\n* * *\n\nYou might not be able to tell by this code snippet, but EL follows the bar-by-bar programming paradigm. The keyword **If** might have given you a hint, though. If you have read the chapter on AmiBroker, you know you usually don't use the keyword **If** when dealing with array programming. When you use the data arrays (open, high, low, close, volume, or opInt) without an index variable you are simply looking at the very last day of data up to that point in the master loop.\n\n**C** is the same as **C[0]**. The **[0]** is optional. Since there is an implied index, you can be assured you are not dealing with array programming. The lack of the index for the last value in the arrays makes EL look more like English. Take a look at the following line of code:\n\n* * *\n\n If close > average(c,200) then buy next bar at open;\n\n* * *\n\nDoesn't this look like English? You bet it does. Hence, the name EasyLanguage. The language is simple on the surface, but can become much more complicated as the complexity of the algorithm increases. This is a good thing\u2014EasyLanguage isn't necessarily easy, but it's not weak by any stretch of the imagination. And it's getting more powerful every year.\n\nThese lines of code direct TradeStation to check the current market position, and if it is flat, to check if today's **close** > the 200-bar **moving average** and the 3-bar **moving average** of **myBollingerB** is less than the **triggerVal**. In this example, the **triggerVal** is set to **0.2**. If the criteria are met, then a market order to buy is placed for the next bar's open. A similar criterion is used to initiate a short position on the next bar's open. The only difference is the **close** must be below the 200-bar **moving average** and the 3-bar **moving average** of the **myBollingerB** variable must be greater than 1 - **triggerVal**.\n\nThere is a lot going on with this code. Any time you use the keyword **if** it must be eventually followed by the keyword **then**. Initiating long positions requires the keyword **buy** and short position requires the keywords **sellShort**. You can give names to your entry and exit signals by following the keywords **Buy\/SellShort\/Sell\/BuyToCover** with the name of the signal enclosed within quotes and parentheses. The buy signal is this example is \" **LongReversion** \" and the short signal is named \" **ShortReversion**.\" This isn't necessary but it does help when you have multiple entry and exit signals. EL requires you to use the words **next bar** or **this bar on\/at close** whenever you direct TradeStation to initiate or liquidate an existing position. When programming in EL, think of yourself sitting in front of the computer screen right at the close of a bar. You can place a market order immediately and get filled at the current close, you can place a market order and get filled at the next bar's open price, or you can place a limit or stop order for the next bar. By limiting you from seeing the next bar (other than the open price), TradeStation eliminates all risks of \"Future Leak.\" In other words, you cannot peek into the future by looking at the next bar and make a trading decision on the current bar. Both the VBA and Python back testers allow you to do this, not in order to cheat, but to allow complete testing flexibility.\n\nTake a look at the next section of code and see if you can tell what is going on.\n\n* * *\n\n If marketposition = 1 then\n begin\n If myBollingerB > 1 - triggerVal then sell(\"L-Exit\") next bar at market;\n If c <= entryPrice - mmStop\/BigPointValue then sell(\"MML-Exit\") next bar at market;\n end;\n If marketposition = -1 then\n begin\n if myBollingerB < triggerVal then buyToCover(\"S-Exit\") next bar at market;\n if c >= entryPrice + mmStop\/BigPointValue then buyToCover(\"MMS-Exit\") next bar at market;\n end;\n\n* * *\n\nIn Python, the keyword **then** would be replaced by the colon (:). Since the code controlled by the **if** consists of more than one line of code, the keywords **begin** and **end** must be used to encapsulate the code. For every **begin** there must be an **end**. The **begin** and **end** informs the compiler that the code is related and must flow through all the lines in the block. If the current market position is 1 or long, then TradeStation in instructed to exit the long position if one of two criteria are met:\n\n 1. If myBollingerB > (1 \u2013 triggerVal) or 0.8, then the long is liquidated on the next bar's open.\n 2. If the difference between the current close price is less than the entryPrice \u2013 2000\/bigPointValue, then the long is liquidated on the next bar's open.\n\nThe short liquidation occurs in a similar manner. If myBollingerB < 0.2 or the close is greater than the entryPrice + 2000\/bigPointvalue. That's the entire mean reversion system that we introduced in Chapter 3.\n\nAnother key and cool feature of EL is that all variables are special arrays. When you declare the variable myBollingerBand in the **vars** : section, you are informing the compiler to create an array with the name **myBollingerBand**. This is a special array because you don't need to worry about keeping track of the values in the array. The value is carried over from one bar to another until it is changed. Because myBollingerBand is an array, you can access the prior bar's value by indexing the variable name. The prior bar's **myBollingerBand** value is accessed by **myBollingerBand** [1]. These variables can be referred to as bar arrays.\n\nOnce you type your code in and want to see if it **Verifies** or compiles, all you need to do is go up under the **Build** menu and select **Verify**. If all goes well, you will see this dialog (Figure 7.11).\n\n**Figure 7.11** A message confirming that your code was verified and will be recalculated based on the new inputs.\n\nIf not, then you might see what's in Figure 7.12. TradeStation is politely informing you that you have made a syntax error. If you double-click on the error, the EL Editor will take you directly to the offending line with the error. The error message also informs you of the line number. If you want the EL Editor to show line numbers, go under the **Tools** menu and select **Options**. A dialog window like the one in Figure 7.13 will open.\n\n**Figure 7.12** TradeStation lists any syntax errors it finds during verification in the bottom pane of the screen. The line number of the error is provided so you can easily find it in your code.\n\n**Figure 7.13** The EasyLanguage editor can display line numbers to make it easy to navigate your code.\n\nClick on **Line Numbers**. The EL Editor has added the capability of grouping strategies, indicators, and functions together in a neat package known as a **Project**. If you build a strategy that calls in a lot of external functions, then putting the strategy into a project makes it easier to access all the different code. Let's create a **Project**. Go under the **File** menu and go to the **Project** menu item and a hierarchical menu will open (see Figure 7.14).\n\n**Figure 7.14** To create a new project using your strategy, select Project from the File menu.\n\nThe EL Editor will ask you for a name and where you would like to save the project. Select a location on your desktop or the C:\\ drive and give your project the name **MeanReversion**. Once the project is created, a small dialog box will open with your new project name inside it. Right-click on the project name and a menu will open like the one in Figure 7.15.\n\n**Figure 7.15** How to add an existing strategy to a new project.\n\nClick on **Add Existing Item** and select **MyMeanReversion1** from **Strategies**. Close the box out and then go under the **File** menu to **Project** and select **Open Project** and select the project you just created, **MeanReversion.elx**. Click on the + beside the name **MyMeanReversion1** , and it will expand and show all the functions or dependencies included in the **Strategy** algorithm (see Figure 7.16).\n\n**Figure 7.16** All dependencies and functions are nested inside their strategy algorithm.\n\nThis is just neat way to keep track of all the code connected to a particular project and is a relatively new feature of the EL Editor.\n\n## Samples of EasyLanguage\n\nHere is a simple Commodity Channel Index (CCI) algorithm:\n\n* * *\n\n {CCI system utilizing 3 ATR Profit\n And a 1 ATR Stop}\n inputs: cciLen(20),smooth(9);\n vars: myCCIVal(0);\n myCCIVal = average(cci(cciLen),smooth);\n If myCCIVal crosses above -100 then buy this bar on close;\n If myCCIVal crosses below 100 then sellShort this bar on close;\n If marketPosition = 1 then\n begin\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close;\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close;\n end;\n If marketPosition =-1 then\n begin\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close;\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close;\n end;\n\n* * *\n\nThis algorithm covers long positions whenever the market closes above the **entryPrice** plus 3 ATRs, or when it closes below the **entryPrice** minus 1 ATR. The same technique is programmed for short trades as well. This algorithm risks one ATR to achieve three.\n\nThe following algorithm is a simple 20-day Donchian breakout that only takes trades in the direction of the 14-day slope of closing prices. The interesting part of the algorithm is found in the trade management.\n\n* * *\n\n Inputs: linearSlopeLength(14),channelLength(20);\n Inputs: atrLen(10),numAtrStop(3),numAtrProfThreshold(5), numAtrTrail(2);\n vars: buyLevel(0),shortLevel(0),maxContractPoints(0);\n buyLevel = Highest(High[1],channelLength);\n shortLevel = Lowest(Low[1],channelLength);\n if marketPosition <> 1 and linearRegSlope(c,linearSlopeLength) > 0 then\n Buy(\"BuyLevelEntry\") tomorrow at buyLevel stop;\n maxContractPoints = maxContractProfit \/ bigPointValue;\n If marketPosition = 1 then\n begin\n sell(\"L-ATR-Stop\") next bar at entryPrice-numAtrStop * avgTrueRange(atrLen) stop;\n if maxContractPoints >= numAtrProfThreshold * avgTrueRange(atrLen) then\n begin\n value1=entryPrice + (maxContractPoints-numAtrTrail * avgTrueRange(atrLen));\n sell(\"L-Trail-Stop\") next bar at value1 stop;\n end;\n end;\n if marketPosition <>-1 and linearRegSlope(c,linearSlopeLength) < 0 then\n Sellshort(\"ShortEntryLevel\") tomorrow at shortLevel stop;\n If marketPosition =-1 then\n begin\n buyToCover(\"S-ATR-Stop\") next bar at entryPrice+numAtrStop *avgTrueRange(atrLen)\n stop;\n if maxContractPoints >= numAtrProfThreshold * avgTrueRange(atrLen) then\n begin\n value1 = entryPrice - (maxContractPoints-numAtrTrail * avgTrueRange(atrLen));\n buyToCover(\"S-Trail-Stop\") next bar at value1 stop;\n end;\n end;\n\n* * *\n\nThis algorithm incorporates a volatility-based protective and trailing stop. EL keeps track of the maximum profit a position achieved during the duration of a trade, and stores it in the keyword **maxContractProfit**. The profit is expressed in terms of dollars, and to get it in terms of points you have to divide by the **bigPointValue** of the underlying instrument. If the **maxContractProfit** achieves a level equal to, in this case, five ATRs, then a trailing stop is engaged to trail the highest point in the trade by two ATRs. If you don't want to use volatility in the stop calculations, you can use dollars. Here is the snippet of the code that engages the trailing stop:\n\n* * *\n\n if maxContractPoints >= numAtrProfThreshold* avgTrueRange(atrLen) then\n begin\n value1=entryPrice + (maxContractPoints-numAtrTrail * avgTrueRange(atrLen));\n sell(\"L-Trail-Stop\") next bar at value1 stop;\n end;\n\n* * *\n\nIf the **maxContractPoints** is greater than the threshold profit level, then the trailing stop level is calculated using the following formula:\n\nvalue1 = entryPrice + (Highest level during trade \u2013 2*ATR)\n\nAs the market continues to climb, so does value1 staying 2 ATR below the highest point achieved. Once the market stops climbing, value1 locks into place and waits for the market to take out the trailing stop.\n\nOnce you master just the fundamentals of programming and a few concepts that are intrinsic to a particular language, you then have most of the tools to test or program any trading idea. Practice makes perfect, so don't just stop after you have programmed your initial trading idea\u2014keep going because I guarantee your creativity won't stop.\n\n## Summary\n\nThe objective of this chapter was to introduce the fundamentals necessary to take a trading idea and program it in EasyLanguage. Along the way we discussed data types, expressions, and statements. EL requires all variables to be declared before use and we reviewed how this is done. The use of inputs, built-in function calls, and how to verify your code was explained as well. The EL Editor is a very powerful tool and is the center of your creativity. TradeStation and its programming language, EasyLanguage, provides a very tightly integrated trading environment that can facilitate the programming of any trading idea. Learning this powerful language is best accomplished by examining as much code as you can. I have used EL for 25 years and I am still learning.\n\nI will leave you with the finite state machine (FSM) code from Chapter 1.\n\n* * *\n\n {Finite State Machine\n Pivot Point Example from Chapter 1.\n The switch case structure is used in place of\n if-then constructs. This increases the readability\n considerably.}\n vars:state(0),maxRsi(0),state1BarCount(0),state1Price(0), state3Price(0),state1BarNumber(0);\n vars: isHiPivot(false);\n isHiPivot = h[1] > h and h[1] > h[2];\n Switch(state)\n begin\n case(0):\n begin\n if isHiPivot then\n begin\n state = 1;\n state1Price = h[1];\n state1BarNumber = barNumber;\n print(date,\" State 1 : \",state1Price, \" \",state1BarNumber);\n value1 = text_new(date[2],time,h+20,\"S1\");;\n end;\n end;\n case(1):\n begin\n if h > state1Price then state1Price = h;\n if low < state1Price * .98 then\n begin\n state = 2;\n print(date,\" State 2 :\",low);\n value1 = text_new(date[1],time, l-10,\"S2\");\n text_setColor(value1,red);\n end;\n end;\n case(2):\n begin\n if isHiPivot and h[1] > state1Price then\n begin\n state = 3;\n state3Price = h;\n print(date,\" State 3 :\", state3Price);\n value1 = text_new(date[2],time, h+20,\"S3\");;\n text_setColor(value1,yellow);\n end;\n end;\n case(3):\n begin\n if h > state3Price then state3Price = h;\n if l < state3Price * .98 then\n begin\n buy this bar on close;\n print(date,\" accept state : \",l);\n value1 = text_new(date[1],time, l-10,\"S4\");;\n text_setColor(value1,GREEN);\n state = 0;\n end;\n end;\n end;\n If barNumber - state1BarNumber > 30 then state = 0;\n Sell next bar at lowest(l,60) stop;\n\n* * *\n\n# Chapter 8 \nGenetic Optimization, Walk Forward, and Monte Carlo Start Trade Analysis\n\n## Utilizing TradeStation and AmiBroker\n\nBoth TradeStation and AmiBroker software includes two very powerful tools that can be utilized to help create robust trading algorithms. If you have used TradeStation or AmiBroker to develop trading algorithms but have not taken advantage of genetic or walk-forward optimization, this chapter will hopefully provide enough information to help enhance your research and unlock the potential of these powerful tools. These tools have been a part of both platforms for several years, but through my observations of other users they have been either ignored or underutilized. Users often note these stumbling blocks:\n\n * They are hard to understand.\n * They are hard to implement.\n * They lead to over-curve-fitting.\n\nThe objective of this chapter is to explain that a computer science degree is not necessary to understand these tools; in some scenarios their use is absolutely necessary, they are very simple to use, and with proper application a user can make sure over-curve-fitting does not take place. Since I am somewhat of a newbie to AmiBroker and in an attempt to cut down on redundancy, a good portion of the concepts in this chapter will be illustrated with TradeStation's tools. An understanding of TradeStation, some EasyLanguage, and input optimization is assumed. As you will see in the latter part of the chapter, the ideas and algorithms will be translatable to AmiBroker and AFL.\n\nThe first part of this chapter explains the concept of a genetic algorithm, proceeds to build one, and then shows how they can be used to optimize a trading algorithm. The genetic algorithm development part is a little longer and requires a close examination. Much of this discussion, including examples and processes, was taken directly from Denny Hermawanto's excellent paper titled, \"Genetic Algorithm for Solving Simple Mathematical Equality Problem.\" Out of all the research used in the writing of this chapter, Hermawanto's description of genetic algorithms was considered one of the easier to understand and implement. Understanding what makes up a genetic algorithm is not necessary to use one. However, even a slight understanding of how one works will eliminate the hesitation of using it and eliminate its \"voodoo\" factor.\n\nThe second part of the chapter describes how a trading algorithm can be automatically reoptimized periodically using the walk-forward optimizer (WFO) in concert with genetic optimization. In addition to changing parameters periodically based on algorithm performance going forward in time, the WFO also creates a report that indicates the degree of the trading algorithm's robustness. In other words, what is the probability of the algorithm continuing to work?\n\n### Genetic Algorithms: What Are They?\n\nThe first question that needs to be answered is, Why use genetic algorithms (GA) in the first place? The same question concerning walk-forward optimization (WFO) will be answered in the second part of this chapter. TradeStation and AmiBroker already have exhaustive search (ES) optimization engines built into their platforms. In this chapter, the words _searching_ and _optimizing_ will be used interchangeably. The ES optimization engine doesn't use any sophistication in its search process, just brute force. Why not just use this brute force approach if it looks at every possible combination of variables and no stone is left unturned? It is true that this feature is very powerful and can fulfill a good portion of a user's optimization needs. However, unlike genetic algorithms, there is a limit to the number of variables (inputs) and their respective iterations that can be optimized in a sequential manner.\n\nGA has limitations as well, but they are very large\u2014large in the sense that a super-large amount of data would be necessary to limit their effectiveness. The major limitation to a brute force approach is, of course, time. Even with today's superfast processors, searching a large search space is extremely time sensitive. Imagine a trading algorithm (TA1) that has five different parameters that can be optimized across 50 different values. Assuming a brute force optimization and three seconds to complete each iteration, it would take the computer almost 30 years to complete or span the entire search space ( _search space_ and _optimization range_ are also interchangeable terms). Here is the math behind the time needed to complete this task:\n\nThis example is an exaggeration, but it shows multiple parameter optimizations can be very time consuming. Figure 8.1 shows how quickly the search space grows as the number of iterations increase for each of the five parameters. This is where artificial intelligence (AI) comes into play; AI uses brains over brawn. In the above example, AI can shrink the overall search space by eliminating some values of each parameter that do not lead to a favorable outcome. In doing so, it cuts down the number of total iterations, and less iteration means less time.\n\n**Figure 8.1** Iteration growth rate of five parameters.\n\nThe first step in the process of incorporating these tools into a trader's algorithm development is to understand the basic foundations of GA. Don't let the words _genetic_ or _algorithms_ scare you away. They are simply terms to explain how a solution to a problem can be quickly and solidly uncovered. As we already know, probably too well, an algorithm is just a set of rules one follows to find a solution to a problem. Genetic refers to the biological process of evolution through reproduction, mutation, and survival of the fittest. Remember time is of the essence but so is a good answer and this type of algorithm provides quick yet robust solutions. Computer software and biology may seem like strange bedfellows but their synthesis makes up a large portion in the study of AI.\n\nJohn Holland's 1975 book titled _Adaptation in Natural and Artificial Systems_ is the bible on GA and his work has paved the way for a majority of researchers in this field. Holland has stated,1 \"Living organisms are consummate problem solvers. They exhibit a versatility that puts the best computer programs to shame.\"\n\nComputer speed and power has come a long way since 1975 and you may think these biologically based optimization\/search algorithms have become obsolete. The exponential growth rate of multiple variable optimizations proves that this is not the case. Also humans are constantly creating more and more complex problems that continually exceed our technology. The relationship between GA and computers is as close as it has ever been.\n\nThe principles that make up GA, if taken one concept at a time, are easy to understand. The combining of these concepts into a complete algorithm can be daunting if each piece is not broken down. I programmed these concepts in a modular manner using VBA for Excel in a very small amount of time. This same software was used to illustrate the concepts and solve the initial problem in this first part of the chapter. Snippets of VBA code will be sprinkled throughout the first part of the chapter to help explain the most important components of genetic algorithms.\n\n## Computers, Evolution, and Problem Solving\n\nGenetic algorithms borrow the following concepts from biology:\n\n * Population and generations\n * Selection of the fittest\n * Reproduction\n * Mutation\n\nAll these terms are easily understood in a biological framework but may not seem initially translatable into a computer\/software\/math paradigm. The application of these concepts to solve a complex problem can be difficult but we need not worry ourselves with this because we know our objective with TradeStation, AmiBroker, or Excel\u2014building the world's best trading algorithms! However, a simple problem needs to be solved so we can demonstrate the eloquence of GA. The ideas and processes that will be discussed for applying a GA to finding a solution to a simple equation were derived directly from Denny Hermawanto's paper titled \"Genetic Algorithm for Solving Simple Mathematical Equality Problem.\" The problem that we will be solving utilizes this very simple equation:\n\nThis equation involves four unknowns and multiple solutions and can be easily solved by trial and error. We could simply set , _,_ and equal to zero and set equal to 20 and be done with it. Remember, this is an oversimplified problem to demonstrate the four core concepts of GA.\n\n## Population\n\nThere are four variables in our equation so continuing to borrow from biology let's create six chromosomes consisting of four values or genes that will be substituted into the variables _,_ _,_ _,_ and . Unlike real chromosomes, these will simply be placeholders for the four different values of the variables (genes). Figure 8.2 illustrates our six amoeba-looking genes.\n\n| | | _Genes_ \n---|---|---|--- \n_Generation 1_ : | _Chromosome(0)_ | _=_ | _[10,11,20,19]_ \n| _Chromosome(1)_ | _=_ | _[13,08,15,20]_ \n| _Chromosome(2)_ | _=_ | _[00,20,05,09]_ \n| _Chromosome(3)_ | _=_ | _[07,27,05,14]_ \n| _Chromosome(4)_ | _=_ | _[10,30,30,04]_ \n| _Chromosome(5)_ | _=_ | _[16,05,13,28]_\n\n**Figure 8.2** An illustration of our chromosomes with different genetic values.\n\nSo the population will consist of six chromosomes that have four different genes that can be swapped or mutated. Why six chromosomes instead of four, you may ask? Just be patient; we will get to that. The initial population of chromosomes will be generated using a random number generator (RNG). Each chromosome will be defined by its genetic value, and these are the values that will be randomized. Values between 0 and 30 for each gene will be initially generated in a random fashion. You will soon discover that GA relies heavily on random numbers. This is yet another similarity with nature\u2014randomness. Here is the initial population generated by the VBA software and its RNG:\n\n## Initial Population Setup Using VBA Excel\n\n 'All Lines starting with single quote is a comment\n 'Random variables into each chromosome's genes\n 'Numbers range between 0 and 30\n 'Chromos will be represented by a table\/matrix\n 'The first index in the chromo table will be row #\n 'The second index in the chromo table will be column #\n 'Excel's RNG is invoked by using the Rnd function call\n 'Int ((upperbound - lowerbound + 1) * Rnd + lowerbound)\n Randomize '<-- must use this to get different numbers\n For i = 0 To 5 ' Six Chromos\n For j = 0 To 3 ' Four Genes\n chromo(i, j) = Int((30 - 0 + 1) * Rnd + 0)\n Next j\n Next i\n\nHow good or fit is this population? Fitness is determined by how close each chromosome comes to providing a solution to our equation. Remember, this is a very simple problem, but these ideas are easily scalable to problems involving extreme complexity. Calculating fitness is quite easy; simply plug in the chromosomes' genes (values) for a, b, c and d. In chromosome (0) its fitness is determined by: . The solution we are seeking is 40 so this fitness doesn't seem to be that good. However, each chromosome's fitness is relative to all the other chromosomes.\n\n_Fitness 1_ : | _Chromosome(0)_ | _=_ | _111_ \n---|---|---|--- \n| _Chromosome(1)_ | _=_ | _94_ \n| _Chromosome(2)_ | _=_ | _64_ \n| _Chromosome(3)_ | _=_ | _90_ \n| _Chromosome(4)_ | _=_ | _164_ \n| _Chromosome(5)_ | _=_ | _93_\n\n## Testing Fitness of Chromosomes Using VBA Excel\n\n 'Equation is : a + 2b + 3c + d = 40\n 'a coefficient = Cell(3,3)\n 'b coefficient = Cell(3,4)\n 'c coefficient = Cells(3,5)\n 'd coefficient = Cells(3,6)\n 'the summation of the equation is in Cells(3,7)\n For generation = 1 To 100 ' total generations\n For i = 0 To 5 'Six Chromos\n FObj(i) = 0\n For j = 0 To 3 ' Four Genes\n 'Calculate each expression in equation and accumulate\n If j = 0 Then FObj(i) = Cells(3, 3) * chromo(i, j)\n If j = 1 Then FObj(i) = FObj(i) + Cells(3, 4) * chromo(i, j)\n If j = 2 Then FObj(i) = FObj(i) + Cells(3, 5) * chromo(i, j)\n If j = 3 Then ' Test the summation against 40\n FObj(i)=Abs((FObj(i)+Cells(3, 6)*chromo(i,j)) -Cells(3,7))\n 'if summation = 40 then solution found\n If (FObj(i) = 0) Then foundSolution = i\n End If\n Next j\n Next i\n\nIf we rank the chromosomes in order of fitness, then we would have the following:\n\n_Chromosome(2)_ | = | _64\u2014closest to the solution (24 away)_ \n---|---|--- \n_Chromosome(3)_ | = | _90\u2014second closest (50 away)_ \n_Chromosome(5)_ | = | _93_ \n_Chromosome(1)_ | = | _94_ \n_Chromosome(0)_ | = | _111_ \n_Chromosome(4)_ | = | _164_\n\n## Selection\n\nNow that we have our initial population and the respective chromosome fitness, we can select the chromosomes that should be carried forward and used for reproduction and mutation. It's easy to see that the top four ranking chromosomes should be selected because they are closer to our solution than the last two (the absolute difference between the chromosome fit score and 40, our solution, is smaller). However, the computer makes the decisions and it makes its selection based on probabilities. This task is accomplished by converting each chromosome's fitness in terms of probability. We can't make the selection decision for the computer, but we can make sure the computer understands that some chromosomes are more fit than others. If you remember probabilities from an old math or stat class, you know the basic premise: Rolling a dice once results in one out of six potential outcomes. With this in mind you have a one-in-six chance of rolling a six or a probability of 16.6666667 percent.\n\n 1. _P_ = Possible favorable outcomes \/ Potential outcomes\n 2. _P_ = 1\/6, or 16.6666667%\n\nKeep in mind probabilities are the cornerstone of GA as well as trading algorithms.\n\nOkay, now on to our selection process. Remember, we need to nudge the computer into making the right decision. The computer will, in effect, roll the dice to choose which chromosome will be carried into the next step for reproduction. If this is a random event, then how do we nudge the computer's decision? Think of a dartboard that has six slices and the slices are the same size. Now assume you train a monkey to throw darts while blindfolded at the dartboard. Also, it is important to assume he always hits the dartboard. The monkey has a one-in-six chance of hitting a particular slice. What if the slices were not the same size? Then he would have a higher probability of hitting the larger slices. This is the concept that will be used to nudge the computer's selection; the more fit chromosomes will get the bigger slices. Here again, we must let the computer decide the sizes of the slices but we can feed it a formula that will give priority to the more fit chromosomes. The first step is to calculate the fitness of each chromosome in terms of the size of the slice. This is a very simple formula as well:\n\nNotice how we use the **ABS** (absolute value) function in our formula. This function simply removes a negative sign from the difference between a chromosome's fitness and our objective of 40; we don't want to have a negative-sized slice. We subtract 40 from each chromosome's fitness because we need to put the fitness in terms of our objective; the closer we are the smaller the fitness value. Since we want to allocate a bigger slice to chromosomes that are closer to our solution we divide one by our fitness score. In doing so, we are making the size of each slice inversely proportional to the fitness score; a lower fitness value (or closer value to 40) will increase size. The number 1 is also added in the denominator to prevent division by zero; computers hate division by zero. Utilizing the above formula we come up with:\n\n**_Fitness 1 in terms of slice size:_**\n\n 1. Chromosome (0) = 1 \/ (1 + 71) = 0.01389\n 2. Chromosome (1) = 1 \/ (1 + 54) = 0.01812\n 3. Chromosome (2) = 1 \/ (1 + 24) = 0.04000\n 4. Chromosome (3) = 1 \/ (1 + 50) = 0.01961\n 5. Chromosome (4) = 1 \/ (1 +124) = 0.00800\n 6. Chromosome (5) = 1 \/ (1 + 53) = 0.01852\n\n### Converting Fitness in Terms of Slice Size\u2014Using VBA Excel\n\n 'fitness in terms slice size\n For l = 0 To 5 'calculate for each of the six chromos\n Fitness(l) = 1 \/ (1 + FObj(l))\n Next l\n\nNow that fitness has been redefined in terms of the size of the slice on the dartboard, we can now calculate the probability of each slice being hit. First off, let's calculate the total size of all slices:\n\nThe dartboard has a total size of 0.11814 units. Don't worry about the units because they are not important. Now that we know the size of the chromosomes' respective slices and we know the total size of the dartboard, we can easily calculate the probability of a dart hitting the individual slices. This is accomplished by dividing the size of each chromosome slice by the total size. The probability of each chromosome slice being hit with a blindfolded monkey are:\n\n### Calculate Probability of Being Hit by Dart\u2014Using VBA Excel\n\n 'calculate chromo probability of being hit by dart\n 'accumulate probabilities and store in bins\n cumProb = 0#\n For l = 0 To 5 'this is a lower case l not a 1\n chromoProb(l) = Fitness(l) \/ totalFitness\n cumProb = cumProb + chromoProb(l)\n chromoProbBin(l) = cumProb\n Next l\n\nNotice how the chromosome that was closest to our solution has a higher probability of being hit by a dart. Chromosome (2) covers nearly 34 percent of the dartboard.\n\nThe next thing the computer needs to do is construct the dartboard. The pie chart in Figure 8.3 is a graphical representation of how the computer would internally construct a dartboard with varying slice or sector sizes.\n\n**Figure 8.3** Chromosome dartboard.\n\n### Creating Chromosome Dartboard\u2014Using VBA Excel\n\n For l = 0 To 5\n chromoProb(l) = Fitness(l) \/ totalFitness\n cumProb = cumProb + chromoProb(l)\n 'starting at 0 degrees in the pie\/circle\n 'work clockwise defining the slices\n 'until the pie\/circle is coverd by slices\n chromoProbBin(l) = cumProb\n 'bin size = slize size\n Next l\n\nOnce the dartboard is constructed, the next step is to start randomly throwing six darts. Since blindfolded monkeys are hard to come by nowadays, the computer can easily replicate one by using our handy RNG. So let's proceed with the simulation and see where the six darts land.\n\n 1. _Dart(0) hits Slice(5)_\n 2. _Dart(1) hits Slice(1)_\n 3. _Dart(2) hits Slice(2)_\n 4. _Dart(3) hits Slice(5)_\n 5. _Dart(4) hits Slice(4)_\n 6. _Dart(5) hits Slice(2)_\n\n### Simulating a Dart-Throwing Blindfolded Monkey Using VBA Excel\n\n 'Generate 6 random numbers between 0 and 1\n 'These numbers represent the locations where\n 'the 6 darts landed\n Randomize\n For l = 0 To 5\n roulette(l) = Rnd(1#)\n Next l\n For i = 0 To 5\n whichBin = -1\n 'which slice did the dart land in?\n For k = 0 To 4\n '6 slices but only 5 bin boundaries ?\n 'if dart doesn't hit slices 1-5 then it must have hit slice 0\n If roulette(i) > chromoProbBin(k) And roulette(i) <=\n chromoProbBin (k + 1) Then\n whichBin = k + 1\n End If\n Next k\n If whichBin = -1 Then whichBin = 0 'dart hit slice 0\n Next i\n\nAfter the six darts are thrown, the selection process is completed. Each dart represents a chromosome, and where it lands is the chromosome that will replace it. Here is the end result:\n\n 1. _Chromosome(0) is discarded and is cloned to be Chromosome(5)_\n 2. _Chromosome(1) stays the same_\n 3. _Chromosome(2) stays the same_\n 4. _Chromosome(3) is discarded and is cloned to be Chromosome(5)_\n 5. _Chromosome(4) stays the same_\n 6. _Chromosome(5) is discarded and is cloned to be Chromosome(2)_\n\n### Chromosome Replacement Function\u2014Using VBA Excel\n\n 'Chromosome switching function\n 'Pass both chromosome tables\/matrices into function\n 'inform the function which chromosome is replaced by which chromosome\n Public Sub switchChromo(tempChromoTable As Variant, chromoTable As Variant, destArrNum, srcArrNum)\n For i = 0 To 3\n tempChromoTable(destArrNum, i) = chromoTable(srcArrNum, i)\n Next i\n\nThe new population after selection is:\n\nThe somewhat fit chromosome (3) was discarded and the worst chromosome (4) was carried over. The fifth worst chromosome (0) was discarded and cloned by the third best chromosome (5). Chromosome (3) was cloned with the third best chromosome (5). Chromosome (5) was then discarded and cloned with the best chromosome (2). The formula tried its best to nudge the computer into making the right decision, but due to the random component the worst candidate was kept. The other chromosomes were somewhat upgraded.\n\n## Reproduction\n\nNow that we have our parent pool, we can start the reproduction process. Some of the parents are from the original population and some are clones, and that is okay. The next step is to pick the parents that will produce offspring. The computer will allow you to input the cross rate (partner matching probability), and in this example, 40 percent was used. The computer will randomly generate six numbers between 0 and 100, and every time a number less than or equal to 40 is generated, it designates a crossing of two parents. In this example, the computer generated a random number for each chromosome. Out of the six random numbers, only two were less than or equal to 40. The random numbers were generated sequentially, and random number (2) and random number (4) met our criteria and were less than or equal to 40. With this information, the computer chose chromosome (2) and chromosome (4) to cross\/reproduce.\n\n### Crossing Chromosomes\/Finding Moms and Pops\u2014Using VBA Excel\n\n 'Determine which chromosomes will cross\n 'using a .4 or 40% cross rate\n crossRate = 0.4\n For i = 0 To 5\n crossArr(i) = 0\n Randomize\n roulette(i) = Rnd(1#)\n If roulette(i) <= crossRate Then\n crossArr(i) = 1\n End If\n Next i\n crossCnt = 0\n For i = 0 To 5\n 'parentsList is a simple class\n 'similar to a point class with 2 coordinates\n 'total of six possible matchings\n parentsList(i).mom = 999\n parentsList(i).dad = 999\n If crossArr(i) <> 0 Then\n crossCnt = crossCnt + 1\n 'found mom but not dad - yet\n 'store mom in parentsList(i)\n parentsList(i).mom = i\n foundMate = False\n cindex = i\n Do While Not (foundMate)\n cindex = cindex + 1\n If cindex > 5 Then cindex = 0\n If crossArr(cindex) <> 0 Then\n 'found dad - store dad in parentsList(i)\n parentsList(i).dad = cindex\n foundMate = True\n End If\n Loop\n End If\n Next i\n\nIn nature, a child will receive genetic material or traits from both parents. Some children will receive more traits from the father than the mother, and vice versa. How is this determined? In nature, who knows, but inside a computer, we can discriminate how much the father and mother will contribute to the offspring. Here again, an RNG saves the day. Each chromosome holds four different genes (numbers), so we need to know how many of the four numbers will be passed on by the father and mother to the new offspring. This is accomplished by randomly calculating the split point where the numbers will be taken from both parents. In other words, if the split equals two, then the mother chromosome will contribute her first two numbers and the father chromosome will contribute his last two numbers. There are four genes in each chromosome, so the random number generator will generate a number between one and four. Figure 8.4 shows how the sharing of genetic material is accomplished when the split point is one.\n\n**Figure 8.4** At split 1 the genes that will be passed onto the offspring by the father and the mother.\n\nIn this example, chromosome (2) is the mother and chromosome (4) is the father. The crossover point was randomly generated at one, so the offspring received one gene or number from the mother and three from the father.\n\n### How to Allocate Genes to Junior\u2014Using VBA Excel\n\n 'make sure mom and dad are not one in the same\n 'we are not dealing with earthworms - right?\n If parentsList(i).dad <> parentsList(i).mom Then\n Randomize\n 'how do we split mom and pop's genes?\n crossPt = Int((3 - 0 + 1) * Rnd + 0)\n 'mom is replaced by combination of old mom and dad\n For k = crossPt To 3\n chromo(parentsList(i).mom,k) = chromo(parentsList(i).dad,k)\n Next k\n\nAfter the creation of the offspring, it was then used to replace the old chromosome (2), just like a child taking over his parents' business. This example chose only one crossing but in later generations (after total simulation was completed) more chromosomes were crossed, and they were crossed at different points. The computer is hoping to create a better offspring than the parents but as in real life this doesn't always happen. Just ask your neighbors whose 35-year-old son still lives in their basement.\n\n## Mutation\n\nIn nature, a mutation is change in a genetic sequence. A mutation can be good or bad, but no matter\u2014it does add diversity. In GA, a mutation occurs infrequently but can tremendously help find a solution to a complex problem. Without mutation, selection and reproduction may eventually converge and produce a nondiverse population. Mutation can randomly change a genetic element and then like a chain reaction create different selections and reproductions.\n\nBefore we mutate the initial population, let's review our chromosome population as it stood after our first selection and reproduction phase:\n\n_Chromosome (0)_ | = | _[16,05,13,28]_ \n---|---|--- \n_Chromosome(1)_ | = | _[13,08,15,20]_ \n_Chromosome(2)_ | = | _[00,20,05,09]_ \n_Chromosome(3)_ | = | _[16,05,13,28]_ \n_Chromosome(4)_ | = | _[10,30,30,04]_ \n_Chromosome(5)_ | = | _[00,20,05,09]_\n\nThe rate of mutation should be low because you do want a convergence to occur. In other words, you want a solution, and a high mutation rate could potentially spin the population off into too many different directions. But at the same time, you don't want your population growing stale, either, and a sufficiently high mutation rate prevents this. In this example, a mutation rate of 10 percent was used. With six chromosomes, there are 24 genes or numbers total, so if the mutation rate of 10 percent is applied, then 2.4 genes will be mutated. Since we can't have a partial gene, the number is rounded down to two. So out of the 24 numbers above, 2 of them will be randomly selected and replaced with two random numbers between 0 and 30 (the same range that we initially used to seed the population).\n\nEach gene is assigned a number between 1 and 24 in order. So chromosome (0) will have genes labeled 1 through 4. Chromosome (1) will have genes 5 through 8, and so on. Relying on the random number generator yet again (range between 1 and 24), it generates two numbers: 7 and 24. Don't put the random number generator away yet; we still need to randomize two more numbers between 0 and 30 to use in our mutation. After pushing the button on the RNG, two numbers, 22 and 15, were generated. If we map 7 and 24 across the matrix of chromosomes, then the following highlighted genes will be mutated with the numbers 22 and 15:\n\nChromosome (0): | 161 | 052 | 133 | 284 \n---|---|---|---|--- \nChromosome (1): | 135 | 086 | __**22**_ 7_ | 208 \nChromosome (2): | 009 | 3010 | 3011 | 0412 \nChromosome (3): | 1613 | 0514 | 1315 | 2816 \nChromosome (4): | 1017 | 3018 | 3019 | 0420 \nChromosome (5): | 0021 | 2022 | 0523 | __**15**_ 24_\n\n### Mutating Chromosomes\u2014Using VBA Excel\n\n mutRate = 0.1 ' rate of mutation\n numMutations = Int(mutRate * 24) ' 24 genes available for mutation\n Call printDivider(lineCount, 4)\n lineCount = lineCount + 1\n Randomize\n For i = 0 To numMutations - 1 'loop for 2 mutations\n chromoMut(i) = Int((24 - 0 + 1) * Rnd + 0) 'which genes to mutate\n genLocRow = Int(chromoMut(i) \/ 4) 'locate the gene in the matrix\n If genLocRow = 0 Then genLocRow = 1\n genLocCol = 4 - chromoMut(i) Mod 4\n chromoMutCoOrds(i, 0) = genLocRow - 1 'found gene row\n chromoMutCoOrds(i, 1) = genLocCol + 1 'found gene column\n Randomize\n rndVal = Int((24 - 0 + 1)*Rnd + 0) 'randomize the new gene value\n chromo(genLocRow - 1, genLocCol - 1) = rndVal\n Next i\n\nAfter selection, reproduction, and mutation a new generation has been created. Here are the second generation's chromosomes and respective fitness values after subtracting 40:\n\n_Chromosome (0)_ | = | _[16,05,13,28]_ | = | _53_ \n---|---|---|---|--- \n_Chromosome (1)_ | = | _[13,08,22,20]_ | = | _75_ \n_Chromosome (2)_ | = | _[00,30,30,04]_ | = | _114_ \n_Chromosome (3)_ | = | _[16,05,13,28]_ | = | _53_ \n_Chromosome (4)_ | = | _[10,30,30,04]_ | = | _124_ \n_Chromosome (5)_ | = | _[00,20,05,15]_ | = | _30_\n\nIt seems redundant to state this again, but here is another example of how genetic algorithms mimic nature by not only creating inferior offspring but also creating an inferior generation. However, since these generations live inside of a computer, they are short-lived and the computer moves quickly onto the next generation until a solution is found. This GA solved the problem in 13 generations after a mutation occurred. Eventually, chromosome (2) with genes [13,0,4,15] was chosen as the solution. Test it!\n\nThis is just one possible solution. You can keep propagating and create a whole slew of solutions, which is what we are after when we use genetic optimization on trading algorithms.\n\nGo through the steps until you understand the processes involved. Each step is logical and nonmath intensive and should give you confidence to utilize this technology in your own research. Even if you don't utilize it in research you can impress your friends at your next cocktail party by explaining what a genetic algorithm is and the impact of a higher mutation rate on subsequent generations.\n\n## Using Genetic Algorithms in Trading System Development\n\n> _\"The same principles which at first view lead to skepticism, pursued to a certain point, bring men back to common sense.\"_\n\nGeorge Berkely\n\nNow armed with a little knowledge the veil of skepticism can be pulled back. This knowledge can now be applied to a real-life trading problem. Earlier in this chapter, a trading algorithm was mentioned that consisted of five optimizable parameters. The system (TA1) utilizes an indicator to determine the market condition so it can either apply a trend-following or choppy-market algorithm. The switch that determines condition measures the actual distance a market travels versus the entire distance a market travels over a certain time period. Imagine a subdivision with a lot of cul-de-sacs. If you leave your house and go in and out of each cul-de-sac prior to exiting the subdivision, you will have traveled a long route to go a very short distance. This indicator is based on momentum and has been around for years. It is known as the Choppy Market Indicator (CMI). Here is the formula to the indicator:\n\nIf the difference between the today's close and the close xBars back is small and the highest high and lowest low xBars back is large, then the CMI will be a small value (Numerator small \/ Denominator large). A low CMI indicates the market has traveled a relatively large distance but hasn't gone anywhere. In other words, the market is chopping around with no evidence of a trend.\n\nThere are two ways we can approach a choppy market condition: We can (1) avoid it; or (2) implement a swing trading algorithm. TA1 attempts the latter by using volatility breakout from the prior day's close as an entry point. If the CMI is less than xLevel, then long entries are placed at today's close plus xPercent times xAR (Exponential Average Range) of the past 20 days. The sellshort signal uses the same algorithm, except instead of adding the volatility level, it subtracts it. Here are the choppy market long and short entries:\n\nNow if the CMI indicates a trending market by exhibiting a higher value, then the system switches to the trend-following mechanism. Here, the system falls back on the old Donchian breakout algorithm. Longs are put on at the Highest High of xTrendBars and shorts are put on at the Lowest Low of xTrendBars. The entry rules for trending markets are:\n\nLooking at our entry rules, we can see there are three optimizable parameters: xLevel, xPercent, and xTrendBars. The last two parameters can be further optimized for long entries and short entries. If we allow these two parameters to be different for longs versus shorts, then instead of two parameters we have four. So all in all, there will be a total of five optimizable parameters:\n\n 1. xLevel\u2014Choppy Market value\n 2. xPercentBuys\u2014Percent of 20-day exponential moving average of Range\n 3. xPercentSells\u2014Percent of 20-day exponential moving average of Range\n 4. xTrendBarsBuys\u2014Number of Highest high\/Lowest low lookback bars\n 5. xTrendBarsSells\u2014Number of Highest high\/Lowest low lookback bars\n\nWe could simply pull out of thin air some values for these parameters or we could use TradeStation's tools to help zero in on a robust solution. We now have a trading system and a set of five optimizable parameters, so the next step is to come up with a range of values that we want to optimize the parameters across. These different ranges can also be called our search space. Here are the ranges and iterations for each of the parameters for our system, TA1:\n\n1. | xLevel | { 25 to 75 by 5 increments } [11 iterations] \n---|---|--- \n2. | xPercentBuys | { 0.25 to 0.75 by 0.05 increments } [11 iterations] \n3. | xPercentSells | { 0.25 to 0.75 by 0.05 increments } [11 iterations] \n4. | xTrendBarsBuy | { 8 to 20 by 4 } [4 iterations] \n5. | xTrendBarsSell | { 8 to 20 by 4 } [4 iterations]\n\nIf we do the math (11 * 11 * 11 * 4 * 4), we come up with a total of 21,296 iterations. It will take this many iterations to search the entire space if we apply an exhaustive search algorithm. So the computer will need to run 21,296 tests on the history of each market. This test was performed on 10 years of Euro currency data and it took my \"typical\" computer 13 minutes. The search space could have been expanded but for brevity sake it was limited to 21,296. If just one increment was added to each of the parameters' range, the total number of iterations would have nearly doubled. The results of the exhaustive search are shown in Table 8.1. ( _Note_ : Results are shown without a commission\/slippage charge.)\n\n**Table 8.1** Results from the Exhaustive Search Algorithm's Five Parameters\n\n**xLevel** | **xPercent Buy** | **xPercent Sell** | **xTrendBars Buy** | **xTrendBars Sell** | **Total Profit** | **Max Intra. Drawdown** \n---|---|---|---|---|---|--- \n25 | 0.3 | 0.75 | 8 | 20 | 103615 | \u221215235 \n25 | 0.4 | 0.75 | 8 | 20 | 102435 | \u221216080 \n25 | 0.4 | 0.7 | 8 | 20 | 101005 | \u221215760 \n25 | 0.7 | 0.75 | 8 | 20 | 96050 | \u221217805 \n25 | 0.75 | 0.7 | 8 | 20 | 96680 | \u221218343 \n25 | 0.45 | 0.75 | 8 | 20 | 97435 | \u221217255 \n25 | 0.75 | 0.75 | 8 | 20 | 94020 | \u221218480 \n25 | 0.7 | 0.7 | 8 | 20 | 96015 | \u22127668 \n25 | 0.5 | 0.75 | 8 | 20 | 93805 | \u221216660 \n25 | 0.4 | 0.65 | 8 | 20 | 98763 | \u221215485\n\nNow let's do the same thing, but instead of using the Exhaustive method let's go with the genetic option. In less than one minute the results in Table 8.2 were computed.\n\n**Table 8.2** Results from the Genetic Search Algorithm's Five Parameters\n\n**xLevel** | **xPercent Buy** | **xPercent \nSell** | **xTrendBars \nBuy** | **xTrendBars \nSell** | **Total Profit** | **Max Intra. \nDrawdown** \n---|---|---|---|---|---|--- \n25 | 0.3 | 0.75 | 8 | 20 | 103615 | \u221215235 \n25 | 0.4 | 0.75 | 8 | 20 | 102435 | \u221216080 \n25 | 0.4 | 0.7 | 8 | 20 | 101005 | \u221215760 \n25 | 0.7 | 0.75 | 8 | 20 | 96050 | \u221217805 \n25 | 0.45 | 0.75 | 8 | 20 | 97435 | \u221217255 \n25 | 0.5 | 0.75 | 8 | 20 | 93805 | \u221216660 \n25 | 0.55 | 0.75 | 8 | 20 | 91650 | \u221215063 \n25 | 0.45 | 0.7 | 8 | 20 | 95655 | \u221216110 \n25 | 0.35 | 0.75 | 8 | 16 | 91575 | \u221218843 \n25 | 0.6 | 0.75 | 8 | 20 | 86850 | \u221215913\n\nThe results from the two tests are quite similar; results only start deviating after the top six parameter sets. This example is not perfect for demonstrating the power of GA, as the brute force approach only took 13 minutes, but the implications of its power is more than evident. In many cases, a brute force optimization scheme will be too time intensive, and the only alternative is a GA.\n\nTradeStation makes using the Genetic form of optimization very simple. All it requires is selecting it over the Exhaustive mode. This simple switch makes implementation simple, but you do have the ability to override the Genetic optimizer's default settings. If you select Genetic as the optimization method and then click Advanced Settings, a dialog box will open that will allow you to override the default settings. Before changing these, you want to make sure you fully understand what you are doing. Here is explanation of each of the Genetic Optimization Settings.\n\n### Generations\n\nThis setting indicates the total number of generations each test will iterate to come up with a solution chromosome. In our very first example, the number of generations concluded after a single chromosome fulfilled the requirements to solve the simple equation. The computer program and process could continue until multiple solutions were uncovered. Trading algorithms don't have a black-or-white solution so you can specify to only go so far in the process. This number should increase with larger search spaces. This setting should be \"Suggested\" by clicking the **Suggest** button.\n\n### Mutation Rate\n\nRemember how a gene in our example chromosomes could be randomly changed? This rate defaults to 0.1 or 10 percent, and this is probably the best value for this setting. Higher mutation rates increase the probability of searching more areas in the search space and may prevent the population from converging on an optimal solution. Searching a larger space takes more time and a mutation could randomly change the gene of a good solution after selection and reproduction and turn it into a nonoptimal solution, thus preventing convergence.\n\n### Population Size\n\nReferring to our initial example of a simple GA, we used six different chromosomes to solve our problem. So its population size was six. Population size grows with the size of the search space. A small population on a large search space could lead to less robust solutions. Initial population sizing is very important and is very difficult to gauge. Again, let the **Suggest** button help here.\n\n### Crossover Rate\n\nThe rate that determines how many parents will mate. If the default value is set to 0.4, or 40 percent, then each chromosome has a probability of 2 out of 5 of being mated with another chromosome and being replaced. If this rate is set to 1.0, or 100 percent, then a new generation is always created\u2014no survivors are allowed. As in life, sometimes it's good to have a member or two from the old generation to help guide us. The **Suggest** button usually changes this value to 0.9, or 90 percent probability of chromosome matching.\n\n## Preventing Over-Curve-Fitting\n\nIf optimization is a form of curve fitting, then why do it at all? Curve fitting is a necessary tool in the development of trading algorithms. If a trading system is based on a sound market principle, then modifying it by adjusting its parameters to increase productivity is a good thing. However, this can be overdone. If you \"tweak\" an algorithm's parameters to catch a large portion of every substantial market move and create an absolutely beautiful equity curve, then you have gone too far. The system might work well in the near future due to curve fit overhang, but the likelihood of it continuing is less probable. The future is unknown but a robust trading algorithm that does not have overly curved fit parameters has a higher probability of success. Take a look at the 3D contour chart in Figure 8.5. The _y_ -axis is profit, _x_ -axis is one parameter, and the _z_ -axis is another parameter. The curve is the different profit levels across the different values of the two parameters. If you are looking to maximize profit, then the best parameter set, historically speaking, would be at the peak (0.75, 0.35). If you are looking for robustness, then you don't want the peak; you want a parameter set located on a high plateau. Robustness is the same as parameter stability. If a parameter is stable, then changing it up or down will not have a huge impact on overall performance. If it does, then the parameter is not considered stable. TradeStation includes, with its genetic optimization method, a parameter stress test. This test includes two inputs, number of stress tests and percentage of parameter change.\n\n**Figure 8.5** Robust parameter sets are found on a level plateau.\n\nIf three is chosen as the number of stress tests and 10 percent as the stress increment, then the total number of tests will triple. For example, 7,250 iterations were generated by a simple algorithm optimized using the genetic method and a stress test of one. When the algorithm was reoptimized with a stress test number set to three and the stress increment to 10 percent, the number of increments increased to 21,750. What the genetic optimizer did was test each parameter set and then increased\/decreased each parameter by 10 percent and then retested, thus creating three different sets of tests. A simple standard deviation algorithm example should help illustrate what the computer is doing:\n\n**Test 1: Normal**\n\n 1. Moving Average Length = 50\n 2. Up Band = 2\n 3. Dn Band = 3\n\n**Test 2: Parameters are stressed upwardly by 10%**\n\n 1. Moving Average Length = 50 + (10% of 50) = 55\n 2. Up Band = 2 + (10% of 2) = 2.2\n 3. Dn Band = 3 + (10% of 3) = 3.3\n\n**Test 3: Parameters are stressed downwardly by 10%**\n\n 1. Moving Average Length = 50 \u2013 (10% of 50) = 45\n 2. Up Band = 2 + (10% of 2) = 1.8\n 3. Dn Band = 3 + (10% of 3) = 2.7\n\nStress testing eliminates parameter sets that fall on top of peaks, therefore theoretically revealing a more robust set. If a certain parameter is profitable, and its neighbors are nearly as profitable, then the parameter is deemed robust.\n\nTradeStation's and AmiBroker's genetic optimization tool is a very important tool in the development of robust trading algorithms. Hopefully, this first part has demystified genetic algorithms and provided sufficient evidence that it can help a trader develop a better mousetrap\u2014one that catches the mouse more often than not.\n\n## Walk-Forward Optimizer: Is It Worth the Extra Work and Time?\n\nThe idea of periodic reoptimization of a trading system's parameters is the one concept that divides the algorithmic trading community more so than any other. You are either pro or con; there is very little middle ground. Walk-forward optimization (WFO) has been around since the beginning of trading algorithms but until lately it has been extremely difficult to implement. TradeStation has done a wonderful job in providing the TS walk-forward optimizer. It does all the work for you.\n\nBefore describing the potential benefits of WFO, the concept and process needs to be explained. In a nutshell, it is a technique in which a system's parameters are optimized on a segment of historical data (in-sample), then tested and verified by using those parameters on a walk-forward basis (out-of-sample). Results from in-sample testing will usually be very good due to the benefit of hindsight. It's the results from testing on unseen data that provides a true reflection of a system's validity. This process is done periodically in hopes the trading algorithm will be using the most optimal parameters available at any given time.\n\n### WFO Example 1\n\nAnother example will definitely help explain the concept. Take a Turtle-like system that buys at the highest high of the past 40 days and sells at the lowest low of the past 40 days. Throughout history, there have been times when a longer (greater than 40-day) breakout or a shorter (less than 40-day) worked better. The magic questions are, of course, when to change the length of the breakouts, and by how much? These questions are easily answered with the use of a time machine.\n\nAssume a trader trades this Turtle-like system for two years and it is somewhat profitable. Being an inquisitive trader he asks, \"Was a 40-day break the best option?\" An optimization run is set up and the 40-day parameter is optimized over the past two years of data, and lo and behold, the trader finds out that a 30-day breakout produced twice as much profit with much less drawdown. With this knowledge, he changes the trading algorithm to utilize a 30-day breakout in place of the 40-day. Another two profitable years go by, and he again asks the same question. This time, the best parameter turned out be the exact one he had implemented; 30 turned out to be the optimal parameter. He then carries the parameter forward another two years, but this time he suffers a large loss and a severe drawdown. This trade, optimize, implement, and trade cycle is easy to see. Testing using this process on a long stream of historical data would be very difficult if tools such as the TS WFO were not available. A test would have to be started, stopped, results recorded, backed up, and optimized on in-sample data, started, stopped, results recorded, backed up, and optimized on in-sample data, started, stopped....You get the picture.\n\nBefore proceeding, please refer to the TradeStation WFO **Help** menu to learn how to set up an optimization and then load that information into the software. The TS WFO **Help** system will also show how to perform an individual walk-forward analysis (WFA), or a cluster WFA.\n\nHere is an individual WFA of a Turtle-like system selectively changing its parameters every two years. The first results shown are with the benefit of hindsight. The best parameters for each time period were utilized to construct the continuous track record. All the reports shown were produced using the TS WFO. The system labeled TA2 will enter and exit the market utilizing the following criteria:\n\n \/\/EasyLanguage Code for Turtle-like Algo\n Buy Next Bar at Highest (H[1],xLongEntryLen) stop;\n Sell Short Next Bar at Lowest (L[1],xShortEntryLen) stop;\n If MarketPosition = 1 Then\n Sell Next Bar at Lowest (L[1],xLongExitLen) stop;\n If MarketPosition =-1 Then\n BuyToCover Next Bar at Highest(H[1],xShortExitLen) stop;\n\n#### In-Sample Testing\n\nYou will notice four optimizable parameters:\n\n 1. xLongEntryLen\n 2. xLongExitLen\n 3. xShortEntryLen\n 4. xShortExitLen\n\nSince the long entry parameter may not be the same as the short this system is not symmetric. This also applies to the long and short exits. Different parameters for long and short entries were used to increase the search space sufficiently to enable a genetic optimization. You will notice if the exhaustive search space is less than 10,000, then the genetic method is disabled. Table 8.3 shows the in-sample testing results of TA2 over the past 14 years on 30-year bonds.\n\n**Table 8.3** In-Sample Testing TA2\n\n**Le Se Lx Sx** | **Begin Date End Date** | **Bars** | **Profit** | **Max DD** \n---|---|---|---|--- \n20 20 12 10 | 2001\/09\/18\u20132005\/06\/15 | 975 | 24,843.75 | \u22129,187.50 \n20 20 12 10 | 2002\/10\/11\u20132006\/07\/07 | 975 | 28,375.00 | \u22129,187.50 \n20 20 16 10 | 2003\/09\/05\u20132007\/06\/27 | 975 | 23,687.50 | \u22128,093.75 \n20 24 12 12 | 2004\/10\/04\u20132008\/06\/26 | 975 | 6,437.50 | \u22128,343.75 \n20 20 12 14 | 2005\/08\/16\u20132009\/04\/07 | 975 | 18,531.25 | \u221211,906.25 \n20 36 10 14 | 2006\/08\/15\u20132010\/06\/04 | 975 | 11,843.75 | \u221213,843.75 \n20 20 12 14 | 2007\/09\/20\u20132011\/04\/18 | 975 | 21,531.25 | \u221213,187.50 \n20 24 12 14 | 2008\/07\/17\u20132012\/04\/06 | 975 | 22,375.00 | \u221217,656.25 \n20 56 10 14 | 2009\/06\/23\u20132013\/03\/27 | 975 | 8,250.00 | \u221215,375.00 \n24 24 12 14 | 2010\/09\/03\u20132014\/04\/04 | 975 | _18,187.50_ | \u221217,656.25 \n| | | 184,062.50 |\n\nTable 8.3 shows the best parameter sets over a four-year period carried one year forward sequentially. Row 1 starts with September 2001 and ends on June 15, 2005. The best-performing parameters were selected over that time period and displayed. Row 2 starts a year later in October 2002 and ends in July 2006, and the best parameters are also shown. The process is continued through April 2014. The results are spectacular, but beware of the benefit of hindsight. Notice how the **Le** , **Lx** , **and Sx** parameters stayed somewhat consistent; this does demonstrate parameter stability. The **Se** parameter was all over the map, and you can see that the system did not want to sell short between June 2009 and March 2013; the sell entry utilized a whopping 56 days in its calculation. Figure 8.6 is a graphic representation of how the analysis rolls forward.\n\n **Figure 8.6** A graphic representation of how the walk-forward analysis (WFA) rolls forward.\n\n#### Out-Of-Sample Testing\n\nWhen you run a WFO, the software builds a database of these \"best\" parameter sets and then informs the algorithm when to adopt and when to abandon them. TradeStation's WFO keeps track of all parameter switching and performance metrics on the trading algorithm as it progresses through the history of whatever you are testing.\n\nThe whole purpose of this software and this type of testing is based on the belief of optimization overhang or carryover; if a parameter has done well for the past four years, it should overhang or carry over into the subsequent year. A practitioner of this school of thought also believes the market is changing and a trading algorithm must change or adapt as well. Table 8.4 shows the WFO of this system on the 30-year bond going back to 2001. Notice how the results start in 2005. The system backed up to 2001 and derived the best parameter set for those four years and then traded that set starting in June 2005 and ending in July 2006.\n\n**Table 8.4** Out-of-Sample Testing\n\n**Le Se Lx Sx** | **Begin Date End Date** | **Bars** | **Profit** | **Max DD** \n---|---|---|---|--- \n20 20 12 10 | 2005\/06\/15\u20132006\/07\/07 | 244 | 4,031.25 | \u22122,562.50 \n20 20 12 10 | 2006\/07\/07\u20132007\/06\/27 | 244 | 4,437.50 | \u22123,093.75 \n20 20 16 10 | 2007\/06\/27\u20132008\/06\/25 | 244 | \u22123,437.50 | \u221210,343.75 \n20 24 12 12 | 2008\/06\/26\u20132009\/04\/07 | 244 | 8,968.75 | \u22127,343.75 \n20 20 12 14 | 2009\/04\/07\u20132010\/04\/16 | 244 | \u22126,437.50 | \u221213,187.50 \n20 36 10 14 | 2010\/06\/04\u20132011\/03\/29 | 244 | 8,250.00 | \u22122,093.75 \n20 20 12 14 | 2011\/04\/18\u20132012\/04\/06 | 244 | \u22122,500.00 | \u221217,562.50 \n20 24 12 14 | 2012\/04\/06\u20132013\/03\/27 | 244 | \u22121,937.50 | \u221211,562.50 \n20 56 10 14 | 2013\/03\/27\u20132014\/04\/04 | 244 | \u22124,062.50 | \u221213,187.50 \n24 24 12 14 | 2014\/04\/04\u20132015\/03\/18 | 244 | _1,718.75_ | \u22125,156.25 \n| | | 9,031.25 |\n\nWhen July 2006 arrived, the system then switched to the second parameter set. These parameters were derived using data from 2002 through 2005 (refer back to table 3\u2014second row). The WFO swapped parameters on an annual basis. Overall, the system was profitable, but the walk-forward efficiency was only 19.03 percent, and it lost 5 out of 10 years. Why did this happen? The only answer is the lack of optimization overhang in the out-of-sample periods.\n\n**System TA2 used the default WFO settings:**\n\n * Walk-forward runs = 10; in this test, the computer switched parameters 10 times over the history of the test. This works out to be about once a year. If the test period had been 20 years, then the WFO would have switched every 2 years.\n * OOS% = 20%; this percentage informs the computer to utilize 80 percent of each interval's data (in-sample) to determine the best parameter set and then carry that parameter set forward 20 percent of the interval (out-of-sample).\n\nIf these settings are changed, then the number of bars used for optimization and the number of bars those optimizations are carried forward will change as well. Here are the various calculations that are used to determine the total number of bars per run, in-sample number of bars, and out-of-sample number of bars.\n\n 1. **TotalBarsPerRun** \u2014Total number of bars \/ (Walk-forward runs * Out-of-sample % + In-sample %). In our example test, there were a total of 3415 bars, 10 walk-forward runs, 20 OOS%, and 80 percent in-sample. WFO uses bars in place of days to calculate the walk-forward window lengths. \n 1. TotalBarsPerRun = 3415 \/ (10 * 0.2 + 0.8) = 1219\n 2. **InSampleBarsPerRun** \u2013 TotalBarsPerRun * In-sample% \n 1. InSampleBarsPerRun = 1219 * 0.8 = 975\n 3. **OutOfSampleBarsPerRun** \u2013 TotalBarsPerRun * Out-of-sample% \n 1. OutOfSampleBarsPerRun = 3414 * 0.2 = 244\n\nThe first interval analyzes the first 975 bars of data and determines the best parameter set and then carries that set on unseen data for 244 bars. The second test starts on bar 976 and ends on 1950 (976 + 974) and then walks forward 244 more days. Figure 8.7 illustrates this process by showing how four years are used to decide the best parameters using hindsight and then how those parameters are applied to unseen data the following year.\n\n **Figure 8.7** How four years of hindsight are used to predict unseen data for the following year.\n\nThe WFO produces a WFA report that determines the usefulness of applying this type of optimization to this particular trading algorithm. Before showing the contents of this report let's create a benchmark parameter set and compare those results with those produced by the WFO. A benchmark can be created by using a fixed parameter set throughout the entire test time period. This is easily accomplished by setting the four parameters to the following values:\n\nIn addition to making the parameters static notice that the system was also made symmetrical; the buy-side parameters are the same as the sell-side parameters. This particular parameter set did perform better over the walk-forward optimization as it produced almost $17,000, whereas the WFO produced nearly $10,000 in profit. The WFO process did not outperform the static parameters on this particular algorithm. The WFA report is shown in Table 8.5.\n\n**Table 8.5** WFA Report on TA2\n\n| **Test Criteria** | **Result** | **Comment** \n---|---|---|--- \n1 | Overall Profitability | Pass | Total Profit > 0. System likely to perform profitably on unseen data. \n2 | Walk-Forward Efficiency | Failed | < 50%. System likely to perform in future at a rate of less than 50% of those achieved during optimization. \n3 | Consistency of Profits | Pass | 50% of walk-forward runs were profitable. \n4 | Distribution of Profits | Failed | Run #6 contributed more than 50% of Total Net Profit. \n5 | Maximum Drawdown | Pass | No individual run had a drawdown of more than 40% of init. capital. \n| **Overall Result** | **FAILED** |\n\nThe WFA agrees with our benchmark analysis that a WFO does not complement this type of trading algorithm. Of the five test criteria, this system failed two. The most important failed test was the walk-forward efficiency (WFE). This value compares the in-sample average profit versus the out of-sample average profit. This algorithm failed with a 19.03 percent efficiency, meaning that the average OOS profit was one fifth the size of the in-sample profit. Now, does this mean TA2 is not a good trading algorithm? The robustness of the system logic and results of the static parameter analysis answers this question with an emphatic \"No!\" Just because a WFO didn't work well with this particular algorithm in the 30-year bonds doesn't mean it is not a good system. Other markets need to be tested and evaluated, as well as different WFO settings.\n\n### WFO Example 2\n\nAnother example of a WFO on a different type of algorithm may be a beneficial demonstration. This time, the WFO will be applied to a short-term ES (emini SP) system that produces more trades than TA2. This system, TA3, will trade in the direction of the long-term trend and buy pullbacks and sell rallies. The trend will be defined by a long-term moving average and pivot points will determine pullbacks and rallies; pivots involving the highs will determine rallies and pivots using the lows will determine pullbacks. Different protective stops and profit objectives will be used for long and short positions. The strength of the pivot points and the number of days that will be used to determine the presence of the pivot points may also be different for long and short entries. Two additional parameters will be used to limit the number of days the system is in the market. That makes a total of 11 optimizable parameters:\n\n1. | movAvgLen | { 50 to 150 by 10 increments } [11 iterations] \n---|---|--- \n2. | pivotHiLookBack | {3 to 5 by 1 increment} [3 iterations] \n3. | pivotHiStrength | {1 to 3 by 1 increment} [3 iterations] \n4. | pivotLowLookBack | {3 to 5 by 1 increment} [3 iterations] \n5. | pivotLowStrength | {1 to 3 by 1 increment} [3 iterations] \n6. | LprofitObjective | {500 to 1500 by 50 increment} [21 iterations] \n7. | LstopLoss | {250 to 750 by 50 increment} [11 iterations] \n8. | SprofitObjective | {500 to 1500 by 50 increment} [21 iterations] \n9. | SstopLoss | {250 to 750 by 50 increment} [11 iterations] \n10. | longExitDays | {5 to 15 by 1} [11 iterations] \n11. | shortExitDays | {5 to 15 by 1} [11 iterations]\n\nThat is nearly 6 billion iterations. Fortunately, the genetic method of optimization is available.\n\nHere is the code for entries and exits:\n\n Value1 = SwingHiBar(1,H,pivotHiStrength,pivotHiLookBack);\n Value2 = SwingLowBar(1,L,pivotLowStrength,pivotLowLookBack);\n If C > Average(C,avgLen) then\n Begin\n If Value1 <> -1 then Buy this Bar on Close;\n End;\n If C < Average(C,avgLen) then\n Begin\n If Value2 <> -1 then SellShort this Bar on Close;\n End;\n If MarketPosition = 1 Then\n Begin\n Sell Next Bar at EntryPrice + LprofitObjective\/bigPointValue limit;\n Sell Next Bar at EntryPrice - longStopLoss\/bigPointValue stop;\n End;\n If MarketPosition = -1 Then\n Begin\n BuyToCover Next Bar at EntryPrice - SprofitObjective\/ bigPointValue limit;\n BuyToCover Next Bar at EntryPrice + shortStopLoss\/ bigPointValue stop;\n End;\n\n#### WFO Cluster Analysis\n\nThe optimization using the genetic method took only a few moments. This time, instead of running a single WFO, the cluster WFO option was chosen. In this example, the cluster analysis ran 30 different walk-forward optimizations. Each optimization changed the values for OOS% and walk-forward runs. In the first single WFA, 10 runs utilizing 20 percent OOS% were evaluated to determine WFO fitness. Figure 8.8 shows the different values of WF runs and OOS% levels in a matrix format.\n\n**Figure 8.8** The Cluster WFO results matrix.\n\nSimilar to the single WFA on the Turtle-like system, this system failed as well, using the 10 WFA runs with 20 percent as the OOS%. However, this system passed the test on several different OOS% \/ Runs values. Please note that in an attempt to increase the likelihood of a passing grade, the criterion for the walk-forward efficiency was lowered from 50 to 30 percent in the test criteria setup. This criterion seems to be the one that rejects a larger portion of optimizations. To expect a 50 percent WFE is perhaps setting the bar a bit too high. The TS WFO selected a WFO using 15 percent for OOS% and 25 runs. It is the dark gray selection from Figure 8.8. This value is the center cell where a majority of its neighboring cells showed promise. This translates to using only 15 percent out-of-sample data and changing the parameters 25 times during the test period. The optimization produced over $52K in profits with a WFE of 49.9 percent. Table 8.6 shows the OOS report.\n\n**Table 8.6** The Out-of-Sample (OOS) Report\n\n**p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11** | **Begin Date End Date** | **Bars** | **Profit** | **Max DD** \n---|---|---|---|--- \n90 5 2 5 2 900 650 13 600 400 9 | 2007\/08\/16\u2013 2007\/12\/11 | 117 | \u22125,512. | \u22127,037 \n100 5 1 5 2 1450 350 14 1050 750 12 | 2007\/12\/11\u20132008\/04\/01 | 112 | 8,325. | \u22124,862 \n70 4 1 4 2 900 550 13 1150 750 8 | 2008\/04\/01\u20132008\/07\/16 | 106 | 4,862. | \u22122,962 \n100 5 1 5 2 1450 350 14 1050 750 12 | 2008\/07\/16\u20132008\/11\/10 | 117 | 21,150 | \u22124,425 \n90 5 1 5 3 1500 350 13 1050 750 5 | 2008\/11\/10\u20132009\/03\/03 | 113 | 10,475 | \u22125,150 \n90 5 1 5 3 1500 350 13 1050 750 5 | 2009\/03\/03\u20132009\/05\/29 | 87 | \u22127,362 | \u221210,400 \n90 5 1 5 3 1500 350 13 1050 750 5 | 2009\/05\/29\u20132009\/10\/02 | 126 | 2,025 | \u22121,925 \n90 5 1 5 1 1400 300 13 1050 750 11 | 2009\/10\/08\u20132010\/02\/02 | 117 | \u22122,675 | \u22124,025 \n90 5 1 5 1 1450 350 8 1050 750 8 | 2010\/02\/02\u20132010\/05\/21 | 108 | 2,050 | \u22123,425 \n90 5 1 5 1 1400 650 9 1100 650 11 | 2010\/05\/21\u20132010\/09\/03 | 105 | \u22122,200 | \u22125,862 \n90 5 1 5 1 1450 350 8 1100 750 13 | 2010\/09\/08\u20132010\/12\/27 | 110 | 4,687 | \u22122,612 \n70 5 1 5 1 1400 450 8 1500 700 8 | 2010\/12\/30\u20132011\/04\/19 | 110 | \u22122,137 | \u22124,775 \n70 5 1 5 1 1450 350 8 1200 700 9 | 2011\/04\/19\u20132011\/08\/08 | 111 | \u22121,475 | \u22126,875. \n100 5 1 3 1 1400 500 11 1100 700 6 | 2011\/08\/08\u20132011\/11\/23 | 107 | 662 | \u22124,937 \n100 5 1 3 1 1200 350 9 1200 700 13 | 2011\/11\/23\u20132012\/03\/22 | 120 | 3,500 | \u22121,675 \n100 3 1 5 1 1450 350 9 1050 750 15 | 2012\/03\/22\u20132012\/07\/06 | 106 | \u22121,937 | \u22123,200 \n100 5 1 3 1 1200 350 9 1200 700 13 | 2012\/07\/12\u20132012\/10\/17 | 97 | 1,512 | \u22123,337 \n90 4 1 3 1 1200 350 6 1200 700 9 | 2012\/10\/17\u20132013\/02\/19 | 125 | \u22121,070 | \u22124,932 \n80 4 1 3 2 1050 550 14 800 300 7 | 2013\/02\/21\u20132013\/06\/12 | 111 | 3,800 | \u22121,650 \n90 4 1 4 1 1500 650 6 600 700 9 | 2013\/06\/12\u20132013\/09\/30 | 111 | \u2212750 | \u22125,300 \n90 4 1 4 1 1500 650 6 600 700 9 | 2013\/09\/30\u20132014\/01\/21 | 113 | 0 | \u22121,662 \n100 5 3 3 1 1200 700 13 1100 700 6 | 2014\/01\/21\u20132014\/05\/13 | 112 | \u22122,125 | \u22124,950 \n150 4 1 5 1 1150 350 13 950 500 14 | 2014\/05\/13\u20132014\/08\/28 | 108 | 3,212 | \u22123,600 \n150 4 1 5 1 1150 350 13 950 500 14 | 2014\/08\/28\u20132014\/12\/18 | 112 | 2,112 | \u22124,737 \n150 4 1 5 1 1150 350 13 950 500 14 | 2014\/12\/18\u20132015\/04\/07 | 110 | 11,075. | \u22124,087\n\nTable 8.7 provides the report card on this system using the optimal optimization values.\n\n**Table 8.7** WFO Report Card TA3\n\n| **Test Criteria** | **Result** | **Comment** \n---|---|---|--- \n1 | Overall Profitability | Pass | Total Profit > 0. System likely to perform profitably on unseen data. \n2 | Walk-Forward Efficiency | Pass | >= 30%. System likely to perform in future at a rate between 30\u2013100% of those achieved during optimization. \n3 | Consistency of Profits | Pass | 50%+ of walk-forward runs were profitable. \n4 | Distribution of Profits | Pass | No individual time period contributed more than 50% of Tot. Profit. \n5 | Maximum Drawdown | Pass | No individual run had a drawdown of more than 40% of init. capital. \n| Overall Result | PASSED |\n\nThe cluster WFA is a very powerful tool because it allows the user to quickly look at different WFOs utilizing different OOS% values and walk-forward periods. A good trading algorithm may be rejected by simply using a single WFA. The e-mini SP system failed on the default 20 OOS% with 10 runs but passed on several different values.\n\nThe TS WFO software provides all the detailed information given in the cluster optimization matrix. A user can select any of the different optimizations and see a plethora of details. The ultimate question is then answered as to what parameter set should be used and how many days that set should be carried forward. If the software-derived optimal set is selected (15 OOS% with 25 runs), then the following parameters are suggested to be used for next 111 days.\n\n1. | movAvgLen | 150 \n---|---|--- \n2. | pivotHiLookBack | 4 \n3. | pivotHiStrength | 1 \n4. | pivotLowLookBack | 5 \n5. | pivotLowStrength | 1 \n6. | LprofitObjective | 1150 \n7. | LstopLoss | 350 \n8. | SprofitObjective | 950 \n9. | SstopLoss | 500 \n10. | longExitDays | 13 \n11. | shortExitDays | 14\n\nNow the question that started this part of the chapter can be answered. The WFO is an incredible tool that can help determine if a trading algorithm needs to be retrained periodically and also if the algorithm demonstrates sufficient robustness to match to some degree the results that were derived during its training.\n\n## Monte Carlo Analysis\n\nAs we have seen, walk-forward analysis can tell us much about an algorithm's robustness. Another tool that can reveal algorithm robustness is Monte Carlo simulation. The key to this form of simulation can be found in random numbers. Once you develop what you consider a good trading algorithm and test it against historical data, you then can really put it to the test by using random numbers and the historical trade history.\n\nThis trade history that is generated by testing your algorithm represents just one path your system traveled. What if you could create many paths by jumbling the order of the trades that your algorithm generated. These different paths could represent alternate universes. Let's say that your algorithm got lucky and had a bunch of winning trades in a row. This streak might be the portion of the equity curve that pulled the system out of mediocre status. If these trades didn't exist or hadn't fallen in place like they did, then the equity curve might look quite a bit different. A robust trading system should still produce robust performance metrics even when the trades are jumbled, some eliminated and some duplicated. If the majority of the alternate paths of an algorithm fail to produce good metrics, then the algorithm should be considered suspect.\n\nCreating alternate paths or parallel universes is a very simple process when you have access to a random number generator and a computer. As you saw earlier in this chapter an RNG is a very special tool. Imagine all of the trades generated by your algorithm are each written on a separate piece of paper and all the pieces are then placed in a bag. You create an alternative trade history by reaching into the bag and randomly selecting trades and writing them down in a trade log in sequential manner. You do this routine until you have recorded the same number of trades that were initially generated by the backtest. One very important thing to remember is to always return the piece of paper to the bag after you record the trade. This process would be very time consuming and you might ask what's the use. Don't worry about the time involved because the computer can do it very quickly and recreating hundreds of alternative paths is well worth the effort. Will it help create a better algorithm? Probably not but it will help you make a decision to allocate real funds to an algorithm or not. Like I stated earlier, the robustness of a trading algorithm will reveal itself through Monte Carlo simulation.\n\n#### Implementation of Monte Carlo Simulation Using Python\n\nThe concept of this form of simulation is easy enough. And putting it into computer language is as easy. The hardest part is getting the initial trade list. Once you have that the rest falls into place relatively easily. Understanding how a computer implementation of a concept works usually helps the understanding of how the concept works in general and how it might be beneficial.\n\nImagine all the trades generated by a backtest are stored in a list. The list is simply an ordered collection of the trade dates and trade profits. The list might look something like this:\n\n 1. TradeList[0] = (20011015,\u2212150)\n 2. TradeList[1] = (20011105,+200)\n 3. TradeList[2] = (20011202,\u2212300)\n 4. TradeList[3] = (20011222,+500)\n\nYou could call this the source list. Now imagine you have another blank list that's called AlternateList1. The objective of the Monte Carlo simulation is to fill the AlternateList1 with trades from the source list. If there are only four elements in the list, you would need an RNG to generate random numbers from 0 to 3. Let's push the RNG button and start the process of filling up AlternateList1:\n\n 1. The RNG generates the number 3 \n 1. AlternateList1[0] = TradeList[3]\n 2. RNG generates the number 0 \n 1. AlternateList[1] = TradeList[0]\n 3. RNG generates the number 1 \n 1. AlternateList[2] = TradeList[1]\n 4. RNG generates the number 3 \n 1. AlternateList[3] = TradeList[3]\n\nOur new alternate list of trades would look like this:\n\n 1. AlternateList[0] = (20011222,+500)\n 2. AlternateList[1] = (20011015,\u2212150)\n 3. AlternateList[2] = (20011105,+200)\n 4. AlternateList[3] = (20011222,+500)\n\nSimple, right? All we are doing is jumbling the order of the original list to create an alternate path the trading system might have followed. Did you notice that the RNG generated the number 3 twice? So AlternateList[3] is the same as AlternateList[0]. Does this seem right? This is correct and exactly what we want our RNG to do. This is called sampling with replacement. Remember how the piece of paper was to be put back into the bag after recording it? This method almost guarantees that we never recreate the original trade listing. This is important because we want to create as many unique alternative paths as we can.\n\nPython provides, to its programmers, some very useful data structures. However, it does not provide the array structure like other languages (you can use arrays in Python if you import them with the NumPy library). Arrays are very powerful and can be multidimensional and this is the structure I would have used if I had used a different language. But Python has this really cool structure called a tuple. A tuple is simply a collection or a list of like data. Here are examples of a classic car tuple:\n\n 1. antiqueCarTuple[0] = (1967, 'Ford' , 'Mustang' , 289)\n 2. antiqueCarTuple[1] = (1971, \"Chevy', 'Chevelle', 402)\n\nAs you can see each tuple element holds the various properties of a classic car. If I need to know the model of the second antique car, I can access it by using the following notation: modelName = antiqueCarTuple[1][2]\n\nThe first bracket following the name of the tuple selects which tuple you are wanting to access from the tuple list. Since Python is 0 based the [1] in this example tells the computer to select the second tuple or car. The next bracket is used to determine which element in the tuple to access. I wanted the model, or third element, of the antique car so I used the number 2 to access it.\n\nIn our Monte Carlo example each tuple will hold the date of the trade exit and the associated profit or loss. Here is the very lengthy and elaborate code for creating 1000 alternate paths of our trading algorithm:\n\n* * *\n\n mcTradeTuple = list()\n for x in range(0,1000): # number of alternate histories\n for y in range(0,len(tradeTuple)):\n randomTradeNum = random.randint(0,len(tradeTuple)-1)\n tradeDate = tradeTuple[randomTradeNum][0]\n tradePL = tradeTuple[randomTradeNum][1]\n mcTradeTuple += ((x,y,tradeDate,tradePL),)\n\n* * *\n\nThat's it! These seven lines of code is all it took to create 1000 different and mostly unique alternate trade histories. I won't bore you with all of the details, but I will step through the code quickly to demonstrate how easy this was to do with Python. Initially I stored all of the trade dates and trade P\/L in a tuple named **tradeTuple**. From this list I culled all of the trades to fill up the 1000 alternate lists. Basically I started with the source list and for each trade in the list I created a random number between 0 and the number of trades:\n\n randomTradeNum = random.randint(0,len(tradeTuple)-1)\n\nPython generates random numbers through its module: **random.randint**. I then used the **randomTradeNum** as an index into the tradeTuple to extract the **tradeDate** and **tradePL** :\n\n tradeDate = tradeTuple[randomTradeNum][0]\n tradePL = tradeTuple[randomTradeNum][1]\n\nRemember the first bracketed number following the tuple selects which tuple. The second bracketed number selects the element in that particular tuple. In the **tradeTuple** , [0] is the trade date and [1] is the trade P\/L. While stepping through the alternate histories sequentially, trades were randomly selected from the original trade history and inserted. All of the alternate histories were then stored in a list of tuples named **mcTradeTuple**. The += operand simply appends the current alternate trade history to the list. In the end, you have one huge list that includes all of the alternate histories.\n\n#### AmiBroker's Monte Carlo Simulation\n\nThe Python Monte Carlo simulation is included in the Python System Backtester. I programmed the simulation because I wanted to fully understand the mechanism. Fortunately, you don't need to program these types of tools because they are usually included in your favorite testing platform. This is the case for AmiBroker and TradeStation. AmiBroker's Monte Carlo analysis is so simple all you have to do is flip a switch. Click the Settings button in an Analysis window and hit the Monte Carlo tab (see Figure 8.9). You have seen this dialog before but this is the first time we have discussed the Monte Carlo settings. The default values are the most popular. The position sizing parameters offers four different options: (1) keep the sizing the same as the initial test, (2) use a fixed size of contracts or shares, (3) use a fixed dollar value for size computation, and (4) use a percentage of equity in fixed fractional approach. The fourth option can introduce serial dependency into the Monte Carlo simulation due to the fact that the size of the current trade is dependent upon the success of all of the prior trades. Utilizing this option might muddy the waters a bit when trying to determine algorithm robustness. Before we move on let's discuss the idea of serial correlation among the trades of a trading algorithm. This concept basically implies there is a relationship or connection between a trade and the subsequent trade or trades. Critics of Monte Carlo simulation on actual trades suggest this important correlation is ignored when trades are jumbled. If you think about it, it sort of makes sense when dealing with a trend-following algorithm. Trend-following trades can follow a cyclical pattern\u2014one large winner due to a trend, followed by a series of small losers that occur in the absence of a trend. You can see that the small losers are a consequence of the dissipation of the trend. This series of trades, big winner, small losers demonstrates a level of trade interdependency. The Turtles felt like a loser might follow a winner and therefore utilized the _Last Trade Was a Loser_ filter. There has been much research on this topic and the consensus has been that if serial correlation existed, it only applied to the first subsequent trade. All other trades were independent events. If serial correlation is a concern, a Monte Carlo simulation on equity curve segments would be a solution. Each segment would contain the same series of trades and therefore maintain the correlation. Since we are dealing with a large majority of alternate paths I don't necessarily think you need to concern yourself with serial correlation. So just go ahead and accept the default settings and click OK. AmiBroker creates a couple of charts\/reports that will illustrate the usefulness of this form of simulation. The first chart is called a Straw Broom chart because of the way it looks (see Figure 8.10).\n\n**Figure 8.9** AmiBroker Monte Carlo settings dialog.\n\n**Figure 8.10** Monte Carlo Straw Broom chart of multiple randomized equity curves.\n\nThis is a representation of all of the alternate trade histories that were created by using the random number generator. As you can see, most of the histories end at different equity values and this is due to sampling with replacement. Had we not allowed replacement, then all of the equity curves would end at the exact same spot. The accumulation of all of the trades, irrespective of order, follows the commutative law. You can easily see the boundary (top and bottom) histories that represent the best and worst performance. The rest of the histories congregate in the middle and create a cloud. This cloud is what you want to see from your own algorithm simulation; many of the random histories created similar outcomes. AmiBroker also creates the following table that provides the statistics derived from the distribution of the simulation results (Table 8.8).\n\n**Table 8.8** Distribution Statistics from Monte Carlo Simulations\n\n| **Final Equity** | **Annual Return** | **Max. Drawdown $** | **Max. Drawdown %** | **Lowest Eq.** \n---|---|---|---|---|--- \n1% | 5706 | \u22127.37% | 1302 | 7.23% | 3618 \n5% | 7987 | \u22123.02% | 1549 | 9.76% | 5853 \n10% | 9706 | **\u22120.41%** | 1726 | 11.32% | 6690 \n25% | 12851 | 3.48% | 2136 | 14.38% | 8107 \n50% | 16174 | 6.78% | 2747 | 19.77% | 9135 \n75% | 19632 | 9.64% | 3563 | 27.63% | 9640 \n90% | 23258 | 12.21% | 4626 | **38.48%** | 9922 \n95% | 25269 | 13.48% | 5292 | 45.47% | 10000 \n99% | 29139 | 15.71% | 7685 | **63.82%** | 10000\n\nThe first column shows the percentile level that certain observations fell. In the first row 1% of all observations had profit levels below $5,706 and maximum drawdowns below $1,302. These two events, based off of their probabilities, are unlikely to happen again. Fifty percent of the time you could expect profits to be less than or equal to $16,174 and maximum drawdown to be less than or equal to $2,747. Ninety-nine percent of the time you could expect drawdowns below $7,685. Keep in mind what we expect and what really happens doesn't always jive. We are basing all of our expectations on historical results, results that have a certain level of built-in hindsight bias.\n\n## Start Trade Drawdown\n\nThe maximum drawdown metric that is derived from backtesting is a key component used to help a trader judge the capitalization requirements of a particular trading algorithm. If an algorithm suffers a $50,000 drawdown, it logically follows that this event could occur again in the future. And accordingly the trader should allocate at least $50,000 to his trading account. What if the algorithm is very good and this one event doesn't cast it in a good light? What if the drawdown follows a large runup? In this case, the drawdown is somewhat a function of the system's success. Another drawdown metric, start trade drawdown, can help shed light on an algorithm's drawdown structure. A trader is most sensitive to drawdown when she initially starts to trade a new algorithm. A $50,000 drawdown that decimates a trader's account right off the bat is completely different than a $50,000 drawdown that occurs after a $200,000 runup. Wouldn't it be nice to know the probability of having a huge drawdown at the beginning of trading? Also wouldn't it be nice to know the probability of the maximum drawdown occurring again in the future for capitalization purposes? This concept of Start Trade drawdown can be attributed to Keith Fitschen. He describes it on his website, www.keithstrading.com, and in his book, _Building Reliable Trading Systems_ (Wiley, 2013, New Jersey). Let's assume you have a trading algorithm that trades 100 times. Would a trader starting at trade #1 have a different drawdown than a trader starting at trade #50? This is a very good question and I guess Mr. Fitschen asked himself this exact same question. You could simply analyze the drawdowns that occur after trade #1 and the drawdowns that occur after trade #50 and answer the question. What if there was an analysis that could provide the probabilities of different drawdown magnitudes derived from the historical results of a trading algorithm? This could definitely help a person decide if a system is worth the risk, and at the same time know how much capital would be required to fund it. Well, thanks to Keith Fitschen, we have this analysis.\n\n#### Calculating Start Trade Drawdown\n\nWith the use of a computer, the process of this calculation is easily accomplished. This calculation is somewhat similar to the Monte Carlo simulation in that you are recreating multiple histories of a trading algorithm. However, this time an RNG is not utilized. The first trade history is the trade history that contains all of the historic trades. Subsequent trade histories start at the subsequent trade in the original history. For example, the second trade history starts at the beginning of trade #2 and the next trade history starts at beginning of trade #3, and so on. An original trade history containing 100 trades will spawn 100 histories starting at different trade numbers. Once all of the histories are created then all one needs to do is flow through each history and keep track of cumulative profit and maximum drawdown.\n\nAfter creating and analyzing the 100 trade histories a cumulative frequency distribution table (CFDT) must be created. A CFDT is created by distributing the 100 drawdowns into different bins. The bins are the same size but have different boundaries. Assume the 100 drawdowns range from $5,000 to $25,000 and you want to store the different drawdown in 20 bins. The range is equal to $20,000 ($25,000 \u2212 $5,000) so each bin would have to be $1,000 wide ($20,000\/20). Bin #1 would contain the drawdowns that ranged from $5,000.00 to $5,999.99, bin #2 would contain the drawdowns that ranged from $6,000 to $6,999.99, bin #3 would contain the drawdowns that ranged from $7,000 to $7,999.99, and so on. See how the bins are the same size but have different low and high boundaries?\n\nOnce the drawdowns are distributed into the different bins you can easily create a cumulative frequency by summing up the number of drawdowns in each bin. Once you have the cumulative frequency it is simple to calculate the probability of occurrence for each bin. With 100 different trade histories starting at different trade numbers, it is not uncommon to have less than 100 distinct max drawdown values. In some cases, the same max drawdown value will be observed when the starting point of each history is in close proximity. I wouldn't be surprised if the max drawdown was the same starting at trade #2 versus starting at trade #3. The fact is you will have 100 max drawdown values but they won't all be distinct. The bins will contain multiple duplicate drawdown values. Each bin will contain N number of values and the probability of the occurrence of that bin's max value and below will be the sum of N up to that bin\/Total N. Let's say bin #1 [$5,000 \u2212 $5,999] contains 5 values and bin #2 [$6,000 \u2212 $6,999] contains 3 values. The probability of a drawdown less than $6,999 would be 8\/100 or 8%. This type of information can be very beneficial at the beginning stage of trading a new algorithm.\n\n### Implementation of Start Trade Drawdown Simulation Using Python\n\nSimulation of the different trade histories depends on the actual number of trades generated by the algorithm. This simulation requires a nested for-loop where the outside loop loops from trade #1 to the last trade. The interior loop loops from the current trade number to the last trade.\n\n* * *\n\n # start trade draw down analysis - utilizing the tradeTuple\n tupleLen = len(tradeTuple)\n tradeTuple = sorted(tradeTuple,key=itemgetter(0))\n for x in range(0,tupleLen):\n cumStartTradeEquity = 0\n maxStartTradeDD = -99999999\n maxCumEquity = 0\n for y in range(x,tupleLen):\n cumStartTradeEquity += tradeTuple[y][1]\n maxCumEquity = max(maxCumEquity,cumStartTradeEquity)\n maxStartTradeDD = max(maxStartTradeDD,maxCumEquity - cumStartTradeEquity)\n startTradeTuple += ((x,cumStartTradeEquity,maxStartTradeDD),)\n\n* * *\n\nThe outer loop indexed by **x** controls the number of trade histories. The inner loop indexed by **y** flows through the different trade histories and keeps track of each history's cumulative equity and maximum drawdown. At the beginning of each trade history, these two values are zeroed out. Each trade's P\/L is stored as the second element in the tuple **tradeTuple**. This value is extracted through each **y** iteration and used to calculate the two performance metrics. Once an individual history is created it is then stored in a list of tuples named **startTradeTuple**. The first element in this tuple is x (the trade history number). The second element **cumStartTradeEquity** stores the cumulative equity of the history and the third element **maxStartTradeDD** stores the max drawdown of the history.\n\nOnce the trade histories are compiled, the bins that hold the different max drawdowns must be constructed. The first step in the construction process is to calculate the largest and smallest historic drawdown values.\n\n* * *\n\n minDD = 99999999\n maxDD = 0\n for y in range(0,len(startTradeTuple)):\n print(startTradeTuple[y][0],' ',startTradeTuple[y][1],' ',startTradeTuple[y][2])\n if startTradeTuple[y][2] < minDD: minDD = startTradeTuple[y][2]\n if startTradeTuple[y][2] > maxDD: maxDD = startTradeTuple[y][2]\n\n* * *\n\nA loop is used to flow through each trade history and keep track of the maximum and minimum values stored in the third element of the startTradeTuple (max drawdown of each history).\n\nTwenty bins will be used in this example to store the individual drawdown values. The bin size is calculated by dividing the range of drawdowns by 20. The size of the bin is stored in the variable **binInc** (bin increment). Each bin is constructed by storing each bin's boundary values in a list of tuples named **binTuple**. Each binTuple contains three elements: binNumber, binBottom, and binTop. The boundary values are calculated by starting at the smallest max drawdown of the histories (bottom of the first bin) and adding the bin size to get the top of the first bin. The next bin's bottom boundary becomes the prior bin's top and its top is calculated by adding the **binInc**. This process is repeated until all 20 bin tuples are filled up with the correct values.\n\n* * *\n\n numBins = 20\n binTuple = list()\n binInc = (maxDD - minDD)\/20.0\n binBot = minDD\n for y in range(0,numBins):\n binTop = binBot + binInc\n binTuple += ((y,binBot,binTop),)\n print(binTuple[y][1],' ',binTuple[y][2])\n binBot = binTop + y\n\n* * *\n\nOnce the bins are constructed all the different histories' max drawdowns are distributed into them. This is accomplished by comparing the max drawdown with each bin's top and bottom boundaries. If the drawdown value falls between the two boundaries, it is then placed into that bin. A blank list of bins is initially created.\n\n* * *\n\n bins = list()\n bins[:] = []\n for x in range(0,numBins):\n bins.append(0)\n\n* * *\n\nThe different histories are looped through and are placed into the different bins. Well, not really, just the frequencies of the drawdowns are stored.\n\n* * *\n\n for x in range(0,len(startTradeTuple)):\n for y in range(0,numBins):\n tempDD = startTradeTuple[x][2]\n tempBot = binTuple[y][1]\n tempTop = binTuple[y][2]\n if (tempDD >= binTuple[y][1] and tempDD < binTuple[y][2]):\n bins[y] += 1\n\n* * *\n\nOnce the frequency of each drawdown is stored in each bin the total number of drawdown occurrences must be calculated.\n\n* * *\n\n freqSum = sum(bins)\n\n* * *\n\nPython has a cool list method **sum**. This method sums up all of the values in the list in one fell swoop. This is the beauty of an object-oriented language. Once the total is calculated, the cumulative probabilities is just a loop away.\n\n* * *\n\n binProb = list()\n for y in range(0,numBins):\n if y == 0:\n binProb.append(bins[y]\/freqSum)\n else:\n binProb.append(bins[y]\/freqSum + binProb[y-1])\n\n* * *\n\nThe probability of bin #1 is simply the number of drawdowns in that bin divided by the total number of max drawdowns. The subsequent bin's probabilities are the probability of the current bin plus the prior bin's probability. This process accumulates the frequencies of the drawdowns. Here is a printout of a probability distribution of an algorithm trading different markets.\n\n* * *\n\n Probability of DD < 1547 is 0.060\n Probability of DD < 3094 is 0.080\n Probability of DD < 4643 is 0.080\n Probability of DD < 6192 is 0.280\n Probability of DD < 7743 is 0.320\n Probability of DD < 9294 is 0.400\n Probability of DD < 10847 is 0.400\n Probability of DD < 12400 is 0.420\n Probability of DD < 13955 is 0.640\n Probability of DD < 15510 is 0.660\n Probability of DD < 17067 is 0.680\n Probability of DD < 18624 is 0.820\n Probability of DD < 20183 is 0.880\n Probability of DD < 21742 is 0.880\n Probability of DD < 23303 is 0.900\n Probability of DD < 24864 is 0.920\n Probability of DD < 26427 is 0.940\n Probability of DD < 27990 is 0.960\n Probability of DD < 29555 is 0.980\n Probability of DD < 31120 is 1.000\n\n* * *\n\nThe maximum drawdown of this algorithm was around $30,000. The probability of this event occurring again is less than 2%. The probability of having a drawdown greater than $20,000 is less than 12%. These drawdowns only include closed trade drawdowns\u2014the amount of drawdown after the trade was closed out, not while it was open. Open trade drawdown will always be greater than or equal to closed trade drawdown. The loss isn't realized until the trade is closed out. Again, keep in mind we are dealing with hypothetical performance metrics with an inherent hindsight bias. Stating that a drawdown has less than a 2% chance of occurring again cannot be said with a straight face. However, historic performance is all we have to hang our hat on.\n\n## Summary\n\nThe purpose of this chapter was to be a guide and explain concepts that on the cover seem to be beyond the reach of a typical algorithmic system developer\/trader. Genetic optimization is just a very smart way to get to a solution quickly. Walk-Forward Optimization, Monte Carlo simulation, and Start Trade drawdown are tools that can provide the necessary evidence that a trading algorithm might have a chance of performing in the future. Python code was peppered throughout the text pertaining to Monte Carlo simulation and Start Trade drawdown to demonstrate how simple the processes are that carry out these particular forms of analysis. None of these tools will provide the \"Holy Grail,\" but in this author's opinion, they will help the user develop a trading solution that best fits his or her own trading style.\n\n1 John H. Holland. Genetic algorithms. _Scientific American_ , 267(1):44\u201350, 1992.\n\n# Chapter 9 \nAn Introduction to Portfolio Maestro, Money Management, and Portfolio Analysis\n\nIt has been mentioned in many trading circles through the years that money management is as important as the algorithm that generates the trade entries. The position size is paramount when it comes to utilizing capital in the most efficient manner. Thus far, we have simply tested on a one-contract basis, and that in of itself is a money management scheme. The one contract per market scheme was utilized, because the primary focus was on developing a trade entry-and-exit algorithm. Now that we have spent a sufficient amount of time on algorithm development, this guide would not be complete without a chapter on money management and portfolio analysis. This time we will lean on TradeStation to carry out our analysis\u2014this platform has the toolset necessary to apply both portfolio and money management schemes to a trading algorithm.\n\n## Fixed Fractional\n\nFixed Fractional is by far the most popular form of money management in the world of futures trading. This approach allocates the same amount of capital to each market. Perceived risk is usually defined as a function of a market's average true range calculated over the last _N_ days. Dividing the amount of capital by market risk gives the position size for the next trade. This form of money management normalizes the markets by maintaining the same amount of perceived risk across all markets in the portfolio. Here is the formula:\n\nAssume you have a $100,000 capital allocation, and you want to risk at most 1 percent on any given trade. Assume the 10-day ATR in Treasury notes is $500. How many contracts should be initiated on the next trade? Plugging into the formula we get:\n\nSo two contracts of T-notes will fit our 1 percent risk criteria. Now assume you want to trade Eurodollars as well and need to know that position size. Let's say the 10-day ATR in Eurodollars is $125. Plugging into the formula again, we get:\n\nEight contracts of Eurodollars provides the same risk as two contracts of T-notes. See how the different markets are normalized to provide the same amount of risk? Utilizing a Donchian 55-day breakout with a trailing 20-day liquidation and a fixed dollar stop, let's see how this money management formula works in practice.\n\n## Portfolio Maestro\n\nPortfolio Maestro (PM) is an add-on to TradeStation and requires an additional monthly fee. If you have it you might want to follow along with this tutorial. If you don't, then read on and see if it might be something you may want to investigate. From TradeStation you can launch PM by clicking on the Trading Apps tab, and then selecting Portfolio Maestro. PM will launch and you will be presented with the window shown in Figure 9.1.\n\n**Figure 9.1** TradeStation's Portfolio Maestro (PM) launch window.\n\nOnce you get used to the interface, building and testing portfolios will become old hat. However, the first few analyses may take multiple attempts to get everything the way you want. Hopefully, this tutorial will help along the way.\n\nPM works around the concepts of a **Strategy Group** and a **Portfolio** of **Strategy Groups**. Before you can do anything you must build a **Strategy Group**. The Strategy Group that we will be using is one that incorporates our Turtle-like 55-day Donchian breakout. If you haven't imported the ELDs from the website, this would be a great time to do so.\n\n### Strategy Group\n\nIn PM, a **Strategy Group** consists of a trading algorithm and the portfolio of markets to which that algorithm will be applied. With the PM window in front of you click on the **File** menu, select **New** , and then select **Strategy Group**. Where it asks for Name type in **MyFirstStrategyGroup** and then select **Futures** as the asset class.\n\nYou will then be sent back to the PM main window. Click on the **Strategies** tab and then click on the **Add Strategy** button. Another window will open and list all of the strategies that are in your strategies library (see Figure 9.2).\n\n**Figure 9.2** Add a strategy to your strategy group.\n\nScroll down the list until you come to **Turtle 55**. If you don't see it, then you might need to reimport the ELD files from this book's companion website (www.wiley.com\/go\/ultimatealgotoolbox). If it's there, click on the name and highlight it. Then click OK. The PM window will now show **Turtle 55** in the **Strategies** window (see Figure 9.3).\n\n**Figure 9.3** The Turtle 55 strategy is now in your strategies window.\n\nWe now have a strategy, but now we need to tell PM to apply it to a list or portfolio of markets. Click on the **Symbol Lists** tab right beside the **Strategies** tab. A window will appear similar to Figure 9.4.\n\n**Figure 9.4** Add a symbol by clicking the Symbol Lists tab (indicated by Arrow 1), then clicking on Add Symbol List (shown with Arrow 2).\n\nPM asks you to select a preexisting list of markets. I've created a custom list for this book, labeled **UGTATS** , and it includes the following markets:\n\nUGTATS Market List\n\n 1. Australian Dollar\n 2. Beans\n 3. British Pound\n 4. Cocoa\n 5. Coffee\n 6. Copper\n 7. Corn\n 8. Cotton\n 9. Crude\n 10. Dollar Index\n 11. Euro FX Currency\n 12. Euro Dollar\n 13. Feeder Cattle\n 14. Five-Year Notes\n 15. Gold\n 16. Heating Oil\n 17. Kansas City Wheat\n 18. Lean Hog\n 19. Live Cattle\n 20. Mini-Russell\n 21. Mini-SP400\n 22. Mini-SP500\n 23. Natural Gas\n 24. Orange Juice\n 25. Platinum\n 26. Silver\n 27. Treasury Notes (2-Year, 5-Year, and 10-Year)\n 28. Treasury Bonds (30-Year)\n 29. Unleaded\n 30. Wheat\n\nIf you need help creating a **Symbol List** , there is a short tutorial at www.georgepruitt.com. After selecting the **UGTATS** list your **Symbol List** window should look something like this (see Figure 9.5).\n\n**Figure 9.5** After selecting the UGTATS list, it will appear in your symbol list window.\n\nIf you click on the plus sign beside the **UGTATS Symbol List** , the symbols of the markets included in the list will be shown (see Figure 9.6).\n\n**Figure 9.6** The UGTATS markets and their corresponding symbols.\n\nNow that we have created a complete strategy group (Strategy and Symbol List), it is now time to create a portfolio. Go back under the **File** menu, select **New** , and then select **Portfolio**. A dialog box similar to the one we used to create a New Strategy Group will pop up. In the **Name** field, type **MyFirstPortfolio** and then click OK. After clicking OK a blank portfolio window will appear. The message in the window (\"This portfolio does not have any strategy groups...\") is informing you that you have not yet selected a strategy group. We can remedy this very quickly by clicking on the **Add Strategy Group** button. A list of strategy groups will be presented (see Figure 9.7). Select **MyFirstStrategyGroup** and it will be inserted into **MyFirstPortfolio** (see Figure 9.8).\n\n**Figure 9.7** A list of available strategy groups, including MyFirstStrategyGroup, which we are using for this exercise.\n\n**Figure 9.8** After selecting MyFirstStrategyGroup, you will see it in MyFirstPortfolio. In the expanded view, you can see the strategies and symbols that are part of your group.\n\nYou might need to expand the boxes to see the **Turtle 55** strategy and the **UGTATS** Symbol List. The **Portfolio** window shows the different strategy groups inside the **Portfolio**. You can have multiple **Strategy Groups** trading different **Strategies** on different **Symbol Lists**. This is a very powerful tool\u2014the ability to merge multiple **Strategies** across multiple **Symbol Lists**. We touched on this exact subject of Multiple Algorithmic Strategies (MAS) in Chapter 3.\n\nBefore we backtest the portfolio, let's change the **Strategy Group** settings by going back to the **Strategy Group**. Click on the **Manage Strategy Group** (puzzle piece) button, and then click on the **Strategy Group Settings** button. The settings dialog box will open and should look similar to Figure 9.9.\n\n**Figure 9.9** How to adjust the settings for a strategy group. Arrow 1 indicates the Manage Strategy Group button. Arrow 2 highlights the Strategy Group Settings button. Arrow 3 points to the controls that change the commission and slippage inputs.\n\nFrom this dialog, we can change the commission and slippage and various other strategy-dependent parameters. You can even change the **Strategy Inputs** by clicking the **Strategy Inputs** tab. Go ahead and change the **Commission** and **Slippage** to $12.50 for each on a **Per Contract** basis. Click **OK** , and then, to be on the safe side, click on the **Symbol List** tab again and make sure the **Asset Class** is still set to **Futures**. PM sometimes switches this back to **Equities**. Once you check this, click the **Manage Portfolios** button and finally click **Backtest Portfolio**. Another dialog window will appear that lets you change the test period, **Initial Capital** , the **Backtest Type** (standard or optimization), and the **Report Name** (Figure 9.10). You can also deselect certain markets by going to the **Symbols** tab. Change the test period to start 10 **Years Back**.\n\n**Figure 9.10** As you prepare to backtest your portfolio, ensure the settings are correct. Begin by clicking the Backtest Portfolio button (marked 1 in the figure). Then, check the initial capital, test period, and backtest type in the appropriate fields (marked with 2). When everything looks good, click the Perform Backtest button (number 3 in the figure).\n\nIf everything looks OK, then click **Perform Backtest**. The test might take a few minutes if you have a large **Symbol List**. TradeStation first pulls the data from their data servers and then applies the strategy to each market. I have a feeling TradeStation will make this process much quicker by caching the data on the hard drive in the future.\n\nOnce the test is complete, PM will ask if you would like to view the report now or later. Go ahead and click **Now**. A window like the one in Figure 9.11 will open, and show you the portfolio performance of your **MyFirstPortfolio**. Remember this portfolio consists of two components, a strategy and a portfolio.\n\n**Figure 9.11** A backtest performance report.\n\nFigure 9.11 illustrates a portion of the performance metrics that are included in the **Summary** report. This portfolio actually did pretty well over the past 10 years: $739,684 in profits with an average trade of $426. You can scroll down and see a plethora of performance metrics. The one thing I would like PM to show in this report is the maximum drawdown. The maximum drawdown is shown but you have to hunt for it. Click on the **Trade Analysis** tab. The **Trade Analysis** drills down and proffers up even more performance metrics. If you are a statistician, then you will think you have died and gone to Heaven. The neatest feature in this tab is located at the bottom right and is labeled **View\/Hide Symbols**. If you hit this button, then every market that was traded and their associated performance metrics will be added to the **Trade Analysis** window (see Figure 9.12).\n\n**Figure 9.12** The Trade Analysis window displays trading statistics. To get to this screen, click the Trade Analysis tab (marked 1). The View\/Hide Symbols button (marked 2) reveals the performance metric for every market in your portfolio (item 3).\n\nScroll around and make yourself comfortable with the report. I could write an entire book just on these neat reports and bore you to death. However, I will leave the exploration of all of the different report tabs up to you. But if you indulge me a little bit more, I will show two very interesting charts that PM generates that show the location of the maximum drawdown. Click on the **Graphs** tab and the equity curve for the portfolio will be plotted and look similar to the one in Figure 9.13.\n\n**Figure 9.13** An equity curve chart that shows the maximum drawdown.\n\nSource: TradeStation\n\nIf you want to see the contribution of each individual market to the portfolio, this is done by selecting Total P\/L by symbol (Figure 9.14). This chart is a histogram of each market's contribution to the grand total. If you want to know the maximum drawdown of the portfolio, you will find this under the **Returns and Equity** tab about halfway down (Figure 9.15). This Turtle-like algorithm produced over $700K in profit but had a $201K drawdown. Not too bad, considering the size of the portfolio. The energy sector packed most of the punch, as you can see from the histogram.\n\n**Figure 9.14** The Total P\/L option displays individual profit and loss data for every market in the portfolio.\n\nSource: TradeStation\n\n**Figure 9.15** The Returns and Equity tab displays the portfolio's maximum drawdown in this case.\n\nThis ability to merge the different equity curves together has not always been available in TradeStation. The lack of portfolio analysis was the major criticism of TradeStation over the years, but with the advent of PM, the critics have a lot less to complain about.\n\n### Fixed Fractional Money Management Overlay\n\nNow that we know how to create a **Strategy Group** and a **Portfolio** , we can now apply a money management overlay and test it. With PM still on your screen, click the **Manage Strategy Groups** button and then the **Money Management** tab. In the **Money Management** window you will find a dropdown menu labeled **Method**. Click the down arrow and select **Fixed Fractional with ATR Risk**.\n\nThe resulting dialog box gives you the opportunity to change the parameters built into the Fixed Fractional formula. You can change these parameters:\n\n * **Percent Risk** \u2014The amount of capital to risk on each and every trade. Set this to 1 percent.\n * **ATR Multiplier** \u2014The number of times you want to multiply the ATR to estimate perceived market risk. The larger this number the riskier you perceive the market to be. Set this to two.\n * **ATR Lookback** \u2014How many days in the ATR calculation. The shorter lookback gives recent history more weight.\n * **Maximum Quantity** \u2014The largest position size that will be allowed on any given trade. Eurodollars are notorious for generating large position sizes. Since execution costs cut into the bottom line you probably should limit this to 10.\n * **Round Quantity** \u2014You cannot trade a fractional part of a futures contract, so always set this to one.\n\nLook at Figure 9.16 and make your changes accordingly.\n\n**Figure 9.16** The arrows indicate the parameters that you can change from the Money Management window. For now, keep the ATR lookback set to 10 and the round quantity set to 1.\n\nNow click on the **Manage Portfolios** button. You will notice that _Money Management: Fixed Fractional with ATR Risk_ has been added directly under **Turtle 55** in the strategy portion of the dialog window. The description of the Money Management strategy is included as well:\n\n_Buy 2 times ATR over 10 bars lookback, but no more than 10. Risk no more than 1.00 percent of Equity_.\n\nThis overlay will calculate two times the 10-day ATR and use it as the denominator in our **Fixed Fractional** formula. The numerator will be 1 percent of the total portfolio balance. Both numerator and denominator will rise and fall. The denominator will replicate market volatility and the numerator will reflect 1 percent of the account as it grows or shrinks. Click on the **Backtest Portfolio** button and change the **Initial Capital** to 500,000. This test will apply the **Turtle 55** algorithm to the **UGTATS Symbol List** all the while overlaying a **Fixed Fractional** money management scheme. Sounds like a lot to carry out, so let's see what happens by clicking the **Perform Backtest** button (make sure you are going 10 **Years Back** ). Figure 9.17 shows the equity curve of the backtest, and yes, you are seeing close to a million-dollar profit.\n\n**Figure 9.17** The equity curve of the backtest reveals a profit of nearly $1 million.\n\nSource: TradeStation\n\nThe profit is spectacular but so is the drawdown\u2014and not in a good way. This is how **Fixed Fractional** works\u2014as the account grows so does the position size. And we all know profit or loss and drawdown are directly proportional to position size. Take a look at Figure 9.18 to see how the position size changes for the different markets in the portfolio.\n\n**Figure 9.18** Profit and drawdown are directly proportional to position size. As your position size changes, so do your commissions and profits and losses.\n\n### Portfolio Analysis\n\nNot only does PM allow you to overlay money management, but it also allows you to control portfolio management from a macroscopic perspective. Professional portfolio managers often tinker with the idea of placing a global portfolio stop after a big losing month. Let's say the portfolio is down 4 percent by midmonth; some managers liquidate all positions and wait until the beginning of the next month to reestablish positions. They also tinker with the idea of liquidating positions intramonth when the portfolio reaches a certain profit level. I have personally seen a fund up 3 to 4 percent midmonth, but by the time the end of the month rolls around, the fund winds up being negative. If only the fund manager had taken a profit, then the gains would have been preserved. This type of trade stoppage sounds great theoretically, but there are risks involved. Let's say a fund manager stops trading when the fund is down 4 percent, but continues to monitor the what-if trades and finds out the fund would have recovered the 4 percent plus an additional 2 percent. The manager realized a real 4 percent loss, but had he continued trading he would have ended up with a 2 percent winner. This is a 6 percent equity swing and could be the difference between holding on to some clients and losing them. The same risk occurs when flattening a fund because of what is perceived to be a \"sizable\" profit. Many times, a plus 4 percent month turns into a plus 8 percent. There is never a black-or-white answer to anything dealing with trading. This is why ideas are converted into diagrams, diagrams into pseudocode, pseudocode into an actual programming language and then tested, and tested, and tested.\n\nSpeaking of testing, let's go back to PM and test the ideas of trade stoppage once the portfolio, on an intramonth basis, digs itself into a 4 percent hole, or when the portfolio achieves a 4 percent profit. Trading will cease until the beginning of the following month. PM enables this type of testing with just a few keystrokes. Go back to PM and click on the **Manage Portfolio** button, then click on **Portfolio Settings** , then on **Portfolio Stops** (Figure 9.19).\n\n**Figure 9.19** Under Portfolio Settings (marked as 1), go to the Portfolio Stops tab (marked as 2) and set the stop strategy of your choosing. Under the dropdown menu, there is a description of how the selected strategy will impact your portfolio (marked as 3).\n\nThe first parameter that needs to be set is the **Portfolio Stop Loss**. Click on the dropdown menu and select **Portfolio Stop Loss** and set the parameters as shown in Figure 9.20. Set the **Loss As Percent** to True, **Loss Target** to 4, and **Period** to 1. Click the **Set Stop** button and the **Portfolio Stop Loss** will be applied to the portfolio strategies.\n\n**Figure 9.20** To set the portfolio stop loss, you can adjust the loss target percentage (marked as 1), loss target (marked as 2), and period (marked as 3).\n\nNow let's set the **Portfolio Profit Target** by setting **Period** to 1, **PrftAsPercent** to True, and **PrftTarget** to 4 (Figure 9.21).\n\n**Figure 9.21** To set the portfolio profit target, you can adjust the period, profit target percentage, and profit target. These options align with those in the stop loss tab.\n\nGo ahead and click **Set Stop** and you will see the **Portfolio Profit Target** will be added to the Strategies. Before we click OK, let's review both portfolio stops to make sure we have the parameters properly set. Expand the **Portfolio Profit Target** and the **Portfolio Stop Loss** strategies. The settings should look exactly like the ones in Figure 9.22.\n\n**Figure 9.22** The portfolio profit target and stop loss now appear as strategies in your portfolio.\n\nJust to review, the **Portfolio Profit Target** will cause the portfolio to cease trading once the portfolio achieves a 4 percent profit level and the **Portfolio Stop Loss** will cease trading if the portfolio loses 4 percent. Once stopped, the portfolio will start trading automatically at the beginning of the next month. Go ahead and click **OK** and you will be returned to the **MyFirstPortfolio** window. You will notice another item has been added to the list, **Portfolio Stop**. Take a quick look at Figure 9.23.\n\n**Figure 9.23** At the bottom of your screen, you should see the portfolio stop option.\n\nIf you see that **Portfolio Stop** has been added, then click **Backtest Portfolio**. All other parameters that were used in the prior Portfolio Analysis should still be set: 500,000 for **Initial Capital** and 10 **Years Back** for the test period. After the test finishes click OK to view the report now. First off, click on the **Graphs** tab to see if the equity curve looks any better utilizing the **Portfolio Stops**. Figure 9.24 shows the equity curve of **MyFirstPortfolio** using the prescribed stop trading schemes.\n\n**Figure 9.24** The equity curve of the portfolio once the stops have been added.\n\nSource: TradeStation\n\nA quick look reveals a smoother equity curve than the one from the prior portfolio analysis. Now click on the **Summary** tab and let's look at the results in a tabular form. Here are the differences between the first test and this test, which used portfolio stops:\n\n**Test 1:**\n\n 1. Total Return: $1,307,354\n 2. Number of Trades: 1685\n 3. % Profitable: 30.92%\n 4. Average Trade: $724.27\n 5. Maximum Drawdown: $1,115,228.36\n\n**Test 2:**\n\n 1. Total Return: $848,197\n 2. Number of Trades: 1940\n 3. % Profitable: 46.96%\n 4. Average Trade: $425.63\n 5. Maximum Drawdown: $350,500.34\n\nWhich test would you trade? Needless to say, the test with the portfolio stops was much better. In Test 2, **Total Return** dropped precipitously, but so did **Maximum DD**. It is interesting to see that **Number of Trades** increased in Test 2, which at first seems counterintuitive. If trading is turned off, then you would expect to have fewer trades. However, the more you think about it, a higher trade count makes sense; trades are turned off, and then turned back on, which creates an additional exit and entry. In Test 1, a trade could have stretched for several weeks, but in Test 2, if trades are turned off, then this particular trade would be liquidated and then reinitialized at the beginning of the next month\u2014thus generating an additional trade. Take a look at Tables 9.1 and 9.2, which show trades without and with the portfolio stops.\n\n**Table 9.1** Portfolio Trades without Stops\n\n**No Portfolio Stops** | | | | | \n---|---|---|---|---|--- \nDate | Mkt | Entry\/Exit | Price | Quant | $P\/L | Entry\/Exit Name \n3\/24\/06 | @AD | Short Entry | 0.4594 | 3 | | Turtle55 Sell \n4\/6\/06 | @AD | Short Exit | 0.4794 | 3 | ($6,100.00) | Turtle55SmmLiq \n4\/26\/06 | @AD | Long Entry | 0.4959 | 3 | | Turtle55 Buy \n6\/1\/06 | @AD | Long Exit | 0.4933 | 3 | ($880.00) | Turtle55LLiq \n8\/10\/06 | @AD | Long Entry | 0.5162 | 3 | | Turtle55 Buy \n8\/25\/06 | @AD | Long Exit | 0.5042 | 3 | ($3,700.00) | Turtle55LLiq \n9\/5\/06 | @AD | Long Entry | 0.5196 | 4 | | Turtle55 Buy \n9\/8\/06 | @AD | Long Exit | 0.503 | 4 | ($6,740.00) | Turtle55LLiq\n\n**Table 9.2** Portfolio Trades with Stops in Place\n\n**With Portfolio Stops** | | | | | \n---|---|---|---|---|--- \nDate | Mkt | Entry\/Exit | Price | Quant | $P\/L | Entry\/Exit Name | First New Signal \n3\/24\/06 | @AD | Short Entry | 0.4594 | 3 | | Turtle55 Sell | \n3\/31\/06 | @AD | Short Exit | 0.4611 | 3 | ($610.00) | Portfolio Stop Short | \n**Stopped Trading 3\/31\/2006; Resume 4\/01\/2006** \n**No Signal Before the Next Stoppage** \n**Stopped Trading 4\/20\/2006; Resume 5\/01\/2006** \n5\/3\/06 | @AD | Long Entry | 0.5105 | 3 | | Turtle55 Buy | First New Signal in May \n5\/11\/06 | @AD | Long Exit | 0.5211 | 3 | $3,080.00 | Portfolio Stop Long | \n**Stopped Trading 5\/11\/2005; Resume 6\/01\/2006** \n8\/10\/06 | @AD | Long Entry | 0.5162 | 4 | | Turtle55 Buy | First New Signal in Aug. \n8\/17\/06 | @AD | Long Exit | 0.5167 | 4 | $100.00 | Portfolio Stop Long | \n**Stopped Trading 8\/17\/2006; Resume 9\/01\/2006** \n9\/5\/06 | @AD | Long Entry | 0.5196 | 5 | | Turtle55 Buy | First New Signal in Sept. \n9\/8\/06 | @AD | Long Exit | 0.503 | 5 | ($8,400.00) | Turtle55LLiq |\n\nPortfolio Maestro does exactly what it is supposed to do. Trades are immediately liquidated on or near the stoppage date, and new trades are initiated on fresh signals after the beginning of the next month.\n\nIt is also interesting to note that the original **Turtle 55** strategy without money management or portfolio stops actually performed the best from a profit-to-drawdown perspective.\n\n## Summary\n\nThis chapter highlighted the capabilities of Portfolio Maestro:\n\n * _Portfolio level analysis_ \u2014PM can test multiple markets and present a portfolio level report of them combined together.\n * _Money management_ \u2014the Fixed Fractional technique was introduced and applied to our large portfolio of 30+ markets using the **Turtle 55** algorithm. Money management offers a process that normalizes one market to another, and offers a method to allocate capital in an efficient manner.\n * _Portfolio analysis_ \u2014PM offers several different ways to manage a portfolio's equity curve: \n * Portfolio profit target\n * Portfolio stop loss\n * Portfolio trailing stop\n\nThe first two methods were tested and reviewed.\n\nIn addition to introducing Portfolio Maestro, this chapter also discussed money management and portfolio analysis. The topics of all three were barely scratched. However, I think enough was provided to excite further research on all three subjects. Ideas such as money management and portfolio management can be hypothesized all day long, but until you put these ideas to the test, you won't know if they are truly valuable. Most beginning traders do not believe money management techniques can be applied to small accounts, and they are partially correct. However, the concept of risk is always universally applicable, and that is a big part of all money management techniques. All traders can learn from these techniques and apply them in one form or another to their own trading.\n\nTo trade or not to trade\u2014that is the question. Traders know there are times when standing aside with a flat position is a good trading strategy. However, determining these times is as difficult as timing the market. Should trading stop when a trading account is down a certain percentage during the month, or is it a good time to stop when the account is up a certain percentage? With tools such as PM, traders no longer need to wonder; they can set up the test and see for themselves. PM has many different built-in criteria, but users are not limited to just those. Its users can also dream up their own what-if scenarios, and program them directly into PM. This chapter solely relied on PM to carry out the various tests, but many of these same tests can also be accomplished with AmiBroker or TradersStudio.\n\n# Appendix A\n\n## AmiBroker\n\nHere is a brief list of token names (keywords and identifiers) that are used internally in AmiBroker.\n\n## Keywords\n\nThe following is a subset of keywords:\n\n * **buy** \u2014Defines \"buy\" (enter long position) trading rule.\n * **sell** \u2014Defines \"sell\" (close long position) trading rule.\n * **short** \u2014Defines \"short\" (enter short position \u2013 short sell) trading rule.\n * **cover** \u2014Defines \"cover\" (close short position \u2013 buy to cover) trading rule.\n * **buyprice** \u2014Defines buying price array (this array is filled in with the default values according to the Automatic Analyser settings).\n * **sellprice** \u2014Defines selling price array (this array is filled in with the default values according to the Automatic Analyser settings).\n * **shortprice** \u2014Defines short selling price array (this array is filled in with the default values according to the Automatic Analyser settings).\n * **coverprice** \u2014Defines buy to cover price array (this array is filled in with the default values according to the Automatic Analyser settings).\n * **exclude** \u2014If defined, a true (or 1) value of this variable excludes current symbol from scan\/exploration\/backtest. They are also not considered in buy-and-hold calculations. Useful when you want to narrow your analysis to certain set of symbols.\n * **roundlotsize** \u2014Defines round lot sizes used by backtester (see explanations below). Automatic Analysis (new in 4.10).\n * **ticksize** \u2014Defines tick size used to align prices generated by built-in stops (see explanations below). (Note: It does not affect entry\/exit prices specified by **buyprice \/ sellprice \/ shortprice \/ coverprice**.)\n * **pointvalue** \u2014Allows to read and modify future contract point value (see backtesting futures). CAVEAT: this AFL variable is by default set to 1 (one) regardless of contents of Information window UNLESS you turn ON futures mode (SetOption(\"FuturesMode\", True )).\n * **margindeposit** \u2014Allows to read and modify future contract margin (see backtesting futures).\n * **positionsize** \u2014Allows control dollar amount or percentage of portfolio that is invested into the trade (more information available in the \"Tutorial: Backtesting Your Trading Ideas\").\n * **positionscore** \u2014Defines the score of the position. (More details: \"Tutorial: Portfolio Backtesting.\") Automatic analysis.\n * **numcolumns** \u2014Exploration only: defines the number of your own columns (excluding predefined ticker and date columns) and assigns the column value to the variable.\n * **filter** \u2014Exploration only: controls which symbols\/quotes are accepted. If \"true\" (or 1) is assigned to that variable for given symbol\/quote, it will be displayed in the report. So, for example, the following formula will accept all symbols with closing prices greater than 50: **filter** = close > 50;.\n\n## Flow Control Structures\n\nHere are some identifiers to help you control program flow:\n\n**Loops:**\n\n 1. **do** (part of do-while statement)\n 2. **while**\n 3. **for**\n\n**Conditional execution \/ Flow control:**\n\n 1. **if** (part of if-else statement)\n 2. **else** (part of if-else statement)\n 3. **switch**\n 4. **break** (part of the switch statement or for\/while statements)\n 5. **case** (part of the switch statement)\n 6. **continue** (part of for\/while statements)\n 7. **default** (part of switch statement)\n\n## Functions\n\nThe following programming constructs are available for the creation of subprograms:\n\n 1. function\n 2. procedure\n 3. return\n 4. local (variable scope)\n 5. global (variable scope)\n\n## Utilizing Exploration for Debugging\n\nAmiBroker provides a very easy to use form of program output to help with analysis and as a tool for debugging. You have probably already seen the **Explore** button right beside the **Backtest** button. **Explore** allows you to output various values created by your **AFL** code in an easy to read spreadsheet format. This output is displayed in the **Results** tab\u2014the same place where a backtest outputs its information. Here is an example of an exploration that prints out various indicator values:\n\n* * *\n\n \/* Sample Exploration\n Print out some indicator values *\/\n Filter= 1;\n myMACD = MACD(12,26);\n myRSI = RSI(14);\n myStoch = StochD(14,3,3);\n myMovAvg = MA(C,19);\n myClose = C;\n AddColumn(myRSI,\"RSI\");\n AddColumn(myStoch,\"StochD\");\n AddColumn(C,\"Close\");\n AddColumn(C>myMovAvg,\"C>MAV(19)\");\n AddColumn(C,\"Close\",format= 1.4);\n\n* * *\n\nThe code snippet starts out by assigning MACD, RSI, StochD, and MAV values to four user-defined variables: myMACD, myRSI, myStoch, and myAvg. These variables are then used in the **AddColumn** function along with a descriptive name. **AddColumn** can take a variable number of parameters, but most of the time you will only need to pass two or three. The first parameter is the name of the array that you want to print and the second parameter is a string that will be printed as the column heading. The third and optional parameter is the format the array will be printed out in. Figure A.1 shows the printout of this particular exploration.\n\n**Figure A.1** Results of an exploration with three parameters.\n\nNotice how the first \"Close\" column only shows two decimal places, whereas the second \"Close\" column has been formatted to show four. The **AddColumn** capability is very powerful because it is so easy to print out the internal workings of your algorithm. This tool comes in really handy when a trading algorithm isn't performing the way you intended\u2014just print out the values that make up the criteria of your **buy \/ sell \/ short \/ cover** logic. Remember to include Filter = 1 at the top of your code listing. This informs AmiBroker to go ahead and allow values to be printed out in a spreadsheet format in the **Results** window.\n\nHere is the source code from Chapter 4 that included some interesting topics that is discussed here.\n\n* * *\n\n \/\/Chapter 2 MACD utilizing AMIBROKERS\n \/\/Exploration Feature\n Filter = 1;\n PositionSize = MarginDeposit = 1;\n\n* * *\n\nSetting **Filter** = 1 turns on the **Exploration** tool. **PositionSize = MarginDeposit = 1** facilitates futures trading mode.\n\n* * *\n\n myMACD = MACD(fast=12,slow =26);\n myMACDAvg = MA(myMACD,9);\n myMACDDiff = myMACD - MYMACDAvg;\n leftBar2 = Ref(myMACDDiff,-4);\n leftBar1 = Ref(myMACDDiff,-3);\n centerBar = Ref(myMACDDiff,-2);\n rightBar1 = Ref(myMACDDiff,-1);\n rightBar2 = Ref(myMACDDiff,0);\n\n* * *\n\nCall the **MACD** function and calculate the difference between it and its nine-period smoothing average. Utilize **Ref** to get historic values in the **myMACDDiff** array. Visualize the MACD difference plotted as a histogram. This bit of code is gathering information to determine if pivot point of the histogram has occurred. **CenterBar** is two bars back and leftBar1, leftBar2, rightBar1, and rightBar2 are self-explanatory.\n\n* * *\n\n COND3 = C > MA(C,100);\n COND1 = centerBar < 0 AND centerBar < Min(leftBar2, leftBar1) AND centerBar < min(rightBar1,rightBar2);\n COND2 = centerBar > 0 AND centerBar > Max(leftBar2, leftBar1) AND centerBar > Max(rightBar1,rightBar2);\n\n* * *\n\n 1. **COND3** is set to true when the close is above the 100-day moving average.\n 2. **COND1** is set to true when the center bar forms a pivot low and is below 0.\n 3. **COND2** is set to true when the center bar forms a pivot high and is above 0.\n\n* * *\n\n Buy = COND1 AND COND3;\n Short = COND2 AND NOT(COND3);\n BuyPrice = C;\n ShortPrice = C;\n longEntryPrice = ValueWhen(Buy,BuyPrice,1);\n shortEntryPrice = ValueWhen(Short,ShortPrice,1);\n Buy = ExRem(Buy,Short);\n Short = ExRem(Short,Buy);\n\n* * *\n\nThe **Buy** array is filled with 1's when a pivot low has formed below zero in the histogram and the current price is below the 100-day moving average. The **Short** array is filled with 1's when a pivot high has formed and the current price is below the 100-day moving average. The **longEntryPrice** is captured when **Buy** is set to 1. The **ValueWhen** function returns the second array value when the first array is set to 1. You must use the **ExRem** function to remove redundant Buys and Shorts. In other words, only turn subsequent Buys on or Shorts on when the existing long\/short positions are either liquidated or reversed.\n\n* * *\n\n Sell = Cross(C, longEntryPrice - 3 * ATR(10));\n Cover = Cross(ShortEntryPrice + 3 *ATR(10),C);\n Buy = ExRem(Buy,Sell);\n Short = ExRem(Short,Cover);\n AddColumn(longEntryPrice,\"BuyPrice\");\n AddColumn(longEntryPrice - 3 * ATR(10),\"longStop\");\n AddColumn(Sell,\"Sell ?\");\n\n* * *\n\n**Sell** array (long liquidation) is turned on when the close crosses 3 ATR below the **longEntryPrice**.\n\n## Position Sizing in Futures Mode\n\nHere is the exact formula used to apply an ATR Risk-Based Fixed Fractional money management scheme to a trading algorithm.\n\n* * *\n\n RiskPerContract = 2 * ATR(10);\n PositionRisk = 1;\n PctSize = PositionRisk * MarginDeposit \/ ( RiskPerContract * PointValue );\n SetPositionSize( PctSize, spsPercentOfEquity );\n\n* * *\n\nAt first, the formula might look confusing, but plugging in some values will help explain things. Assume you are working with the emini-SP and the **MarginDeposit** is $5,600, **PointValue** is $50, , and .\n\n**PctSize** then can be used to calculate **PositionSize** :\n\nCompare this to the Fixed Fractional calculation without using the **marginDeposit** :\n\nYou get the exact same number of contracts, and since you can't have a partial contract, the number of contracts is rounded down to 2.\n\n# Appendix B\n\n## Excel System Backtester\n\nThe Excel System Backtester (ESB) utilizes Visual Basic for Applications and Excel spreadsheets to carry out the backtesting of your algorithms. There are several data arrays, keywords, and identifiers you will want to be aware of and not use as user-defined variables. This list will be updated regularly on www.georgepruitt.com. You can link to the page from this book's companion site.\n\nThe ESB source code is open source. Feel free to use it and modify it. A lengthy discussion on how the software works can be found at www.georgepruitt.com.\n\n## Data Arrays\n\n 1. myDate()\n 2. myHigh()\n 3. myLow()\n 4. myOpen()\n 5. myClose()\n 6. myRange()\n 7. myTrueRange()\n 8. myVol()\n 9. myOpInt()\n 10. equityStream()\n\n## Keywords\n\n 1. prevMarketPosition\n 2. marketPosition\n 3. entryPrice\n 4. executionCount\n 5. entryBar\n 6. intraDayTrdCnt\n 7. multiDayOrders\n 8. Buy\n 9. Sell\n 10. ExitLong\n 11. ExitShort\n 12. myTickValue\n 13. myMinTick\n 14. RampUp\n 15. symbol\n 16. totProfit\n 17. maxDD\n 18. perCentWins\n 19. numTrades\n 20. numWins\n 21. numLosses\n 22. commsn\n 23. equityPeak\n 24. dVal\n 25. dSloVal\n 26. signalName\n 27. orderKindArr(10)\n 28. trdPriceArr(10)\n 29. orderTypeArr(10)\n 30. sigNameArr(10)\n 31. barsLong\n 32. barsShort\n 33. tradeDays\n 34. numRecords\n 35. stp\n 36. lmt\n 37. mkt\n 38. moc\n 39. myTradeCollection\n 40. EquityClass\n 41. myEquityCollection\n 42. TradeInfo\n\n## Functions and Subroutines\n\nHere is a list of available functions and subroutines in this current version of the ESB. Several of the indicators' functions are \"Data Length Dependent,\" meaning that the current value of the indicator is dependent on when it was first applied to the data. This dependency does not have an impact if a large amount of data is used. The RSI on a six-week crude chart read 59.77, whereas it read 56.77 on a one-year chart. This dependency requires the last value to be carried over into the current indicator calculation, and this is no big deal unless you call the indicator function\/subroutine multiple times on a single bar of data. Let's say you want an RSI(14) and an RSI(30) indicator calculated on the same bar; this requires a multiple function\/subroutine call where the last values of the respective RSI calculations need to be carried over. Without the use of a class structure, the only way this can be handled is to pass values back and forth to the subroutine. Here is an example of how to handle a multiple subroutine call with different parameter values:\n\n 1. **Call RSISub(myClose, 14, rsiVal1, upSumAvg1, dnSumAvg1, i, 1)**\n 2. **Call RSISub(myClose, 30, rsiVal2, upSumAvg2, dnSumAvg2, i, 1)**\n\nThe first subroutine call holds the RSI value in **rsiVal1** and the **upSumAvg1** and **dnSumAvg1** values are held over until the next subroutine call. The second subroutine call stores its RSI value in **rsiVal2** and the up sum and down sum averages in **upSumAvg2** and **dnSumAvg2** , respectively. So keep in mind that if you want to call a subroutine more than once, then you will need to create separate parameter names so that the subroutine can keep track of the different lookback lengths and indicator values.\n\n#### _Function Highest(dataList, length, index, offset)_\n\n* * *\n\n Function Highest(dataList, length, index, offset)\n Dim i As Integer\n Dim tempHH As Integer\n tempHH = 0\n For i = (index - offfset) - (length - 1) To (index - offset)\n If (dataList(i) > tempHH) Then tempHH = myHigh(i)\n Next i\n Highest = tempHH\n End Function\n\n* * *\n\n#### _Sub RSISub(dataList, length, rsiVal, upSumAvg, dnSumAvg, index, offset)_\n\n* * *\n\n Sub RSISub(dataList, length, rsiVal, upSumAvg, dnSumAvg, index, offset)\n Dim i As Integer\n Dim diff1, diff2, upSum, dnSum As Double\n upSum = 0\n dnSum = 0\n If upSumAvg = 0 And dnSumAvg = 0 Then 'seed the original RSI Value\n For i = (index - offset) - (length - 1) To\n (index - offset)\n If dataList(i) > dataList(i - 1) Then\n diff1 = dataList(i) - dataList(i - 1)\n upSum = upSum + diff1\n End If\n If dataList(i) < dataList(i - 1) Then\n diff2 = dataList(i - 1) - dataList(i)\n dnSum = dnSum + diff2\n End If\n Next i\n upSumAvg = upSum \/ length\n dnSumAvg = dnSum \/ length\n Else\n If dataList(index - offset) > dataList(index - 1 - offset) Then\n diff1 = dataList(index - offset) - dataList(index - 1 - offset)\n upSum = upSum + diff1\n End If\n If dataList(index - offset) < dataList(index - 1 - offset) Then\n diff2 = dataList(index - 1 - offset) - dataList(index - offset)\n dnSum = dnSum + diff2\n End If\n upSumAvg = (upSumAvg * (length - 1) + upSum) \/ length\n dnSumAvg = (dnSumAvg * (length - 1) + dnSum) \/ length\n End If\n If upSumAvg + dnSumAvg <> 0 Then\n rsiVal = (100 * (upSumAvg)) \/ (upSumAvg + dnSumAvg)\n Else\n rsiVal = 0\n End If\n End Sub\n\n* * *\n\n#### _Function RSI(dataList, length, index, offset)_\n\n* * *\n\n Function RSI(dataList, length, index, offset)\n Dim i As Integer\n Dim diff1, diff2, upSum, dnSum As Double\n Static upSumAvg, dnSumAvg As Double\n upSum = 0\n dnSum = 0\n If upSumAvg = 0 And dnSumAvg = 0 Then\n 'seed the original RSI Value\n For i = (index - offset) - (length - 1) To\n (index - offset)\n If dataList(i) > dataList(i - 1) Then\n diff1 = dataList(i) - dataList(i - 1)\n upSum = upSum + diff1\n End If\n If dataList(i) < dataList(i - 1) Then\n diff2 = dataList(i - 1) - dataList(i)\n dnSum = dnSum + diff2\n End If\n Next i\n upSumAvg = upSum \/ length\n dnSumAvg = dnSum \/ length\n Else\n If dataList(index - offset) > dataList(index - 1 - offset) Then\n diff1 = dataList(index - offset) -\n \t dataList(index - 1 - offset)\n upSum = upSum + diff1\n End If\n If dataList(index - offset) < dataList(index - 1 - offset) Then\n diff2 = dataList(index - 1 - offset) - dataList(index - offset)\n dnSum = dnSum + diff2\n End If\n upSumAvg = (upSumAvg * (length - 1) + upSum) \/ length\n dnSumAvg = (dnSumAvg * (length - 1) + dnSum) \/ length\n End If\n If upSumAvg + dnSumAvg <> 0 Then\n RSI = (100 * (upSumAvg)) \/ (upSumAvg + dnSumAvg)\n Else\n RSI = 0\n End If\n End Function\n\n* * *\n\n#### _Function Lowest(dataList, length, index, offset)_\n\n* * *\n\n Function Lowest(dataList, length, index, offset)\n Dim i As Integer\n Dim tempLL As Double\n tempLL = 999999\n For i = (index - offset) - (length - 1) To (index - offset)\n If (dataList(i) < tempLL) Then tempLL = myLow(i)\n Next i\n Lowest = tempLL\n End Function\n\n* * *\n\n#### _Sub BollingerBand(dataList, length, numDevs, avg, upBand, dnBand, index, offset)_\n\n* * *\n\n Sub BollingerBand(dataList, length, numDevs, avg, upBand,\n dnBand, index, offset)\n Dim i As Integer\n Dim sum, sum1, myDev As Double\n For i = (index - offset) - (length - 1) To (index - offset)\n sum = sum + dataList(i)\n sum1 = sum1 + dataList(i) ^ 2\n Next i\n avg = sum \/ length\n myDev = ((length * sum1 - sum ^ 2) \/ (length * (length - 1))) ^ 0.5\n upBand = avg + myDev * numDevs\n dnBand = avg - myDev * numDevs\n End Sub\n\n* * *\n\n#### _Function Average(dataList, length, index, offset)_\n\n* * *\n\n Function Average(dataList, length, index, offset)\n Dim i As Integer\n Dim sum, sum1, myDev As Double\n For i = (index - offset) - (length - 1) To index - offset\n sum = sum + dataList(i)\n Next i\n Average = sum \/ length\n End Function\n\n* * *\n\n#### _Function Xaverage(dataList, prevXavg, length, index, offset)_\n\n* * *\n\n Function Xaverage(dataList, prevXavg, length, index, offset)\n If prevXavg = 0 Then\n Xaverage = dataList(index - offset)\n Else\n Xaverage = prevXavg + 2 \/ length * (dataList(index\n - offset) - prevXavg)\n End If\n End Function\n\n* * *\n\n#### _Sub MACD(dataList, shortLen, longLen, smooth, myMacd, mySmoothMacd, xMavg1, xMavg2, index, offset)_\n\n* * *\n\n Sub MACD(dataList, shortLen, longLen, smooth, myMacd,\n mySmoothMacd, xMavg1, xMavg2, index, offset)\n If xMavg1 = 0 And xMavg2 = 0 Then\n xMavg1 = dataList(index - offset)\n xMavg2 = dataList(index - offset)\n myMacd = 0\n mySmoothMacd = 0\n Else\n xMavg1 = xMavg1 + 2 \/ shortLen * (dataList(index\n - offset) - xMavg1)\n xMavg2 = xMavg2 + 2 \/ longLen * (dataList(index\n - offset) - xMavg2)\n myMacd = xMavg1 - xMavg2\n mySmoothMacd = mySmoothMacd + 2 \/ smooth * (myMacd - mySmoothMacd)\n End If\n End Sub\n\n* * *\n\n### Sub Stochastic(kLen, dLen, dSloLen, kVal, dVal, dSloVal, index, offset)\n\n* * *\n\n Sub Stochastic(kLen, dLen, dSloLen, kVal, dVal, dSloVal, index, offset)\n Dim index1, index2, hh, ll, sum As Double\n Dim i, j, k As Integer\n Dim kSto(100) As Double\n Dim dSto(100) As Double\n indexPt = index - offset\n index1 = kLen + dLen\n index2 = dLen - 1\n If (kVal + dVal + dSloVal = 0) Then\n 'seed the original Sto Value\n For i = 1 To dLen + dSloLen - 1\n hh = 0\n ll = 999999\n For k = indexPt - (index1 - (i - 1)) To\n indexPt - (index2 - (i - 1))\n If (myHigh(k) > hh) Then hh = myHigh(k)\n If (myLow(k) < ll) Then ll = myLow(k)\n Next k\n If (hh - ll = 0) Then hh = ll + 1\n kSto(i) = (myClose(indexPt - (index2 - (i - 1)))\n - ll) \/ (hh - ll) * 100#\n kVal = kSto(i)\n If (i > dLen) Then\n sum = 0#\n For j = i - 2 To i\n sum = sum + kSto(j)\n Next j\n dSto(i) = sum \/ dLen\n dVal = dSto(i)\n End If\n If (i >= dLen + dSloLen - 1) Then\n sum = 0#\n For j = i - 2 To i\n sum = sum + dSto(j)\n Next j\n dSloVal = sum \/ dSloLen\n End If\n Next i\n Else\n hh = 0\n ll = 999999\n For i = indexPt - (kLen - 1) To indexPt\n If (myHigh(i) > hh) Then hh = myHigh(i)\n If (myLow(i) < ll) Then ll = myLow(i)\n Next i\n kVal = (myClose(indexPt) - ll) \/ (hh - ll) * 100\n dVal = ((dVal * (dLen - 1)) + kVal) \/ dLen\n dSloVal = ((dSloVal * (dSloLen - 1)) + dVal) \/ dSloLen\n End If\n End Sub\n\n* * *\n\n# Appendix C\n\n## Python System Backtester\n\nThe Python System Backtester (PSB) utilizes the Python programming language to carry out the backtesting of your algorithms. There are several data arrays, keywords, and identifiers you will want to be aware of and not use as user-defined variables. This list will be updated regularly on www.georgepruitt.com.\n\n## Data Arrays or Lists\n\n 1. listOfTrades\n 2. marketPosition\n 3. entryPrice\n 4. entryQuant\n 5. exitQuant\n 6. trueRanges\n 7. myDate\n 8. myTime\n 9. myOpen\n 10. myHigh\n 11. myLow\n 12. myClose\n 13. myVolume\n 14. myOpInt\n 15. dataClassList\n 16. systemMarketList\n 17. equityDataList\n 18. fileList\n 19. exitQuant\n\n## Keywords and Identifiers\n\n 1. currentPrice\n 2. totComms\n 3. barsSinceEntry\n 4. numRuns\n 5. myBPV\n 6. allowPyr\n 7. curShares\n 8. numMarkets\n 9. portfolio\n 10. commission\n 11. numBarsToGoBack\n 12. rampUp\n 13. price\n 14. trades\n 15. totProfit\n 16. todaysCTE\n 17. todaysOTE\n 18. tradeName\n 19. mp\n 20. entryDate\n 21. exitDate\n\n## Classes\n\n#### _equityClass_\n\n* * *\n\n class equityClass(object):\n def __init__(self):\n self.equityDate = list()\n self.equityItm = list()\n self.clsTrdEquity = list()\n self.openTrdEquity = list()\n self.cumuClsEquity = 0\n self.dailyEquityVal = list()\n self.peakEquity = 0\n self.minEquity = 0\n self.maxDD = 0\n def setEquityInfo(self,equityDate,equityItm,clsTrdEquity, openTrdEquity):\n self.equityDate.append(equityDate)\n self.equityItm.append(equityItm)\n self.cumuClsEquity += clsTrdEquity\n tempEqu =self.cumuClsEquity+openTrdEquity\n self.dailyEquityVal.append(tempEqu)\n self.peakEquity = max(self.peakEquity,tempEqu)\n maxEqu = self.peakEquity\n self.minEquity = min(self.minEquity,tempEqu)\n minEqu = self.minEquity\n self.maxDD = max(self.maxDD,maxEqu-tempEqu)\n maxDD = self.maxDD\n maxDD = maxDD\n\n* * *\n\n#### _marketDataClass_\n\n* * *\n\n class marketDataClass(object):\n def __init__(self):\n self.symbol = \"\"\n self.minMove = 0\n self.bigPtVal = 0\n self.seed = 0\n self.date = list()\n self.open = list()\n self.high = list()\n self.low = list()\n self.close = list()\n self.volume = list()\n self.opInt = list()\n self.dataPoints = 0\n def setDataAttributes(self,symbol,bigPtVal,minMove):\n self.symbol = symbol\n self.minMove = minMove\n self.bigPtVal = bigPtVal\n def readData(self,date,open,high,low,close,volume,opInt):\n self.date.append(date)\n self.open.append(open)\n self.high.append(high)\n self.low.append(low)\n self.close.append(close)\n self.volume.append(volume)\n self.opInt.append(opInt)\n self.dataPoints += 1\n\n* * *\n\n#### _tradeInfoClass_\n\n* * *\n\n class tradeInfo(object):\n def __init__(self,tradeOrder,tradeDate,tradeName, tradePrice,quant,entryOrExit):\n self.tradeOrder = tradeOrder\n self.tradeDate = tradeDate\n self.tradeName = tradeName\n self.tradePrice = tradePrice\n self.quant = quant\n self.tradeProfit = 0\n self.cumuProfit = 0\n self.entryOrExit = entryOrExit\n # print(\"populating info: \",self.tradeName,' ', # self.tradePrice)\n def calcTradeProfit(self,order,curPos,entryPrice,\n exitPrice,entryQuant,numShares):\n profit = 0\n totEntryQuant = 0\n tempNumShares = numShares\n numEntriesLookBack = 0\n for numEntries in range(0,len(entryPrice)):\n ## totEntryQuant += entryQuant[numEntries]\n if tempNumShares >= entryQuant[numEntries]:\n tempNumShares -= entryQuant[numEntries]\n numEntriesLookBack += 1\n if tempNumShares > 0 : numEntriesLookBack += 1\n tempNumShares = numShares\n for numEntries in range(0,numEntriesLookBack):\n if numEntries < 0:\n numEntries = 1\n if entryQuant[numEntries] < tempNumShares:\n peelAmt = entryQuant[numEntries]\n tempNumShares = tempNumShares - peelAmt\n if entryQuant[numEntries] >= tempNumShares:\n peelAmt = tempNumShares\n if order == 'buy':\n if curPos < 0:\n profit = profit + (entryPrice[numEntries] - exitPrice) * peelAmt\n elif order == 'sell':\n if curPos > 0:\n profit = profit + (exitPrice - entryPrice[numEntries]) * peelAmt\n elif order == 'liqLong':\n if curPos > 0:\n profit = profit + (exitPrice - entryPrice[numEntries]) * peelAmt\n elif order == 'liqShort':\n if curPos < 0:\n profit = profit + (entryPrice[numEntries] - exitPrice) * peelAmt\n if entryQuant[numEntries] == peelAmt :\n entryPrice.pop(numEntries)\n entryQuant.pop(numEntries)\n elif entryQuant[numEntries] > peelAmt:\n entryQuant[numEntries] = entryQuant[numEntries] - peelAmt\n return profit\n def printTrade(self):\n print( '%8.0f %10s %2.0d %8.4f %10.2f %10.2f' % (self.tradeDate, self.tradeName, self.quant, self.tradePrice,self.tradeProfit, self.cumuProfit))\n\n* * *\n\n#### _portfolioClass_\n\n* * *\n\n from systemMarket import systemMarketClass\n class portfolioClass(object):\n def __init__(self):\n self.portfolioName = \"\"\n self.systemMarkets = list()\n self.portEquityDate = list()\n self.portEquityVal = list()\n self.portclsTrdEquity = list()\n self.portDailyEquityVal = list()\n self.portPeakEquity = 0\n self.portMinEquity = 0\n self.portMaxDD = 0\n tempEqu = 0\n cumEqu = 0\n maxEqu = -999999999\n minEqu = 999999999\n maxDD = 0\n def setPortfolioInfo(self,name,systemMarket):\n self.portfolioName = name\n self.systemMarkets = list(systemMarket)\n masterDateList = list()\n monthList = list()\n monthEquity = list()\n combinedEquity = list()\n self.portPeakEquity = -999999999999\n self.portMinEquity = -999999999999\n for i in range(0,len(self.systemMarkets)):\n masterDateList += self.systemMarkets[i].equity.equityDate\n sysName = self.systemMarkets[i].systemName\n market = self.systemMarkets[i].symbol\n avgWin = self.systemMarkets[i].avgWin\n sysMark =self.systemMarkets[i]\n avgLoss = sysMark.avgLoss\n totProf = sysMark.profitLoss\n totTrades = sysMark.numTrades\n maxD = sysMark.maxxDD\n perWins = sysMark.perWins\n tempStr =\"\"\n if len(sysName) - 9 > 0:\n for j in range(0,len(sysName)-8):\n tempStr = tempStr + ' '\n if i == 0: print('SysName',tempStr,'Market TotProfit MaxDD AvgWin AvgLoss PerWins TotTrades')\n print('%s %s %12d %6d %5d %5d %3.2f %4d' % (sysName,market,totProf,maxD, avgWin,avgLoss,perWins,totTrades))\n masterDateList = removeDuplicates(masterDateList)\n masterDateList = sorted(masterDateList)\n # print(masterDateList)\n self.portEquityDate = masterDateList\n monthList = createMonthList(masterDateList)\n for i in range(0,len(masterDateList)):\n cumuVal = 0\n for j in range(0,len(self.systemMarkets)):\n skipDay = 0\n try:\n idx = self.systemMarkets[j] .equity.equityDate.index(masterDateList[i])\n except ValueError:\n skipDay = 1\n if skipDay == 0:\n cumuVal += self.systemMarkets[j] .equity.dailyEquityVal[idx]\n combinedEquity.append(cumuVal)\n self.portEquityVal.append(cumuVal)\n if cumuVal > self.portPeakEquity: self .portPeakEquity = cumuVal\n self.portMinEquity = max(self.portMinEquity, self.portPeakEquity - cumuVal)\n self.portMaxDD = self.portMinEquity\n print(\"Combined Equity: \",self.portEquityVal[-1])\n print(\"Combined MaxDD: \",self.portMaxDD)\n print(\"Combined Monthly Return\")\n for j in range(0,len(monthList)):\n idx = masterDateList.index(monthList[j])\n if j == 0:\n monthEquity.append(combinedEquity[idx])\n prevCombinedDailyEquity = monthEquity[-1]\n else:\n combinedDailyEquity = combinedEquity[idx]\n monthEquity.append(combinedDailyEquity - prevCombinedDailyEquity)\n prevCombinedDailyEquity = combinedDailyEquity\n print('%8d %10.0f %10.0f ' % (monthList[j], monthEquity[j],combinedEquity[idx]))\n def removeDuplicates(li):\n my_set = set()\n res = []\n for e in li:\n if e not in my_set:\n res.append(e)\n my_set.add(e)\n return res\n def createMonthList(li):\n myMonthList = list()\n for i in range(0,len(li)):\n if i != 0:\n tempa = int(li[i]\/100)\n pMonth = int(li[i-1]\/100) % 100\n month = int(li[i]\/100) % 100\n if pMonth != month:\n myMonthList.append(li[i-1])\n if i == len(li)-1:\n myMonthList.append(li[i])\n return myMonthList\n\n* * *\n\n## Indicator Classes and Functions\n\nSome indicators are programmed as classes due to their \"data length dependence.\" Each indicator class can be instantiated multiple times, so the same indicator can be calculated multiple times on the same data bar.\n\n#### _class stochClass(object)_\n\n* * *\n\n class stochClass(object):\n def __init__(self):\n self.fastK = 0\n self.fastD = 0\n self.slowD = 0\n self.seed = 0\n def calcStochastic(self,kLen,dLen,dSloLen,hPrices, lPrices,cPrices,curBar,offset):\n curBarLookBack = curBar - offset\n testSeed = self.seed\n if self.seed == 0:\n self.seed = 1\n stoKList =[]\n stoDList = []\n index1 = kLen - 1 + dLen - 1 + dSloLen -1\n index2 = dLen - 1 + dSloLen -1\n loopCnt = 0\n for i in range(0,index2+1):\n loopCnt = loopCnt + 1\n hh = 0\n ll = 9999999\n lowRngBound = curBarLookBack - (index1 - i)\n highRngBound =lowRngBound + 3\n for k in range(lowRngBound,highRngBound):\n if hPrices[k] > hh:\n hh = hPrices[k]\n if lPrices[k] < ll:\n ll = lPrices[k]\n if hh - ll == 0.0:\n hh = ll + 1\n whichClose = curBarLookBack - (index2 -i)\n stoKList.append((cPrices[whichClose] - ll) \/ (hh - ll) *100)\n lenOfStoKList = len(stoKList)\n self.fastK = stoKList[len(stoKList)-1]\n if (i >= dLen-1):\n tempSum = 0\n lowRngBound = len(stoKList)-dLen\n highRngBound = lowRngBound + dLen\n for j in range(lowRngBound,highRngBound):\n tempSum += stoKList[j]\n stoDList.append(tempSum\/dLen)\n self.fastD = stoDList[len(stoDList)-1]\n if (i == index2):\n tempSum = 0\n lowRngBound = len(stoDList) - dSloLen\n highRngBound = lowRngBound + dSloLen\n for j in range(lowRngBound,highRngBound):\n tempSum += stoDList[j]\n self.slowD = tempSum \/ dSloLen\n else:\n hh = 0\n ll = 999999\n lowRngBound = curBarLookBack - (kLen - 1)\n highRngBound = lowRngBound + 3\n for i in range(lowRngBound, highRngBound):\n if hPrices[i] > hh:\n hh = hPrices[i]\n if lPrices[i] < ll:\n ll = lPrices[i]\n self.fastK = (cPrices[curBarLookBack] - ll )\/ (hh - ll) * 100\n self.fastD = (self.fastD * (dLen - 1) + self.fastK) \/ dLen\n self.slowD = ((self.slowD * (dSloLen - 1)) + self.fastD) \/ dSloLen\n return(self.fastK,self.fastD,self.slowD)\n\n* * *\n\n#### _class rsiClass(object)_\n\n* * *\n\n class rsiClass(object):\n oldDelta1 = 0\n def __init__(self):\n self.delta1 = 0\n self.delta2 = 0\n self.rsi = 0\n self.seed = 0\n def calcRsi(self,prices,lookBack,curBar,offset):\n upSum = 0.0\n dnSum = 0.0\n if self.seed == 0:\n self.seed = 1\n for i in range((curBar - offset) - (lookBack-1), curBar - offset +1):\n if prices[i] > prices[i-1]:\n diff1 = prices[i] - prices[i-1]\n upSum += diff1\n if prices[i] < prices[i-1]:\n diff2 = prices[i-1] - prices[i]\n dnSum += diff2\n self.delta1 = upSum\/lookBack\n self.delta2 = dnSum\/lookBack\n else:\n if prices[curBar - offset] > prices[curBar - 1 - offset]:\n diff1 = prices[curBar - offset] - prices[curBar - 1 - offset]\n upSum += diff1\n if prices[curBar - offset] < prices[curBar - 1 - offset]:\n diff2 = prices[curBar - 1 - offset] - prices[curBar - offset]\n dnSum += diff2\n self.delta1 = (self.delta1 * (lookBack -1) + upSum) \/ lookBack\n self.delta2 = (self.delta2 * (lookBack -1) + dnSum) \/ lookBack\n if self.delta1 + self.delta2 != 0:\n self.rsi = (100.0 * self.delta1) \/ (self.delta1 + self.delta2)\n else:\n self.rsi = 0.0\n return (self.rsi)\n\n* * *\n\n#### _Highest Function\/Module_\n\n* * *\n\n def highest(prices,lookBack,curBar,offset):\n result = 0.0\n maxVal = 0.00\n for index in range((curBar - offset) - (lookBack-1), curBar - offset +1):\n if prices[index] > maxVal:\n maxVal = prices[index]\n result = maxVal\n return result\n\n* * *\n\n#### _Lowest Function\/Module_\n\n* * *\n\n def lowest(prices,lookBack,curBar,offset):\n result = 0.0\n minVal = 9999999.0\n for index in range((curBar - offset) - (lookBack-1), curBar - offset +1):\n if prices[index] < minVal:\n minVal = prices[index]\n result = minVal\n return result\n\n* * *\n\n#### _Simple Average Function\/Module_\n\n* * *\n\n def sAverage(prices,lookBack,curBar,offset):\n result = 0.0\n for index in range((curBar - offset) - (lookBack-1), curBar - offset +1):\n result = result + prices[index]\n result = result\/float(lookBack)\n return result\n\n* * *\n\n#### _Bollinger Bands Function\/Module_\n\n* * *\n\n def bollingerBands(dates,prices,lookBack,numDevs,curBar,offset):\n sum1 = 0.0\n sum2 = 0.0\n startPt = (curBar - offset)- (lookBack-1)\n endPt = curBar - offset + 1\n for index in range(startPt,endPt):\n tempDate = dates[index]\n sum1 = sum1 + prices[index]\n sum2 = sum2 + prices[index]**2\n mean = sum1 \/ float(lookBack)\n stdDev = ((lookBack * sum2 - sum1**2) \/ (lookBack * (lookBack -1)))**0.5\n upBand = mean + numDevs*stdDev\n dnBand = mean - numDevs*stdDev\n # print(mean,\" \",stdDev,\" \",upBand,\" \",dnBand)\n return upBand, dnBand, mean\n\n* * *\n\n## Python-Specific Keywords\n\n 1. and\n 2. as\n 3. assert\n 4. break\n 5. class\n 6. continue\n 7. def\n 8. del\n 9. elif\n 10. else\n 11. except\n 12. exec\n 13. finally\n 14. for\n 15. from\n 16. global\n 17. if\n 18. import\n 19. in\n 20. is\n 21. lambda\n 22. not\n 23. or\n 24. pass\n 25. print\n 26. raise\n 27. return\n 28. try\n 29. while\n 30. with\n 31. yield\n\n### Monte Carlo and Start Trade Drawdown Source Code\n\n#### _Start Trade Drawdown section_\n\n* * *\n\n # start trade draw down analysis - utilizing the tradeTuple\n tupleLen = len(tradeTuple)\n tradeTuple = sorted(tradeTuple,key=itemgetter(0))\n for x in range(0,tupleLen):\n cumStartTradeEquity = 0\n maxStartTradeDD = -99999999\n maxCumEquity = 0\n for y in range(x,tupleLen):\n # print(\"Trade Tuple \",tradeTuple[y][0],\" \",# tradeTuple[y][1]);\n cumStartTradeEquity += tradeTuple[y][1]\n maxCumEquity = max(maxCumEquity, cumStartTradeEquity)\n maxStartTradeDD = max(maxStartTradeDD,maxCumEquity - cumStartTradeEquity)\n startTradeTuple += ((x,cumStartTradeEquity, maxStartTradeDD),)\n minDD = 99999999\n maxDD = 0\n for y in range(0,len(startTradeTuple)):\n print(startTradeTuple[y][0],' ',startTradeTuple[y][1], ' ',startTradeTuple[y][2])\n if startTradeTuple[y][2] < minDD: minDD = startTradeTuple[y][2]\n if startTradeTuple[y][2] > maxDD: maxDD = startTradeTuple[y][2]\n numBins = 20\n binTuple = list()\n binMin = minDD\n binMax = maxDD\n binInc = (maxDD - minDD)\/20.0\n binBot = binMin\n for y in range(0,numBins):\n binTop = binBot + binInc\n binTuple += ((y,binBot,binTop),)\n print(binTuple[y][1],' ',binTuple[y][2])\n binBot = binTop + y\n bins = list()\n bins[:] = []\n for x in range(0,numBins):\n bins.append(0)\n for x in range(0,len(startTradeTuple)):\n for y in range(0,numBins):\n tempDD = startTradeTuple[x][2]\n tempBot = binTuple[y][1]\n tempTop = binTuple[y][2]\n if (tempDD >= binTuple[y][1] and tempDD < binTuple[y][2]):\n # tempVal = bins(y) + 1\n # bins.insert(y,tempVal)\n bins[y] += 1\n freqSum = sum(bins)\n binProb = list()\n for y in range(0,numBins):\n if y == 0:\n binProb.append(bins[y]\/freqSum)\n else:\n binProb.append(bins[y]\/freqSum + binProb[y-1])\n for y in range(0,numBins):\n print(\"Probability of DD < %7d is %4.3f\\n\" % (binTuple[y][2], binProb[y]))\n\n* * *\n\n#### _Monte Carlo Analysis_\n\n* * *\n\n # Monte Carlo Analysis\n mcTradeTuple = list()\n for x in range(0,5): # number of alternate histories\n for y in range(0,len(tradeTuple)):\n randomTradeNum = random.randint(0, len(tradeTuple)-1)\n mcTradeTuple += ((x,y, tradeTuple[randomTradeNum][1], tradeTuple[randomTradeNum][0]),)\n mcTradeResultsTuple = list()\n whichAlt = -1\n for x in range(0,len(mcTradeTuple)):\n if mcTradeTuple[x][1]==0:\n print('New Alternate History Generated')\n cumEquity = 0\n maxTradeDD = -99999999\n maxCumEquity = 0\n cumEquity += mcTradeTuple[x][2]\n print('Randomized trade listing : ', mcTradeTuple[x][3],' ',mcTradeTuple[x][2])\n maxCumEquity = max(maxCumEquity,cumEquity)\n maxTradeDD = max(maxTradeDD,maxCumEquity - cumEquity)\n if mcTradeTuple[x][1] == len(tradeTuple)-1 :\n mcTradeResultsTuple += ((cumEquity,maxTradeDD, cumEquity\/len(tradeTuple)),)\n for x in range(0,len(mcTradeResultsTuple)):\n mcCumEquity = mcTradeResultsTuple[x][0]\n mcMaxDD = mcTradeResultsTuple[x][1]\n mcAvgTrd = mcTradeResultsTuple[x][2]\n print('Alt history %5d Profit: %10d MaxDD: %10d Avg Trade %6d\\n' % (x,mcCumEquity, mcMaxDD,mcAvgTrd))\n\n* * *\n\n# Appendix D\n\n## TradeStation and EasyLanguage\n\n## Importing ELD file from Book Website\n\nIf you need help installing the EasyLanguage code from the book website, just follow these instructions.\n\nDownload **UATSTB.eld** from website and save to your Desktop. Launch the **TradeStation Development Environmen** t and go under the **File** menu. Select **Import\/Export** and a dialog similar to the one in Figure D.1 should appear on your screen.\n\n**Figure D.1**\n\nSelect the **Import ELD** , **ELS** , **or ELA** Wizard and then click **Next**. Another dialog will appear and look like Figure D.2.\n\n**Figure D.2**\n\nNavigate to the location of your **UATSTB.eld** file. If you saved it to your Desktop, it should be there. If not, then you will need to browse to it. Select the **UATSTB.eld** file and click **Open**. Once the ELD file is open it will list the **Analysis Types** that are included (see Figure D.3). The current, hot-off-the-press, **UATSTB.eld** file may contain more types than those listed in the figure. They all should be selected already, but if they are not, then click the box beside **Select All** and then click **Next**.\n\n**Figure D.3**\n\nThe final dialog will now open and all of the Analysis Techniques included in the ELD file will be listed (see Figure D.4). If you click **Finish** , they will all be imported into your own library. Once this process has completed then you will be able to follow along in the book.\n\n**Figure D.4**\n\n## Keywords and Functions\n\nThe number of reserved words, skip words, and functions are too numerous to include in an appendix. Here is a link to a TradeStation website that provides a complete and concise list: .\n\n## Sample Algorithm Codes\n\nAll code presented in the book is available as a download on the companion website. This code includes all the necessary functions as well. Expanded research utilizing TradeStation, EasyLanguage, and Portfolio Maestro will also be included at www.georgepruitt.com.\n\n#### _Simple RSI with Profit Objective and Protective Stop_\n\n* * *\n\n inputs: rsiLen(14),overBot(70),overSold(30);\n If rsi(c,14) < overSold then buy this bar on close;\n If rsi(c,14) > overBot then sellShort this bar on close;\n If marketPosition = 1 then\n begin\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close;\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close;\n end;\n If marketPosition = 1 then\n begin\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close;\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close;\n end;\n\n* * *\n\n#### _Simple Stochastic with Profit Objective and Protective Stop_\n\n* * *\n\n inputs: rawKlen(14),smooth1(3),smooth2(3);\n vars: myFastK(0),myFastD(0),mySlowK(0),mySlowD(0);\n Value1 = stochastic(h,l,c,rawKLen,smooth1,smooth2,1,myFastK,myFastD,mySlowK,mySlowD);\n If mySlowK cross above mySlowD and mySlowD < 20 then buy this bar on close;\n If mySlowK cross below mySlowD and mySlowD > 80 then sellShort this bar on close;\n If marketPosition = 1 then\n begin\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close;\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close;\n end;\n If marketPosition =-1 then\n begin\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close;\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close;\n end;\n\n* * *\n\n#### _Simple CCI with Profit Objective and Protective Stop_\n\n* * *\n\n inputs: cciLen(20),smooth(9);\n vars: myCCIVal(0);\n myCCIVal = average(cci(cciLen),smooth);\n If myCCIVal crosses above -100 then buy this bar on close;\n If myCCIVal crosses below 100 then sellShort this bar on close;\n If marketPosition = 1 then\n begin\n If c > entryPrice + 3* avgTrueRange(10) then sell this bar on close;\n if c < entryPrice - 1* avgTrueRange(10) then sell this bar on close;\n end;\n If marketPosition =-1 then\n begin\n If c < entryPrice - 3* avgTrueRange(10) then buyToCover this bar on close;\n if c > entryPrice + 1* avgTrueRange(10) then buyToCover this bar on close;\n end;\n\n* * *\n\n#### _Connors \/ Alvarez with Time-Based Exit_\n\n* * *\n\n inputs: mavlen(200),rsiLen(2),rsiBuyVal(20),rsiSellVal(80),holdPeriod(5);\n Condition1 = c > average(c,mavLen);\n Condition2 = rsi(c,rsiLen) < rsiBuyVal;\n Condition3 = rsi(c,rsiLen) > rsiSellVal;\n If condition1 and condition2 then buy this bar on close;\n If not(condition1) and condition3 then sellShort this bar on close;\n If barsSinceEntry = holdPeriod then\n Begin\n if marketPosition = 1 then sell this bar on close;\n if marketPosition =-1 then buytocover this bar on close;\n end;\n\n* * *\n\n#### _Turtle with LTL Filter, Pyramiding and Position Sizing_\n\n* * *\n\n inputs: absEntryChanLen(55),entryChanlen(20),exitChanLen(10),\n lastTradeLoserFilter(TRUE),accountSize(100000),riskPerTradePer(.01),numPyraMids(1);\n vars:lastTradeLoser(true),mp(0),virtmp(0),tradeProfit(0),\n virtBuyPrice(0),virtSellPrice(0),\n virtLongLiqPrice(0),virtShortLiqPrice(0),\n virtLongLoss(0),virtShortLoss(0),\n myFillPrice(0),N(0),N$(0),dollarRisk(0),lotSize(0),\n stopLoss(0),buyPrice(0),sellPrice(0),\n hh20(0),hh55(0),ll20(0),ll55(0),iCnt(0),initPrice(0),stopLossPts(0),debug(TRUE);\n mp = marketPosition;\n if mp = 0 then\n begin\n N = AvgTrueRange(20);\n N$ = N*BigPointValue;\n dollarRisk = AccountSize * riskPerTradePer;\n lotSize = IntPortion(DollarRisk\/N$);\n if lotSize < 1 then lotSize = 1;\n lotSize = 1;\n StopLoss = 2 * N$ * lotSize;\n StopLossPts = 2 * N * lotSize;\n StopLossPts = 2000\/bigPointValue;\n hh20 = highest(high,entryChanLen);\n hh55 = highest(high,absEntryChanLen);\n ll20 = lowest(low,entryChanLen);\n ll55 = lowest(low,absEntryChanLen);\n end;\n If mp <> 1 and mp[1] = 1 then\n Begin\n tradeProfit = ExitPrice(1) - EntryPrice(1);\n lastTradeLoser = true;\n If tradeProfit > 0 then lastTradeLoser = false;\n if debug then\n print(date,\" Long Trader \",tradeProfit *bigPointValue,\" \",lastTradeLoser,\n \" ExitPrice \",ExitPrice(1):6:6,\" entryPrice \",entryPrice(1):6:6);\n end;\n If mp <> -1 and mp[1] = -1 then\n Begin\n tradeProfit = EntryPrice(1) - ExitPrice(1);\n lastTradeLoser = true;\n If tradeProfit > 0 then lastTradeLoser = false;\n if debug then\n print(date,\" **** Short Trader \",tradeProfit *bigPointValue,\" \",lastTradeLoser,\n \" mp \",mp,\" \",mp[1]);\n end;\n If lastTradeLoserFilter = False then lastTradeLoser = True;\n If lastTradeLoser = False then\n Begin\n if debug then\n print(date,\" In Virtual Section And VirtTmp = \",virTmp);\n If(virtmp = 1) then\n Begin\n virtLongLiqPrice = maxList(lowest(low[1],exitChanLen),virtLongLoss);\n if(virtualLongExit(virtLongLiqPrice,1,myFillPrice) =1) then\n Begin\n tradeProfit = myFillPrice - virtBuyPrice;\n If tradeProfit < 0 then lastTradeLoser = true;\n virtmp = 0;\n if debug then print(\" Long Exit @ \",myFillPrice);\n end;\n end;\n If(virtmp = -1) then\n Begin\n virtShortLiqPrice = minList(highest(high[1],exitChanLen),virtShortLoss);\n if(virtualShortExit(virtShortLiqPrice,1,myFillPrice) =1) then\n Begin\n tradeProfit = virtSellPrice - myFillPrice;\n If tradeProfit < 0 then lastTradeLoser = true;\n virtmp = 0;\n if debug then print(\" ShortExit @ \", myFillPrice);\n end;\n end;\n if(virtualBuy(highest(high[1],entryChanLen),1,myFillPrice) = 1) then\n Begin\n if virtmp <> 1 then\n begin\n virtBuyPrice = myFillPrice;\n virtLongLoss = myFillPrice - stopLossPts;\n virtmp = 1;\n tradeProfit = 0;\n If virtmp[1] = -1 then tradeProfit = virtSellPrice - virtBuyPrice;\n If tradeProfit < 0 then lastTradeLoser = true;\n if debug then print(\" Long @ \",myFillPrice);\n end;\n end;\n if(virtualSell(lowest(low[1],entryChanLen),1,myFillPrice) = 1) then\n Begin\n if virtmp <> -1 then\n begin\n virtsellPrice = myFillPrice;\n virtShortLoss = myFillPrice + stopLossPts;\n virtmp = -1;\n tradeProfit = 0;\n If virtmp[1] = 1 then tradeProfit = virtBuyPrice - virtSellPrice;\n If tradeProfit < 0 then lastTradeLoser = true;\n if debug then print(\" Short @ \",myFillPrice, \" trade Profit\" , tradeProfit);\n end;\n end;\n if debug then print(\"End of Virtual Module : virTmp = \",virTmp,\" \",lastTradeLoser);\n end;\n for iCnt = 0 to numPyraMids-1\n begin\n if lastTradeLoser then\n begin\n if mp <> -1 and currentContracts = iCnt * lotSize then\n begin\n buyPrice = hh20 + iCnt * N\/2;\n end;\n if mp <> 1 and currentContracts = iCnt * lotSize then\n begin\n sellPrice = ll20 - iCnt * N\/2;\n end;\n virTmp = 0;\n end;\n if lastTradeLoser = false then\n begin\n if mp <> -1 and currentContracts = iCnt * lotSize then\n begin\n buyPrice = hh55 + iCnt * N\/2;\n end;\n if mp <> 1 and currentContracts = iCnt * lotSize then\n begin\n sellPrice = ll55 - iCnt * N\/2;\n end;\n virTmp = 0;\n end;\n end;\n if lastTradeLoser then\n begin\n if currentContracts < numPyraMids * lotsize then Buy (\"Turtle20Buy\") lotSize contracts next bar at buyPrice stop;\n if currentContracts < numPyraMids * lotsize then Sellshort (\"Turtle20Sell\") lotsize contracts next bar at sellPrice stop;\n if currentContracts < 4 * lotsize and debug then print(date,\" 20sellPrice \",sellPrice:6:6,\" \", currentContracts);\n end;\n if lastTradeLoser = false then\n begin\n if currentContracts < numPyraMids * lotsize then Buy (\"Turtle55Buy\") lotSize contracts next bar at buyPrice stop;\n if currentContracts < numPyraMids * lotsize then Sellshort (\"Turtle55Sell\") lotsize contracts next bar at sellPrice stop;\n if debug then print(date,\" \",iCnt,\" 55sellPrice \", sellPrice:6:6);\n end;\n If mp = 1 then Sell (\"TurtleSys1LExit\") from entry(\"Turtle20Buy\") next bar at lowest(low,exitChanLen) stop;\n If mp = -1 then BuyToCover(\"TurtleSys1SExit\")from entry(\"Turtle20Sell\") next bar at highest(high,exitChanLen) stop;\n If mp = 1 then Sell (\"TurtleSys2LExit\") from entry(\"Turtle55Buy\") next bar at lowest(low,20) stop;\n If mp = -1 then BuyToCover(\"TurtleSys2SExit\")from entry(\"Turtle55Sell\") next bar at highest(high,20) stop;\n If mp = 1 then Sell (\"TurtleLExit2N\") next bar at entryPrice - stopLossPts stop;\n If mp = -1 then BuyToCover(\"TurtleSExit2N\") next bar at entryPrice + stopLossPts stop;\n\n* * *\n\n#### _EasyLanguage Code for TA1_\n\n* * *\n\n inputs:\n cmiLen(20),cmiSmooth(9),markCondIndicVal(50),chopBuyPer(.5),chopSellPer(.5),trendBBOLen(9),trendSBOLen(9);\n inputs: volLen(20)\n value1 = choppyMarketIndex(cmiLen);\n value2 = xaverage(value1,cmiSmooth);\n if value2 < markCondIndicVal then\n begin\n buy(\"ChopBuy\")next bar at highest(h,trendBBOLen) stop;\n sellshort(\"ChopSell\") next bar at lowest(l,trendSBOLen) stop;\n end;\n if value2 >= markCondIndicVal then\n begin\n buy(\"TrendBuy\") next bar at c + xaverage(range,volLen)*volPer stop;\n sellShort(\"TrendSell\") next bar at c - xaverage(range,volLen)*volPer stop;\n end;\n\n* * *\n\n#### _EasyLanguage Code for TA2_\n\n* * *\n\n Inputs: buyLen(40),sellLen(40),longLiqLen(20),sellliqLen(20);\n Buy next bar at highest(h[1],buyLen) stop;\n Sellshort next bar at lowest(l[1],sellLen) stop;\n If Marketposition = 1 then sell next bar at lowest(low[1],longLiqLen) stop;\n If Marketposition = -1 then buytocover next bar at highest(high[1],sellLiqLen) stop;\n\n* * *\n\n### EasyLanguage Code for TA3\n\n* * *\n\n inputs:movAvgLen(50),pivotHiLookBack(10),pivotHiStrength(2),pivotLowLookBack(10),pivotLowStrength(2);\n inputs: LprofitObj(500),LstopLoss(500),longExitDays(10),SprofitObj(500),SstopLoss(500),shortExitDays(10);\n Value1 = swingHighBar(1,h,pivotHiStrength,pivotHiLookBack);\n Value2 = swingLowBar(1,l,pivotLowStrength,pivotLowLookBack);\n If c > average(c,movAvgLen) then\n Begin\n If Value2 > -1 and marketPosition <> 1 then buy this bar on close;\n end;\n If c < average(c,movAvgLen) then\n Begin\n If Value1 > -1 and marketPosition <> -1 then sellshort this bar on close;\n end;\n If Marketposition = 1 then\n Begin\n sell(\"L-profitObj\") next bar at entryPrice + LprofitObj\/Bigpointvalue limit;\n sell(\"L-protStop\") next bar at entryPrice - LstopLoss\/Bigpointvalue stop;\n If Barssinceentry >= longExitDays then sell this bar on close;\n end;\n If Marketposition = -1 then\n Begin\n Buytocover(\"S-profitObj\") next bar at entryPrice - SprofitObj\/Bigpointvalue limit;\n BuyToCover(\"S-protStop\") next bar at entryPrice + SstopLoss\/Bigpointvalue stop;\n If Barssinceentry >= shortExitDays then sell this bar on close;\n end;\n\n* * *\n\n# Appendix E\n\n### A list of George's favorite books on Algorithmic Trading\n\n**Oldies**\n\n * **Computer Analysis of the Futures Market** by LeBeau and Lucas\n * **New Concepts in Technical Trading Systems** by Welles Wilder\n * **The Elements of Successful Trading** by Robert Rotella\n * **Portfolio Management Formulas** by Ralph Vince\n * **Trading Systems and Methods** (any edition) by Perry Kaufman\n * **Trading Systems That Work** by Thomas Stridsman\n * **Money Management Strategies for Futures Traders** by Nauzer Balsara\n * **Street Smarts: High Probability Short-Term Trading Strategies** by Linda Bradford Raschke and Laurence A. Connors\n * **New Market Timing Techniques** by Tom DeMark\n * **How I Made One Million Dollars Last Year Trading Commodities** by Larry Williams\n * **Trading for a Living** by Alexander Elder\n * **How to Make Money in Commodities** by Chester Keltner\n\n**Newbies**\n\n * **Quantitative Technical Analysis** by Dr. Howard Bandy\n * **Modeling Trading System Performance** by Dr. Howard Bandy\n * **Evidenced-Based Technical Analysis** by David Aronson\n * **Statistically Sound Machine Learning for Algorithmic Trading of Financial Instruments** by David Aronson and Timothy Masters\n * **The Evaluation and Optimization of Trading Strategies** by Bob Pardo\n * **Building Winning Algorithmic Trading Systems** by Kevin Davey\n * **Trading Systems: A New Approach to System Development and Portfolio Optimization** by Emilio Tomasini\n * **Algorithmic Trading** by Ernie Chan\n * **Building Reliable Trading System** by Keith Fitschen\n * **Using EasyLanguage 9.X** by Murray Ruggiero\n\n**Programming Books**\n\n * **Python Programming** by John Zelle\n * **Genetic Algorithms and Investment Strategies** by Richard Bauer\n * **Mastering VBA for Microsoft Office** by Richard Mansfield\n * **Python for Finance** by Yves Hilpisch\n\n# About the Companion Website\n\nAll of the source code for the trading algorithms, data, and testing platforms is included on the Wiley website.\n\nIn addition, the website www.georgepruitt.com will provide updates to the trading algorithms, data, and testing platforms. You will also find more tools to add to your toolbox that weren't mentioned in the book. Questions can be directed to George using his george.p.pruitt@gmail.com email address.\n\n# Index\n\n## A\n\n 1. Absolute price oscillator (APO)\n 2. ACCEPT state\n 3. _Adaptation in Natural and Artificial Systems_ (Holland)\n 4. ADX. _See_ Average Directional Movement Index \n 5. ADXR\n 6. AFL. _See_ AmiBroker Function Language \n 7. Algorithm \n 1. backtesting \n 1. Excel, usage\n 2. Python, usage\n 2. CCI algorithm, trades (generation)\n 3. codes. _See_ EasyLanguage; TradeStation.\n 4. criteria\n 5. defining\n 6. development\n 7. flowchart (FC), stochastic oscillator crossover (entry signal usage)\n 8. genetic algorithms, identification\n 9. mean reversion algorithm, equity curve\n 10. parameters \n 1. comparison\n 2. results\n 3. sets\n 11. pseudocode, example\n 12. ramp-up data, insufficiency\n 13. RSI algorithm, performance\n 14. stochastic algorithm, performance\n 15. trading algorithm, example\n 8. Algorithmic traders, programmer ability\n 9. Algorithmic trading, books (source)\n 10. Algo Testing Software, example\n 11. AmiBroker \n 1. debugging, Exploration (usage)\n 2. Exploration, results\n 3. functions\n 4. keywords\n 5. loop programming \n 1. code, sample\n 6. Monte Carlo settings dialog\n 7. Monte Carlo simulation\n 8. position sizing, futures mode\n 9. walk-forward optimizer, usage\n 12. AmiBroker Function Language (AFL) \n 1. array programming\n 2. Automatic Analysis dialog box\n 3. backtest, parameters (setting)\n 4. broker integration (feature)\n 5. Check icon\n 6. code samples\n 7. Code Wizard \n 1. Add item\n 2. button\n 3. Edit Rule dropdown list\n 4. window\n 8. data \n 1. algorithm, application\n 2. types\n 9. Editor \n 1. auto-completion tool\n 2. function helper\n 3. launching\n 4. window, example\n 10. Edit Rule pane, parameters (change)\n 11. error warning\n 12. expressions \n 1. results\n 13. features\n 14. initiation\n 15. integrated development environment (IDE)\n 16. knowledge, programmer requirements\n 17. operators \n 1. precedence\n 18. parameters, setting\n 19. portfolio results\n 20. power (feature)\n 21. price (feature)\n 22. request (sending), exclamation point (clicking)\n 23. Send to Analysis window icon\n 24. Set Futures mode\n 25. simple moving average crossover\n 26. speed (feature)\n 27. syntax\n 28. 3-D optimization chart\n 29. trade-by-trade report\n 30. usage\n 31. variable naming\n 32. variables \n 1. names, restrictions\n 33. Wizard\n 13. (AmiBroker keyword) \n 1. flow control structures\n 14. Analysis phase\n 15. Analysis window\n 16. Annual return, performance metric\n 17. APO. _See_ Absolute price oscillator \n 18. Appels, Gerald\n 19. ApplyStop function\n 20. Arguments, usage\n 21. Arithmetic expressions\n 22. ASCII \n 1. database (futures prices)\n 2. data importer\n 23. ATR. _See_ Average true range \n 24. Auto-generated formula\n 25. Average (VBA function)\n 26. Average Directional Index (ADX)\n 27. Average Directional Movement Index (ADX) \n 1. 14-day ADX, calculation\n 2. length\n 3. trend detector function\n 28. Averages\n 29. Average true range (ATR) \n 1. ATR Sell MOC\n 2. BuyToCover MOC\n 3. 5X ATR profit objective, usage\n 4. lookback, parameter (change)\n 5. multiplier, parameter (change)\n 6. 3X ATR stop, usage\n 7. 2 ATR, usage\n 8. usage\n 30. Averaging methods, performances\n 31. avgLen, default value\n 32. avgMP\n 33. AvgTrueRange\n\n## B\n\n 1. Backtest \n 1. equity curve, profit (display)\n 2. parameters, setting\n 3. performance report\n 2. Backtest button\n 3. Backtester settings, example\n 4. Backtesting \n 1. Excel, usage\n 2. software structure \n 1. flowchart\n 5. Bandy, Howard\n 6. Bars held, performance metric\n 7. BASIC. _See_ Beginner's All-purpose Symbolic Instruction Code \n 8. BBandBot\n 9. BBandTop\n 10. Beginner's All-purpose Symbolic Instruction Code (BASIC)\n 11. Berkely, George\n 12. Berlinski, David\n 13. bin increment (binInc) variable\n 14. binTuple\n 15. Bollinger algorithm \n 1. benchmark\n 2. optimization\n 16. Bollinger Bands \n 1. algorithm \n 1. best parameter sets\n 2. version 1 (performance)\n 3. version 2 (performance)\n 2. breakout\n 3. calculation \n 1. 2 standard deviations, usage\n 2. 60 days standard deviation, usage\n 4. data, Keltner Channel data (comparison)\n 5. example\n 6. function\n 7. Function Module\n 8. optimization\n 9. routine, defining\n 10. 60-day, two-SD Bollinger Band, example\n 11. subroutine\n 12. system, example\n 13. trend algorithm\n 14. trend follower function\n 17. BollingerBand subroutine\n 18. Bollinger Benchmark, Keltner Challengers (contrast)\n 19. Bollinger, John\n 20. Bollinger performance, three-dimensional contour chart\n 21. Boolean expression\n 22. Boolean flags, usage\n 23. BOTTOM failure\n 24. bottoming out, term (removal)\n 25. _Building Reliable Trading Systems_ (Fitschen)\n 26. buy (AmiBroker keyword)\n 27. Buy-and-hold mentality\n 28. BUY order\n 29. buyprice (AmiBroker keyword)\n 30. buy (keyword), recognition\n\n## C\n\n 1. CCI. _See_ Commodity Channel Index \n 2. CFDT. _See_ Cumulative frequency distribution table \n 3. change (keyword), recognition\n 4. Choppy Market Indicator (CMI)\n 5. Chromosomes \n 1. crossing, VBA Excel (usage)\n 2. dartboard \n 1. creation, VBA Excel (usage)\n 2. example\n 3. dart-throwing blindfolded monkey (simulation), VBA Excel (usage)\n 4. finding moms and pops, VBA Excel (usage)\n 5. fitness of chromosomes (testing), VBA Excel (usage)\n 6. genes allocation process, VBA Excel (usage)\n 7. genes passage\n 8. initial population setup, VBA Excel (usage)\n 9. mutation \n 1. VBA Excel, usage\n 10. population\n 11. probability of being hit by dart calculation, VBA Excel (usage)\n 12. replacement function, VBA Excel (usage)\n 13. reproduction\n 14. selection\n 15. slice size \n 1. fitness conversion, VBA Excel (usage)\n 6. class (object)\n 7. ClassicShell\n 8. class rsiClass(object):\n 9. class stochClass(object):\n 10. Cluster analysis. _See_ Walk-forward optimization \n 11. CMI. _See_ Choppy Market Indicator \n 12. Code, arguments (presence)\n 13. Code Wizard. _See_ AmiBroker Function Language \n 14. Coincident indicator performance\n 15. Combination lock (workings), finite statement machine modeling\n 16. Comment text, usage\n 17. Commitment of Traders Report (COT)\n 18. commName\n 19. Commodity Channel Index (CCI) \n 1. algorithm \n 1. coincident indicator performance\n 2. example\n 3. performance\n 4. trades, generation\n 2. OB\/OS system description\n 3. profit objective, usage\n 4. protective stop, usage\n 5. system, usage\n 6. trend following system \n 1. p-code\n 7. 20-day CCI, calculation\n 20. Computer language, syntax (understanding)\n 21. Conditional execution\n 22. Connors\/Alvarez, time-based exit (usage)\n 23. Consecutive bar exact sequence paradigm\n 24. Consecutive bar sequence\n 25. COT. _See_ Commitment of Traders Report \n 26. cover (AmiBroker keyword)\n 27. Cover arrays\n 28. coverprice (AmiBroker keyword)\n 29. Crossover rate\n 30. Crude oil-day, two-SD Bollinger Band (example)\n 31. Cumulative daily equity\/drawdown, plotting (example)\n 32. Cumulative frequency distribution table (CFDT)\n 33. curBar (sAverage function parameter)\n 34. Curve fitting \n 1. prevention\n 35. Customize Ribbon\n\n## D\n\n 1. Daily bars (pivot high points), strength differences (examples)\n 2. Dartboard \n 1. creation, VBA Excel (usage)\n 2. example\n 3. Dart-throwing blindfolded monkey (simulation), VBA Excel (usage)\n 4. Data arrays (ESB)\n 5. Data arrays (PSB)\n 6. DataMaster worksheet, usage (example). _See_ Excel System Backtester \n 7. DC. _See_ Donchian Channels \n 8. Definiteness (algorithm criteria)\n 9. Dependencies, nesting\n 10. Developer tab option, example\n 11. Directional movement (DM) \n 1. algorithm \n 1. performance\n 2. concept, introduction\n 3. examples\n 4. system description\n 12. Directional Movement Index (DX)\n 13. DM. _See_ Directional movement \n 14. DMA. _See_ Double simple moving average \n 15. dnSum (variable)\n 16. Donchian algorithms, results\n 17. Donchian Channels (DC) \n 1. breakout\n 18. Donchian lengths, Donchian Channel breakout (usage)\n 19. Double simple moving average (DMA) algorithm\n 20. Double simple moving average (DMA) crossover \n 1. algorithm\n 21. downward, term (removal)\n 22. Draw down. _See_ Trade draw down \n 23. DX. _See_ Directional Movement Index\n\n## E\n\n 1. EasyLanguage \n 1. abbreviations\n 2. algorithm codes\n 3. chart, strategy application\n 4. codes, usage\n 5. comments\n 6. Connors\/Alvarez, time-based exit (usage)\n 7. editor \n 1. line number display\n 8. editor, usage\n 9. functions\n 10. inputs, change (process)\n 11. keywords\n 12. mean reversion strategy (change), input variables (usage)\n 13. profit objective, usage\n 14. project \n 1. creation\n 2. strategy, addition\n 15. protective stop, usage\n 16. remarks\n 17. reversion analysis strategy\n 18. samples\n 19. SKIP words\n 20. strategy \n 1. adjustment process\n 2. algorithm, dependencies\/functions (nesting)\n 21. syntax\n 22. Turtle, LTL filter\/pyramiding\/position sizing (usage)\n 2. Editor. _See_ AmiBroker Function Language \n 1. line number display (EasyLanguage)\n 3. Edit (keyword), recognition\n 4. Effectiveness (algorithm criteria)\n 5. ELD files \n 1. importing\n 2. reimporting\n 6. EMA. _See_ Exponential moving average \n 7. End Of Day (EOD) \n 1. data feeds\n 2. historic database\n 8. Entry logic\n 9. Entry rules, template (example)\n 10. EOD. _See_ End Of Day \n 11. equityClass\n 12. Equity curve \n 1. chart, maximum drawdown (display)\n 2. creation\n 3. example\n 4. mean reversion algorithm\n 5. multiple randomized equity curves, chart\n 6. pattern system\n 7. profit, display\n 8. stops, addition\n 13. EquityStream worksheet, macro (launch)\n 14. ES. _See_ Exhaustive search \n 15. ESB. _See_ Excel System Backtester \n 16. Eurocurrency downturn, CCI system detection\n 17. Excel \n 1. data \n 1. worksheet, example\n 2. ribbon, customization\n 3. usage. _See also_ Visual Basic for Applications. \n 4. Visual Basic Editor, example\n 18. ExcelSystemBackTester\n 19. Excel System Backtester (ESB) \n 1. components\n 2. data arrays\n 3. DataMaster worksheet, usage (example)\n 4. EquityStream worksheet, macro (launch)\n 5. functions\n 6. keywords\n 7. programming environment\n 8. Results worksheet, trades\/performance metrics listing\n 9. source code\n 10. subroutines\n 11. VBA code\n 20. ExcelSystemTester, functions\/subroutines\n 21. exclude (AmiBroker keyword)\n 22. Exhaustive search (ES) \n 1. algorithm, parameters (results)\n 23. Exhaustive search (ES) optimization engines\n 24. Exit \n 1. procedure\n 2. rules, template (example)\n 25. Exit logic\n 26. exitPos function\n 27. Exploration \n 1. results\n 2. usage\n 28. Exponential moving average (EMA)\n 29. Expressions \n 1. AmiBroker Function Language (AFL)\n 2. arithmetic expressions\n 3. logical expressions\n 4. results\n\n## F\n\n 1. Failure swing algorithm, performance\n 2. Failure swing system description. _See_ Relative Strength Index \n 3. Fast %D\n 4. Fast %K\n 5. filter (AmiBroker keyword)\n 6. filterTrade variable\n 7. Finding moms and pops, VBA Excel (usage)\n 8. Finiteness (algorithm criteria)\n 9. Finite state machine (FSM) \n 1. code, example\n 2. diagram\n 3. modeling\n 10. Fitness conversion, VBA Excel (usage)\n 11. Fitness of chromosomes (testing), VBA Excel (usage)\n 12. Fitschen, Keith\n 13. 5X ATR profit objective, usage\n 14. Fixed Fractional \n 1. formula\n 2. money management overlay \n 1. parameters, change\n 15. Flowchart (FC) \n 1. example\n 2. usage, example\n 16. Flow control structures\n 17. for loop\n 18. for-loop\n 19. FORTRAN\n 20. 14-day ADX, calculation\n 21. 14-day RSI, calculation\n 22. 14-day stochastic (FAST), calculation\n 23. FSM. _See_ Finite state machine \n 24. Functions \n 1. definition, colon (usage)\n 25. Functions, nesting\n 26. Future leak, advantage\n 27. Futures mode option\n 28. Futures prices, ASCII database\n\n## G\n\n 1. Garbage in garbage out (GIGO)\n 2. Generation \n 1. concepts\n 3. Genes allocation process, VBA Excel (usage)\n 4. Genetic algorithms (GAs) \n 1. concepts\n 2. crossover rate\n 3. curve fitting, prevention\n 4. generations\n 5. identification\n 6. mutation rate\n 7. population size\n 8. usage\n 5. Genetic optimization (GO)\n 6. getData()\n 7. GetData (ESB component)\n 8. Graphical user interface (GUI)\n\n## H\n\n 1. head (variable)\n 2. Helper functions (PSB)\n 3. Hermawanto, Denny\n 4. Highest Function\/Module\n 5. Hindsight, usage\n 6. Histogram pivot points, usage\n 7. Histogram system. _See_ Moving Average Convergence Divergence \n 8. Holland, John\n 9. _How to Make Money in Commodities_ (Keltner)\n\n## I\n\n 1. IDE. _See_ Integrated development environment \n 2. Identifiers (PSB)\n 3. IDLE. _See_ Integrated DeveLopment Environment \n 4. Indicator.py\n 5. Indicators \n 1. categories\n 2. classes\/functions (PSB)\n 6. input (algorithm criteria)\n 7. InSampleBarsPerRun\n 8. In-sample (IS) testing\n 9. In-sample (IS) time period \n 1. Bollinger algorithm, optimization\n 2. Donchian algorithm, results\n 3. portfolio, parameters\n 10. Instruction ste, variability\n 11. Integrated development environment (IDE)\n 12. Integrated DeveLopment Environment (IDLE), usage\n 13. IS. _See_ In-sample \n 14. Iteration growth rate, parameters (example)\n\n## J\n\n 1. Janeczko, Tomasz\n\n## K\n\n 1. Kaufman, Perry\n 2. Keltner Challengers, Bollinger Benchmark (contrast)\n 3. Keltner Channel \n 1. algorithm, best parameter sets\n 2. calculation \n 1. 2 ATR, usage\n 2. 60 days, usage\n 3. data, Bollinger Bands data (comparison)\n 4. optimization\n 5. trend follower function\n 4. Keltner, Chester\n 5. Keywords (EasyLanguage)\n\n## L\n\n 1. Lagging indicator\n 2. Lambert, Donald\n 3. Lane, George C.\n 4. LastBarOfMonth (LBM) pattern\n 5. Last trade was a loser filter (LTLF) \n 1. absence \n 1. examples\n 2. engagement\n 3. inclusion, examples\n 4. usage\n 6. LBM. _See_ LastBarOfMonth \n 7. Limit (lmt) order\n 8. Lists, initiation (PSB)\n 9. load (keyword), recognition\n 10. Logical expressions\n 11. Long division procedure, example\n 12. Long entries\n 13. Long entry signal description \n 1. usage\n 14. LONG position, establishment\n 15. Long position exit instruction (TradeStation)\n 16. lookback (sAverage function parameter)\n 17. Loops \n 1. programming. _See_ AmiBroker loop programming.\n 18. Lowest Function\/Module\n 19. LTLF. _See_ Last trade was a loser filter\n\n## M\n\n 1. MACD. _See_ Moving Average Convergence Divergence \n 2. Macro, ESB launching\n 3. MarginDeposit\n 4. margindeposit (AmiBroker keyword)\n 5. marketDataClass \n 1. objects\n 6. marketDataClass() method\n 7. Market on Close (moc) \n 1. order\n 8. Market (mkt) order\n 9. Markets To Test, opening\n 10. marketSystemClass\n 11. MAS. _See_ Multi-algorithm strategy \n 12. maxContractPoints\n 13. maxContractProfit\n 14. Maximum drawdown, display\n 15. Maximum quantity, parameter (change)\n 16. Mean reversion (MR) \n 1. algorithm, equity curve (usage)\n 2. strategy (change), input variables (usage)\n 17. MeanReversion (name)\n 18. Mini Russell day trading system, narrow range day (usage)\n 19. mmStop defaults\n 20. MOC. _See_ Time-based market order \n 21. moc. _See_ Market on Close \n 22. Money management \n 1. Fixed Fractional money management overlay\n 2. stop, exit procedure\n 23. Money Management window \n 1. parameters, change\n 24. Monte Carlo analysis\n 25. Monte Carlo settings, AmiBroker Monte Carlo settings dialog\n 26. Monte Carlo simulation \n 1. AmiBroker Monte Carlo simulation\n 2. distribution statistics\n 3. implementation, Python (usage)\n 27. Monte Carlo source code\n 28. Monte Carlo straw broom chart\n 29. Moving Average Convergence Divergence (MACD) \n 1. calculation-day\/26-day moving averages (usage)\n 2. histogram system\n 30. Moving averages \n 1. crossover algorithm\n 2. double simple moving average (DMA) crossover \n 1. algorithm\n 3. exponential moving averages\n 4. simple moving averages\n 5. single simple moving average (SMA) crossover \n 1. algorithm\n 6. triple simple moving average (TMA) crossover \n 1. algorithm\n 7. 20-day moving averages, examples\n 8. 200-day moving average\n 9. weighted moving averages\n 31. MR. _See_ Mean reversion \n 32. Multi-algorithm strategy (MAS)\n 33. Multiple randomized equity curves, chart\n 34. Mutation \n 1. concepts\n 2. occurrence\n 3. rate\n 4. VBA Excel, usage\n 35. myAvg\n 36. myCondition, variable (initiation)\n 37. myDayCount\n 38. MyFirstPortfolio\n 39. MyFirstStrategyGroup \n 1. list\n 2. selection, result\n 40. myProfitTarg\n 41. MySecondAlgoWizard\n 42. mySum\n 43. myTickValue\n 44. myTrueRange\n 45. myValue\n\n## N\n\n 1. Narrow range day, usage\n 2. Net profit, performance metric\n 3. _New Concepts In Technical Trading Systems_ (Wilder)\n 4. _New Trading Systems and Methods_ (Kaufman)\n 5. Number of trades, performance metric\n 6. numcolumns (AmiBroker keyword)\n\n## O\n\n 1. OB\/OS system description. _See_ Commodity Channel Index \n 2. offset (sAverage function parameter)\n 3. OOS. _See_ Out-of-sample \n 4. Operators \n 1. AmiBroker Function Language (AFL)\n 2. precedence\n 5. Optimization \n 1. genetic optimization\n 2. parameter sets\n 3. 3-D optimization chart\n 6. Optimize button\n 7. Orders, types\n 8. Oscillators \n 1. crossover, entry signal usage. _See_ Stochastics.\n 9. Outlining\n 10. Out-of-sample (OOS) \n 1. in-sample (IS), ratio\n 2. number of bars\n 3. percentage\n 4. report\n 5. testing \n 1. example\n 6. time period, Donchian algorithm results\n 7. timespan\n 11. OutOfSampleBarsPerRun\n 12. output (algorithm criteria)\n\n## P\n\n 1. Paintbar\n 2. Paradigms, example\n 3. Parameters \n 1. Bollinger performance, three-dimensional contour chart\n 2. change\n 3. comparison\n 4. sets \n 1. optimization usage\n 2. robust parameter sets, presence\n 5. setting\n 6. stress\n 4. Partner matching probability\n 5. Pattern system, equity curve\n 6. p-code\n 7. Percentage price oscillator (PPO)\n 8. Percent Risk, parameter (change)\n 9. Performance metrics \n 1. example\n 10. Peters, Tim\n 11. Pivot bar, strength (basis)\n 12. Pivot high points, strength differences (examples)\n 13. Pivot point entry algorithm, example\n 14. Pivot-point long-entry algorithm, FSM modeling\n 15. PM. _See_ Portfolio Maestro \n 16. pointvalue (AmiBroker keyword)\n 17. Population \n 1. concepts\n 2. initial population setup, VBA Excel (usage)\n 3. size\n 18. Portfolio \n 1. AFL results\n 2. algorithm, usage (decision)\n 3. analysis\n 4. backtesting, preparation\n 5. composition\n 6. correlation matrix, portion\n 7. equity curve, stops (addition)\n 8. parameters\n 9. profit targets, examples\n 10. sample, Turtle system 2 (example)\n 11. Settings\n 12. setup, PSB (usage)\n 13. stop loss \n 1. appearance\n 2. setting\n 14. stop option\n 15. trades, stops \n 1. exclusion\n 2. inclusion\n 19. portfolioClass\n 20. Portfolio Maestro (PM) \n 1. backtest performance report\n 2. equity curve chart, maximum drawdown (display)\n 3. fixed fractional money management overlay\n 4. launch window\n 5. Manage Strategy Group button, indication\n 6. Money Management window, parameters (change)\n 7. MyFirstPortfolio\n 8. MyFirstStrategyGroup, selection\n 9. portfolio \n 1. analysis\n 2. backtesting, preparation\n 3. equity curve, stops (addition)\n 4. profit targets, examples\n 5. stop loss, appearance\n 6. stop option\n 10. Portfolio Settings\n 11. position size, profit\/drawdown (correlation)\n 12. Returns and Equity tab, maximum drawdown (display)\n 13. strategy group \n 1. list\n 2. settings, adjustment\n 3. strategy, addition\n 14. Strategy Group settings button\n 15. symbol, addition\n 16. Total P\/L option\n 17. Trade Analysis window, trading statistics display\n 18. Turtle 55 strategy, appearance\n 19. UGTATS list, selection\n 20. UGTATS Market List\n 21. UGTATS markets, symbols\n 21. Portfolio Profit Target, impact\n 22. Portfolio sample, Turtle system 1 \n 1. last trade was a loser filter (LTLF) \n 1. absence\n 2. inclusion, examples\n 23. positionscore (AmiBroker keyword)\n 24. PositionSize\n 25. positionsize (AmiBroker keyword)\n 26. Position size, profit\/drawdown (correlation)\n 27. Position sizing \n 1. futures mode (AmiBroker)\n 2. usage\n 28. PPO. _See_ Percentage price oscillator \n 29. Predictive indicator\n 30. Price bar interface \n 1. reserved words\n 31. Price-based indicators\n 32. prices (sAverage function parameter)\n 33. Probability of being hit by dart (calculation), VBA Excel (usage)\n 34. Problem solving\n 35. Profit factor, performance metric\n 36. Profit\/loss, performance metric\n 37. Profit objective, usage\n 38. Programming environment\n 39. Protective stop, usage\n 40. PSB. _See_ Python System Backtester \n 41. PSBBollinger, opening\n 42. Pseudocode \n 1. algorithm pseudocde\n 2. conversion process\n 43. Pyramiding, usage\n 44. Python \n 1. code, example\n 2. dynamic typing\n 3. installation\n 4. interpreted language\n 5. shell, presence\n 6. usage \n 1. reasons\n 7. user's group, presence\n 45. Python Monte Carlo simulation\n 46. _Python Programming_ (Zelle)\n 47. Python System Backtester (PSB) \n 1. Bollinger Bands Function Module\n 2. classes\n 3. class rsiClass(object):\n 4. class stochClass(object):\n 5. configuration\n 6. data arrays\n 7. data import\n 8. equityClass\n 9. helper functions\n 10. Highest Function\/Module\n 11. identifiers\n 12. IDLE, usage\n 13. import section\n 14. indicator classes\/functions\n 15. indicator.py\n 16. installation\n 17. keywords\n 18. lists \n 1. initiation\n 19. Lowest Function\/Module\n 20. marketDataClass\n 21. Monte Carlo \n 1. analysis\n 2. source code\n 22. portfolioClass\n 23. portfolio setup\n 24. rsiClass\n 25. sAverage \n 1. function, parameters\n 26. Simple Average Function\/Module\n 27. Start Trade Drawdown \n 1. section\n 2. source code\n 28. structure\n 29. SystemTester.py\n 30. tradeInfoClass\n 31. usage\n 32. variables, initiation\n\n## Q\n\n 1. _Quantitative Trading Systems_ (Bandy)\n\n## R\n\n 1. rampUp\n 2. Ramp-up data, insufficiency\n 3. Random number generator (RNG) \n 1. tool\n 2. usage\n 4. Range \n 1. function\n 2. 10-day average, calculation\n 5. Real Time data feeds\n 6. Relative strength (RS)\n 7. Relative Strength Index (RSI) \n 1. algorithm, performance\n 2. divergence, example\n 3. failure swing algorithm, performance\n 4. failure swing system description\n 5. 14-day RSI, calculation\n 6. pivots, value\n 7. profit objective, usage\n 8. protective stop, usage\n 9. system \n 1. description \n 2. p-code\n 10. trading algorithm, flowchart (FC) diagram\n 11. usage, example\n 12. VBA function\n 8. removeDuplicates\n 9. Replacement function, VBA Excel (usage)\n 10. Reproduction \n 1. concepts\n 11. Reserved words\n 12. Results worksheet. _See_ Excel System Backtester \n 13. Reversal, algorithm exit procedure\n 14. Reversion analysis strategy (EasyLanguage)\n 15. Risk aversion\n 16. Risk of ruin (RoR) \n 1. calculation\n 2. competitors, examples\n 3. impact\n 17. RNG. _See_ Random number generator \n 18. Robust parameter sets, presence\n 19. RoR. _See_ Risk of ruin \n 20. roundlotsize (AmiBroker keyword)\n 21. Round quantity, parameter (change)\n 22. RSI. _See_ Relative Strength Index \n 23. rsiClass\n 24. Ruin, risk \n 1. calculation\n 2. impact\n 25. Run menu\n 26. run (keyword), recognition\n\n## S\n\n 1. sAverage \n 1. function, parameters\n 2. save (keyword), recognition\n 3. Selection (chromosomes)\n 4. Selection of the fittest, concepts\n 5. sell (AmiBroker keyword)\n 6. Sell arrays\n 7. SELL order\n 8. sellprice (AmiBroker keyword)\n 9. Send To Analysis\n 10. setSysMarkInfo\n 11. Sharpe ratio, performance metric\n 12. short (AmiBroker keyword)\n 13. Short entries\n 14. shortprice (AmiBroker keyword)\n 15. short (keyword), recognition\n 16. Simple Average Function\/Module\n 17. Simple moving average crossover algorithm\n 18. Simple moving average crossover system \n 1. AFL usage\n 2. 3X ATR stop, usage\n 19. Simple moving averages\n 20. Single simple moving average (SMA) crossover \n 1. algorithm, example\n 21. SKIP words\n 22. Slow %D\n 23. Slow %K\n 24. Slow stochastic system description\n 25. SMA. _See_ Single simple moving average \n 26. Source code, initiation\n 27. Standard deviation (SD) Bollinger Band\n 28. START state\n 29. Start Trade Drawdown \n 1. analysis\n 2. calculation\n 3. source code\n 30. Stochastic (STO) \n 1. algorithm, performance\n 2. 14-day stochastic (FAST), calculation\n 3. oscillator crossover, entry signal usage\n 4. profit objective, usage\n 5. protective stop, usage\n 6. slow stochastic system \n 1. description\n 2. p-code\n 7. trading algorithm, flowchart (FC) diagram\n 8. usage, examples\n 9. VBA function\n 31. Stop loss, setting\n 32. Stop (stp) order\n 33. Strategy Group \n 1. concepts\n 2. creation\n 34. Straw broom chart\n 35. Subroutines. _See_ Visual Basic \n 1. returns\n 2. values\n 36. Symbol List, creation\n 37. Syntax \n 1. AmiBroker Function Language (AFL)\n 2. EasyLanguage\n 3. errors, list (TradeStation)\n 38. Sys Drawdown, performance metric\n 39. systemMarket\n 40. systemMarketClass\n 41. System TA2, WFO default settings (usage)\n 42. SystemTester module\n 43. SystemTester.py\n\n## T\n\n 1. TA. _See_ Trading algorithm \n 2. TDE. _See_ TradeStation Development Environment \n 3. 10-day average, calculation\n 4. TestSystem (ESB component)\n 5. 3D Optimization chart\n 6. 3D Optimization chart\n 7. 3X ATR stop, usage\n 8. ticksize (AmiBroker keyword)\n 9. Time-based market order (MOC), exit procedure\n 10. TMA. _See_ Triple simple moving average \n 11. TOP failure swing, occurrence\n 12. TotalBarsPerRun\n 13. Total P\/L option\n 14. Total transaction costs, performance metric\n 15. TP. _See_ Typical price \n 16. Trade Analysis \n 1. ta\n 2. window, trading statistics display\n 17. Trade-by-trade report\n 18. Trade draw down, initiation\n 19. tradeInfoClass\n 20. Trades \n 1. example (generation), RSI (usage)\n 2. generation (example), stochastics (usage)\n 3. signals (initiation), histogram pivot points (usage)\n 4. skipping\n 21. TradeStation \n 1. algorithm codes\n 2. Connors\/Alvarez, time-based exit (usage)\n 3. dates\/times, storage\n 4. functions\n 5. keywords\n 6. long position exit instruction\n 7. Portfolio Maestro (PM) launch window\n 8. profit objective, usage\n 9. protective stop, usage\n 10. syntax errors, list\n 11. Turtle, LTL filter\/pyramiding\/position sizing (usage)\n 12. usage\n 22. TradeStation Development Environment (TDE) \n 1. algorithm\n 2. code verification\/recalculation, confirming message\n 3. EasyLanguage editor\n 4. initial screen\n 23. TradeStation IDE \n 1. home screen\n 2. trading apps\n 24. tradeTuple\n 25. Trading \n 1. idea, pseudocode conversion process\n 2. statistics, display\n 3. system development, genetic algorithms (usage)\n 26. Trading algorithm 1 (TA1), EasyLanguage Code (usage)\n 27. Trading algorithm 2 (TA2) \n 1. EasyLanguage code, usage\n 2. WFA report\n 28. Trading algorithm 3 (TA3) \n 1. EasyLanguage code, usage\n 2. WFO report card TA3\n 29. Trading algorithms \n 1. describing\/programming\n 2. example\n 3. flowchart (FC) \n 1. example\n 2. usage, example\n 4. programming, Boolean flags (usage)\n 5. RSI trading algorithm, flowchart (FC) diagram\n 6. stochastic trading algorithm, flowchart (FC) diagram\n 30. Trading Blox testing platform\n 31. Trend \n 1. detector, function\n 2. follower\n 3. following system. _See_ Commodity Channel Index.\n 4. trading\n 32. Trend follower function \n 1. Bollinger Bands\n 2. Keltner Channel\n 33. Trigger, incorporation\n 34. Triple simple moving average (TMA) crossover \n 1. algorithm\n 35. True range (TR)\n 36. Turtle 55 strategy, appearance\n 37. Turtle, LTL filter\/pyramiding\/position sizing (usage)\n 38. Turtle system \n 1. examples\n 2. LTLF \n 1. absence, examples\n 2. inclusion, examples\n 3. trading algorithm flowchart, example\n 39. 12-day moving averages, usage\n 40. 20-day CCI, calculation\n 41. 20-day moving averages, examples\n 42. 26-day moving averages, usage\n 43. Typical price (TP)\n\n## V\n\n 1. Variable bar liberal sequence paradigm\n 2. Variable bar sequence \n 1. depiction, long entry signal description\n 3. Variables \n 1. initiation (PSB)\n 2. names, restrictions\n 4. Vars statement\n 5. VBE. _See_ Visual Basic Editor \n 6. Visual Basic Editor (VBE) \n 1. example\n 7. Visual Basic for Applications (VBA) \n 1. average, function\n 2. code. _See_ Excel System Backtester.\n 3. code, comment text (usage)\n 4. comments, ending\n 5. error message, example\n 6. Excel, usage\n 7. functions\/subroutines\n 8. RSI function\n 9. source code, initiation\n 10. stochastic function\n 11. usage\n 8. Volatility \n 1. cycle, function\n 2. usage\n\n## W\n\n 1. Walk forward\n 2. Walk-forward analysis (WFA) \n 1. forward roll, graphic representation\n 2. report\n 3. Walk-forward efficiency (WFE)\n 4. Walk-forward optimization (WFO) \n 1. cluster analysis\n 2. cluster results matrix\n 3. default settings, usage\n 4. entries\/exits code\n 5. examples\n 6. in-sample testing \n 1. TA2, example\n 7. out-of-sample (OOS) \n 1. report\n 2. testing \n 1. example\n 8. report card TA3\n 5. Walk-forward optimizer \n 1. usage\n 2. value\n 6. Walk-forward performance, equity curve (example)\n 7. Walk-forward testing \n 1. backtest, usage\n 2. out-of-sample (OOS) time period\n 3. steps\n 8. Weighted moving averages\n 9. WFA. _See_ Walk-forward analysis \n 10. WFE. _See_ Walk-forward efficiency \n 11. WFO. _See_ Walk-forward optimization \n 12. Wilder, J. Welles\n\n## Z\n\n 1. Zelle, John\n\n# WILEY END USER LICENSE AGREEMENT\n\nGo to www.wiley.com\/go\/eula to access Wiley's ebook EULA. \n","meta":{"redpajama_set_name":"RedPajamaBook"}}