Search code examples
pythonalgorithmic-tradinginteractive-brokers

IB Python API - Placing an Order


I would like to place an order using the native IB Python API.

The code I am using for this is the following:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *
from threading import Timer


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('Order Executed: ', reqId, contract.symbol, contract.secType, contract.currency, execution.execId,
              execution.orderId, execution.shares, execution.lastLiquidity)

    def start(self):
        contract = Contract()
        contract.symbol = "DAI"
        contract.secType = 'STK'
        contract.exchange = 'SMART'
        contract.currency = "EUR"
        contract.primaryExchange = "SMART"

        order = Order()
        order.action = "Buy"
        order.totalQuantity = 1 
        order.orderType =  "MKT"
        order.lmtPrice = 99

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

def  main():
    app = TestApp()
    app.nextOrderId = 1
    app.connect('127.0.0.1', 7497, 123)

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

if __name__ == "__main__":
    main()

The output I am getting is:

Error:  -1   2104   Market data farm connection is OK:usfarm.nj
Error:  -1   2104   Market data farm connection is OK:eufarm
Error:  -1   2106   HMDS data farm connection is OK:euhmds
Error:  -1   2106   HMDS data farm connection is OK:fundfarm
Error:  -1   2106   HMDS data farm connection is OK:ushmds
Error:  -1   2158   Sec-def data farm connection is OK:secdefeu

But no order is placed.

I have placed the ibapi-folder in my working directory and logged into my TWS paper trading account.

Why is no order being placed?


Solution

  • You don't place the order. https://interactivebrokers.github.io/tws-api/order_submission.html

    Add self.placeOrder(self.nextOrderId, contract, order) after making the order.

    Don't forget a nextOrderId += 1.