TSI MACD Crossover Strategy
Implements a crossover system based on the True Strength Index (TSI) and its exponential moving average signal line.
The strategy subscribes to 4-hour candles by default and calculates the TSI using configurable short and long smoothing lengths. An additional EMA produces the signal line. A long position is opened when the TSI crosses above the signal line; a short position is opened when the TSI crosses below the signal line. Opposite positions are closed automatically on the reverse cross.
- Indicators: True Strength Index, Exponential Moving Average
- Parameters:
CandleType– candle series to process.LongLength– long smoothing period for TSI.ShortLength– short smoothing period for TSI.SignalLength– period of the EMA signal line.
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>
/// True Strength Index MACD crossover strategy.
/// Generates buy when TSI crosses above its signal line and sell on opposite cross.
/// </summary>
public class TsiMacdCrossoverStrategy : Strategy
{
private readonly StrategyParam<decimal> _minSpread;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevTsi;
private decimal _prevSignal;
private bool _initialized;
private int _cooldownRemaining;
/// <summary>
/// Minimum absolute spread between TSI and signal required for a valid crossover.
/// </summary>
public decimal MinSpread
{
get => _minSpread.Value;
set => _minSpread.Value = value;
}
/// <summary>
/// Number of completed candles to wait after a position change.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Candle type for processing.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public TsiMacdCrossoverStrategy()
{
_minSpread = Param(nameof(MinSpread), 2m)
.SetDisplay("Min Spread", "Minimum TSI-signal spread", "Signal");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetDisplay("Cooldown Bars", "Completed candles to wait after a signal", "Signal");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var tsi = new TrueStrengthIndex();
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(tsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, tsi);
DrawOwnTrades(area);
}
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevTsi = 0m;
_prevSignal = 0m;
_initialized = false;
_cooldownRemaining = 0;
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue tsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!tsiValue.IsFinal)
return;
var tv = (ITrueStrengthIndexValue)tsiValue;
if (tv.Tsi is not decimal tsi || tv.Signal is not decimal signal)
return;
if (!_initialized)
{
_prevTsi = tsi;
_prevSignal = signal;
_initialized = true;
return;
}
var crossUp = _prevTsi <= _prevSignal && tsi > signal;
var crossDown = _prevTsi >= _prevSignal && tsi < signal;
var spread = Math.Abs(tsi - signal);
if (_cooldownRemaining > 0)
_cooldownRemaining--;
if (crossUp && spread >= MinSpread && _cooldownRemaining == 0 && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_cooldownRemaining = CooldownBars;
}
else if (crossDown && spread >= MinSpread && _cooldownRemaining == 0 && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_cooldownRemaining = CooldownBars;
}
_prevTsi = tsi;
_prevSignal = signal;
}
}
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 TrueStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class tsi_macd_crossover_strategy(Strategy):
def __init__(self):
super(tsi_macd_crossover_strategy, self).__init__()
self._min_spread = self.Param("MinSpread", 2.0) \
.SetDisplay("Min Spread", "Minimum TSI-signal spread", "Signal")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Completed candles to wait after a signal", "Signal")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_tsi = 0.0
self._prev_signal = 0.0
self._initialized = False
self._cooldown_remaining = 0
@property
def min_spread(self):
return self._min_spread.Value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(tsi_macd_crossover_strategy, self).OnReseted()
self._prev_tsi = 0.0
self._prev_signal = 0.0
self._initialized = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(tsi_macd_crossover_strategy, self).OnStarted2(time)
tsi = TrueStrengthIndex()
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(tsi, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, tsi)
self.DrawOwnTrades(area)
def process_candle(self, candle, tsi_value):
if candle.State != CandleStates.Finished:
return
if not tsi_value.IsFinal:
return
tsi_val = tsi_value.Tsi
signal_val = tsi_value.Signal
if tsi_val is None or signal_val is None:
return
tsi_val = float(tsi_val)
signal_val = float(signal_val)
if not self._initialized:
self._prev_tsi = tsi_val
self._prev_signal = signal_val
self._initialized = True
return
cross_up = self._prev_tsi <= self._prev_signal and tsi_val > signal_val
cross_down = self._prev_tsi >= self._prev_signal and tsi_val < signal_val
spread = abs(tsi_val - signal_val)
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
min_spread = float(self.min_spread)
if cross_up and spread >= min_spread and self._cooldown_remaining == 0 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
elif cross_down and spread >= min_spread and self._cooldown_remaining == 0 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown_remaining = self.cooldown_bars
self._prev_tsi = tsi_val
self._prev_signal = signal_val
def CreateClone(self):
return tsi_macd_crossover_strategy()