Мульти-таймфреймовый MACD
Стратегия использует MACD на рабочем и более высоком таймфреймах. Сделки открываются, когда сигналы обоих таймфреймов совпадают по пересечению линий или пересечению нулевого уровня.
Детали
- Данные: ценовые свечи двух таймфреймов.
- Условия входа:
- Лонг: зависит от параметра
Entry. По умолчанию — бычье пересечение на обоих таймфреймах. - Шорт: противоположно лонгу.
- Лонг: зависит от параметра
- Условия выхода: противоположный сигнал или трейлинг-стоп.
- Стопы: опциональный трейлинг-стоп.
- Значения по умолчанию:
FastLength= 12SlowLength= 26SignalLength= 9CandleType= tf(5)HigherCandleType= tf(1d)ShowCurrentTimeframe= trueShowHigherTimeframe= trueEntry= CrossoverUseTrailingStop= falseTrailingStopPercent= 2
- Фильтры:
- Категория: Тренд
- Направление: Лонг и Шорт
- Индикаторы: MACD
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Мульти-таймфрейм (5m/1d)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// MACD crossover strategy with EMA trend filter.
/// </summary>
public class MultiTimeframeMacdStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _trendLength;
private readonly StrategyParam<DataType> _candleType;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int TrendLength { get => _trendLength.Value; set => _trendLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MultiTimeframeMacdStrategy()
{
_fastLength = Param(nameof(FastLength), 12)
.SetGreaterThanZero()
.SetDisplay("Fast", "Fast EMA", "MACD");
_slowLength = Param(nameof(SlowLength), 26)
.SetGreaterThanZero()
.SetDisplay("Slow", "Slow EMA", "MACD");
_trendLength = Param(nameof(TrendLength), 50)
.SetGreaterThanZero()
.SetDisplay("Trend", "Trend EMA period", "Trend");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastLength };
var slowEma = new ExponentialMovingAverage { Length = SlowLength };
var trendEma = new ExponentialMovingAverage { Length = TrendLength };
var prevFast = 0m;
var prevSlow = 0m;
var initialized = false;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, trendEma, (candle, fastVal, slowVal, trendVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!fastEma.IsFormed || !slowEma.IsFormed || !trendEma.IsFormed)
return;
if (!initialized)
{
prevFast = fastVal;
prevSlow = slowVal;
initialized = true;
return;
}
var macd = fastVal - slowVal;
var prevMacd = prevFast - prevSlow;
// MACD crosses zero up + price above trend => buy
if (prevMacd <= 0 && macd > 0 && candle.ClosePrice > trendVal && Position <= 0)
BuyMarket();
// MACD crosses zero down + price below trend => sell
else if (prevMacd >= 0 && macd < 0 && candle.ClosePrice < trendVal && Position > 0)
SellMarket();
prevFast = fastVal;
prevSlow = slowVal;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, trendEma);
DrawOwnTrades(area);
}
}
}
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 multi_timeframe_macd_strategy(Strategy):
def __init__(self):
super(multi_timeframe_macd_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetGreaterThanZero() \
.SetDisplay("Fast", "Fast EMA", "MACD")
self._slow_length = self.Param("SlowLength", 26) \
.SetGreaterThanZero() \
.SetDisplay("Slow", "Slow EMA", "MACD")
self._trend_length = self.Param("TrendLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("Trend", "Trend EMA period", "Trend")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
@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(multi_timeframe_macd_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
def OnStarted2(self, time):
super(multi_timeframe_macd_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_length.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_length.Value
self._trend_ema = ExponentialMovingAverage()
self._trend_ema.Length = self._trend_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self._trend_ema, self.OnProcess).Start()
def OnProcess(self, candle, fast_val, slow_val, trend_val):
if candle.State != CandleStates.Finished:
return
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed or not self._trend_ema.IsFormed:
return
fv = float(fast_val)
sv = float(slow_val)
tv = float(trend_val)
close = float(candle.ClosePrice)
if not self._initialized:
self._prev_fast = fv
self._prev_slow = sv
self._initialized = True
return
macd = fv - sv
prev_macd = self._prev_fast - self._prev_slow
if prev_macd <= 0.0 and macd > 0.0 and close > tv and self.Position <= 0:
self.BuyMarket()
elif prev_macd >= 0.0 and macd < 0.0 and close < tv and self.Position > 0:
self.SellMarket()
self._prev_fast = fv
self._prev_slow = sv
def CreateClone(self):
return multi_timeframe_macd_strategy()