{"id":475,"date":"2020-03-08T11:17:49","date_gmt":"2020-03-08T10:17:49","guid":{"rendered":"http:\/\/market-and-us.com\/blog\/?p=475"},"modified":"2020-03-08T11:21:40","modified_gmt":"2020-03-08T10:21:40","slug":"how-to-code-all-about-orders-with-interactive-brokers","status":"publish","type":"post","link":"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/","title":{"rendered":"How to code all about orders with Interactive Brokers"},"content":{"rendered":"\n<p>In this article you&#8217;ll find how to get your <strong>positions<\/strong>, set, modify and cancel <strong>orders<\/strong> and get your <strong>account value<\/strong> and current <strong>unrealized profits<\/strong> by Python Code for Interactive Brokers <em>(see below under <a href=\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#finalwords\">Final Words<\/a> what tasks are discussed in this article)<\/em>.<\/p>\n\n\n\n<p>And yes, I found a <strong>simple library<\/strong> for all that, named <a href=\"https:\/\/ib-insync.readthedocs.io\"><code>ib_insync<\/code><\/a> and created by Ewald de Wit!<\/p>\n\n\n\n<h2>Connect to Interactive Brokers<\/h2>\n\n\n\n<p>At first you have to <a href=\"https:\/\/ib-insync.readthedocs.io\/readme.html#installation\">install the library<\/a> and the code start by <strong>importing the libraries and connecting to the broker<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from ib_insync import *\nfrom random import choice\n\nib = IB()\nib.connect('127.0.0.1', 7496, clientId=1)<\/code><\/pre>\n\n\n\n<p>I imported <code>choice<\/code> to pick some random elements from the list. Of course, you only need it for our example.<br>And you have to check if the port is the same set in your API settings within TWS or Gateway.<\/p>\n\n\n\n<h2>Get all your running positions<\/h2>\n\n\n\n<p>Now we can <strong>read all positions<\/strong> from the server:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pos = ib.positions()<\/code><\/pre>\n\n\n\n<p>And here we pick one random position and <strong>show some details<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p = choice(pos)\n\n# the account to which the position belongs:\nprint(p.account)\n# the ticker symbol:\nprint(p.contract.symbol)\n# the amount of shares (negative when sold):\nprint(p.position)\n# the average price (including the commissions):\nprint(p.avgCost)<\/code><\/pre>\n\n\n\n<h2>Get the current account value<\/h2>\n\n\n\n<p>Also, we can <strong>request the NetLiquidation<\/strong> value (NLV, current value of the whole account) and the <strong>unrealized profit<\/strong> (or loss):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>avs = ib.accountValues()\n\nfor i in range(len(avs)):\n    if avs[i].tag == \"NetLiquidation\":\n        print(avs[i])\n    elif avs[i].tag == \"UnrealizedPnL\" and avs[i].currency == \"BASE\":\n        print(avs[i])<\/code><\/pre>\n\n\n\n<p>If you have several account under one login then it will show the data for both account.<\/p>\n\n\n\n<h2>Create a contract and get the current price<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>contract = Stock('JPM', 'SMART', 'USD')\nprint(contract)\n\nbars = ib.reqHistoricalData(\n        contract,\n        endDateTime='',\n        durationStr='1 D',\n        barSizeSetting='1 min',\n        whatToShow='MIDPOINT',\n        useRTH=False,\n        formatDate=1)\ndf = util.df(bars)\n\nprint(\"current price:\", df.close.iloc[-1])<\/code><\/pre>\n\n\n\n<p>Easy, isn&#8217;t it? <a href=\"https:\/\/market-and-us.com\/blog\/how-to-get-historical-stock-data-212\/\">One of my first articles<\/a> was about getting historical data with the original IB API and it was so complicated. And here it is: Simple, fast and I hope it&#8217;s easy to understand.<\/p>\n\n\n\n<p>First, we define the<strong> contract for JPM<\/strong> and then we request some <strong>sample data<\/strong> for the 1 minute candles of the last day. But we only need the <strong>last close <\/strong>which is solved by <code>.iloc[-1]<\/code>. I set <code>useRTH=False<\/code>, so it shows also the last data of the after hours at weekends.<\/p>\n\n\n\n<h2>Set, modify and cancel orders<\/h2>\n\n\n\n<p>To place an order, we have to <strong>create an order object and place the order<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>order = StopOrder('SELL', 10, 105.0)\nprint(order)\ntrade = ib.placeOrder(contract, order)\nprint(trade)\n\nib.sleep(1)\nprint(trade.log)<\/code><\/pre>\n\n\n\n<p>You can check the <code>trade.log<\/code> to get more informations, for example if the order is already submitted, &#8230;<\/p>\n\n\n\n<p>Pay attention on using <code>ib.sleep()<\/code> instead of <code>time.sleep()<\/code>!<\/p>\n\n\n\n<p>Now we wait 4 seconds before <strong>changing the stop price<\/strong> from 105.0 (as set above) to 104.9. We have to change the order element and then place the order again. It is not sent twice, it&#8217;s just to change the order:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ib.sleep(4)\norder.auxPrice = 104.9\ntrade = ib.placeOrder(contract, order)\nprint(trade)<\/code><\/pre>\n\n\n\n<p>And finally, we can <strong>cancel the order<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ib.sleep(5)\nprint(ib.cancelOrder(order))\n\nprint(trade.log)<\/code><\/pre>\n\n\n\n<p>The <code>sleep<\/code> commands are only to have the possibility to <strong>check the whole process by watching the JPM chart in your TWS<\/strong>!<\/p>\n\n\n\n<h2 id=\"finalwords\">Final words<\/h2>\n\n\n\n<p><strong>If you do need anything else or want to know more about one of the above steps then just comment below!<\/strong><\/p>\n\n\n\n<p>The reason for this article was a <strong>request of a friend<\/strong> of mine to solve the following:<\/p>\n\n\n\n<ol><li>read the <strong>NLV<\/strong> each minute <em>&#8230; checked<\/em><\/li><li>get the <strong>current price<\/strong> of each position minute by minute <em>&#8230; checked<\/em><\/li><li><strong>change orders<\/strong> like the ones of stop and entry <em>&#8230; checked<\/em><\/li><li><strong>close positions<\/strong> by market order <em>&#8230; eh, just use <code>MarketOrder()<\/code> in the opposite direction of the entry (<code>SELL<\/code> or <code>BUY<\/code>)<\/em><\/li><li>know <strong>how many positions<\/strong> are open<em> &#8230; use <code>len(pos)<\/code> after <code>pos = ib.positions()<\/code><\/em><\/li><li>know the <strong>average entry price<\/strong> of each position to calculate break even <em>&#8230; checked<\/em><\/li><\/ol>\n\n\n\n<p>Here it is!<br>And I hope many of you could profit from this article about how to code all about orders with Interactive Brokers. It&#8217;s simple and everyone can <strong>code some little tools to save time<\/strong> with the everyday trading tasks.<\/p>\n\n\n\n<p><strong><em>Good profits!<\/em><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article you&#8217;ll find how to get your positions, set, modify and cancel orders and get your account value and current unrealized profits by Python Code for Interactive Brokers (see below under Final Words what tasks are discussed in this article). And yes, I found a simple library for all that, named ib_insync and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":479,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"yasr_overall_rating":0,"yasr_post_is_review":"","yasr_auto_insert_disabled":"","yasr_review_type":""},"categories":[7],"tags":[84,20,25,137,53,135,134,21,31,136],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to code all about orders with Interactive Brokers - The Market and Us<\/title>\n<meta name=\"description\" content=\"In this article you&#039;ll find how to get your positions, set orders, modify them and cancel them by Python Code for Interactive Brokers.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to code all about orders with Interactive Brokers - The Market and Us\" \/>\n<meta property=\"og:description\" content=\"In this article you&#039;ll find how to get your positions, set orders, modify them and cancel them by Python Code for Interactive Brokers.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/\" \/>\n<meta property=\"og:site_name\" content=\"The Market and Us\" \/>\n<meta property=\"article:published_time\" content=\"2020-03-08T10:17:49+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-03-08T10:21:40+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2020\/03\/order-sign.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1350\" \/>\n\t<meta property=\"og:image:height\" content=\"900\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"4 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\",\"url\":\"https:\/\/market-and-us.com\/blog\/\",\"name\":\"The Market and Us\",\"description\":\"Weekly Analysis of the Stock Market, Financial Coding and Online-Tools\",\"publisher\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/market-and-us.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2020\/03\/order-sign.jpg\",\"contentUrl\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2020\/03\/order-sign.jpg\",\"width\":1350,\"height\":900},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#webpage\",\"url\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/\",\"name\":\"How to code all about orders with Interactive Brokers - The Market and Us\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#primaryimage\"},\"datePublished\":\"2020-03-08T10:17:49+00:00\",\"dateModified\":\"2020-03-08T10:21:40+00:00\",\"description\":\"In this article you'll find how to get your positions, set orders, modify them and cancel them by Python Code for Interactive Brokers.\",\"breadcrumb\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/\",\"url\":\"https:\/\/market-and-us.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#webpage\"}}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#webpage\"},\"author\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"headline\":\"How to code all about orders with Interactive Brokers\",\"datePublished\":\"2020-03-08T10:17:49+00:00\",\"dateModified\":\"2020-03-08T10:21:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#webpage\"},\"commentCount\":11,\"publisher\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"image\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#primaryimage\"},\"keywords\":[\"accounts\",\"code\",\"how to code\",\"ib_insync\",\"Interactive Brokers\",\"NetLiquidation\",\"orders\",\"Python\",\"Python3\",\"Unrealized Profits\"],\"articleSection\":[\"Knowledge\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-all-about-orders-with-interactive-brokers-475\/#respond\"]}]},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\",\"name\":\"Alexander\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/market-and-us.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"http:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/redakteur-96x96.png\",\"contentUrl\":\"http:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/redakteur-96x96.png\",\"caption\":\"Alexander\"},\"logo\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#personlogo\"},\"description\":\"Alexander bought his first stock in October 2009 without knowing about the luck for this point of time. In 2016 he started to trade, since 2017 he notes down watchlists and statistics every day and because he knows how to code since he was a child, he uses Python, PHP, HTML5 and JS for making the daily to-dos easier. Because many of his friends wanted him not to stop writing about the markets he started this blog to share his ideas and tools.\",\"sameAs\":[\"https:\/\/market-and-us.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yasr_visitor_votes":{"number_of_votes":0,"sum_votes":0,"stars_attributes":{"read_only":false,"span_bottom":false}},"_links":{"self":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/475"}],"collection":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/comments?post=475"}],"version-history":[{"count":6,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/475\/revisions"}],"predecessor-version":[{"id":482,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/475\/revisions\/482"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media\/479"}],"wp:attachment":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media?parent=475"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/categories?post=475"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/tags?post=475"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}