<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: spongechameleon</title>
    <description>The latest articles on Forem by spongechameleon (@spongechameleon).</description>
    <link>https://forem.com/spongechameleon</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F387210%2F294c1af1-827e-4e94-a432-d9a17b780aa1.png</url>
      <title>Forem: spongechameleon</title>
      <link>https://forem.com/spongechameleon</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/spongechameleon"/>
    <language>en</language>
    <item>
      <title>How to request and store data using the Interactive Brokers API</title>
      <dc:creator>spongechameleon</dc:creator>
      <pubDate>Tue, 27 Oct 2020 05:02:45 +0000</pubDate>
      <link>https://forem.com/spongechameleon/how-to-request-and-store-data-using-the-interactive-brokers-api-n38</link>
      <guid>https://forem.com/spongechameleon/how-to-request-and-store-data-using-the-interactive-brokers-api-n38</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;If you've started working with the Interactive Brokers API (via the &lt;code&gt;ibapi&lt;/code&gt; python package) but you're confused about how to interact with TWS, you're in the right place!&lt;/p&gt;

&lt;p&gt;In this post I will present one methodology of reliably asking for and receiving data from the TWS GUI using the &lt;code&gt;ibapi&lt;/code&gt; package in your programs. &lt;/p&gt;

&lt;p&gt;The methodology consists of the two main sections in this post:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Tying together the &lt;code&gt;EClient&lt;/code&gt; and &lt;code&gt;EWrapper&lt;/code&gt; classes&lt;/li&gt;
&lt;li&gt;Implementing a strategy to create, read from and destroy &lt;code&gt;queue&lt;/code&gt; objects &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Before we dive in, though, &lt;strong&gt;I'm going to assume that you already have a working connection to TWS from your python program.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;If you do not, there are already plenty of great blog posts and examples walking you through how to get setup and connected, including &lt;a href="https://interactivebrokers.github.io/tws-api/initial_setup.html" rel="noopener noreferrer"&gt;the official docs&lt;/a&gt; and &lt;a href="https://dev.to/wrighter/how-to-connect-to-interactive-brokers-using-python-3142"&gt;this post&lt;/a&gt; from &lt;a class="mentioned-user" href="https://dev.to/wrighter"&gt;@wrighter&lt;/a&gt;, so go ahead and get connected &amp;amp; then jump back here for the low-down.&lt;/p&gt;

&lt;h1&gt;
  
  
  But first, the big picture
&lt;/h1&gt;

&lt;p&gt;Let's first review the high level flow:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Fvhn4oKV.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2Fvhn4oKV.png" alt="ibapi_tws_highlevel"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The TWS GUI is our source of truth. It is what our python program talks to- which is why the TWS GUI must be running locally for our program to work. &lt;/p&gt;

&lt;p&gt;Hence, the one and only API we are using is the API for this local GUI program. Any communication external to our machine is handled by the TWS GUI itself- which is not our concern (as long as you have internet).&lt;/p&gt;

&lt;p&gt;Also, the API &lt;em&gt;is&lt;/em&gt; the collection of class definitions given to us in the &lt;code&gt;ibapi&lt;/code&gt; package- it's not a URL, as you may have assumed (this confused me for a while).&lt;/p&gt;

&lt;p&gt;And here's a screenshot of TWS just so we're all on the same page about what's what:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FcHLWlWf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FcHLWlWf.png" alt="tws_gui"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we've got that sorted let's get right into it.&lt;/p&gt;
&lt;h1&gt;
  
  
  Tying together the EClient and EWrapper classes
&lt;/h1&gt;

&lt;p&gt;As you may have already learned from the &lt;a href="https://interactivebrokers.github.io/tws-api/client_wrapper.html" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt;, the &lt;code&gt;ibapi&lt;/code&gt; package instructs us to work with two classes, &lt;code&gt;EWrapper&lt;/code&gt; and &lt;code&gt;EClient&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;EClient&lt;/code&gt; class gives us one-way communication to send messages to TWS. The messages &lt;code&gt;EClient&lt;/code&gt; sends are &lt;em&gt;requests&lt;/em&gt; for data.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;EWrapper&lt;/code&gt; class gives us one-way communication to receive messages from TWS. The messages &lt;code&gt;EWrapper&lt;/code&gt; receives &lt;em&gt;are&lt;/em&gt; data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FPP3WPOO.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FPP3WPOO.png" alt="ibapi_flows"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Herein lies the crux of the problem. We can ask for data from our &lt;code&gt;EClient&lt;/code&gt; methods, but we're not going to receive a response in those methods. We only receive messages from &lt;code&gt;EWrapper&lt;/code&gt; methods.&lt;/p&gt;

&lt;p&gt;So how do we coordinate asking for and receiving data across these two different classes?&lt;/p&gt;

&lt;p&gt;If you're from the web development world like me, and you're used to requesting and receiving data in the same method call using something like: &lt;code&gt;fetch('https://google.com').then(res =&amp;gt; res.json())...&lt;/code&gt; this presents a serious paradigm shift (at least until we work some magic 😁).&lt;/p&gt;

&lt;p&gt;Part of the answer is to tie the &lt;code&gt;EClient&lt;/code&gt; and &lt;code&gt;EWrapper&lt;/code&gt; classes together in one instantiated object. This process is given to us by the official docs in this (slightly modified) code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from ibapi.wrapper import EWrapper
from ibapi.client import EClient

class TestWrapper(EWrapper):
    def __init__(self):
        pass

class TestClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

class TestApp(TestWrapper, TestClient):
    def __init__(self):
        TestWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First you'll see that &lt;code&gt;TestWrapper&lt;/code&gt; is just a direct copy of &lt;code&gt;EWrapper&lt;/code&gt; (we'll do something useful and different later).&lt;/p&gt;

&lt;p&gt;Next, we see that our new client class &lt;code&gt;TestClient&lt;/code&gt; is just the good old &lt;code&gt;EClient&lt;/code&gt; that we know and love, except that upon instantiation, it must be provided with access to a &lt;code&gt;wrapper&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;And so when we instantiate &lt;code&gt;TestApp&lt;/code&gt; via &lt;code&gt;app = TestApp()&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We first instantiate &lt;code&gt;TestWrapper&lt;/code&gt; to the &lt;code&gt;app&lt;/code&gt; variable&lt;/li&gt;
&lt;li&gt;We then pass that &lt;code&gt;app&lt;/code&gt; variable to &lt;code&gt;TestClient&lt;/code&gt; as &lt;code&gt;wrapper&lt;/code&gt;, and then re-instantiate the &lt;code&gt;app&lt;/code&gt; variable as a &lt;code&gt;TestClient&lt;/code&gt; instance instead&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you look carefully at the &lt;code&gt;EClient.__init__()&lt;/code&gt; definition you'll see that the &lt;code&gt;wrapper&lt;/code&gt; argument is attached to the new object as &lt;code&gt;self.wrapper&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class EClient(object):
    def __init__(self, wrapper):
        self.wrapper = wrapper
        ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So the end result is that we now have an &lt;code&gt;app&lt;/code&gt; object:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;That has access to &lt;code&gt;TestClient&lt;/code&gt; properties and methods via &lt;code&gt;app.some_client_method()&lt;/code&gt; calls&lt;/li&gt;
&lt;li&gt;That has access to &lt;code&gt;TestWrapper&lt;/code&gt; properties and methods via &lt;code&gt;app.wrapper.some_wrapper_method()&lt;/code&gt; calls &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is basically a clever way to have two object instances in one. &lt;code&gt;app&lt;/code&gt; is a full-blown &lt;code&gt;TestClient&lt;/code&gt; instance with a full-blown &lt;code&gt;TestWrapper&lt;/code&gt; instance attached to the &lt;code&gt;app.wrapper&lt;/code&gt; property.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implementing a strategy to create, read from and destroy &lt;code&gt;queue&lt;/code&gt; objects
&lt;/h1&gt;

&lt;p&gt;OK great, now we've tied together our &lt;code&gt;EClient&lt;/code&gt; and &lt;code&gt;EWrapper&lt;/code&gt; classes via this &lt;code&gt;TestApp&lt;/code&gt; class. But... so what?&lt;/p&gt;

&lt;p&gt;How do I make a request to TWS for my account summary? And after I do, how do I collect that data? Well now that we've connected our wrapper and client via our &lt;code&gt;app&lt;/code&gt; object, we can design a flow to answer both of those questions.&lt;/p&gt;

&lt;p&gt;Let's be very explicit and continue with the account summary example.&lt;/p&gt;

&lt;p&gt;First, we can request our account summary from TWS via the &lt;code&gt;EClient.reqAccountSummary&lt;/code&gt; method. How did I know that? Well, the purpose and description of this and all API-provided methods can be found in the &lt;code&gt;ibapi&lt;/code&gt; source itself, or in (once again) &lt;a href="https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html" rel="noopener noreferrer"&gt;the official docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Looking at the docstring for &lt;code&gt;reqAccountSummary&lt;/code&gt; in &lt;code&gt;EClient&lt;/code&gt;, we see:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. &lt;strong&gt;The data is returned by accountSummary().&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now here we must discuss a very important point. &lt;code&gt;accountSummary&lt;/code&gt; is an &lt;code&gt;EWrapper&lt;/code&gt; method. In fact, it's not just a method but an event! That means that &lt;code&gt;accountSummary&lt;/code&gt; will be &lt;strong&gt;automatically called&lt;/strong&gt; when TWS is ready to deliver our requested account summary. This is how all of these wrapper methods/events work (&lt;code&gt;openOrder&lt;/code&gt;, &lt;code&gt;tickPrice&lt;/code&gt;, etc..)&lt;/p&gt;

&lt;p&gt;To be 100% clear:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We request our account summary from TWS by running &lt;code&gt;reqAccountSummary()&lt;/code&gt; (an &lt;code&gt;EClient&lt;/code&gt; method)&lt;/li&gt;
&lt;li&gt;TWS will take however much time it needs to gather that data, and when it's ready to send it back to us...&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;accountSummary()&lt;/code&gt; method (from &lt;code&gt;EWrapper&lt;/code&gt;) will be automatically called, containing the data in its method arguments&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Again, we do not manually call &lt;code&gt;accountSummary&lt;/code&gt;, it's called automatically!&lt;/p&gt;

&lt;p&gt;OK so what happens to the data delivered in &lt;code&gt;accountSummary&lt;/code&gt;? Let's look at its definition in &lt;code&gt;EWrapper&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def accountSummary(self, reqId:int, account:str, tag:str, value:str, currency:str):
    self.logAnswer(current_fn_name(), vars())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First let's note the function arguments. We're getting back the following data: &lt;code&gt;reqId&lt;/code&gt;, &lt;code&gt;account&lt;/code&gt;, &lt;code&gt;tag&lt;/code&gt;, &lt;code&gt;value&lt;/code&gt; and &lt;code&gt;currency&lt;/code&gt; (the &lt;code&gt;:int&lt;/code&gt; and &lt;code&gt;:str&lt;/code&gt; are just type annotations).&lt;/p&gt;

&lt;p&gt;Looking at the function body, there's really nothing going on. And that's intentional. Interactive Brokers expects us to overwrite this &lt;code&gt;accountSummary&lt;/code&gt; method in &lt;code&gt;TestWrapper&lt;/code&gt; to dictate what we want to do with the returned data. This is why the &lt;code&gt;TestWrapper&lt;/code&gt; class definition was empty earlier (but now we're going to fill it in!)&lt;/p&gt;

&lt;p&gt;Here is where we implement our data flow strategy. The gist of the methodology revolves around two principles:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We control client methods, but we do not control wrapper methods

&lt;ul&gt;
&lt;li&gt;Yes, we control what wrapper methods do (we override &lt;code&gt;EWrapper&lt;/code&gt; methods with our own definitions in &lt;code&gt;TestWrapper&lt;/code&gt;), but we do not control when they run. TWS will fire specific methods (such as &lt;code&gt;EWrapper.accountSummary&lt;/code&gt;) automatically.&lt;/li&gt;
&lt;li&gt;However, we do control when client methods will run.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The client part of our &lt;code&gt;app&lt;/code&gt; object knows about the wrapper, but the wrapper does not know about the client

&lt;ul&gt;
&lt;li&gt;When we instantiated &lt;code&gt;TestApp&lt;/code&gt;, we gave our &lt;code&gt;TestClient&lt;/code&gt; class an instantiated &lt;code&gt;TestWrapper&lt;/code&gt; object.&lt;/li&gt;
&lt;li&gt;As we've already discussed, this means that the client methods and properties on &lt;code&gt;app&lt;/code&gt; have access to the wrapper methods/props on &lt;code&gt;app.wrapper&lt;/code&gt;, but the reverse is not true. The wrapper methods/props on &lt;code&gt;app.wrapper&lt;/code&gt; have no knowledge of the client methods/props on the base &lt;code&gt;app&lt;/code&gt; object.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;What does this mean for our design? Our client methods should be our command center and contain our conditional checks &amp;amp; flow control. We want this because the client methods/props have supreme visibility across the object and because we control when the methods run. On the other hand our wrapper methods should be dead simple because they have limited visibility across the object and because we do not control when some of them run.&lt;/p&gt;

&lt;h2&gt;
  
  
  The gameplan to request data from TWS (using a &lt;code&gt;TestClient&lt;/code&gt; method)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Initialize data storage on the wrapper object (think &lt;code&gt;app.wrapper&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Request data from TWS (think &lt;code&gt;EClient.reqAccountSummary&lt;/code&gt;)

&lt;ul&gt;
&lt;li&gt;(Auto-run wrapper method puts data into storage -&amp;gt; think &lt;code&gt;TestWrapper.accountSummary&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Retrieve target data from storage on the wrapper&lt;/li&gt;
&lt;li&gt;Delete data storage on the wrapper object&lt;/li&gt;
&lt;li&gt;Check for errors that may have occurred during this process&lt;/li&gt;
&lt;li&gt;Return the retrieved data&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For all the visual folks:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FLDFFSlq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FLDFFSlq.png" alt="schema"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In our case we want our account summary. So let's tackle these step-by-step and then bring it all together at the end in one &lt;code&gt;TestClient&lt;/code&gt; method definition.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Initialize data storage on the wrapper object
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;First, let's define a method on &lt;code&gt;TestWrapper&lt;/code&gt; that will build us an empty &lt;code&gt;queue&lt;/code&gt;:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import queue

class TestWrapper(EWrapper):

    def init_accountSummary_queue(self):                                                                              
        self.accountSummary_queue = queue.Queue()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;What's a &lt;code&gt;queue&lt;/code&gt;? It's just a first-in-first-out (FIFO) list. Why use this instead of a &lt;code&gt;List&lt;/code&gt; or something else? Stay tuned!&lt;/li&gt;
&lt;li&gt;OK great. Now we have a place on the wrapper to put our account summary data. (As a sanity check, if you instantiate &lt;code&gt;app = TestApp()&lt;/code&gt; right now, you'd have access to this method from &lt;code&gt;app.wrapper.init_accountSummary_queue&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Step 2: Request data from TWS
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;This is achieved by running the correct &lt;code&gt;EClient&lt;/code&gt; method. All we have to do here is call &lt;code&gt;reqAccountSummary&lt;/code&gt; from &lt;code&gt;EClient&lt;/code&gt; (with the appropriate arguments of course)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Step 2b: Auto-run wrapper method puts data into storage
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Here's where we define our custom &lt;code&gt;TestWrapper&lt;/code&gt; method overriding the default &lt;code&gt;EWrapper.accountSummary&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TestWrapper(EWrapper):

    def accountSummary(
        self, reqId: int, account: str, tag: str, value: str, currency: str
    ):
        """
        Triggered by EClient.reqAccountSummary()
        """
        if hasattr(self, "accountSummary_queue"):
            self.accountSummary_queue.put(
                {
                    "reqId": reqId,
                    "account": account,
                    "tag": tag,
                    "value": value,
                    "currency": currency,
                }
            )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Note that (a) we're keeping it simple and just passing the arguments through to our &lt;code&gt;queue&lt;/code&gt; in a dictionary and (b) we only do this if the &lt;code&gt;queue&lt;/code&gt; already exists (we do not want to accumulate data that we didn't ask for, in case TWS fires events on its own)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Step 3: Retrieve target data from storage on the wrapper
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Here is where &lt;code&gt;queue&lt;/code&gt; objects shine, because we can repeatedly try to get something from an (initially) empty queue until it either: (a) gives us something or (b) times out&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Quick proof-of-concept&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Init an empty queue
myQ = queue.Queue()

try:
    # Try to remove an item from the queue    
    myItem = myQ.get(timeout=5)
except queue.Empty:
    print("myQ was empty and max time has been reached")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;This will of course raise the &lt;code&gt;queue.Empty&lt;/code&gt; exception, but if some data were to magically be &lt;code&gt;put&lt;/code&gt; into the queue during the five second timeout window... we would get the data and avoid the exception!&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Step 4: Delete data storage on the wrapper object
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Since the wrapper methods run automatically, we don't want our &lt;code&gt;queue&lt;/code&gt; objects to accumulate data sent to us from TWS unprompted. We only want data when we ask for it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Proof-of-concept&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class A():
    def __init__(self):
        self.myQ = queue.Queue()

a = A()
del a.myQ
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 5: Check for errors that may have occurred during this process
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;We're going to keep track of errors on the wrapper side, because if you think about it, just like we receive data that we want on &lt;code&gt;TestWrapper&lt;/code&gt;, that's also how we receive error messages from TWS too...
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TestWrapper(EWrapper):

    def init_error(self):
        self.my_errors_queue = queue.Queue()

    def is_error(self):
        error_exist = not self.my_errors_queue.empty()
        return error_exist

    def get_error(self, timeout=5):
        if self.is_error():
            try:
                return self.my_errors_queue.get(timeout=timeout)
            except queue.Empty:
                return None
        return None

    def error(self, id, errorCode, errorString):
        errormessage = (
            "IB returns an error with %d errorcode %d that says %s"
            % (
                id,
                errorCode,
                errorString,
            )
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 6: Return the retrieved data
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Well, this one speaks for itself&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Bringing it all together into one &lt;code&gt;TestClient&lt;/code&gt; method
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TestClient(EClient):

    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)
        # Maximum timeout we're comfortable with, in seconds
        self.max_wait_time = 5

    def getAccountSummary(self):
        """
        Runs EClient.reqAccountSummary()
        Returns value from EWrapper.accountSummary()
        """
        # [1] Init a queue on the wrapper
        self.wrapper.init_accountSummary_queue()

        # [2] Request data from TWS
        self.reqAccountSummary(
            9001, "All", "TotalCashValue, BuyingPower, AvailableFunds"
        )

        try:
            # [3] Get data from queue (if it shows up) or eventually timeout
            accountSummary = self.wrapper.accountSummary_queue.get(
                timeout=self.max_wait_time
            )
        except queue.Empty:
            print("accountSummary queue was empty or max time reached")
            accountSummary = None

        # [4] Delete queue from wrapper
        del self.wrapper.accountSummary_queue

        # [5] Check for errors
        while self.wrapper.is_error():
            print("Error:")
            print(self.get_error(timeout=self.max_wait_time)

        # [6] Return data
        return accountSummary
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;I should also mention that you &lt;strong&gt;must&lt;/strong&gt; use &lt;code&gt;threading&lt;/code&gt; for this approach to work- otherwise wrapper events could be blocked by currently executing client functions.&lt;/p&gt;

&lt;p&gt;To achieve that, put this in your &lt;code&gt;TestApp&lt;/code&gt; definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from threading import Thread

class TestApp(TestWrapper, TestClient):

    def __init__(self, ...):
        ...
        thread = Thread(target=self.run)
        thread.start()
        setattr(self, "_thread", thread)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that should do it! Is this the best way to implement the IB API? Probably not, but it seems to be a fairly reliable way to do so (at least in my thus far limited experience).&lt;/p&gt;

&lt;p&gt;Let me know what you think of this design in the comments and finally, thanks for reading!&lt;/p&gt;

</description>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>A short story on npm scripts &amp; killing processes (how to make your tools work for you!)</title>
      <dc:creator>spongechameleon</dc:creator>
      <pubDate>Sun, 23 Aug 2020 06:46:42 +0000</pubDate>
      <link>https://forem.com/spongechameleon/a-short-story-on-npm-scripts-killing-processes-how-to-make-your-tools-work-for-you-13o7</link>
      <guid>https://forem.com/spongechameleon/a-short-story-on-npm-scripts-killing-processes-how-to-make-your-tools-work-for-you-13o7</guid>
      <description>&lt;h1&gt;
  
  
  The background
&lt;/h1&gt;

&lt;p&gt;I have a project. It has static files. They are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A HTML file&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A Sass file (.scss)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A Typescript file (.ts)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To get my sass to compile into regular .css, I use the &lt;code&gt;node-sass&lt;/code&gt; npm package.&lt;/p&gt;

&lt;p&gt;To get my typescript to compile into regular .js, I use the &lt;code&gt;tsc&lt;/code&gt; compiler.&lt;/p&gt;

&lt;p&gt;To get my browser to automatically update whenever one of these files is changed, I use the &lt;code&gt;browser-sync&lt;/code&gt; npm package.&lt;/p&gt;

&lt;h3&gt;
  
  
  How I start up:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Open a terminal. Go to project directory. Start &lt;code&gt;vim&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Open another terminal. Go to project directory. Run &lt;code&gt;tsc &amp;amp; node-sass &amp;amp; browser-sync &amp;amp;&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;(Full disclosure: &lt;code&gt;node-sass&lt;/code&gt; and &lt;code&gt;browser-sync&lt;/code&gt; are run with options, but that's not important)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Go back to vim and edit.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How I close down:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Close vim (&lt;em&gt;but how?!&lt;/em&gt;). Close terminal.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Go to the other terminal. Find and kill my processes, one-by-one:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ps aux | grep node-sass&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Mentally take note of the displayed PID (process ID) from the second column&lt;/li&gt;
&lt;li&gt;&lt;code&gt;kill &amp;lt;PID I definitely always remember perfectly&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Repeat for &lt;code&gt;tsc&lt;/code&gt; and &lt;code&gt;browser-sync&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is clearly a lot of typing and PID-remembering. Nobody likes that. We can do better.&lt;/p&gt;




&lt;h1&gt;
  
  
  The npm script
&lt;/h1&gt;

&lt;p&gt;My start up command is too much typing. So we’re going to have &lt;code&gt;package.json&lt;/code&gt; do the heavy lifting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“scripts”: {
  “ts”: “tsc”,
  “sass”: “node-sass”,
  “browser”: “browser-sync”,
  “serve”: “npm run ts &amp;amp; npm run sass &amp;amp; npm run browser &amp;amp;”
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, all we have to run is &lt;code&gt;npm run serve&lt;/code&gt; and everything is taken care of for us.&lt;/p&gt;

&lt;p&gt;OK, but why go through all the trouble of making scripts for each single command? Why not just do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“scripts”: {
  “serve”: “tsc &amp;amp; node-sass &amp;amp; browser-sync &amp;amp;”
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The answer to that is all about our friend, &lt;code&gt;&amp;amp;&lt;/code&gt;, the ampersand. Anything with an &lt;code&gt;&amp;amp;&lt;/code&gt; will run continuously and show up in the output of &lt;code&gt;ps aux&lt;/code&gt;. And we intentionally want all of our processes- whatever they really are- to show up as &lt;code&gt;npm&lt;/code&gt; processes!&lt;/p&gt;

&lt;p&gt;Hence:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;“serve”&lt;/code&gt; script that only runs &lt;code&gt;npm&lt;/code&gt; commands&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The absence of an &lt;code&gt;&amp;amp;&lt;/code&gt; in the &lt;code&gt;“ts/sass/browser”&lt;/code&gt; scripts&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  The kill
&lt;/h1&gt;

&lt;p&gt;So here’s why we want all of those tools to show up as &lt;code&gt;npm&lt;/code&gt; commands:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ps aux | grep [n]pm | awk ‘{ print $2 }’&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Outputs all processes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Filters by &lt;code&gt;[n]pm&lt;/code&gt; (only considers processes with the first letter of “n”)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Grabs the second column/word of output, which in this case is the PID&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now all that’s left is to kill all of those PIDs we collected:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;kill $(ps aux | grep [n]pm | awk ‘{ print $2 }’)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Booyah. But… hate typing that? Me too. So, we can either just alias this in our .bashrc as ‘npmkill’ or something…&lt;/p&gt;




&lt;h1&gt;
  
  
  The generalized, easy to type kill
&lt;/h1&gt;

&lt;p&gt;…or take an extra minute to whip together a quick bash script that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Accepts a grep search term&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lets us see our processes before we kill them&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/usr/bin/bash
ps aux | grep $1

read -p ‘kill processes? (y/n): ‘ confirm

if [ $confirm == ‘y’ ]
then
  kill $(ps aux | grep $1 | awk ‘{ print $2 }’)
fi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;$1&lt;/code&gt; refers to the first argument passed to the script, so if we call our script &lt;code&gt;pidkill.sh&lt;/code&gt; then running &lt;code&gt;pidkill [n]pm&lt;/code&gt; would mean &lt;code&gt;$1&lt;/code&gt; == &lt;code&gt;[n]pm&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;read -p ‘&amp;lt;prompt&amp;gt;: ‘ confirm&lt;/code&gt; allows us to (a) enter our response on the same line and (b) saves our response to the &lt;code&gt;$confirm&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;Then it’s a simple if statement and our shell expansion!&lt;/p&gt;

&lt;p&gt;Don’t forget to alias your script in .bashrc if you want to be able to use it anywhere, otherwise you’ll have to be in the directory of the script or type out its path every time.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;alias pidkill=’~/pidkill.sh’&lt;/code&gt; does the trick for me.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thanks for reading and happy coding!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;sponge&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>bash</category>
      <category>npm</category>
      <category>productivity</category>
    </item>
  </channel>
</rss>
