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>
/// Two timeframe moving average crossover strategy.
/// </summary>
public class DiffTfMaStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<DataType> _higherCandleType;
private readonly StrategyParam<bool> _reverseSignals;
private SimpleMovingAverage _baseMa;
private SimpleMovingAverage _higherMa;
private decimal? _higherMaLast;
private decimal? _higherMaPrev;
private decimal? _baseMaLast;
private decimal? _baseMaPrev;
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public DataType HigherCandleType
{
get => _higherCandleType.Value;
set => _higherCandleType.Value = value;
}
public bool ReverseSignals
{
get => _reverseSignals.Value;
set => _reverseSignals.Value = value;
}
public DiffTfMaStrategy()
{
_maPeriod = Param(nameof(MaPeriod), 10)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Moving average length on the higher timeframe", "General")
.SetOptimize(5, 30, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Base Candle", "Trading timeframe", "General");
_higherCandleType = Param(nameof(HigherCandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Higher Candle", "Higher timeframe for confirmation", "General");
_reverseSignals = Param(nameof(ReverseSignals), false)
.SetDisplay("Reverse Signals", "Invert the crossover logic", "General");
Volume = 0.1m;
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, HigherCandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_higherMaLast = null;
_higherMaPrev = null;
_baseMaLast = null;
_baseMaPrev = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (CandleType.Arg is not TimeSpan baseSpan || baseSpan <= TimeSpan.Zero)
throw new InvalidOperationException("CandleType must contain a positive TimeSpan argument.");
if (HigherCandleType.Arg is not TimeSpan higherSpan || higherSpan <= TimeSpan.Zero)
throw new InvalidOperationException("HigherCandleType must contain a positive TimeSpan argument.");
var ratio = higherSpan.TotalMinutes / baseSpan.TotalMinutes;
var baseLength = Math.Max(1, (int)(MaPeriod * ratio));
_baseMa = new SimpleMovingAverage { Length = baseLength };
_higherMa = new SimpleMovingAverage { Length = MaPeriod };
var higherSubscription = SubscribeCandles(HigherCandleType);
higherSubscription.Bind(_higherMa, ProcessHigher).Start();
var baseSubscription = SubscribeCandles(CandleType);
baseSubscription.Bind(_baseMa, ProcessBase).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, baseSubscription);
DrawOwnTrades(area);
}
}
private void ProcessHigher(ICandleMessage candle, decimal higherMaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_higherMa.IsFormed)
return;
// Store the last two higher timeframe MA values for crossover comparison.
_higherMaPrev = _higherMaLast;
_higherMaLast = higherMaValue;
}
private void ProcessBase(ICandleMessage candle, decimal baseMaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_baseMa.IsFormed)
return;
// Track the last two base timeframe MA values.
_baseMaPrev = _baseMaLast;
_baseMaLast = baseMaValue;
if (_higherMaPrev is not decimal higherPrev || _higherMaLast is not decimal higherLast)
return;
if (_baseMaPrev is not decimal basePrev || _baseMaLast is not decimal baseLast)
return;
var crossUp = higherPrev < basePrev && higherLast > baseLast;
var crossDown = higherPrev > basePrev && higherLast < baseLast;
if (ReverseSignals)
(crossUp, crossDown) = (crossDown, crossUp);
// Execute orders according to the detected crossover direction.
if (crossUp && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
else if (crossDown && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class diff_tf_ma_strategy(Strategy):
def __init__(self):
super(diff_tf_ma_strategy, self).__init__()
self._ma_period = self.Param("MaPeriod", 10)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1)))
self._higher_candle_type = self.Param("HigherCandleType", DataType.TimeFrame(TimeSpan.FromHours(4)))
self._reverse_signals = self.Param("ReverseSignals", False)
self.Volume = 0.1
self._base_ma = None
self._higher_ma = None
self._higher_ma_last = None
self._higher_ma_prev = None
self._base_ma_last = None
self._base_ma_prev = None
@property
def MaPeriod(self):
return self._ma_period.Value
@property
def CandleType(self):
return self._candle_type.Value
@property
def HigherCandleType(self):
return self._higher_candle_type.Value
@property
def ReverseSignals(self):
return self._reverse_signals.Value
def OnStarted2(self, time):
super(diff_tf_ma_strategy, self).OnStarted2(time)
base_span = self.CandleType.Arg
higher_span = self.HigherCandleType.Arg
ratio = higher_span.TotalMinutes / base_span.TotalMinutes
base_length = max(1, int(self.MaPeriod * ratio))
self._base_ma = SimpleMovingAverage()
self._base_ma.Length = base_length
self._higher_ma = SimpleMovingAverage()
self._higher_ma.Length = self.MaPeriod
higher_sub = self.SubscribeCandles(self.HigherCandleType)
higher_sub.Bind(self._higher_ma, self._process_higher).Start()
base_sub = self.SubscribeCandles(self.CandleType)
base_sub.Bind(self._base_ma, self._process_base).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, base_sub)
self.DrawOwnTrades(area)
def _process_higher(self, candle, higher_ma_value):
if candle.State != CandleStates.Finished:
return
if not self._higher_ma.IsFormed:
return
self._higher_ma_prev = self._higher_ma_last
self._higher_ma_last = float(higher_ma_value)
def _process_base(self, candle, base_ma_value):
if candle.State != CandleStates.Finished:
return
if not self._base_ma.IsFormed:
return
self._base_ma_prev = self._base_ma_last
self._base_ma_last = float(base_ma_value)
if self._higher_ma_prev is None or self._higher_ma_last is None:
return
if self._base_ma_prev is None or self._base_ma_last is None:
return
cross_up = self._higher_ma_prev < self._base_ma_prev and self._higher_ma_last > self._base_ma_last
cross_down = self._higher_ma_prev > self._base_ma_prev and self._higher_ma_last < self._base_ma_last
if self.ReverseSignals:
cross_up, cross_down = cross_down, cross_up
pos = float(self.Position)
if cross_up and pos <= 0:
self.BuyMarket(float(self.Volume) + abs(pos))
elif cross_down and pos >= 0:
self.SellMarket(float(self.Volume) + abs(pos))
def OnReseted(self):
super(diff_tf_ma_strategy, self).OnReseted()
self._higher_ma_last = None
self._higher_ma_prev = None
self._base_ma_last = None
self._base_ma_prev = None
def CreateClone(self):
return diff_tf_ma_strategy()