In [1]:
from ib_insync import *
util.startLoop()
import logging
# util.logToConsole(logging.DEBUG)
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=11)
Out[1]:
Suppose we want to find the contract details for AMD stock. Let's create a stock object and request the details for it:
In [2]:
amd = Stock('AMD')
cds = ib.reqContractDetails(amd)
len(cds)
Out[2]:
We get a long list of contract details. Lets print the first one:
In [3]:
cds[0]
Out[3]:
The contract itself is in the 'contract' property of the contract details. Lets make a list of contracts and look at the first:
In [4]:
contracts = [cd.contract for cd in cds]
contracts[0]
Out[4]:
To better spot the difference between all the contracts it's handy to convert to a DataFrame. There is a utility function to do that:
In [5]:
util.df(contracts)
Out[5]:
We can see from this that AMD trades in different currencies on different exchanges. Suppose we want the one in USD on the SMART exchange. The AMD contract is adjusted to reflect that and becomes unique:
In [6]:
amd = Stock('AMD', 'SMART', 'USD')
assert len(ib.reqContractDetails(amd)) == 1
Lets try the same for Intel:
In [7]:
intc = Stock('INTC', 'SMART', 'USD')
assert len(ib.reqContractDetails(intc)) == 1
Let's try a non-existing contract:
In [8]:
xxx = Stock('XXX', 'SMART', 'USD')
assert len(ib.reqContractDetails(xxx)) == 0
or a Forex contract
In [9]:
eurusd = Forex('EURUSD')
assert len(ib.reqContractDetails(eurusd)) == 1
With the qualifyContracts
method the extra information that is send back
from the contract details request is used to fill in the original contracts.
Lets do that with amd
and compare before and aftwards:
In [10]:
amd
Out[10]:
In [11]:
ib.qualifyContracts(amd)
amd
Out[11]:
TIP: When printing a contract, the output can be copy-pasted and it will be valid Python code.
The conId
that is returned can by itself be used to uniquely specify a contract:
In [12]:
contract_4391 = Contract(conId=4391)
ib.qualifyContracts(contract_4391)
assert contract_4391 == amd
A whole bunch of contracts can be qualified at the same time. A list of all the successfull ones is returned:
In [13]:
qualContracts = ib.qualifyContracts(amd, intc, xxx, eurusd)
assert intc in qualContracts
assert xxx not in qualContracts
There is also an API function to request stocks (only stocks) that match a pattern:
In [14]:
matches = ib.reqMatchingSymbols('intc')
matchContracts = [m.contract for m in matches]
matches
Out[14]:
In [15]:
assert intc in matchContracts
In [16]:
ib.disconnect()