Key error in TWS API for python while incrementing nextOrderId

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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()

New contributor

Dominic Buckley is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật