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

仓位最小手数赋值异常求助:qty_position未正确获取min_position值

问题分析

你的代码核心问题是:qty_position的更新逻辑只监听了deposit和leverage的变化,但完全忽略了min_position的核心依赖项——current_price的实时变动。

从日志能明显看出:当前计算的min_position是1357(基于最新价格),但qty_position停留在122,说明这个值是之前某个价格下的计算结果,之后价格发生了变化,但因为deposit和leverage没改动,你的更新逻辑根本没触发,导致qty_position没有同步最新的min_position。

修复方案

要解决这个问题,需要把current_price也纳入qty_position的更新条件中,或者直接让qty_position实时同步min_position(根据你的业务逻辑选择)。

方案1:实时同步最小手数(每次K线更新都刷新)

如果需要qty_position始终等于最新的min_position,可以直接简化代码,去掉不必要的全局变量判断:

// Get the current price of the instrument
entry = 21 // Number of entries into the position
current_price = float(close)
calculated_min_position = (deposit * leverage) / (current_price * entry)
min_position = math.floor(calculated_min_position)

// 直接实时同步最小手数
int qty_position = min_position

// Logging values for checking
log.info("Final value of qty_position: " + str.tostring(qty_position))
log.info("Calculated value of min_position: " + str.tostring(min_position))
log.info("Manual calculation: " + str.tostring(deposit * leverage / current_price / entry))

方案2:仅在关键参数变化时更新(deposit/leverage/price)

如果需要仅当核心参数变动时才更新qty_position,可以新增价格的历史变量监听:

// Get the current price of the instrument
entry = 21 // Number of entries into the position
current_price = float(close)
calculated_min_position = (deposit * leverage) / (current_price * entry)
min_position = math.floor(calculated_min_position)

// Global variables
var float prev_deposit = na
var int prev_leverage = na
var float prev_price = na
var int qty_position = na  

// Force initialization of qty_position on first call
if na(qty_position)
    qty_position := min_position
    prev_deposit := deposit
    prev_leverage := leverage
    prev_price := current_price

// Update qty_position when any key parameter changes
if deposit != prev_deposit or leverage != prev_leverage or current_price != prev_price
    qty_position := min_position
    prev_deposit := deposit
    prev_leverage := leverage
    prev_price := current_price

// Logging values for checking
log.info("Final value of qty_position: " + str.tostring(qty_position))
log.info("Calculated value of min_position: " + str.tostring(min_position))
log.info("Manual calculation: " + str.tostring(deposit * leverage / current_price / entry))
额外提示
  • 代码中用close作为当前价格,对应每根K线的收盘价;如果需要Tick级别的实时价格,可根据平台提供的变量替换(比如bid或ask)。
  • 可以给价格变化设置阈值(比如math.abs(current_price - prev_price) > 0.01),避免因微小价格波动频繁更新。

内容的提问来源于stack exchange,提问作者Сергей

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:23:11