简体   繁体   中英

Adding a Time Condition to an order in Interactive Broker's API

Good evening, I need big help and it will be greatly appreciated. I am trying to add a time condition to my order but I don't understand IBKR's API.

This is the sample code they provide:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *
from threading import Timer
from ibapi.order_condition import OrderCondition, Create

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId , errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    def nextValidId(self, orderId ):
        self.nextOrderId = orderId
        self.start()

    def orderStatus(self, orderId , status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice):
        print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ", filled, ", Remaining: ", remaining, ", LastFillPrice: ", lastFillPrice)

    def openOrder(self, orderId, contract, order, orderState):
        print("OpenOrder. ID:", orderId, contract.symbol, contract.secType, "@", contract.exchange, ":", order.action, order.orderType, order.totalQuantity, orderState.status)

    def execDetails(self, reqId, contract, execution):
        print("ExecDetails. ", reqId, contract.symbol, contract.secType, contract.currency, execution.execId,
              execution.orderId, execution.shares, execution.lastLiquidity)
    
  

    

    def start(self):
        
        
        contract = Contract()
        contract.symbol = "AAPL"
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"

        order = Order()
        order.action = "BUY"
        order.totalQuantity = 10
        order.orderType = "MKT"
        
    
        self.placeOrder(self.nextOrderId, contract, order)
        
        



    def stop(self):
        self.done = True
        self.disconnect()

def main():
    app = TestApp()
    app.nextOrderId = 0
    app.connect("127.0.0.1", 7497, 9)

    Timer(3, app.stop).start()
    app.run()

if __name__ == "__main__":
    main()

The documentation for Order Conditioning is found at:

https://interactivebrokers.github.io/tws-api/order_conditions.html

How do I plug the time condition in the above code. Let's say I am buying 100 stocks of AAPL on July 20th 2023 at 2:30pm? Any help would be greatly appreciated.

Here is a sample bit of code that will do what you want. If you pass an order to this function it will add a time based condition and return the order.

from ibapi.order_condition import OrderCondition, Create

def add_time_condition(order, start_datetime, orth=True):
    
    time_condition = Create(OrderCondition.Time)
    time_condition.time = datetime.strftime(start_datetime, '%Y%m%d %H:%M:%S')
    time_condition.isMore = True
    # isMore = True : specified time is the earliest acceptable time
    # isMore = False: specified time is the latest acceptable time
    time_condition.isConjunctionConnection = "AND"  # alternatively "OR"
    
    order.conditions.append(time_condition)
    order.conditionsIgnoreRth = orth

    return order

You can see that the basic idea is to create an OrderCondition.Time object, and populate it with the relevant parameters (time, isMore, and isConjunctionConnection if multiple conditions are being added).

You then append that Condition to the conditions parameter of the Order object. The conditions parameter of the Order object is just a list and you can append multiple Conditions to that list. If you are adding multiple Conditions you will need to set the isConjunctionConnection parameter of each Condition.

A separate parameter on the Order object is the conditionsIgnoreRth - this tells the API whether the condition(s) should operate in extended trading hours or just regular trading hours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM