I’m trying to trade multiple stocks at a time that meet the same conditions for a trade. To track the data, I’m storing the data in a dictionary using the nextOrderId as the key, and the contract details and bar data as the values. While incrementing the nextOrderId, I get a key error.
The nextOrderId seems to be incrementing fine for the stocks I have in a list, but then it makes one more incrementation than I need. I think that’s what’s triggering the error. I was expecting the incrementation to happen only when there is a stock in the list. I’m not sure how to avoid this.
from ibapi.client import *
from ibapi.wrapper import *
from ibapi.contract import Contract
from ibapi.order import *
from datetime import datetime, timedelta
class ibapi(EClient, EWrapper):
EClient.__init__(self,self)
self.contract = (0, Contract())
def nextValidId(self, orderId: OrderId):
self.nextOrderId = orderId
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
self.contract = (reqId, contractDetails.contract)
def error(self, reqId, errorCode, errorString, advancedOrderReject = ''):
print(f'reqId: {reqId}, errorCode: {errorCode}, errorString:{errorString}, order reject: {advancedOrderReject}')
def historicalDataUpdate(self, reqId, bar):
if reqId not in BAR_TRACKER:
BAR_TRACKER[self.nextOrderId] = (self.contract, [])
BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def historicalData(self, reqId, bar):
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, count):
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((time, open_, high, low, close, volume))
#def requestData(self, contract, isHistorical=True):
#self.reqHistoricalData(self.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=False, chartOptions=[])
#self.reqRealTimeBars(self.nextOrderId, contract=contract, barSize=5, whatToShow="TRADES", useRTH=True, realTimeBarsOptions=[])
def updateAccountValue(self, key: str, val: str, currency: str, accountName: str):
ACCOUNT_INFO[key] = float(val)
def updatePortfolio(self, contract: Contract, position: Decimal, marketPrice: float, marketValue: float, averageCost: float, unrealizedPNL: float, realizedPNL: float, accountName: str):
ACCOUNT_INFO[contract.localSymbol] = {"contract":contract,"position": float(position), "marketPrice": marketPrice, "marketValue": marketValue, "averageCost": averageCost}
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState):
print(f"openOrder. orderId: {orderId}, contract: {contract}, order: {order}")
def execDetails(self, reqId: int, contract: Contract, execution: Execution):
print(f"execDetails. reqId: {reqId}, contract: {contract}, execution: {execution}")
def buildContracts(app: ibapi, tickers: list):
contract.exchange = 'SMART'
contract.currency = 'USD'
app.reqContractDetails(reqId, contract)
if app.contract[0] == reqId:
contracts.append(app.contract[1])
def marketMonitor(app: ibapi, contracts: list):
for contract in contracts:
app.reqHistoricalData(app.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=True, chartOptions=[])
#app.requestData(contract, isHistorical=True)
#app.requestData(contract, isHistorical=False)
def porfolioMonitor(app: ibapi):
app.reqAccountUpdates(True)
def tradeStrategy(app: ibapi):
for contract in BAR_TRACKER:
ohlcv = BAR_TRACKER[app.nextOrderId][1]
for contract in BAR_TRACKER:
ohlcv = ohlcv = BAR_TRACKER[app.nextOrderId][1] #key error thrown here
mycon = BAR_TRACKER[app.nextOrderId][0]
app.connect('127.0.0.1', port, 1001)
app_obj = threading.Thread(target = app.run)
tickers = ['QUBT','SGMT']
contracts = buildContracts(app, tickers)
marketMonitor(app, contracts)
trd_obj = threading.Thread(target=tradeStrategy, args=(app,))
if __name__ == "__main__":
<code>import ibapi
from ibapi.client import *
from ibapi.wrapper import *
from ibapi.contract import Contract
from ibapi.order import *
import ta
import numpy as np
import pandas as pd
import pytz
import math
from datetime import datetime, timedelta
import threading
import time
port = 7497
BAR_TRACKER = {}
ACCOUNT_INFO = {}
class ibapi(EClient, EWrapper):
def __init__(self):
EClient.__init__(self,self)
self.nexOrderId = 1
self.contract = (0, Contract())
#self.data = {}
def nextValidId(self, orderId: OrderId):
self.nextOrderId = orderId
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
self.contract = (reqId, contractDetails.contract)
def error(self, reqId, errorCode, errorString, advancedOrderReject = ''):
print(f'reqId: {reqId}, errorCode: {errorCode}, errorString:{errorString}, order reject: {advancedOrderReject}')
def historicalDataUpdate(self, reqId, bar):
if reqId not in BAR_TRACKER:
BAR_TRACKER[self.nextOrderId] = (self.contract, [])
BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def historicalData(self, reqId, bar):
# Store historical data
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, count):
# Store real-time data
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((time, open_, high, low, close, volume))
#def requestData(self, contract, isHistorical=True):
#if isHistorical:
#self.reqHistoricalData(self.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=False, chartOptions=[])
#else:
#self.reqRealTimeBars(self.nextOrderId, contract=contract, barSize=5, whatToShow="TRADES", useRTH=True, realTimeBarsOptions=[])
def updateAccountValue(self, key: str, val: str, currency: str, accountName: str):
if key == "CashBalance":
ACCOUNT_INFO[key] = float(val)
def updatePortfolio(self, contract: Contract, position: Decimal, marketPrice: float, marketValue: float, averageCost: float, unrealizedPNL: float, realizedPNL: float, accountName: str):
ACCOUNT_INFO[contract.localSymbol] = {"contract":contract,"position": float(position), "marketPrice": marketPrice, "marketValue": marketValue, "averageCost": averageCost}
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState):
print(f"openOrder. orderId: {orderId}, contract: {contract}, order: {order}")
def execDetails(self, reqId: int, contract: Contract, execution: Execution):
print(f"execDetails. reqId: {reqId}, contract: {contract}, execution: {execution}")
def buildContracts(app: ibapi, tickers: list):
reqId = 1
contracts = []
for symbol in tickers:
contract = Contract()
contract.symbol = symbol
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.currency = 'USD'
app.reqContractDetails(reqId, contract)
requested = True
while requested:
if app.contract[0] == reqId:
contracts.append(app.contract[1])
requested = False
reqId += 1
return contracts
def marketMonitor(app: ibapi, contracts: list):
for contract in contracts:
app.nextOrderId += 1
app.reqHistoricalData(app.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=True, chartOptions=[])
#app.requestData(contract, isHistorical=True)
#app.requestData(contract, isHistorical=False)
def porfolioMonitor(app: ibapi):
app.reqAccountUpdates(True)
def tradeStrategy(app: ibapi):
for contract in BAR_TRACKER:
ohlcv = BAR_TRACKER[app.nextOrderId][1]
print(ohlcv)
order = Order()
order.orderType = 'MKT'
order.tif = 'GTC'
order.outsideRth = True
while True:
for contract in BAR_TRACKER:
ohlcv = ohlcv = BAR_TRACKER[app.nextOrderId][1] #key error thrown here
mycon = BAR_TRACKER[app.nextOrderId][0]
app.nextOrderId +=1
#trading logic
def main():
app = ibapi()
app.connect('127.0.0.1', port, 1001)
time.sleep(3)
app_obj = threading.Thread(target = app.run)
app_obj.start()
porfolioMonitor(app)
tickers = ['QUBT','SGMT']
contracts = buildContracts(app, tickers)
marketMonitor(app, contracts)
time.sleep(5)
trd_obj = threading.Thread(target=tradeStrategy, args=(app,))
trd_obj.start()
if __name__ == "__main__":
main()
</code>
import ibapi
from ibapi.client import *
from ibapi.wrapper import *
from ibapi.contract import Contract
from ibapi.order import *
import ta
import numpy as np
import pandas as pd
import pytz
import math
from datetime import datetime, timedelta
import threading
import time
port = 7497
BAR_TRACKER = {}
ACCOUNT_INFO = {}
class ibapi(EClient, EWrapper):
def __init__(self):
EClient.__init__(self,self)
self.nexOrderId = 1
self.contract = (0, Contract())
#self.data = {}
def nextValidId(self, orderId: OrderId):
self.nextOrderId = orderId
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
self.contract = (reqId, contractDetails.contract)
def error(self, reqId, errorCode, errorString, advancedOrderReject = ''):
print(f'reqId: {reqId}, errorCode: {errorCode}, errorString:{errorString}, order reject: {advancedOrderReject}')
def historicalDataUpdate(self, reqId, bar):
if reqId not in BAR_TRACKER:
BAR_TRACKER[self.nextOrderId] = (self.contract, [])
BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def historicalData(self, reqId, bar):
# Store historical data
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume))
#def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, count):
# Store real-time data
#if reqId not in BAR_TRACKER:
#BAR_TRACKER[self.nextOrderId] = (self.contract, [])
#BAR_TRACKER[self.nextOrderId][1].append((time, open_, high, low, close, volume))
#def requestData(self, contract, isHistorical=True):
#if isHistorical:
#self.reqHistoricalData(self.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=False, chartOptions=[])
#else:
#self.reqRealTimeBars(self.nextOrderId, contract=contract, barSize=5, whatToShow="TRADES", useRTH=True, realTimeBarsOptions=[])
def updateAccountValue(self, key: str, val: str, currency: str, accountName: str):
if key == "CashBalance":
ACCOUNT_INFO[key] = float(val)
def updatePortfolio(self, contract: Contract, position: Decimal, marketPrice: float, marketValue: float, averageCost: float, unrealizedPNL: float, realizedPNL: float, accountName: str):
ACCOUNT_INFO[contract.localSymbol] = {"contract":contract,"position": float(position), "marketPrice": marketPrice, "marketValue": marketValue, "averageCost": averageCost}
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState):
print(f"openOrder. orderId: {orderId}, contract: {contract}, order: {order}")
def execDetails(self, reqId: int, contract: Contract, execution: Execution):
print(f"execDetails. reqId: {reqId}, contract: {contract}, execution: {execution}")
def buildContracts(app: ibapi, tickers: list):
reqId = 1
contracts = []
for symbol in tickers:
contract = Contract()
contract.symbol = symbol
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.currency = 'USD'
app.reqContractDetails(reqId, contract)
requested = True
while requested:
if app.contract[0] == reqId:
contracts.append(app.contract[1])
requested = False
reqId += 1
return contracts
def marketMonitor(app: ibapi, contracts: list):
for contract in contracts:
app.nextOrderId += 1
app.reqHistoricalData(app.nextOrderId, contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 min", whatToShow="TRADES", useRTH=1, formatDate=1, keepUpToDate=True, chartOptions=[])
#app.requestData(contract, isHistorical=True)
#app.requestData(contract, isHistorical=False)
def porfolioMonitor(app: ibapi):
app.reqAccountUpdates(True)
def tradeStrategy(app: ibapi):
for contract in BAR_TRACKER:
ohlcv = BAR_TRACKER[app.nextOrderId][1]
print(ohlcv)
order = Order()
order.orderType = 'MKT'
order.tif = 'GTC'
order.outsideRth = True
while True:
for contract in BAR_TRACKER:
ohlcv = ohlcv = BAR_TRACKER[app.nextOrderId][1] #key error thrown here
mycon = BAR_TRACKER[app.nextOrderId][0]
app.nextOrderId +=1
#trading logic
def main():
app = ibapi()
app.connect('127.0.0.1', port, 1001)
time.sleep(3)
app_obj = threading.Thread(target = app.run)
app_obj.start()
porfolioMonitor(app)
tickers = ['QUBT','SGMT']
contracts = buildContracts(app, tickers)
marketMonitor(app, contracts)
time.sleep(5)
trd_obj = threading.Thread(target=tradeStrategy, args=(app,))
trd_obj.start()
if __name__ == "__main__":
main()