Interactive Brokers Python API - 执行多笔交易

Interactive Brokers Python API - Executing multiple trades

我正在尝试为 Python API 创建一个程序,以便一次下多个 trades/market 订单。我使用在线教程获取了部分代码并进行了一些更改。但是,我无法一次下多个订单。我使用 2 个列表,1 个用于符号,另一个用于数量。 (例如:购买 3 支 Apple 股票)。我的代码只执行最后一个订单:“购买 3 支 CRM 股票”。 谁能帮我弄清楚如何下多个订单?

这是我的 Python 代码:

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

t = ['AAPL', 'CRM']

n = [2, 3]

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):
    for i in t:
        contract = Contract()
        contract.symbol = i
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"

    for j in n:
        order = Order()
        order.action = "BUY"
        order.totalQuantity = j
        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()

问题出在您的 for 循环上:

for j in n:
    order = Order()
    order.action = "BUY"
    order.totalQuantity = j
    order.orderType = "MKT"

self.placeOrder(self.nextOrderId, contract, order)

此代码创建 order n 次,然后向 IB 提交一个订单。如果要提交n个订单,需要在for循环内调用self.placeOrder

for j in n:
    order = Order()
    order.action = "BUY"
    order.totalQuantity = j
    order.orderType = "MKT"
    self.placeOrder(self.nextOrderId, contract, order)

确保在每次下单后递增 self.nextOrderId