Ema612CrossoverStrategy
概述
- 将 MetaTrader 5 智能交易程序 "EMA 6.12 (barabashkakvn's edition)" 移植到 StockSharp 的高级 API。
- 使用一条快速和一条慢速的简单移动平均线(原脚本同样基于 MODE_SMA)交叉作为交易信号。
- 通过绝对价格单位定义的可选止盈与移动止损,使策略可以针对不同交易品种灵活调参。
交易逻辑
数据准备
- 策略订阅由
CandleType指定的 K 线(默认 15 分钟)。 - 计算两条 SMA:
FastPeriod为快速曲线的长度,SlowPeriod为慢速曲线的长度,并要求慢速周期大于快速周期。
入场条件
- 仅在每根 K 线收盘后评估信号。
- 当上一根 K 线上慢速 SMA 在快速 SMA 之上,而当前 K 线慢速 SMA 下穿快速 SMA 时判定为看多交叉。若持有空头则先平仓,再按
Volume开多头。 - 当上一根 K 线上慢速 SMA 在快速 SMA 之下,而当前 K 线慢速 SMA 上穿快速 SMA 时判定为看空交叉。若持有多头则先平仓,再按
Volume开空头。
出场条件
- 出现相反交叉信号时立即平掉当前仓位。
- 若
TakeProfitOffset大于 0,则在入场价格基础上计算固定止盈:多头目标价entry + TakeProfitOffset,空头目标价entry - TakeProfitOffset。 - 若
TrailingStopOffset大于 0,则启用移动止损。只有当浮动利润超过TrailingStopOffset + TrailingStepOffset后才开始上移/下移止损,使其与最新收盘价保持TrailingStopOffset的距离,并且新的止损价必须至少向盈利方向移动TrailingStepOffset。多头使用最低价触发止损,空头使用最高价触发。
参数
| 参数 | 默认值 | 说明 |
|---|---|---|
CandleType |
15 分钟时间框架 | 计算均线与生成信号所使用的 K 线类型。 |
FastPeriod |
6 | 快速 SMA 的周期,必须大于 0 且小于 SlowPeriod。 |
SlowPeriod |
54 | 慢速 SMA 的周期,必须大于 0 且大于 FastPeriod。 |
Volume |
1 | 新开仓时提交的交易量。 |
TakeProfitOffset |
0.001 | 以绝对价格单位定义的止盈距离,设置为 0 可关闭。 |
TrailingStopOffset |
0.005 | 移动止损与价格之间的绝对距离,设置为 0 可关闭。 |
TrailingStepOffset |
0.0005 | 每次调整移动止损所需的额外盈利幅度。 |
提示: 所有距离参数均使用绝对价格单位。请根据交易品种的最小报价单位进行换算,例如 EURUSD 的最小报价增量为 0.0001,则默认值约等于 10、50 和 5 个点。
实现细节
- 使用项目规范要求的
SubscribeCandles().Bind()高级管线搭建指标和回调。 - 若环境支持图表,将绘制两条 SMA 并标记交易。
- 使用字段保存入场价、当前移动止损和止盈,重现 MQL5 版本的状态管理。
- 在启动时强制检查
SlowPeriod > FastPeriod,避免错误的指标设置。
使用建议
- 根据市场特性优化时间框架与 SMA 周期(短周期适合日内,长周期适合波段)。
- 在运行前把点数或跳动值换算成绝对价格,以正确配置止盈和移动止损。
- 把
TrailingStopOffset设为 0 可以关闭移动止损,此时仅依靠反向交叉或可选止盈离场。
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// EMA 6/12 crossover strategy with trailing stop management.
/// </summary>
public class Ema612CrossoverStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<decimal> _takeProfitOffset;
private readonly StrategyParam<decimal> _trailingStopOffset;
private readonly StrategyParam<decimal> _trailingStepOffset;
private ExponentialMovingAverage _fastSma;
private ExponentialMovingAverage _slowSma;
private decimal? _prevFast;
private decimal? _prevSlow;
private decimal? _entryPrice;
private decimal? _stopPrice;
private decimal? _takeProfitPrice;
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Fast moving average period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow moving average period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Take profit distance in absolute price units.
/// </summary>
public decimal TakeProfitOffset
{
get => _takeProfitOffset.Value;
set => _takeProfitOffset.Value = value;
}
/// <summary>
/// Trailing stop distance in absolute price units.
/// </summary>
public decimal TrailingStopOffset
{
get => _trailingStopOffset.Value;
set => _trailingStopOffset.Value = value;
}
/// <summary>
/// Additional distance required to move the trailing stop.
/// </summary>
public decimal TrailingStepOffset
{
get => _trailingStepOffset.Value;
set => _trailingStepOffset.Value = value;
}
/// <summary>
/// Initializes <see cref="Ema612CrossoverStrategy"/>.
/// </summary>
public Ema612CrossoverStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Candle resolution", "General");
_fastPeriod = Param(nameof(FastPeriod), 6)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Fast SMA length", "Moving Averages");
_slowPeriod = Param(nameof(SlowPeriod), 54)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Slow SMA length", "Moving Averages");
_takeProfitOffset = Param(nameof(TakeProfitOffset), 0.001m)
.SetNotNegative()
.SetDisplay("Take Profit", "Target distance in price units", "Risk");
_trailingStopOffset = Param(nameof(TrailingStopOffset), 0.005m)
.SetNotNegative()
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk");
_trailingStepOffset = Param(nameof(TrailingStepOffset), 0.0005m)
.SetNotNegative()
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetPositionState();
_prevFast = null;
_prevSlow = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (SlowPeriod <= FastPeriod)
throw new InvalidOperationException("Slow period must be greater than fast period.");
_fastSma = new ExponentialMovingAverage { Length = FastPeriod };
_slowSma = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastSma, _slowSma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastSma);
DrawIndicator(area, _slowSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastSma.IsFormed || !_slowSma.IsFormed)
return;
var bullishCross = false;
var bearishCross = false;
if (_prevFast.HasValue && _prevSlow.HasValue)
{
// Detect crossovers using previous candle values.
bullishCross = _prevSlow > _prevFast && slow < fast;
bearishCross = _prevSlow < _prevFast && slow > fast;
}
HandleExistingPosition(candle, bullishCross, bearishCross);
if (Position == 0)
{
if (bullishCross)
{
// Slow MA crossed below the fast MA - go long.
EnterLong(candle);
}
else if (bearishCross)
{
// Slow MA crossed above the fast MA - go short.
EnterShort(candle);
}
}
_prevFast = fast;
_prevSlow = slow;
}
private void HandleExistingPosition(ICandleMessage candle, bool bullishCross, bool bearishCross)
{
if (Position > 0)
{
// Update trailing stop for the long position before evaluating exits.
UpdateLongTrailing(candle);
var exit = bearishCross;
if (!exit && _takeProfitPrice.HasValue && candle.HighPrice >= _takeProfitPrice.Value)
{
// Price reached the take profit objective.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
{
// Price retraced to the trailing stop.
exit = true;
}
if (exit)
{
SellMarket(Position);
ResetPositionState();
}
}
else if (Position < 0)
{
// Update trailing stop for the short position before evaluating exits.
UpdateShortTrailing(candle);
var exit = bullishCross;
if (!exit && _takeProfitPrice.HasValue && candle.LowPrice <= _takeProfitPrice.Value)
{
// Price reached the take profit objective for the short trade.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
{
// Price rallied back to the trailing stop level.
exit = true;
}
if (exit)
{
BuyMarket(Math.Abs(Position));
ResetPositionState();
}
}
}
private void EnterLong(ICandleMessage candle)
{
BuyMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice + TakeProfitOffset : null;
_stopPrice = null;
}
private void EnterShort(ICandleMessage candle)
{
SellMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice - TakeProfitOffset : null;
_stopPrice = null;
}
private void UpdateLongTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = candle.ClosePrice - _entryPrice.Value;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice - TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || candidate - _stopPrice.Value > minAdvance)
{
// Move stop loss closer only when price progressed enough.
_stopPrice = candidate;
}
}
private void UpdateShortTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = _entryPrice.Value - candle.ClosePrice;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice + TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || _stopPrice.Value - candidate > minAdvance)
{
// Move stop loss for the short only after sufficient favorable movement.
_stopPrice = candidate;
}
}
private void ResetPositionState()
{
_entryPrice = null;
_stopPrice = null;
_takeProfitPrice = null;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_612_crossover_strategy(Strategy):
"""
EMA 6/12 crossover strategy with trailing stop management.
Enters on EMA crossover, manages position with take profit and trailing stop.
"""
def __init__(self):
super(ema_612_crossover_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Candle resolution", "General")
self._fast_period = self.Param("FastPeriod", 6) \
.SetDisplay("Fast Period", "Fast EMA length", "Moving Averages")
self._slow_period = self.Param("SlowPeriod", 54) \
.SetDisplay("Slow Period", "Slow EMA length", "Moving Averages")
self._take_profit_offset = self.Param("TakeProfitOffset", 0.001) \
.SetDisplay("Take Profit", "Target distance in price units", "Risk")
self._trailing_stop_offset = self.Param("TrailingStopOffset", 0.005) \
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk")
self._trailing_step_offset = self.Param("TrailingStepOffset", 0.0005) \
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk")
self._prev_fast = None
self._prev_slow = None
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
self._fast_ema = None
self._slow_ema = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_612_crossover_strategy, self).OnReseted()
self._reset_position_state()
self._prev_fast = None
self._prev_slow = None
def OnStarted2(self, time):
super(ema_612_crossover_strategy, self).OnStarted2(time)
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_period.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._fast_ema)
self.DrawIndicator(area, self._slow_ema)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed:
return
fast_val = float(fast_val)
slow_val = float(slow_val)
bullish_cross = False
bearish_cross = False
if self._prev_fast is not None and self._prev_slow is not None:
bullish_cross = self._prev_slow > self._prev_fast and slow_val < fast_val
bearish_cross = self._prev_slow < self._prev_fast and slow_val > fast_val
self._handle_existing_position(candle, bullish_cross, bearish_cross)
if self.Position == 0:
if bullish_cross:
self._enter_long(candle)
elif bearish_cross:
self._enter_short(candle)
self._prev_fast = fast_val
self._prev_slow = slow_val
def _handle_existing_position(self, candle, bullish_cross, bearish_cross):
if self.Position > 0:
self._update_long_trailing(candle)
do_exit = bearish_cross
if not do_exit and self._take_profit_price is not None and float(candle.HighPrice) >= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
do_exit = True
if do_exit:
self.SellMarket()
self._reset_position_state()
elif self.Position < 0:
self._update_short_trailing(candle)
do_exit = bullish_cross
if not do_exit and self._take_profit_price is not None and float(candle.LowPrice) <= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
do_exit = True
if do_exit:
self.BuyMarket()
self._reset_position_state()
def _enter_long(self, candle):
self.BuyMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close + tp if tp > 0 else None
self._stop_price = None
def _enter_short(self, candle):
self.SellMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close - tp if tp > 0 else None
self._stop_price = None
def _update_long_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = close - self._entry_price
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close - trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or candidate - self._stop_price > min_advance:
self._stop_price = candidate
def _update_short_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = self._entry_price - close
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close + trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or self._stop_price - candidate > min_advance:
self._stop_price = candidate
def _reset_position_state(self):
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
def CreateClone(self):
return ema_612_crossover_strategy()