Reputation: 41
I am new to Python and I would like to get in a variable the price snapshot of a list of securities using the native TWS Python API (Interactive Brokers API). For example, for the stocks APPL, AMZN and NFLX, I would like to get something like snaphot = ['APPL', 195.2, 'AMZN', 1771.5, 'NFLX', 306].
Thank you in advance for your help.
I found the guide from Interactive Brokers difficult to understand and with a lack of examples. The one example they provide is for one stock only and it never stops running.
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
import time
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
def error(self, reqId, errorCode, errorString):
print("Error: ", reqId, " ", errorCode, " ", errorString)
def tickPrice(self, reqId, tickType, price, attrib):
print("Tick Price. Ticker Id:", reqId, "tickType:",
TickTypeEnum.to_str(tickType), "Price:", price, end=' ')
def tickSize(self, reqId, tickType, size):
print("Tick Size. Ticker Id:", reqId, "tickType:",
TickTypeEnum.to_str(tickType), "Size:", size)
def main():
app = TestApp()
app.connect("127.0.0.1", 7496, 0)
time.sleep(0.1)
contract = Contract()
contract.secType = "FUT"
contract.exchange = "DTB"
contract.currency = "EUR"
contract.localSymbol = "FDXM SEP 19"
app.reqMarketDataType(4) # 1 for live, 4 for delayed-frozen data if live is not available
app.reqMktData(1, contract, "", True, False, [])
app.run()
if __name__ == "__main__":
main()
Upvotes: 4
Views: 1816
Reputation: 816
You would just need to define Contract objects for the stocks, e.g.
appl_contract = Contract()
appl_contract.symbol = "AAPL"
appl_contract.secType = "STK"
appl_contract.exchange = "SMART"
appl_contract.primaryExchange = "ISLAND"
appl_contract.currency = "USD"
Then invoke reqMktData with each Contract object, using a unique tickerId argument for each outstanding request (meaning the request is still active). In the tickPrice callback, you receive the returned price data and use the tickerId to match the data to the original request. If you just want the last traded price, you would filter for tickType == 4.
After you have received data for the last instrument in your list you could call disconnect() if you want to disconnect/end the program.
You may also be interested in the Python TWS API Traders Academy Course on the IBKR website:
Upvotes: 3