简体   繁体   中英

Need help printing execution details when I manually place a trade using IBKR API (Interactive Brokers)

I am trying to print execution details when an order is filled. I got this working in code using the execDetails method, however it only prints the execution details when it's the bot that places a trade. I am trying to get it to print execution details when I manually place a trade on the TWS platform. Is this possible to achieve?

This is my code which works only when the bot places a trade:

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

import threading
import time


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

    def nextValidId(self, orderId: int):
        super().nextValidId(orderId)
        self.nextorderId = orderId
        print('The next valid order id is: ', self.nextorderId)

    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 run_loop():
    app.run()


# Function to create FX Order contract
def spy_order():
    contract = Contract()
    contract.symbol = "SPY"
    contract.secType = "STK"
    contract.currency = "USD"
    contract.exchange = "SMART"
    contract.primaryExchange = "ARCA"
    return contract


app = IBapi()
app.connect('127.0.0.1', 7497, 123)

app.nextorderId = None

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

# Check if the API is connected via orderid
while True:
    if isinstance(app.nextorderId, int):
        print('connected')
        print()
        break
    else:
        print('waiting for connection')
        time.sleep(1)

# Create order object
order = Order()
order.action = 'BUY'
order.totalQuantity = 1
order.orderType = 'MKT'

# Place order
app.placeOrder(app.nextorderId, spy_order(), order)
app.nextorderId += 1

Alright, I figured it out. To get it to talk back to you with manual orders, you need to go to your TWS API settings and set the Master API Client ID to 0, then match it with the connect clientID:

app.connect('127.0.0.1', 7497, 0)

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