用PineScript回测:EMA5触发的即时多空限价下单策略
PineScript 实时触发EMA5的多空策略实现
核心逻辑
- 牛市判定:EMA5上穿EMA20后,维持多头趋势
- 熊市判定:EMA5下穿EMA20后,维持空头趋势
- 买入信号:牛市中,价格实时回踩触及EMA5时,挂限价买入单(价格=EMA5)
- 做空信号:熊市中,价格实时反弹触及EMA5时,挂限价做空单(价格=EMA5)
- 触发时机:在价格触碰EMA5的当下立即执行订单,无需等待K线收盘
完整代码实现(Pine Script v5)
//@version=5 strategy("EMA5 实时多空策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, commission_type=strategy.commission.percent, commission_value=0.1) // 计算均线 ema5 = ta.ema(close, 5) ema20 = ta.ema(close, 20) // 定义牛熊趋势 bullish = ta.crossover(ema5, ema20) or (bullish[1] and ema5 > ema20) bearish = ta.crossunder(ema5, ema20) or (bearish[1] and ema5 < ema20) // 实时检测价格触碰EMA5的条件 touch_ema5_bull = bullish and ta.low <= ema5 and ta.low[1] > ema5 // 牛市中价格从上方回踩触及EMA5 touch_ema5_bear = bearish and ta.high >= ema5 and ta.high[1] < ema5 // 熊市中价格从下方反弹触及EMA5 // 下单逻辑:实时触发,使用限价单 if (barstate.isrealtime and touch_ema5_bull) strategy.entry("Long", strategy.long, limit=ema5) if (barstate.isrealtime and touch_ema5_bear) strategy.entry("Short", strategy.short, limit=ema5) // 绘制均线 plot(ema5, color=color.new(color.blue, 0), title="EMA5") plot(ema20, color=color.new(color.red, 0), title="EMA20")
关键细节说明
- 趋势延续逻辑:用
bullish[1]和bearish[1]维持趋势状态,避免仅靠单次交叉信号反复切换趋势 - 实时触发:通过
barstate.isrealtime确保订单在实时行情(含回测模拟实时场景)中触发 - 触碰判定:对比当前与前一根K线的高低价,判断价格首次触及EMA5,避免重复下单
- 限价单设置:
limit=ema5确保订单在价格到达EMA5价位时立即成交,符合实时触发需求
内容的提问来源于stack exchange,提问作者xxddoo
相关产品推荐
相关产品推荐

