{"id":175889,"date":"2020-09-25T15:53:00","date_gmt":"2020-09-25T19:53:00","guid":{"rendered":"https:\/\/ibkrcampus.com\/trading-lessons\/sample-trading-strategy\/"},"modified":"2023-04-25T21:01:30","modified_gmt":"2023-04-26T01:01:30","slug":"sample-trading-strategy","status":"publish","type":"trading-lessons","link":"https:\/\/www.interactivebrokers.com\/campus\/trading-lessons\/sample-trading-strategy\/","title":{"rendered":"Sample Trading Strategy"},"content":{"rendered":"<h4>In this lesson, you would:<\/h4>\n<ul>\n<li>Learn how to construct and execute a trading strategy<\/li>\n<li>Precautions to be taken in automated trading<\/li>\n<\/ul>\n<h3>Sample Trading Strategy<\/h3>\n<p>The strategy first connects to the TWS. In the next step, we source the snapshot script which holds the custom callback function.<\/p>\n<p><img decoding=\"async\" class=\"size-medium wp-image-3441 aligncenter lazyload\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/Screen-Shot-2020-09-29-at-3.20.09-PM.png\" alt=\"\" width=\"960\" height=\"324\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 960px; aspect-ratio: 960\/324;\" \/><\/p>\n<p>On line 6, we create a contract using the tws stock function.<\/p>\n<p>From lines 8 to 11, we set the parameters for the two simple moving averages and the initial current position to zero.<\/p>\n<p>Next, we pull the initial require market data using the custom callback.<\/p>\n<p><img decoding=\"async\" class=\"size-medium wp-image-3442 aligncenter lazyload\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/Screen-Shot-2020-09-29-at-3.21.15-PM.png\" alt=\"\" width=\"757\" height=\"540\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 757px; aspect-ratio: 757\/540;\" \/><\/p>\n<p>The strategy then enters a while loop on line 19. On line 20, we use the rbind function to combine the data frames by row. On line 22, we use the unique function to eliminate the duplicate rows from the data frame.<\/p>\n<p>The If statement block starting on line 23, keeps checking the data until there is enough data for the strategy to proceed further. From line 31 to 34, we define the logic for buy and sell signals based on the two simple moving averages.<\/p>\n<p>Once a signal is obtained, an order is constructed using the twsOrder function and is place using the placeOrder function. The current position is updated on every buy or sell position filled.<\/p>\n<p>On execution, the strategy produces the following output:<\/p>\n<p><img decoding=\"async\" class=\"size-medium wp-image-3443 aligncenter lazyload\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/Screen-Shot-2020-09-29-at-3.22.58-PM.png\" alt=\"\" width=\"792\" height=\"540\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 792px; aspect-ratio: 792\/540;\" \/><\/p>\n<p>Initially there is not enough data for the signals to generate. Once the data is collected, signals are placed and you can see the orders getting executed in the R console and also on the trader workstation orders window. Since the trading logic is placed in the while loop with a true value, the strategy will keep placing orders until it is stopped.<\/p>\n<h3>Precautions<\/h3>\n<p>Following are the precautions that the trades have to keep in mind when they are trading algorithmically using the trading APIs.<\/p>\n<ul>\n<li>Traders should have a robust risk management in place in case the default TWS risk management does not catch all the strategy specific risks.<\/li>\n<li>Code block to ensure order price and order quantity sanity.<\/li>\n<li>Write test case to ensure that the strategy does not run into order sending loops.<\/li>\n<li>Write test cases to run on every API upgrade to ensure that nothing is broken.<\/li>\n<li>Write robust codes to handle socket connection losses, error messages from Interactive Brokers, and network errors.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>The functions from the IBrokers package are easy to use and can be implemented to construct various kinds of trading strategies for automated trading on TWS. This concludes the final lesson in the \u201cTrading Using R\u201d Online Course. We hope that you liked it. Thank You!<\/p>\n<p>Note \u2013 The IBrokers package provides native R access to Interactive Brokers Trader Workstation API<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this lesson, we will see how to construct and execute a sample trading strategy on TWS.<\/p>\n","protected":false},"author":688,"featured_media":175893,"parent":0,"comment_status":"open","ping_status":"open","template":"","meta":{"_acf_changed":false,"footnotes":""},"contributors-categories":[13576],"traders-academy":[13126,13128,13132],"class_list":{"0":"post-175889","1":"trading-lessons","2":"type-trading-lessons","3":"status-publish","4":"has-post-thumbnail","6":"contributors-categories-interactive-brokers","7":"traders-academy-intermediate-trading","8":"traders-academy-level","9":"traders-academy-trading-lesson"},"pp_statuses_selecting_workflow":false,"pp_workflow_action":"current","pp_status_selection":"publish","acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v26.9 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Archives | Traders&#039; Academy | IBKR Campus<\/title>\n<meta name=\"description\" content=\"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/trading-lessons\/175889\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Sample Trading Strategy\" \/>\n<meta property=\"og:description\" content=\"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.interactivebrokers.com\/campus\/trading-lessons\/sample-trading-strategy\/\" \/>\n<meta property=\"og:site_name\" content=\"IBKR Campus US\" \/>\n<meta property=\"article:modified_time\" content=\"2023-04-26T01:01:30+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/trading-using-R.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1280\" \/>\n\t<meta property=\"og:image:height\" content=\"720\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:title\" content=\"Sample Trading Strategy\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\n\t    \"@context\": \"https:\\\/\\\/schema.org\",\n\t    \"@graph\": [\n\t        {\n\t            \"@type\": \"WebPage\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/\",\n\t            \"name\": \"Sample Trading Strategy\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\"\n\t            },\n\t            \"primaryImageOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/#primaryimage\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/01\\\/trading-using-R.jpg\",\n\t            \"datePublished\": \"2020-09-25T19:53:00+00:00\",\n\t            \"dateModified\": \"2023-04-26T01:01:30+00:00\",\n\t            \"description\": \"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.\",\n\t            \"breadcrumb\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/#breadcrumb\"\n\t            },\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"ReadAction\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/\"\n\t                    ]\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"ImageObject\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/#primaryimage\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/01\\\/trading-using-R.jpg\",\n\t            \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/01\\\/trading-using-R.jpg\",\n\t            \"width\": 1280,\n\t            \"height\": 720,\n\t            \"caption\": \"Sample Trading Strategy\"\n\t        },\n\t        {\n\t            \"@type\": \"BreadcrumbList\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/sample-trading-strategy\\\/#breadcrumb\",\n\t            \"itemListElement\": [\n\t                {\n\t                    \"@type\": \"ListItem\",\n\t                    \"position\": 1,\n\t                    \"name\": \"Academy Lessons\",\n\t                    \"item\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/trading-lessons\\\/\"\n\t                },\n\t                {\n\t                    \"@type\": \"ListItem\",\n\t                    \"position\": 2,\n\t                    \"name\": \"Sample Trading Strategy\"\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"WebSite\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"name\": \"IBKR Campus US\",\n\t            \"description\": \"Financial Education from Interactive Brokers\",\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"SearchAction\",\n\t                    \"target\": {\n\t                        \"@type\": \"EntryPoint\",\n\t                        \"urlTemplate\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/?s={search_term_string}\"\n\t                    },\n\t                    \"query-input\": {\n\t                        \"@type\": \"PropertyValueSpecification\",\n\t                        \"valueRequired\": true,\n\t                        \"valueName\": \"search_term_string\"\n\t                    }\n\t                }\n\t            ],\n\t            \"inLanguage\": \"en-US\"\n\t        },\n\t        {\n\t            \"@type\": \"Organization\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\",\n\t            \"name\": \"Interactive Brokers\",\n\t            \"alternateName\": \"IBKR\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"logo\": {\n\t                \"@type\": \"ImageObject\",\n\t                \"inLanguage\": \"en-US\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\",\n\t                \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"width\": 669,\n\t                \"height\": 669,\n\t                \"caption\": \"Interactive Brokers\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\"\n\t            },\n\t            \"publishingPrinciples\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/about-ibkr-campus\\\/\",\n\t            \"ethicsPolicy\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/cyber-security-notice\\\/\"\n\t        }\n\t    ]\n\t}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Archives | Traders' Academy | IBKR Campus","description":"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/trading-lessons\/175889\/","og_locale":"en_US","og_type":"article","og_title":"Sample Trading Strategy","og_description":"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.","og_url":"https:\/\/www.interactivebrokers.com\/campus\/trading-lessons\/sample-trading-strategy\/","og_site_name":"IBKR Campus US","article_modified_time":"2023-04-26T01:01:30+00:00","og_image":[{"width":1280,"height":720,"url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/trading-using-R.jpg","type":"image\/jpeg"}],"twitter_card":"summary_large_image","twitter_title":"Sample Trading Strategy","twitter_misc":{"Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/","url":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/","name":"Sample Trading Strategy","isPartOf":{"@id":"https:\/\/ibkrcampus.com\/campus\/#website"},"primaryImageOfPage":{"@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/#primaryimage"},"image":{"@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/trading-using-R.jpg","datePublished":"2020-09-25T19:53:00+00:00","dateModified":"2023-04-26T01:01:30+00:00","description":"In this lesson, we will see how to construct and execute a sample trading strategy on TWS.","breadcrumb":{"@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/#primaryimage","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/trading-using-R.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/01\/trading-using-R.jpg","width":1280,"height":720,"caption":"Sample Trading Strategy"},{"@type":"BreadcrumbList","@id":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/sample-trading-strategy\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Academy Lessons","item":"https:\/\/ibkrcampus.com\/campus\/trading-lessons\/"},{"@type":"ListItem","position":2,"name":"Sample Trading Strategy"}]},{"@type":"WebSite","@id":"https:\/\/ibkrcampus.com\/campus\/#website","url":"https:\/\/ibkrcampus.com\/campus\/","name":"IBKR Campus US","description":"Financial Education from Interactive Brokers","publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ibkrcampus.com\/campus\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/ibkrcampus.com\/campus\/#organization","name":"Interactive Brokers","alternateName":"IBKR","url":"https:\/\/ibkrcampus.com\/campus\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","width":669,"height":669,"caption":"Interactive Brokers"},"image":{"@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/"},"publishingPrinciples":"https:\/\/www.interactivebrokers.com\/campus\/about-ibkr-campus\/","ethicsPolicy":"https:\/\/www.interactivebrokers.com\/campus\/cyber-security-notice\/"}]}},"_links":{"self":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/trading-lessons\/175889","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/trading-lessons"}],"about":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/types\/trading-lessons"}],"author":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/users\/688"}],"replies":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/comments?post=175889"}],"version-history":[{"count":0,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/trading-lessons\/175889\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media\/175893"}],"wp:attachment":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media?parent=175889"}],"wp:term":[{"taxonomy":"contributors-categories","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/contributors-categories?post=175889"},{"taxonomy":"traders-academy","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/traders-academy?post=175889"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}