簡體   English   中英

盈透證券 Python API - 執行多筆交易

[英]Interactive Brokers Python API - Executing multiple trades

我正在嘗試為 Python API 創建一個程序,以便一次下多個交易/市場訂單。 我使用在線教程來獲取其中的一些代碼並進行了一些更改。 但是,我無法一次下多個訂單。 我正在使用 2 個列表 1 用於符號,另一個用於它們的數量。 (例如:購買 3 支蘋果股票)。 我的代碼只執行最后一個訂單:即“購買 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM