Moving Average Crossover 策略
当短期SMA向上穿越长期SMA时买入,向下穿越时卖出。出现反向信号时仓位反转。
详情
- 入场条件:
- 短期SMA上穿长期SMA时做多。
- 短期SMA下穿长期SMA时做空。
- 多空方向:双向。
- 出场条件:反向交叉时反转仓位。
- 止损:无。
- 默认值:
ShortLength= 9LongLength= 21CandleType= TimeSpan.FromMinutes(1)
- 过滤器:
- 分类:Crossover
- 方向:双向
- 指标:SMA
- 止损:无
- 复杂度:基础
- 时间框架:日内
- 季节性:无
- 神经网络:无
- 背离:无
- 风险等级:中等
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// EMA crossover strategy with signal cooldown.
/// </summary>
public class MovingAverageCrossoverStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _cooldownBars;
private ExponentialMovingAverage _fastEma;
private ExponentialMovingAverage _slowEma;
private decimal _prevFast;
private decimal _prevSlow;
private bool _initialized;
private int _barsSinceSignal;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
public MovingAverageCrossoverStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_fastLength = Param(nameof(FastLength), 72)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast EMA length", "Indicators");
_slowLength = Param(nameof(SlowLength), 89)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow EMA length", "Indicators");
_cooldownBars = Param(nameof(CooldownBars), 200)
.SetGreaterThanZero()
.SetDisplay("Cooldown Bars", "Minimum bars between signals", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fastEma = null;
_slowEma = null;
_prevFast = 0m;
_prevSlow = 0m;
_initialized = false;
_barsSinceSignal = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fastEma = new ExponentialMovingAverage { Length = FastLength };
_slowEma = new ExponentialMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(_fastEma, _slowEma, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastEma.IsFormed || !_slowEma.IsFormed)
return;
if (!_initialized)
{
_prevFast = fast;
_prevSlow = slow;
_initialized = true;
_barsSinceSignal = CooldownBars;
return;
}
_barsSinceSignal++;
if (_barsSinceSignal >= CooldownBars)
{
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
if (crossUp)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
else if (Position == 0)
BuyMarket();
_barsSinceSignal = 0;
}
else if (crossDown)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
else if (Position == 0)
SellMarket();
_barsSinceSignal = 0;
}
}
_prevFast = fast;
_prevSlow = slow;
}
}
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 moving_average_crossover_strategy(Strategy):
def __init__(self):
super(moving_average_crossover_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._fast_length = self.Param("FastLength", 72) \
.SetGreaterThanZero() \
.SetDisplay("Fast Length", "Fast EMA length", "Indicators")
self._slow_length = self.Param("SlowLength", 89) \
.SetGreaterThanZero() \
.SetDisplay("Slow Length", "Slow EMA length", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 200) \
.SetGreaterThanZero() \
.SetDisplay("Cooldown Bars", "Minimum bars between signals", "Risk")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._bars_since_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(moving_average_crossover_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._bars_since_signal = 0
def OnStarted2(self, time):
super(moving_average_crossover_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._bars_since_signal = 0
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_length.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self.OnProcess).Start()
def OnProcess(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
fv = float(fast)
sv = float(slow)
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed:
return
if not self._initialized:
self._prev_fast = fv
self._prev_slow = sv
self._initialized = True
self._bars_since_signal = self._cooldown_bars.Value
return
self._bars_since_signal += 1
if self._bars_since_signal >= self._cooldown_bars.Value:
cross_up = self._prev_fast <= self._prev_slow and fv > sv
cross_down = self._prev_fast >= self._prev_slow and fv < sv
if cross_up:
if self.Position <= 0:
self.BuyMarket()
self._bars_since_signal = 0
elif cross_down:
if self.Position >= 0:
self.SellMarket()
self._bars_since_signal = 0
self._prev_fast = fv
self._prev_slow = sv
def CreateClone(self):
return moving_average_crossover_strategy()