{"id":141743,"date":"2022-06-07T12:00:00","date_gmt":"2022-06-07T16:00:00","guid":{"rendered":"https:\/\/ibkrcampus.com\/?p=141743"},"modified":"2023-01-19T18:16:33","modified_gmt":"2023-01-19T23:16:33","slug":"an-introduction-to-tws-api-with-jupyter-notebooks","status":"publish","type":"post","link":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/","title":{"rendered":"An Introduction to TWS API with Jupyter Notebooks"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" width=\"1000\" height=\"563\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg\" alt=\"Quant\" class=\"wp-image-141305 lazyload\" data-srcset=\"https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg 1000w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant-700x394.jpg 700w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant-300x169.jpg 300w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant-768x432.jpg 768w\" data-sizes=\"(max-width: 1000px) 100vw, 1000px\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 1000px; aspect-ratio: 1000\/563;\" \/><\/figure>\n\n\n\n<p><strong>What is an API?<\/strong><\/p>\n\n\n\n<p>According to&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/API\">Wikipedia<\/a>, an Application Programming Interface (API) is defined as a software intermediary that facilitates communication between two different pieces of software. The TWS API was developed with the intention of allowing Interactive Brokers&#8217; clients to automate common tasks in Trader Workstation, a desktop based trading application developed by IBKR.<\/p>\n\n\n\n<p>TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is&nbsp;<a href=\"https:\/\/ib-insync.readthedocs.io\/api.html\">ib_insync<\/a>, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Getting-Started\"><strong>Getting Started<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\"><li>Download and install the stable version of Trader Workstation:&nbsp;<a href=\"https:\/\/www.interactivebrokers.com\/en\/trading\/tws.php\">https:\/\/www.interactivebrokers.com\/en\/trading\/tws.php<\/a><\/li><li>Create and activate a new Python virtual environment.<\/li><li>Install ibapi_insync.<\/li><li>Install pandas for better data formatting.<\/li><li>Start TWS and log in using a paper account.<\/li><\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Connecting-to-Trader-Workstation\"><strong>Connecting to Trader Workstation<\/strong><\/h3>\n\n\n\n<p>Communication between the client application and TWS takes place over a local socket connection defined by a host and port number. Unless you are deploying your deploying your app to a server the host will usually be your computer&#8217;s localhost, i.e. 127.0.0.1. In addition to the host, we also need to know the port number on which TWS is listening to requests. This can be found in TWS by clicking File -&gt; Global Configuration -&gt; API -&gt; Settings -&gt; Socket Port. When logging in with a paper account, this will usually be set to port 7497, however you are free to change this to any port that is open on the current device. Each client application connecting to TWS via the API must be identified by a unique clientId.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\"><span class=\"has-vivid-green-cyan-color has-text-color\">from<\/span> ib_insync <span class=\"has-vivid-green-cyan-color has-text-color\">import<\/span>\n<span class=\"has-vivid-purple-color has-text-color\">*<\/span>\n<br><br>\nHOST <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> <span class=\"has-vivid-red-color has-text-color\">&#8216;127.0.0.1&#8217;<\/span><br>\nPORT <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> 7497<br>\nCLIENT_ID = 1\n<br><br>\nutil.startLoop<span class=\"has-vivid-cyan-blue-color has-text-color\">()<\/span> <span class=\"has-light-green-cyan-color has-text-color\"><i># Starts loop that allows us to work with the API in Jupyter notebooks &#8211; this is not necessary in a script<\/i><\/span><br>\nib_client <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> IB<span class=\"has-vivid-cyan-blue-color has-text-color\">()<\/span> <span class=\"has-light-green-cyan-color has-text-color\"><i># Creates an instance of the IB client class<\/i><\/span><br>\nib_client.connect(HOST, PORT, CLIENT_ID) <span class=\"has-light-green-cyan-color has-text-color\"><i># Connects to TWS<\/i><\/span><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;IB connected to 127.0.0.1:7497 clientId=1&gt;\n<\/code><\/pre>\n\n\n\n<p>We should now be connected to TWS. To check that everything is working correctly, let&#8217;s request the account summary for the currently signed in user using the&nbsp;<code>accountSummary()<\/code>&nbsp;method. This returns a list of account summary objects. Since we are using a single account, let&#8217;s just take a look at the first element of that list.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\"><em>\n# Retrieve account summary for currently signed in user<\/em><\/span><br><br>\naccounts = ib_client.accountSummary()<br>\nprint(<span class=\"has-vivid-red-color has-text-color\">f&#8221;Account currently signed in to TWS is: {<\/span>accounts[<span class=\"has-vivid-green-cyan-color has-text-color\">0<\/span>]<span class=\"has-vivid-red-color has-text-color\">}&#8221;<\/span>)<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Account currently signed in to TWS is: AccountValue(account='DU4760065', tag='AccountType', value='INDIVIDUAL', currency='', modelCode='')<\/code><\/pre>\n\n\n\n<p>Information about the user, including account type and client type, is returned to client application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Requesting-Contract-details\"><strong>Requesting Contract details<\/strong><\/h3>\n\n\n\n<p>Contracts are the fundamental blocks of most requests made using the API. Contract objects represent trading instruments such as stocks, futures, or options. Requests requiring contracts are first sent to TWS, where they are matched with available data, and, where ambiguity in the contract exists, an error is returned to the client. Ambiguous contracts can be resolved by passing additional data about the instrument, for example the contract ID, or the exchange on which the instrument is traded.<\/p>\n\n\n\n<p>Let&#8217;s create two example contracts for which we will request the contract details. A forex contract for the currency pair EUR.USD, and the the AAPL@NASDAQ stock contract.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\"><em># Request details for Forex and Stock contracts<\/em><\/span><br><br>\n\nforex_contract <span class=\"has-vivid-purple-color has-text-color\"> = <\/span> Forex(<span class=\"has-vivid-red-color has-text-color\">&#8220;EURUSD&#8221;<\/span>)<br>\nstock_contract <span class=\"has-vivid-purple-color has-text-color\"> = <\/span> Stock(<span class=\"has-vivid-red-color has-text-color\">&#8220;AAPL&#8221;<\/span>, exchange<strong>=<\/strong><span class=\"has-vivid-red-color has-text-color\">&#8220;ISLAND&#8221;<\/span>) <br><br>\n\nfull_forex_contract_details <span class=\"has-vivid-purple-color has-text-color\"> = <\/span> ib_client<strong>.<\/strong>reqContractDetails(forex_contract)<br>\nfull_stock_contract_details <span class=\"has-vivid-purple-color has-text-color\"> = <\/span> ib_client<strong>.<\/strong>reqContractDetails(stock_contract)<br><br>\n\nprint(<span class=\"has-vivid-red-color has-text-color\">f&#8221;Full contract details for EURUSD: {<\/span>full_forex_contract_details<span class=\"has-vivid-red-color has-text-color\">}<\/span>&#8220;, end<span class=\"has-vivid-purple-color has-text-color\"> = <\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;\\n\\n&#8221;<\/span>)<br>\nprint(<span class=\"has-vivid-red-color has-text-color\">f&#8221;Full contract details for AAPL stock: {<\/span>full_stock_contract_details<span class=\"has-vivid-red-color has-text-color\">}&#8221;<\/span>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Full contract details for EURUSD: &#91;ContractDetails(contract=Contract(secType='CASH', conId=12087792, symbol='EUR', exchange='IDEALPRO', currency='USD', localSymbol='EUR.USD', tradingClass='EUR.USD'), marketName='EUR.USD', minTick=5e-05, sizeMinTick=1.0, orderTypes='ACTIVETIM,AD,ADJUST,ALERT,ALGO,ALLOC,AVGCOST,BASKET,CASHQTY,COND,CONDORDER,DAY,DEACT,DEACTDIS,DEACTEOD,GAT,GTC,GTD,GTT,HID,IOC,LIT,LMT,MIT,MKT,NONALGO,OCA,REL,RELPCTOFS,SCALE,SCALERST,STP,STPLMT,TRAIL,TRAILLIT,TRAILLMT,TRAILMIT,WHATIF', validExchanges='IDEALPRO', priceMagnifier=1, underConId=0, longName='European Monetary Union Euro', contractMonth='', industry='', category='', subcategory='', timeZoneId='US\/Eastern', tradingHours='20220526:1715-20220527:1700;20220528:CLOSED;20220529:1715-20220530:1700;20220530:1715-20220531:1700;20220531:1715-20220601:1700;20220601:1715-20220602:1700', liquidHours='20220526:1715-20220527:1700;20220528:CLOSED;20220529:1715-20220530:1700;20220530:1715-20220531:1700;20220531:1715-20220601:1700;20220601:1715-20220602:1700', evRule='', evMultiplier=0, mdSizeMultiplier=1, aggGroup=4, underSymbol='', underSecType='', marketRuleIds='239', secIdList=&#91;], realExpirationDate='', lastTradeTime='', stockType='', cusip='', ratings='', descAppend='', bondType='', couponType='', callable=False, putable=False, coupon=0, convertible=False, maturity='', issueDate='', nextOptionDate='', nextOptionType='', nextOptionPartial=False, notes='')]\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Full contract details for AAPL stock: &#91;ContractDetails(contract=Contract(secType='STK', conId=265598, symbol='AAPL', exchange='ISLAND', primaryExchange='NASDAQ', currency='USD', localSymbol='AAPL', tradingClass='NMS'), marketName='NMS', minTick=0.01, sizeMinTick=100.0, orderTypes='ACTIVETIM,AD,ADJUST,ALERT,ALLOC,AON,AVGCOST,BASKET,BENCHPX,CASHQTY,COND,CONDORDER,DAY,DEACT,DEACTDIS,DEACTEOD,DIS,GAT,GTC,GTD,GTT,HID,IOC,LIT,LMT,LOC,MIT,MKT,MOC,MTL,NGCOMB,NONALGO,OCA,OPG,PEGBENCH,RTH,SCALE,SCALERST,SNAPMID,SNAPMKT,SNAPREL,STP,STPLMT,TRAIL,TRAILLIT,TRAILLMT,TRAILMIT,WHATIF', validExchanges='SMART,AMEX,NYSE,CBOE,PHLX,ISE,CHX,ARCA,ISLAND,DRCTEDGE,BEX,BATS,EDGEA,CSFBALGO,JEFFALGO,BYX,IEX,EDGX,FOXRIVER,PEARL,NYSENAT,LTSE,MEMX,PSX', priceMagnifier=1, underConId=0, longName='APPLE INC', contractMonth='', industry='Technology', category='Computers', subcategory='Computers', timeZoneId='US\/Eastern', tradingHours='20220527:0400-20220527:2000;20220528:CLOSED;20220529:CLOSED;20220530:CLOSED;20220531:0400-20220531:2000;20220601:0400-20220601:2000', liquidHours='20220527:0930-20220527:1600;20220528:CLOSED;20220529:CLOSED;20220530:CLOSED;20220531:0930-20220531:1600;20220601:0930-20220601:1600', evRule='', evMultiplier=0, mdSizeMultiplier=100, aggGroup=1, underSymbol='', underSecType='', marketRuleIds='26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26', secIdList=&#91;TagValue(tag='ISIN', value='US0378331005')], realExpirationDate='', lastTradeTime='', stockType='COMMON', cusip='', ratings='', descAppend='', bondType='', couponType='', callable=False, putable=False, coupon=0, convertible=False, maturity='', issueDate='', nextOptionDate='', nextOptionType='', nextOptionPartial=False, notes='')]\n<\/code><\/pre>\n\n\n\n<p>Full information about the contract, including the contract ID, security type, exchange, trading hours, and the available order types are returned.<\/p>\n\n\n\n<p>Note how the exchange was explicitly passed to the stock contract. This is done to retrieve data for just the stock traded on the NASDAQ (ISLAND) exchange. To get information about the stock on all exchanges, you can remove this parameter.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Realtime-and-Historical-data-requests\"><strong>Realtime and Historical data requests<\/strong><\/h3>\n\n\n\n<p>Now that we have some contracts set up, let&#8217;s request data for them. Clients using TWS API can request both live and historical market data for most instruments provided that they have the appropriate&nbsp;<a href=\"https:\/\/www.interactivebrokers.com\/en\/pricing\/research-news-marketdata.php\">market data subscriptions<\/a>. Interactive Brokers provides free market data for Forex contracts, so we will use this for the subsequent examples.<\/p>\n\n\n\n<p>One of the simplest data requests that can be made using the API is a snapshot request. Snapshot requests, as the name suggest, provide an overview of the instrument&#8217;s market data at the time of request. In order to invoke a snapshot market data request, the&nbsp;<code>reqMktData<\/code>&nbsp;method can be used with the parameter snapshot set to True.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\"><em># Requesting a single snapshot<\/em><\/span><br><br>\n\nsnapshot <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqMktData(forex_contract, snapshot<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\"><strong>True<\/strong><\/span>)<br>\nprint(snapshot)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 37, 246483, tzinfo=datetime.timezone.utc), bid=1.07147, bidSize=2800000.0, ask=1.07148, askSize=1000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 37, 246483, tzinfo=datetime.timezone.utc), tickType=6, price=1.0765, size=0.0), TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 37, 246483, tzinfo=datetime.timezone.utc), tickType=7, price=1.06975, size=0.0), TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 37, 246483, tzinfo=datetime.timezone.utc), tickType=9, price=1.073, size=0.0), TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 37, 246483, tzinfo=datetime.timezone.utc), tickType=49, price=0.0, size=0)])\n<\/code><\/pre>\n\n\n\n<p>Where streaming market data is preferred, the snapshot parameter can be set to False. This will continuously retrieve ticker updates from TWS until the request is cancelled. The below example retrieves 10 ticks for the EUR.USD ticker. Ticks are spaced apart by 1 second.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\">\n<em># Request the next 10 ticks<\/em><\/span><br><br>\n\nNUM_TICKS <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> <span class=\"has-vivid-green-cyan-color has-text-color\">10<\/span><br><br>\n\nticker <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqMktData(forex_contract, snapshot<strong>=<\/strong><span class=\"has-vivid-green-cyan-color has-text-color\"><strong>False<\/strong><\/span>)<br>\n<span class=\"has-vivid-green-cyan-color has-text-color\"><strong>while<\/strong><\/span> NUM_TICKS <span class=\"has-vivid-purple-color has-text-color\"><strong> != <\/strong><\/span> <span class=\"has-vivid-green-cyan-color has-text-color\">0:<\/span><br>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ib_client<strong>.<\/strong>sleep<span class=\"has-vivid-green-cyan-color has-text-color\">(1)<\/span><br>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class=\"has-vivid-green-cyan-color has-text-color\"><strong>if<\/strong><\/span> ticker <strong>is<\/strong> <span class=\"has-vivid-green-cyan-color has-text-color\"><strong>None<\/strong><\/span>:<br>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class=\"has-vivid-green-cyan-color has-text-color\"><strong>continue<\/strong><\/span><br>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(ticker, end<span class=\"has-vivid-purple-color has-text-color\"><span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;\\n\\n&#8221;<\/span>)<br>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NUM_TICKS <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> <span class=\"has-vivid-green-cyan-color has-text-color\">1<\/span><br><br>\n\nib_client<strong>.<\/strong>cancelMktData(forex_contract)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 48, 312572, tzinfo=datetime.timezone.utc), bid=1.07147, bidSize=1000000.0, ask=1.07148, askSize=3000000.0, prevBid=1.07148, prevBidSize=2000000.0, prevAsk=1.07149, prevAskSize=2000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 48, 312572, tzinfo=datetime.timezone.utc), tickType=1, price=1.07147, size=1000000.0), TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 48, 312572, tzinfo=datetime.timezone.utc), tickType=2, price=1.07148, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 49, 226633, tzinfo=datetime.timezone.utc), bid=1.07148, bidSize=1000000.0, ask=1.07149, askSize=3000000.0, prevBid=1.07147, prevBidSize=2000000.0, prevAsk=1.07148, prevAskSize=4000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 49, 226633, tzinfo=datetime.timezone.utc), tickType=1, price=1.07148, size=1000000.0), TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 49, 226633, tzinfo=datetime.timezone.utc), tickType=2, price=1.07149, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 50, 717092, tzinfo=datetime.timezone.utc), bid=1.07149, bidSize=1000000.0, ask=1.0715, askSize=1000000.0, prevBid=1.07148, prevBidSize=2000000.0, prevAsk=1.07149, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 50, 717092, tzinfo=datetime.timezone.utc), tickType=3, price=1.0715, size=1000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 51, 518501, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=1000000.0, ask=1.07144, askSize=3000000.0, prevBid=1.07143, prevBidSize=2000000.0, prevAsk=1.07143, prevAskSize=1000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 51, 518501, tzinfo=datetime.timezone.utc), tickType=1, price=1.07142, size=1000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 52, 618759, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=2000000.0, ask=1.07144, askSize=3500000.0, prevBid=1.07143, prevBidSize=1000000.0, prevAsk=1.07143, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 52, 618759, tzinfo=datetime.timezone.utc), tickType=0, price=1.07142, size=2000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 53, 421083, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=2000000.0, ask=1.07144, askSize=3000000.0, prevBid=1.07143, prevBidSize=1000000.0, prevAsk=1.07143, prevAskSize=3500000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 53, 421083, tzinfo=datetime.timezone.utc), tickType=3, price=1.07144, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 53, 921868, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=2000000.0, ask=1.07144, askSize=2000000.0, prevBid=1.07143, prevBidSize=1000000.0, prevAsk=1.07143, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 53, 921868, tzinfo=datetime.timezone.utc), tickType=3, price=1.07144, size=2000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=3000000.0, ask=1.07144, askSize=2000000.0, prevBid=1.07143, prevBidSize=2000000.0, prevAsk=1.07143, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), tickType=0, price=1.07142, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=3000000.0, ask=1.07144, askSize=2000000.0, prevBid=1.07143, prevBidSize=2000000.0, prevAsk=1.07143, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), tickType=0, price=1.07142, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Ticker(contract=Forex('EURUSD', exchange='IDEALPRO'), time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), bid=1.07142, bidSize=3000000.0, ask=1.07144, askSize=2000000.0, prevBid=1.07143, prevBidSize=2000000.0, prevAsk=1.07143, prevAskSize=3000000.0, high=1.0765, low=1.06975, close=1.073, halted=0.0, ticks=&#91;TickData(time=datetime.datetime(2022, 5, 27, 13, 16, 55, 125149, tzinfo=datetime.timezone.utc), tickType=0, price=1.07142, size=3000000.0)])\n<\/code><\/pre>\n\n\n\n<p>When developing trading strategies, API user&#8217;s may also want to retrieve historical data. This can be easily done using the&nbsp;<code>reqHistoricalData<\/code>&nbsp;method. Note the&nbsp;<code>endDateTime<\/code>&nbsp;parameter. Setting this to a particular point in time will result in data prior to that point being returned. Where the parameter is left as a blank string, the current time is used instead. The following request retrieves previous month&#8217;s data with a bar size of 1 day.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\"><em># Request historical bars for the last month with bar size of 1 day<\/em><\/span><br><br>\n\nhistorical_bars <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqHistoricalData<span class=\"has-vivid-cyan-blue-color has-text-color\">(<\/span><br>\n&nbsp;&nbsp;&nbsp;&nbsp;forex_contract,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;endDateTime<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;durationStr<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;1 M&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;barSizeSetting<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;1 day&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;whatToShow<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;MIDPOINT&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;useRTH<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><strong><span class=\"has-vivid-green-cyan-color has-text-color\">False<\/span><\/strong>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;formatDate<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\">1<\/span><br>\n<span class=\"has-vivid-cyan-blue-color has-text-color\">)<\/span><br><br>\n\ndf <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> util<strong>.<\/strong>df<span class=\"has-vivid-cyan-blue-color has-text-color\">(<\/span>historical_bars<span class=\"has-vivid-cyan-blue-color has-text-color\">)<\/span><br>\nprint<span class=\"has-vivid-cyan-blue-color has-text-color\">(<\/span>df<span class=\"has-vivid-cyan-blue-color has-text-color\">)<\/span><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><\/td><td>date<\/td><td>open <\/td><td>high <\/td><td>low <\/td><td>close<\/td><td>volume<\/td><td>average<\/td><td>barCount<\/td><\/tr><tr><td>0<\/td><td>2022-04-28<\/td><td>1.05610 <\/td><td>1.05650 <\/td><td>1.04715 <\/td><td>1.04990<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>1<\/td><td>2022-04-29<\/td><td>1.05005 <\/td><td>1.05930 <\/td><td>1.04915 <\/td><td>1.05425<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>2<\/td><td>2022-05-02<\/td><td>1.05440 <\/td><td>1.05685 <\/td><td>1.04905 <\/td><td>1.05065<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>3<\/td><td>2022-05-03<\/td><td>1.05040 <\/td><td>1.05780 <\/td><td>1.04925 <\/td><td>1.05200<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>4<\/td><td>2022-05-04<\/td><td>1.05220 <\/td><td>1.06310 <\/td><td>1.05060 <\/td><td>1.06200<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>5<\/td><td>2022-05-05<\/td><td>1.06255 <\/td><td>1.06420 <\/td><td>1.04925 <\/td><td>1.05395<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>6<\/td><td>2022-05-06<\/td><td>1.05450 <\/td><td>1.05990 <\/td><td>1.04830 <\/td><td>1.05435<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>7<\/td><td>2022-05-09<\/td><td>1.05480 <\/td><td>1.05925 <\/td><td>1.04955 <\/td><td>1.05605<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>8<\/td><td>2022-05-10<\/td><td>1.05625 <\/td><td>1.05855 <\/td><td>1.05255 <\/td><td>1.05285<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>9<\/td><td>2022-05-11<\/td><td>1.05325 <\/td><td>1.05775 <\/td><td>1.05020 <\/td><td>1.05125<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>10<\/td><td>2022-05-12<\/td><td>1.05150 <\/td><td>1.05295 <\/td><td>1.03540 <\/td><td>1.03805<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>11<\/td><td>2022-05-13<\/td><td>1.03795 <\/td><td>1.04195 <\/td><td>1.03495 <\/td><td>1.04135<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>12<\/td><td>2022-05-16<\/td><td>1.04065 <\/td><td>1.04430 <\/td><td>1.03890 <\/td><td>1.04330<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>13<\/td><td>2022-05-17<\/td><td>1.04325 <\/td><td>1.05560 <\/td><td>1.04285 <\/td><td>1.05505<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>14<\/td><td>2022-05-18<\/td><td>1.05495 <\/td><td>1.05640 <\/td><td>1.04605 <\/td><td>1.04630<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>15<\/td><td>2022-05-19<\/td><td>1.04625 <\/td><td>1.06070 <\/td><td>1.04600 <\/td><td>1.05845<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>16<\/td><td>2022-05-20<\/td><td>1.05860 <\/td><td>1.05995 <\/td><td>1.05330 <\/td><td>1.05610<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>17<\/td><td>2022-05-23<\/td><td>1.05635 <\/td><td>1.06975 <\/td><td>1.05600 <\/td><td>1.06905<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>18<\/td><td>2022-05-24<\/td><td>1.06900 <\/td><td>1.07490 <\/td><td>1.06610 <\/td><td>1.07360<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>19<\/td><td>2022-05-25<\/td><td>1.07290 <\/td><td>1.07390 <\/td><td>1.06425 <\/td><td>1.06780<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>20<\/td><td>2022-05-26<\/td><td>1.06820 <\/td><td>1.07320 <\/td><td>1.06625 <\/td><td>1.07280<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><tr><td>21<\/td><td>2022-05-27<\/td><td>1.07255 <\/td><td>1.07650 <\/td><td>1.06970 <\/td><td>1.07150<\/td><td>-1.0<\/td><td>-1.0<\/td><td>-1<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>When requesting historical data, it may also be important to know how far back data is available. This can be found for a contract using the&nbsp;<code>reqHeadTimestamp<\/code>&nbsp;method.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\">\n<em># Request timestamp of earliest available data for this contract<\/em><\/span><br><br>\nhead_timestamp <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqHeadTimeStamp(forex_contract, <span class=\"has-vivid-red-color has-text-color\">&#8220;MIDPOINT&#8221;<\/span>, useRTH<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\"><strong>True<\/strong><span class=\"has-vivid-green-cyan-color has-text-color\">)<br>\nprint(<span class=\"has-vivid-red-color has-text-color\">f&#8221;Head timestamp for EURUSD: {<\/span>head_timestamp<span class=\"has-vivid-red-color has-text-color\">}&#8221;<\/span>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Head timestamp for EURUSD: 2005-03-09 04:30:00\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Placing-&amp;-Managing-Orders\"><strong>Placing &amp; Managing Orders<\/strong><\/h3>\n\n\n\n<p>Now that we can request contracts and market data, it&#8217;s time to move on to the most important aspect of TWS API &#8211; order placement and management.<\/p>\n\n\n\n<p>First we&#8217;ll place an example limit order for the AAPL@NASDAQ stock contract. To ensure that the order is not immediately filled, we&#8217;ll set the limit price to a value well above the current ask price. Optional parameters such as the time-in-force, and whether to use certain price management algorithms can also be passed into the order object at this stage. Once the order is set up, orders can be placed for specific contracts using the&nbsp;<code>placeOrder<\/code>&nbsp;method by passing both the contract and order details.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\"><em>\n# Create a LMT type order to buy 1 contract of AAPL stock<\/em><\/span><br><br>\n\norder_details <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> Order<span class=\"has-vivid-green-cyan-color has-text-color\">(<\/span><br>\n&nbsp;&nbsp;&nbsp;&nbsp;action<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;BUY&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;orderType<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;LMT&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;totalQuantity<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\">1<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;lmtPrice<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\">999<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;tif<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;DAY&#8221;<\/span>,<br>\n&nbsp;&nbsp;&nbsp;&nbsp;usePriceMgmtAlgo<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-green-cyan-color has-text-color\">True<\/span><br><br>\n<span class=\"has-vivid-green-cyan-color has-text-color\">)<\/span><br>\norder <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client.placeOrder(stock_contract, order_details)<\/p>\n\n\n\n<p>To get the status for all open orders we can use the&nbsp;<code>reqOpenOrders<\/code>&nbsp;method. An open order is an order that has yet to be filled. Filled orders are referred to as executions.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\">\n<em># Request open orders from TWS<\/em><\/span><br><br>\n\nopen_orders <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqOpenOrders()<br>\n[print(order, end<span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span><span class=\"has-vivid-red-color has-text-color\">&#8220;\\n\\n&#8221;<\/span>) <strong>for<\/strong> order <span class=\"has-vivid-purple-color has-text-color\"><strong> in <\/strong><\/span> open_orders]<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Order(orderId=62, clientId=1, permId=338637127, action='BUY', totalQuantity=1.0, orderType='LMT', lmtPrice=999.0, auxPrice=0.0, tif='DAY', ocaType=3, displaySize=2147483647, trailStopPrice=1000.0, volatilityType=0, deltaNeutralOrderType='None', deltaNeutralOpenClose='?', referencePriceType=0, account='DU4760065', clearingIntent='IB', adjustedOrderType='None', cashQty=0.0, dontUseAutoPriceForHedge=True, usePriceMgmtAlgo=True)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;None]\n<\/code><\/pre>\n\n\n\n<p>To modify orders, we can call the&nbsp;<code>placeOrder<\/code>&nbsp;method again with the updated order details. Information such as the order ID need to be passed into the updated Order object to ensure it&#8217;s correctly matched to an existing order in TWS. Let&#8217;s modify the limit price field for the order above to a more sensible value.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">\n<span class=\"has-light-green-cyan-color has-text-color\">\n<em># Modify the order to be of type <\/em><\/span><br><br>\n\nexisting_order <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> open_orders[<span class=\"has-vivid-green-cyan-color has-text-color\">0<\/span>]<br>\nexisting_order<strong>.<\/strong>lmtPrice <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> <span class=\"has-vivid-green-cyan-color has-text-color\">200<\/span><br>\nib_client<strong>.<\/strong>placeOrder(stock_contract, existing_order)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Trade(contract=Stock(symbol='AAPL', exchange='ISLAND'), order=Order(orderId=62, clientId=1, permId=338637127, action='BUY', totalQuantity=1.0, orderType='LMT', lmtPrice=999.0, auxPrice=0.0, tif='DAY', usePriceMgmtAlgo=True), orderStatus=OrderStatus(orderId=62, status='PreSubmitted', filled=0.0, remaining=1.0, avgFillPrice=0.0, permId=338637127, parentId=0, lastFillPrice=0.0, clientId=1, whyHeld='', mktCapPrice=0.0), fills=&#91;], log=&#91;TradeLogEntry(time=datetime.datetime(2022, 5, 27, 13, 17, 11, 752164, tzinfo=datetime.timezone.utc), status='PendingSubmit', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2022, 5, 27, 13, 17, 12, 265494, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2022, 5, 27, 13, 17, 37, 833807, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='Modify', errorCode=0)])\n<\/code><\/pre>\n\n\n\n<p>If we request&nbsp;<code>openOrders<\/code>&nbsp;once more, we should see the first order&#8217;s limit price has changed to $200.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\">open_orders <span class=\"has-vivid-purple-color has-text-color\"><strong> = <\/strong><\/span> ib_client<strong>.<\/strong>reqOpenOrders()<br>\nprint(open_orders[<span class=\"has-vivid-green-cyan-color has-text-color\">0<\/span>])<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Order(orderId=62, clientId=1, permId=338637127, action='BUY', totalQuantity=1.0, orderType='LMT', lmtPrice=200.0, auxPrice=0.0, tif='DAY', ocaType=3, displaySize=2147483647, volatilityType=0, deltaNeutralOrderType='None', deltaNeutralOpenClose='?', referencePriceType=0, account='DU4760065', clearingIntent='IB', adjustedOrderType='None', cashQty=0.0, dontUseAutoPriceForHedge=True, usePriceMgmtAlgo=True)\n<\/code><\/pre>\n\n\n\n<p>Finally, let&#8217;s cancel all outstanding orders. This can be done by looping over all existing orders and passing them to the&nbsp;<code>cancelOrder<\/code>&nbsp;method.<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c230\"><em># Cancel all open orders<\/em><br><br>\n\n<strong>for<\/strong> order <strong>in<\/strong> open_orders:<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ib_client<strong>.<\/strong>cancelOrder(order)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Conclusion\"><strong>Conclusion<\/strong><\/h3>\n\n\n\n<p>The examples above serve as a very general introduction into the capabilities of TWS API. Some of the content not covered in this introduction includes market scanners, functionalities for financial advisors, options calculations, and the various order types and price management algorithms. For a full list of functionality we recommend taking a look at the official TWS API documentation:&nbsp;<a href=\"https:\/\/interactivebrokers.github.io\/tws-api\">https:\/\/interactivebrokers.github.io\/tws-api<\/a><\/p>\n\n\n\n<p>Example use cases of TWS API can be found on the IBKR Quant Blog:&nbsp;<a href=\"\/campus\/category\/ibkr-quant-news\/\">\/campus\/category\/ibkr-quant-news\/<\/a>&nbsp;. The official download for&nbsp;<a href=\"https:\/\/interactivebrokers.github.io\/#\">TWS API<\/a>&nbsp;also contains sample client apps.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is ib_insync, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.<\/p>\n","protected":false},"author":839,"featured_media":141305,"comment_status":"closed","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[339,340,343,349,338,350,341,351,352,344,2197],"tags":[851,806,1006,865,12013,575,6614,778,1224,11707,10670],"contributors-categories":[13576],"class_list":{"0":"post-141743","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-science","8":"category-api-development","9":"category-programing-languages","10":"category-python-development","11":"category-ibkr-quant-news","12":"category-quant-asia-pacific","13":"category-quant-development","14":"category-quant-europe","15":"category-quant-north-america","16":"category-quant-regions","17":"category-quant-south-america","18":"tag-algo-trading","19":"tag-data-science","20":"tag-fintech","21":"tag-github","22":"tag-ibapi_insync","23":"tag-ibkr-api","24":"tag-jupyter-notebook","25":"tag-nasdaq","26":"tag-pandas","27":"tag-python-api","28":"tag-tws-api","29":"contributors-categories-interactive-brokers"},"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.8) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>An Introduction to TWS API with Jupyter Notebooks<\/title>\n<meta name=\"description\" content=\"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to...\" \/>\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\/posts\/141743\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"An Introduction to TWS API with Jupyter Notebooks | IBKR Quant Blog\" \/>\n<meta property=\"og:description\" content=\"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is ib_insync, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/\" \/>\n<meta property=\"og:site_name\" content=\"IBKR Campus US\" \/>\n<meta property=\"article:published_time\" content=\"2022-06-07T16:00:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-01-19T23:16:33+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1000\" \/>\n\t<meta property=\"og:image:height\" content=\"563\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Damian Anslik\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Damian Anslik\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 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\": \"NewsArticle\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/#article\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/\"\n\t            },\n\t            \"author\": {\n\t                \"name\": \"Damian Anslik\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/1afc8abe9374493a185779b0f9db61c5\"\n\t            },\n\t            \"headline\": \"An Introduction to TWS API with Jupyter Notebooks\",\n\t            \"datePublished\": \"2022-06-07T16:00:00+00:00\",\n\t            \"dateModified\": \"2023-01-19T23:16:33+00:00\",\n\t            \"mainEntityOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/\"\n\t            },\n\t            \"wordCount\": 1745,\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2022\\\/06\\\/interactive-digital-quant.jpg\",\n\t            \"keywords\": [\n\t                \"Algo Trading\",\n\t                \"Data Science\",\n\t                \"fintech\",\n\t                \"GitHub\",\n\t                \"ibapi_insync\",\n\t                \"IBKR API\",\n\t                \"Jupyter Notebook\",\n\t                \"Nasdaq\",\n\t                \"Pandas\",\n\t                \"Python API\",\n\t                \"TWS API\"\n\t            ],\n\t            \"articleSection\": [\n\t                \"Data Science\",\n\t                \"IBKR API Development\",\n\t                \"Programming Languages\",\n\t                \"Python Development\",\n\t                \"Quant\",\n\t                \"Quant Asia Pacific\",\n\t                \"Quant Development\",\n\t                \"Quant Europe\",\n\t                \"Quant North America\",\n\t                \"Quant Regions\",\n\t                \"Quant South America\"\n\t            ],\n\t            \"inLanguage\": \"en-US\"\n\t        },\n\t        {\n\t            \"@type\": \"WebPage\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/\",\n\t            \"name\": \"An Introduction to TWS API with Jupyter Notebooks | IBKR Quant Blog\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\"\n\t            },\n\t            \"primaryImageOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/#primaryimage\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2022\\\/06\\\/interactive-digital-quant.jpg\",\n\t            \"datePublished\": \"2022-06-07T16:00:00+00:00\",\n\t            \"dateModified\": \"2023-01-19T23:16:33+00:00\",\n\t            \"description\": \"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is ib_insync, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"ReadAction\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/\"\n\t                    ]\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"ImageObject\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/an-introduction-to-tws-api-with-jupyter-notebooks\\\/#primaryimage\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2022\\\/06\\\/interactive-digital-quant.jpg\",\n\t            \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2022\\\/06\\\/interactive-digital-quant.jpg\",\n\t            \"width\": 1000,\n\t            \"height\": 563,\n\t            \"caption\": \"Quant\"\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            \"@type\": \"Person\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/1afc8abe9374493a185779b0f9db61c5\",\n\t            \"name\": \"Damian Anslik\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/author\\\/damian-anslik\\\/\"\n\t        }\n\t    ]\n\t}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"An Introduction to TWS API with Jupyter Notebooks","description":"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to...","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\/posts\/141743\/","og_locale":"en_US","og_type":"article","og_title":"An Introduction to TWS API with Jupyter Notebooks | IBKR Quant Blog","og_description":"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is ib_insync, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.","og_url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/","og_site_name":"IBKR Campus US","article_published_time":"2022-06-07T16:00:00+00:00","article_modified_time":"2023-01-19T23:16:33+00:00","og_image":[{"width":1000,"height":563,"url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","type":"image\/jpeg"}],"author":"Damian Anslik","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Damian Anslik","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"NewsArticle","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/#article","isPartOf":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/"},"author":{"name":"Damian Anslik","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/1afc8abe9374493a185779b0f9db61c5"},"headline":"An Introduction to TWS API with Jupyter Notebooks","datePublished":"2022-06-07T16:00:00+00:00","dateModified":"2023-01-19T23:16:33+00:00","mainEntityOfPage":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/"},"wordCount":1745,"publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"image":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","keywords":["Algo Trading","Data Science","fintech","GitHub","ibapi_insync","IBKR API","Jupyter Notebook","Nasdaq","Pandas","Python API","TWS API"],"articleSection":["Data Science","IBKR API Development","Programming Languages","Python Development","Quant","Quant Asia Pacific","Quant Development","Quant Europe","Quant North America","Quant Regions","Quant South America"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/","url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/","name":"An Introduction to TWS API with Jupyter Notebooks | IBKR Quant Blog","isPartOf":{"@id":"https:\/\/ibkrcampus.com\/campus\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/#primaryimage"},"image":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","datePublished":"2022-06-07T16:00:00+00:00","dateModified":"2023-01-19T23:16:33+00:00","description":"TWS API has official clients for C#, C++, Java, Visual Basic, and Python. In addition, a number of third-party libraries have also been developed to make it easier for developers to work with TWS. One of these libraries is ib_insync, which allows for asynchronous communication with TWS, and allows us to write code in a linear programming style. ib_insync also allows us to use the API with Jupyter notebooks.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/an-introduction-to-tws-api-with-jupyter-notebooks\/#primaryimage","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","width":1000,"height":563,"caption":"Quant"},{"@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\/"},{"@type":"Person","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/1afc8abe9374493a185779b0f9db61c5","name":"Damian Anslik","url":"https:\/\/www.interactivebrokers.com\/campus\/author\/damian-anslik\/"}]}},"jetpack_featured_media_url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2022\/06\/interactive-digital-quant.jpg","_links":{"self":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/141743","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/users\/839"}],"replies":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/comments?post=141743"}],"version-history":[{"count":0,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/141743\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media\/141305"}],"wp:attachment":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media?parent=141743"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/categories?post=141743"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/tags?post=141743"},{"taxonomy":"contributors-categories","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/contributors-categories?post=141743"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}