You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中For-If循环未按预期工作,总买入数量计算异常

问题分析与解决:total_entered_qty_buy始终显示为单tranche数量的4倍

我在运行以下代码时遇到问题:total_entered_qty_buy始终显示为单个tranche数量的4倍(总tranche数为4),哪怕只执行了1、2或3个tranche,这影响了后续计算。调整变量位置和初始化逻辑后仍未解决,求指出循环处理中的错误。

total_tranches = 4
tranche_portfolio_value = initial_portfolio_value / total_tranches
buy_qty_tranches = [0, 0, 0, 0]
entry_price_buy = [0, 0, 0, 0]
position_profit = 0
entry_tranches = [False, False, False, False]

while True:
    try:
        time.sleep(2)
        total_entered_qty_buy = 0
        total_entered_qty_sell = 0
        # Request market data
        app.reqMktData(app.req_id, contract_buy, '', False, False, [])
        app.reqMktData(app.req_id + 1, contract_sell, '', False, False, [])
        time.sleep(0.5)

        # Cancel market data subscription
        app.cancelMktData(app.req_id)
        app.cancelMktData(app.req_id + 1)

        if all([app.bid_price1, app.ask_price1]):
            log_message(f"Updated Prices: {stock_to_buy} - Bid: {app.bid_price1}, Ask: {app.ask_price1}")
           
            for tranche in range(total_tranches):
                if not entry_tranches[tranche]:
                    if tranche == 0 or (tranche > 0 and position_profit > 500 * tranche):
                        entry_tranches[tranche] = True
                        entry_price_buy[tranche] = app.ask_price1
                        buy_qty_tranches[tranche] = round(tranche_portfolio_value / app.ask_price1)
                        app.handle_tiered_entry(stock_to_buy, contract_buy, 'BUY', tranche + 1, total_tranches, tranche_portfolio_value)

                # Only update the total quantities if a new tranche was entered
                if entry_tranches[tranche]:
                    total_entered_qty_buy += buy_qty_tranches[tranche]
                   

            
            # Log the total entered quantities for buy and sell
            log_message(f"Total Entered Quantity Buy: {total_entered_qty_buy}")

核心问题排查

1. 所有tranche被意外激活

代码中tranche的激活条件为:

if tranche == 0 or (tranche > 0 and position_profit > 500 * tranche):

如果position_profit被错误赋值(比如在handle_tiered_entry或其他未展示代码中被设为远大于1500的值),会触发所有4个tranche的激活条件,导致entry_tranches全为True。此时total_entered_qty_buy会累加4个tranche的数量,自然是单个的4倍。

  • 解决:检查position_profit的更新逻辑,确认其值是否符合实际利润计算,避免被错误赋值。

2. buy_qty_tranches数组被全局修改

如果有其他未展示代码修改了buy_qty_tranches的所有元素,即使tranche未被激活,buy_qty_tranches[tranche]也有非零值,会导致累加时计入所有4个元素。

  • 解决:确认只有当entry_tranches[tranche]被设为True时,才对buy_qty_tranches[tranche]赋值,排查其他可能修改该数组的代码。

3. 对total_entered_qty_buy的含义误解

当前代码中total_entered_qty_buy是所有已激活tranche的总数量,而非单次循环新增的数量。如果4个tranche都激活,总数量就是单个的4倍。若你需要的是单次新增数量,需单独记录。


代码优化建议

如果需要区分总数量和单次新增数量,可修改代码如下:

total_tranches = 4
tranche_portfolio_value = initial_portfolio_value / total_tranches
buy_qty_tranches = [0, 0, 0, 0]
entry_price_buy = [0, 0, 0, 0]
position_profit = 0
entry_tranches = [False, False, False, False]

while True:
    try:
        time.sleep(2)
        total_entered_qty_buy = 0
        new_entered_qty_buy = 0  # 记录本次循环新增的数量
        total_entered_qty_sell = 0
        # Request market data
        app.reqMktData(app.req_id, contract_buy, '', False, False, [])
        app.reqMktData(app.req_id + 1, contract_sell, '', False, False, [])
        time.sleep(0.5)

        # Cancel market data subscription
        app.cancelMktData(app.req_id)
        app.cancelMktData(app.req_id + 1)

        if all([app.bid_price1, app.ask_price1]):
            log_message(f"Updated Prices: {stock_to_buy} - Bid: {app.bid_price1}, Ask: {app.ask_price1}")
           
            for tranche in range(total_tranches):
                if not entry_tranches[tranche]:
                    if tranche == 0 or (tranche > 0 and position_profit > 500 * tranche):
                        entry_tranches[tranche] = True
                        entry_price_buy[tranche] = app.ask_price1
                        buy_qty_tranches[tranche] = round(tranche_portfolio_value / app.ask_price1)
                        app.handle_tiered_entry(stock_to_buy, contract_buy, 'BUY', tranche + 1, total_tranches, tranche_portfolio_value)
                        new_entered_qty_buy += buy_qty_tranches[tranche]  # 仅累加本次新增

            # 计算所有已激活tranche的总数量
            total_entered_qty_buy = sum(qty for qty in buy_qty_tranches if qty > 0)
            
            # Log the total entered quantities for buy and sell
            log_message(f"Total Entered Quantity Buy: {total_entered_qty_buy}")
            log_message(f"New Entered Quantity Buy (this cycle): {new_entered_qty_buy}")

内容的提问来源于stack exchange,提问作者Labeeb Nazim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:14:55