Ergodic Ticks Volume OSMA 策略
概述
该策略是 MQL5 专家 "Exp_Ergodic_Ticks_Volume_OSMA" 在 StockSharp 平台上的改写。原始专家使用自定义指标来评估逐笔成交量动量,本版本使用 MACD 直方图来近似这个指标。
策略根据直方图的连续变化开仓或平仓:
- 连续两次上升触发做多,并关闭现有空头。
- 连续两次下降触发做空,并关闭现有多头。
在启动时调用 StartProtection() 以避免与现有仓位冲突。
参数
FastLength– MACD 快速 EMA 周期,默认 12。SlowLength– MACD 慢速 EMA 周期,默认 26。SignalLength– MACD 信号 EMA 周期,默认 9。CandleType– 使用的蜡烛周期,默认 8 小时。
交易逻辑
- 订阅所选
CandleType的蜡烛。 - 对每根完成的蜡烛计算 MACD 直方图。
- 直方图连续上升两次时,平空并买入。
- 直方图连续下降两次时,平多并卖出。
- 每当出现新蜡烛时重复上述步骤。
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>
/// Strategy based on MACD histogram as an approximation of the Ergodic Ticks Volume OSMA indicator.
/// </summary>
public class ErgodicTicksVolumeOsmaStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _signalLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevHist;
private decimal _prevPrevHist;
private int _candleCount;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int SignalLength { get => _signalLength.Value; set => _signalLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ErgodicTicksVolumeOsmaStrategy()
{
_fastLength = Param(nameof(FastLength), 12).SetDisplay("Fast EMA", "Fast EMA length", "Indicators");
_slowLength = Param(nameof(SlowLength), 26).SetDisplay("Slow EMA", "Slow EMA length", "Indicators");
_signalLength = Param(nameof(SignalLength), 9).SetDisplay("Signal EMA", "Signal EMA length", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame()).SetDisplay("Timeframe", "Timeframe", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevHist = default;
_prevPrevHist = default;
_candleCount = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var macd = new MovingAverageConvergenceDivergenceSignal(
new MovingAverageConvergenceDivergence
{
ShortMa = { Length = FastLength },
LongMa = { Length = SlowLength },
},
new ExponentialMovingAverage { Length = SignalLength }
);
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macd, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue value)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (value is not MovingAverageConvergenceDivergenceSignalValue macdTyped)
return;
if (macdTyped.Macd is not decimal macdVal || macdTyped.Signal is not decimal signalVal)
return;
var hist = macdVal - signalVal;
_candleCount++;
if (_candleCount <= 2)
{
_prevPrevHist = _prevHist;
_prevHist = hist;
return;
}
var rising = _prevHist >= _prevPrevHist && hist >= _prevHist;
var falling = _prevHist <= _prevPrevHist && hist <= _prevHist;
if (rising && Position <= 0)
{
BuyMarket();
}
else if (falling && Position >= 0)
{
SellMarket();
}
_prevPrevHist = _prevHist;
_prevHist = hist;
}
}
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 MovingAverageConvergenceDivergence, MovingAverageConvergenceDivergenceSignal, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ergodic_ticks_volume_osma_strategy(Strategy):
def __init__(self):
super(ergodic_ticks_volume_osma_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators")
self._slow_length = self.Param("SlowLength", 26) \
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators")
self._signal_length = self.Param("SignalLength", 9) \
.SetDisplay("Signal EMA", "Signal EMA length", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(8))) \
.SetDisplay("Timeframe", "Timeframe", "General")
self._prev_hist = 0.0
self._prev_prev_hist = 0.0
self._candle_count = 0
@property
def FastLength(self):
return self._fast_length.Value
@FastLength.setter
def FastLength(self, value):
self._fast_length.Value = value
@property
def SlowLength(self):
return self._slow_length.Value
@SlowLength.setter
def SlowLength(self, value):
self._slow_length.Value = value
@property
def SignalLength(self):
return self._signal_length.Value
@SignalLength.setter
def SignalLength(self, value):
self._signal_length.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(ergodic_ticks_volume_osma_strategy, self).OnStarted2(time)
inner_macd = MovingAverageConvergenceDivergence()
inner_macd.ShortMa.Length = self.FastLength
inner_macd.LongMa.Length = self.SlowLength
signal_ema = ExponentialMovingAverage()
signal_ema.Length = self.SignalLength
macd = MovingAverageConvergenceDivergenceSignal(inner_macd, signal_ema)
self.SubscribeCandles(self.CandleType) \
.BindEx(macd, self.ProcessCandle) \
.Start()
def ProcessCandle(self, candle, value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
macd_val = value.Macd
signal_val = value.Signal
if macd_val is None or signal_val is None:
return
hist = float(macd_val) - float(signal_val)
self._candle_count += 1
if self._candle_count <= 2:
self._prev_prev_hist = self._prev_hist
self._prev_hist = hist
return
rising = self._prev_hist >= self._prev_prev_hist and hist >= self._prev_hist
falling = self._prev_hist <= self._prev_prev_hist and hist <= self._prev_hist
if rising and self.Position <= 0:
self.BuyMarket()
elif falling and self.Position >= 0:
self.SellMarket()
self._prev_prev_hist = self._prev_hist
self._prev_hist = hist
def OnReseted(self):
super(ergodic_ticks_volume_osma_strategy, self).OnReseted()
self._prev_hist = 0.0
self._prev_prev_hist = 0.0
self._candle_count = 0
def CreateClone(self):
return ergodic_ticks_volume_osma_strategy()