{"id":9482,"date":"2020-08-28T19:08:00","date_gmt":"2020-08-28T19:08:00","guid":{"rendered":"https:\/\/ibkrcampus.eu\/trading-lessons\/essential-components-of-tws-api-programs\/"},"modified":"2024-07-02T18:51:55","modified_gmt":"2024-07-02T18:51:55","slug":"essential-components-of-tws-api-programs","status":"publish","type":"trading-lessons","link":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/","title":{"rendered":"Essential components of TWS API programs"},"content":{"rendered":"<p>Welcome to this lesson on the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, a function call to create a connection to TWS, and a run loop for processing returned messages in the queue. This lesson will also include a brief discussion of the nextValidId method, and we can implement threading. Finally, we\u2019ll walk through our reqCurrentTime method to create a basic \u201cHello World\u201d style script.<\/p>\n<p>To begin, in any TWS API program you\u2019ll always see two main classes, which would be EClient and EWrapper.\u00a0 EClient is used for outgoing messages which are sent from the API program to TWS or the IB Gateway.\u00a0 EWrapper is used to handle incoming messages from the Interactive Brokers server through TWS or IB Gateway.<\/p>\n<p>For this lesson, I will be using Visual Studio Code. However, you can use any development environment of your choice, or even just the command lines and a text editor. To begin, I will start by importing the necessary modules. I will start by importing EClient, using \u201cfrom ibapi.client import *\u201d and EWrapper, using \u201cfrom ibapi.wrapper import *\u201d.\u00a0 I will also be importing the time and threading modules, which we will touch on later.<\/p>\n<p>After importing my modules, I will create a class to combine the EClient and EWrapper modules. I will type \u201cclass TestApp(EClient, EWrapper):\u201d. Next, we instantiate the class by defining our init method with def __init__(self): followed by a newline EClient init request using EClient.__init__(self,self).<\/p>\n<p>After our init, let\u2019s create the EWrapper object for NextValidId(self, orderId): to receive order Ids. This will receive the EWrapper return of next valid order id, and retain valid session throughout the trading day to prevent duplicate values. Here, I can create an object for the order id, self.orderId = orderId. Now it may be confusing, but we can now make a new function, nextId, only retaining the object. Within the function, I will increment our newly made self.orderId value by 1, and then return the self.order variable. This way we can maintain the order Id throughout future requests and return the order id to our request.<\/p>\n<p>We will circle back to some of the more elaborate EWrapper functionality in a moment. However, for now, we can just print out this id by creating our TestApp reference. All this takes is setting a variable, let\u2019s use \u201capp\u201d, equal to the TestApp() class. Now, we\u2019ll connect our app to Trader Workstation, by calling app.connect(\u201c127.0.0.1\u201d, 7497, 0). The values in this method are the host, port, and clientId.<\/p>\n<p>Assuming your TWS is on the same machine where your API code is running, this will always be \u201c127.0.0.1\u201d or \u201clocalhost\u201d. We have included a description of the standard port values in the transcript of this video. You can also review your TWS socket port setting in our prior video on setting up the Trader Workstation for API use. And then our client ID can be any value, as long as another client ID connection is not using the same value.<\/p>\n<table width=\"129\">\n<tbody>\n<tr>\n<td width=\"84\">\n<p>Platform<\/p>\n<\/td>\n<td width=\"45\">\n<p>Port<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td width=\"84\">\n<p>TWS Live<\/p>\n<\/td>\n<td width=\"45\">\n<p>7496<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td width=\"84\">\n<p>TWS Paper<\/p>\n<\/td>\n<td width=\"45\">\n<p>7497<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td width=\"84\">\n<p>IBG Live<\/p>\n<\/td>\n<td width=\"45\">\n<p>4001<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td width=\"84\">\n<p>IBG Paper<\/p>\n<\/td>\n<td width=\"45\">\n<p>4002<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>With our connect methodology in place, we can implement a little bit of threading to get started. The simple implementation would be to call threading.Thread(target=app.run).start().<\/p>\n<p>Please be aware that we reference the object of app.run, without including the parenthesis. Next, we\u2019ll add a quick time.sleep(1) reference, to allow our object to instantiate before we start sending requests. This value will largely depend on your internal machine speed, so you increase or decrease this value as you see fit.<\/p>\n<p>Then, as a quick test to show off our nextId method, we can use a for loop as the example.\u00a0 I will write the loop as <em>for I in range(0,5):<\/em> and then printing the app.nextId() method each time. If we run this script as is, we should see some notifications indicating our connection is OK, followed by our printed ids. These request IDs are used throughout our programming and need to be uniquely assigned on each request. As a result, creating this reliable incrementation tool will be essential.\u00a0<\/p>\n<p>We will explore this further through future videos.<\/p>\n<p>But as a simple implementation of the EClient \u2013 EWrapper duality, we can move on to a call for the current time in Trader Workstation. Within our <em>for<\/em> loop, after our call for the nextId value, I will add a new request for app.reqCurrentTime(). This begins the initial request through EWrapper, but to capture the response, we should define the currentTime function within our class.<\/p>\n<p>Calling <em>def currentTime(self,time):<\/em> we can receive our time value. Within the function, we can print our time value. This function will return the current epoch time observed in Trader Workstation. Epoch time is a single integer time representing the current timestamp in milliseconds. The connection between EClient.reqCurrentTime and EWrapper.currentTime will be an ongoing theme observed through nearly all endpoints used within the API. One external request will be met with one or more asynchronous responses.<\/p>\n<p>One final method to create that will be used throughout the TWS API programming will be our EWrapper.error function. Error will automatically return any error generated by the Trader Workstation while processing your request. This will include values like invalid order formats, market data issues, and more. This will not reflect code issues or similar programming logic failures.<\/p>\n<p>To define this, add the new definition for <em>error<\/em> within our <em>TestApp<\/em> class, containing the arguments for self, reqId, errorCode, errorString, and advancedOrderReject. While you are welcome to simply print all of these values directly, I will be adding context to each message through an <em>f-string<\/em> so we can quickly distinguish which value refers to which argument. If we run our script now, you\u2019ll see various \u201cerror\u201d messages. If we read the errorString value of these messages, we\u2019ll realize these are just notifications mentioning that various market data connections are OK. While this method will largely capture error messages, we will receive system notifications such as the market data connectivity through EWrapper.error as well.<\/p>\n<p>That concludes our lesson on the Essential Components of the TWS API. Thank you for watching. If you have any questions, please be sure to review our documentation or leave a comment below this video. We look forward to having you in the next lesson of our TWS API series.<\/p>\n<h4>Code Snippet &#8211; essentials.py<\/h4>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from ibapi.wrapper import *\nimport time\nimport threading\n\nclass TestApp(EClient, EWrapper):\n  def __init__(self):\n    EClient.__init__(self, self)\n  \n  def nextValidId(self, orderId):\n    self.orderId = orderId\n  \n  def nextId(self):\n    self.orderId += 1\n    return self.orderId\n  \n  def currentTime(self, time):\n    print(time)\n\n  def error(self, reqId, errorCode, errorString, advancedOrderReject):\n    print(f\"reqId: {reqId}, errorCode: {errorCode}, errorString: {errorString}, orderReject: {advancedOrderReject}\")\n\napp = TestApp()\napp.connect(\"127.0.0.1\", 7497, 0)\nthreading.Thread(target=app.run).start()\ntime.sleep(1)\n\n# for i in range(0,5):\n#   print(app.nextId())\napp.reqCurrentTime()<\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, a function call to create a connection to TWS, and a run loop for processing returned messages in the queue. We\u2019ll walk through a simple \u201cHello World\u201d example which implements each of these components in order to send a query for details about a financial instrument and then print received details to the console. We&#8217;ll then discuss the more comprehensive sample program &#8220;Program.py&#8221; which is included with the API download and shows the syntax of all API functions.<\/p>\n","protected":false},"author":850,"featured_media":195697,"parent":0,"comment_status":"open","ping_status":"closed","template":"","meta":{"_acf_changed":true,"footnotes":""},"contributors-categories":[149],"traders-academy":[101,103,105],"class_list":{"0":"post-9482","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=\"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!\" \/>\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\/9482\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Essential components of TWS API programs\" \/>\n<meta property=\"og:description\" content=\"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"IBKR Campus EU\" \/>\n<meta property=\"article:modified_time\" content=\"2024-07-02T18:51:55+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.interactivebrokers.eu\/campus\/wp-content\/uploads\/sites\/3\/2020\/08\/less4-py.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\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=\"Essential components of TWS API programs\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 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:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/\",\n\t            \"name\": \"Essential components of TWS API programs\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.eu\\\/campus\\\/#website\"\n\t            },\n\t            \"primaryImageOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/#primaryimage\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/3\\\/2020\\\/08\\\/less4-py.jpg\",\n\t            \"datePublished\": \"2020-08-28T19:08:00+00:00\",\n\t            \"dateModified\": \"2024-07-02T18:51:55+00:00\",\n\t            \"description\": \"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!\",\n\t            \"breadcrumb\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/#breadcrumb\"\n\t            },\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"ReadAction\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/\"\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.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/#primaryimage\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/3\\\/2020\\\/08\\\/less4-py.jpg\",\n\t            \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/3\\\/2020\\\/08\\\/less4-py.jpg\",\n\t            \"width\": 1920,\n\t            \"height\": 1080,\n\t            \"caption\": \"Working on laptop, graphic\"\n\t        },\n\t        {\n\t            \"@type\": \"BreadcrumbList\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/essential-components-of-tws-api-programs\\\/#breadcrumb\",\n\t            \"itemListElement\": [\n\t                {\n\t                    \"@type\": \"ListItem\",\n\t                    \"position\": 1,\n\t                    \"name\": \"Home\",\n\t                    \"item\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/\"\n\t                },\n\t                {\n\t                    \"@type\": \"ListItem\",\n\t                    \"position\": 2,\n\t                    \"name\": \"Academy Lessons\",\n\t                    \"item\": \"https:\\\/\\\/www.interactivebrokers.eu\\\/campus\\\/trading-lessons\\\/\"\n\t                },\n\t                {\n\t                    \"@type\": \"ListItem\",\n\t                    \"position\": 3,\n\t                    \"name\": \"Essential components of TWS API programs\"\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"WebSite\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.eu\\\/campus\\\/#website\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.eu\\\/campus\\\/\",\n\t            \"name\": \"IBKR Campus EU\",\n\t            \"description\": \"\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"SearchAction\",\n\t                    \"target\": {\n\t                        \"@type\": \"EntryPoint\",\n\t                        \"urlTemplate\": \"https:\\\/\\\/ibkrcampus.eu\\\/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}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Archives | Traders' Academy | IBKR Campus","description":"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!","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\/9482\/","og_locale":"en_US","og_type":"article","og_title":"Essential components of TWS API programs","og_description":"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!","og_url":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/","og_site_name":"IBKR Campus EU","article_modified_time":"2024-07-02T18:51:55+00:00","og_image":[{"width":1920,"height":1080,"url":"https:\/\/www.interactivebrokers.eu\/campus\/wp-content\/uploads\/sites\/3\/2020\/08\/less4-py.jpg","type":"image\/jpeg"}],"twitter_card":"summary_large_image","twitter_title":"Essential components of TWS API programs","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/","url":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/","name":"Essential components of TWS API programs","isPartOf":{"@id":"https:\/\/ibkrcampus.eu\/campus\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/#primaryimage"},"image":{"@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.eu\/campus\/wp-content\/uploads\/sites\/3\/2020\/08\/less4-py.jpg","datePublished":"2020-08-28T19:08:00+00:00","dateModified":"2024-07-02T18:51:55+00:00","description":"This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, and more!","breadcrumb":{"@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/#primaryimage","url":"https:\/\/www.interactivebrokers.eu\/campus\/wp-content\/uploads\/sites\/3\/2020\/08\/less4-py.jpg","contentUrl":"https:\/\/www.interactivebrokers.eu\/campus\/wp-content\/uploads\/sites\/3\/2020\/08\/less4-py.jpg","width":1920,"height":1080,"caption":"Working on laptop, graphic"},{"@type":"BreadcrumbList","@id":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/essential-components-of-tws-api-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.interactivebrokers.eu\/campus\/"},{"@type":"ListItem","position":2,"name":"Academy Lessons","item":"https:\/\/www.interactivebrokers.eu\/campus\/trading-lessons\/"},{"@type":"ListItem","position":3,"name":"Essential components of TWS API programs"}]},{"@type":"WebSite","@id":"https:\/\/ibkrcampus.eu\/campus\/#website","url":"https:\/\/ibkrcampus.eu\/campus\/","name":"IBKR Campus EU","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ibkrcampus.eu\/campus\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/trading-lessons\/9482","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/trading-lessons"}],"about":[{"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/types\/trading-lessons"}],"author":[{"embeddable":true,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/users\/850"}],"replies":[{"embeddable":true,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/comments?post=9482"}],"version-history":[{"count":0,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/trading-lessons\/9482\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/media\/195697"}],"wp:attachment":[{"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/media?parent=9482"}],"wp:term":[{"taxonomy":"contributors-categories","embeddable":true,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/contributors-categories?post=9482"},{"taxonomy":"traders-academy","embeddable":true,"href":"https:\/\/ibkrcampus.eu\/campus\/wp-json\/wp\/v2\/traders-academy?post=9482"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}