Ключевая ошибка в TWS API для Python при увеличении nextOrderIdPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ключевая ошибка в TWS API для Python при увеличении nextOrderId

Сообщение Anonymous »

Я пытаюсь торговать несколькими акциями одновременно, которые соответствуют одинаковым условиям торговли. Чтобы отслеживать данные, я сохраняю их в словаре, используя nextOrderId в качестве ключа, а детали контракта и данные бара — в качестве значений. При увеличении nextOrderId я получаю ключевую ошибку.
Кажется, что nextOrderId увеличивается нормально для акций, которые есть в моем списке, но затем он делает еще одно увеличение, чем мне нужно. Я думаю, именно это и вызывает ошибку. Я ожидал, что прирост произойдет только тогда, когда в списке появится акция. Я не знаю, как этого избежать.
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()


Подробнее здесь: https://stackoverflow.com/questions/792 ... extorderid
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»