交易脚本报错修复求助:'strategy'为nil及方法调用失败
交易脚本报错修复方案
错误原因
strategy变量未初始化:直接调用strategy:xxx但未获取平台提供的策略实例,导致nil错误。- 不存在
set_stop_loss方法:原代码调用的方法不符合平台策略API规范,全局设置止损止盈的方式错误。 - 指标重复创建:每次
OnCalculate都重新创建SMA、ATR,会引发性能问题和数据错误。 - 数组越界:
index=0时访问index-1超出数组范围,触发错误。 - 无效的流设置:
targetProfit是数值变量,不是指标对象,不能调用setStream方法。
修复后的代码
-- 全局变量声明,用于存储策略和指标实例 local strategy local fastMA local slowMA local atrIndicator function Init() -- 获取平台策略实例(适配Compilation Trading Station API) strategy = core.app:strategy() strategy:name("Ma stratégie") strategy:type(core.Both) -- 使用平台常量替代数字1,提高可读性 -- 在初始化阶段创建指标,避免重复创建 fastMA = core.indicators:create("SMA", source.close, 50) slowMA = core.indicators:create("SMA", source.close, 200) atrIndicator = core.indicators:create("ATR", source, 14) end function OnCalculate(index) -- 更新指标到当前K线数据 fastMA:update(index) slowMA:update(index) atrIndicator:update(index) -- 跳过前200根K线,确保slowMA有足够数据,同时避免index-1越界 if index < 200 then return end local atrValue = atrIndicator.DATA[index] -- 计算多单止盈价 local longTakeProfit = source.close[index] + (source.close[index] - (source.low[index] - atrValue)) * 2 -- 金叉(多单信号)和死叉(空单信号)判断 local buySignal = fastMA.DATA[index] > slowMA.DATA[index] and fastMA.DATA[index-1] <= slowMA.DATA[index-1] local sellSignal = fastMA.DATA[index] < slowMA.DATA[index] and fastMA.DATA[index-1] >= slowMA.DATA[index-1] if buySignal then local stopLoss = source.low[index] - atrValue -- 开多单 strategy:entry("Buy", strategy.Long, nil, source.close[index]) -- 设置多单止损 strategy:order_stop("Buy_SL", "Buy", stopLoss) -- 设置多单止盈 strategy:order_limit("Buy_TP", "Buy", longTakeProfit) elseif sellSignal then local stopLoss = source.high[index] + atrValue -- 计算空单止盈价(与止损幅度成2倍比例) local shortTakeProfit = source.close[index] - (stopLoss - source.close[index]) * 2 -- 开空单 strategy:entry("Sell", strategy.Short, nil, source.close[index]) -- 设置空单止损 strategy:order_stop("Sell_SL", "Sell", stopLoss) -- 设置空单止盈 strategy:order_limit("Sell_TP", "Sell", shortTakeProfit) end end
核心修复说明
- 策略实例初始化:通过
core.app:strategy()获取平台提供的策略对象,解决strategy为nil的问题。 - 指标预创建:将指标创建移至
Init函数,每次计算仅更新数据,避免重复创建导致的错误。 - 修正止损止盈调用:使用平台原生的
order_stop和order_limit方法为每个订单单独设置止损止盈,替换原错误的全局设置方法。 - 越界防护:跳过前200根K线(对应slowMA的周期),确保
index-1的访问有效。 - 修正止盈逻辑:空单止盈重新基于止损幅度计算,逻辑更自洽,避免依赖多单的计算结果。
内容的提问来源于stack exchange,提问作者Anass.89
相关产品推荐
相关产品推荐

