I am beginner to implement interactive brokers api in Python.Now, I am confusing about checking active order function from ibapi. I just want to get the current active order ID , but not all the historical order ID. Furthermore, it would be A one-cancels-the-other (OCO) order.However, My code list all the order ID
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import datetime
import threading
import time
import pandas
from ibapi.order import Order
import pandas as pd
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.data =[]# Initialize variable to store candle
self.order_df = pd.DataFrame(columns=[ 'OrderId', 'Symbol', 'Status'])
def historicalData(self, reqId, bar):
# print(f'DateTime: {bar.date} Open: {bar.open} High: {bar.high} Close: {bar.close} Low: {bar.low} Volume: {bar.volume}')
self.data.append([bar.date, bar.open,bar.high,bar.close,bar.low,bar.volume])
if len(self.data)==62:
self.data =[]# Initialize variable to store candle
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
self.nextorderId = orderId
print('The next valid order id is: ', self.nextorderId)
def start(self):
self.reqAllOpenOrders()
def openOrder(self, orderId, contract, order, orderState):
super().openOrder(orderId, contract, order, orderState)
print( " OrderId:", orderId,
"Symbol:", contract.symbol, "Status:", orderState.status)
dictionary = {"OrderId": orderId,
"Symbol": contract.symbol, "Status": orderState.status}
#if "Submitted" in dictionary :
#self.order_df = self.order_df.append(dictionary, ignore_index=True)
def run_loop():
app.run()
def marketOrder(direction,quantity):
order = Order()
order.action = direction
order.orderType = "MKT"
order.totalQuantity = quantity
return order
def limitOrder(direction,quantity,lt_price):
order = Order()
order.action = direction
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = lt_price
return order
def stopOrder(direction,quantity,st_price):
order = Order()
order.action = direction
order.orderType = "STP"
order.totalQuantity = quantity
order.auxPrice = st_price
return order
app = IBapi()
app.connect('127.0.0.1', 7497, 123)
# Start the socket in a thread
app.nextorderId = None
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
time.sleep(1) # Sleep interval to allow time for connection to server
# Create contract object
contract = Contract()
contract.symbol = 'DAX'
contract.secType = 'FUT'
contract.exchange = 'Eurex'
contract.currency = 'EUR'
contract.lastTradeDateOrContractMonth = '202312'
# Request historical candles
starttime = time.time()
timeout = time.time() + 60*60*6
#print(datetime.datetime.now().minute % 5)
# print(datetime.datetime.now().second)
while (time.time() <= timeout ):
if (datetime.datetime.now().minute % 1==0 )and (datetime.datetime.now().second<40):
app.reqHistoricalData(1, contract, '', '3000 S', '1 min', 'TRADES', 0, 1, False, [])
time.sleep(2) # sleep to allow enough time for data to be returned
# headers = ['DateTime', 'Open', 'High', 'Low', 'Close','Volume']
# print(dict(zip(headers, app.data)))
df_data = {}
df = pandas.DataFrame(app.data)
df.columns=['DateTime','Open','High','Close','Low','Volume']
# df['Datetime'] = df['DateTime'].dt.tz_localize('UTC')
# print (df['DateTime'] )
df1=MACD(df)
order_id=app.nextorderId
number=1
if ( number==1):
time.sleep(2)
# order_id=app.nextorderId
app.placeOrder(order_id,contract,marketOrder("BUY",1))
app.placeOrder(order_id+1,contract,stopOrder("Sell",1,df["Close"].iloc[-1]-10))
app.placeOrder(order_id+2,contract,limitOrder("Sell",1,df["Close"].iloc[-1]+20))
#print(time.localtime(time.time()))
time.sleep(60*1 - ((time.time() - starttime) % 60.0))
app.reqOpenOrders()
time.sleep(2)
order_list=app.order_df.OrderId.tolist()
stop_id=order_id+1
profit_id=order_id+2
print(stop_id)
print(profit_id)
print(order_list)
if str(int(stop_id)) in order_list:
app.cancelOrder(profit_id,"")
if str(int(profit_id)) in order_list:
app.cancelOrder(stop_id,"")
enter code here