StopOrder 和 LimitOrders 未使用 ib_insync

问题描述 投票:0回答:0

我正在使用盈透证券 TWS 桌面应用程序和 python 库 ib_insync 来处理模拟交易账户。我的目标是下达 GBP.USD 市价订单,头寸规模为 25k,下达获利了结限价订单和止损订单。止盈限价订单和止损订单的预定金额高于/低于平均成交价格。当我运行代码时,父订单(在本例中为长 25k GBP.USD)始终会通过,但 StopOrder 和 LimitOrder 不会显示在我的 IB TWS 桌面应用程序中。

这是我的代码:

from ib_insync import *

# Create a connection to the IB gateway or TWS
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1) # adjust these as needed

# Define the contract and order
contract = Forex('GBPUSD')
ib.qualifyContracts(contract)
order = MarketOrder('BUY', 25000)

# Submit the order
trade = ib.placeOrder(contract, order)
print("Order submitted.")
ib.sleep(30)
# Wait for the order to fill
while trade.orderStatus.status != 'Filled':
    ib.waitOnUpdate()
print(f"Order status: {trade.orderStatus.status}")

if trade.orderStatus.status == 'Filled':
    print("Order filled, placing child orders.")

    # Define the prices for the child orders
    stop_loss_price = trade.orderStatus.avgFillPrice - 0.00150
    profit_target_price = trade.orderStatus.avgFillPrice + 0.00200
    print(f"Stop loss price: {stop_loss_price}, Profit target price: {profit_target_price}")
    ib.sleep(30)
    # If the order is filled, place a stop loss order
    stop_loss_order = StopOrder('SELL', 25000, stop_loss_price)
    stop_loss_order.orderId = ib.client.getReqId() # get a new order id
    stop_loss_trade = ib.placeOrder(contract, stop_loss_order)
    ib.sleep(30)
    print(f"Stop loss order placed, status: {stop_loss_trade.orderStatus.status}")
    ib.sleep(30)
    # And place a profit taking order
    profit_taking_order = LimitOrder('SELL', 25000, profit_target_price)
    profit_taking_order.orderId = ib.client.getReqId() # get a new order id
    profit_taking_trade = ib.placeOrder(contract, profit_taking_order)
    ib.sleep(30)
    print(f"Profit taking order placed, status: {profit_taking_trade.orderStatus.status}")
    ib.sleep(30)
ib.disconnect()
#ib.run()

我尝试增加延迟,并在工作日晚上 7 点至晚上 10 点(东部标准时间)之间测试我的代码,因此市场是活跃的,波动不应该成为问题。我注意到有时当我关闭 IB TWS 桌面应用程序、重新打开它并重新运行我的代码时,所有订单都会通过(但并非总是如此)。同样,多头 25,000 GBPUSD 的母订单始终会执行,但是,如果 StopOrder 未执行,则 LimitOrder 也不会执行。在这种情况下,StopOrder 和 LimitOrder 的状态均为“PendingSubmit”。除了使用 ChatGPT 尝试解决问题之外,我还尝试浏览 ib_insync 和 IB API 文档,但这些来源都没有帮助我。

python trading algorithmic-trading interactive-brokers ib-insync
© www.soinside.com 2019 - 2024. All rights reserved.