Tripple MACD Strategy
Combines four MACD calculations with an RSI filter. A long position opens when the averaged MACD histogram turns positive on a bullish candle and RSI is below 55. The trade closes on the opposite condition.
- Indicators: MACD, RSI
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>
/// Combines multiple EMA difference lines (simulating MACD histogram) with RSI filter.
/// Buys when averaged MACD histogram turns positive with RSI below threshold.
/// </summary>
public class TrippleMacdStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _takeProfitPercent;
private readonly StrategyParam<int> _fast1;
private readonly StrategyParam<int> _slow1;
private readonly StrategyParam<int> _fast2;
private readonly StrategyParam<int> _slow2;
private decimal _prevHist;
private decimal _prevRsi;
private int _cooldown;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
public decimal TakeProfitPercent { get => _takeProfitPercent.Value; set => _takeProfitPercent.Value = value; }
public int Fast1 { get => _fast1.Value; set => _fast1.Value = value; }
public int Slow1 { get => _slow1.Value; set => _slow1.Value = value; }
public int Fast2 { get => _fast2.Value; set => _fast2.Value = value; }
public int Slow2 { get => _slow2.Value; set => _slow2.Value = value; }
public TrippleMacdStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetDisplay("RSI Period", "RSI calculation length", "Indicators");
_takeProfitPercent = Param(nameof(TakeProfitPercent), 4m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_fast1 = Param(nameof(Fast1), 8).SetDisplay("Fast1", "Fast period 1", "Indicators");
_slow1 = Param(nameof(Slow1), 21).SetDisplay("Slow1", "Slow period 1", "Indicators");
_fast2 = Param(nameof(Fast2), 13).SetDisplay("Fast2", "Fast period 2", "Indicators");
_slow2 = Param(nameof(Slow2), 34).SetDisplay("Slow2", "Slow period 2", "Indicators");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_prevHist = 0;
_prevRsi = 0;
_cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var emaFast1 = new ExponentialMovingAverage { Length = Fast1 };
var emaSlow1 = new ExponentialMovingAverage { Length = Slow1 };
var emaFast2 = new ExponentialMovingAverage { Length = Fast2 };
var emaSlow2 = new ExponentialMovingAverage { Length = Slow2 };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(emaFast1, emaSlow1, emaFast2, emaSlow2, rsi, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, emaFast1);
DrawIndicator(area, emaSlow1);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal f1, decimal s1, decimal f2, decimal s2, decimal rsiVal)
{
if (candle.State != CandleStates.Finished)
return;
// Simulated MACD histograms
var macd1 = f1 - s1;
var macd2 = f2 - s2;
var hist = (macd1 + macd2) / 2m;
if (_prevHist == 0 || _prevRsi == 0)
{
_prevHist = hist;
_prevRsi = rsiVal;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevHist = hist;
_prevRsi = rsiVal;
return;
}
// histogram trend direction
var histUp = hist > 0m;
var histDown = hist < 0m;
// RSI cross 50
var rsiUp = _prevRsi <= 50m && rsiVal > 50m;
var rsiDown = _prevRsi >= 50m && rsiVal < 50m;
// Exit on opposite RSI cross
if (Position > 0 && rsiDown)
{
SellMarket();
_cooldown = 80;
}
else if (Position < 0 && rsiUp)
{
BuyMarket();
_cooldown = 80;
}
// Entry: RSI cross 50 + histogram confirms
if (Position == 0)
{
if (rsiUp && histUp)
{
BuyMarket();
_cooldown = 80;
}
else if (rsiDown && histDown)
{
SellMarket();
_cooldown = 80;
}
}
_prevRsi = rsiVal;
_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 ExponentialMovingAverage, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class tripple_macd_strategy(Strategy):
def __init__(self):
super(tripple_macd_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI calculation length", "Indicators")
self._take_profit_percent = self.Param("TakeProfitPercent", 4) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._prev_rsi = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def take_profit_percent(self):
return self._take_profit_percent.Value
def OnReseted(self):
super(tripple_macd_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(tripple_macd_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
ema_fast = ExponentialMovingAverage()
ema_fast.Length = 8
ema_slow = ExponentialMovingAverage()
ema_slow.Length = 21
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, ema_fast, ema_slow, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema_fast)
self.DrawIndicator(area, ema_slow)
self.DrawOwnTrades(area)
def on_process(self, candle, rsi_val, ema_fast, ema_slow):
if candle.State != CandleStates.Finished:
return
rsi_val = float(rsi_val)
ema_fast = float(ema_fast)
ema_slow = float(ema_slow)
if self._prev_rsi == 0 or self._prev_fast == 0 or self._prev_slow == 0:
self._prev_rsi = rsi_val
self._prev_fast = ema_fast
self._prev_slow = ema_slow
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_rsi = rsi_val
self._prev_fast = ema_fast
self._prev_slow = ema_slow
return
hist = ema_fast - ema_slow
hist_up = hist > 0
hist_down = hist < 0
rsi_cross_up = self._prev_rsi <= 50 and rsi_val > 50
rsi_cross_down = self._prev_rsi >= 50 and rsi_val < 50
if self.Position > 0 and rsi_cross_down:
self.SellMarket()
self._cooldown = 80
elif self.Position < 0 and rsi_cross_up:
self.BuyMarket()
self._cooldown = 80
if self.Position == 0:
if rsi_cross_up and hist_up:
self.BuyMarket()
self._cooldown = 80
elif rsi_cross_down and hist_down:
self.SellMarket()
self._cooldown = 80
self._prev_rsi = rsi_val
self._prev_fast = ema_fast
self._prev_slow = ema_slow
def CreateClone(self):
return tripple_macd_strategy()