#!/usr/bin/env python # coding: utf-8 # # Basics # # Let's first take a look at what's inside the ``ib_insync`` package: # In[1]: import ib_insync print(ib_insync.__all__) # ### Importing # The following two lines are used at the top of all notebooks. The first line imports everything and the second # starts an event loop to keep the notebook live updated: # In[2]: from ib_insync import * util.startLoop() # *Note that startLoop() only works in notebooks, not in regular Python programs.* # ### Connecting # The main player of the whole package is the "IB" class. Let's create an IB instance and connect to a running TWS/IBG application: # In[3]: ib = IB() ib.connect('127.0.0.1', 7497, clientId=10) # If the connection failed, then verify that the application has the API port enabled and double-check the hostname and port. For IB Gateway the default port is 4002. Make sure the clientId is not already in use. # # If the connection succeeded, then ib will be synchronized with TWS/IBG. The "current state" is now available via methods such as ib.positions(), ib.trades(), ib.openTrades(), ib.accountValues() or ib.tickers(). Let's list the current positions: # In[4]: ib.positions() # Or filter the account values to get the liquidation value: # In[5]: [v for v in ib.accountValues() if v.tag == 'NetLiquidationByCurrency' and v.currency == 'BASE'] # The "current state" will automatically be kept in sync with TWS/IBG. So an order fill will be added as soon as it is reported, or account values will be updated as soon as they change in TWS. # ### Contracts # # Contracts can be specified in different ways: # * The ibapi way, by creating an empty Contract object and setting its attributes one by one; # * By using Contract and giving the attributes as keyword argument; # * By using the specialized Stock, Option, Future, Forex, Index, CFD, Commodity, # Bond, FuturesOption, MutualFund or Warrant contracts. # # Some examples: # In[6]: Contract(conId=270639) Stock('AMD', 'SMART', 'USD') Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ') Forex('EURUSD') CFD('IBUS30') Future('ES', '20180921', 'GLOBEX') Option('SPY', '20170721', 240, 'C', 'SMART') Bond(secIdType='ISIN', secId='US03076KAA60'); # ### Sending a request # # The IB class has nearly all request methods that the IB API offers. The methods that return a result will block until finished and then return the result. Take for example reqContractDetails: # In[7]: contract = Stock('TSLA', 'SMART', 'USD') ib.reqContractDetails(contract) # ### Current state vs request # # Doing a request involves network traffic going up and down and can take considerable time. The current state on the other hand is always immediately available. So it is preferable to use the current state methods over requests. For example, use ``ib.openOrders()`` in preference over ``ib.reqOpenOrders()``, or ``ib.positions()`` over ``ib.reqPositions()``, etc: # In[8]: get_ipython().run_line_magic('time', 'l = ib.positions()') # In[9]: get_ipython().run_line_magic('time', 'l = ib.reqPositions()') # ### Logging # # The following will put log messages of INFO and higher level under the current active cell: # In[10]: util.logToConsole() # To see all debug messages (including network traffic): # In[11]: import logging util.logToConsole(logging.DEBUG) # ### Disconnecting # # The following will disconnect ``ib`` and clear all its state: # In[12]: ib.disconnect()