Multi-Step Vegas SuperTrend Strategy
Combines a volatility-adjusted SuperTrend with a Vegas channel. Opens long when price is above the trend and short when below. Optional multi-step take profits close portions of the position at increasing targets.
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>
/// Vegas SuperTrend strategy using SMA and RSI for trend following.
/// </summary>
public class MultiStepVegasSuperTrendStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _smaLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<decimal> _entryRsiLevel;
private readonly StrategyParam<decimal> _exitRsiLevel;
private readonly StrategyParam<int> _signalCooldownBars;
private decimal? _prevClose;
private decimal? _prevSma;
private int _cooldownRemaining;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int SmaLength { get => _smaLength.Value; set => _smaLength.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public decimal EntryRsiLevel { get => _entryRsiLevel.Value; set => _entryRsiLevel.Value = value; }
public decimal ExitRsiLevel { get => _exitRsiLevel.Value; set => _exitRsiLevel.Value = value; }
public int SignalCooldownBars { get => _signalCooldownBars.Value; set => _signalCooldownBars.Value = value; }
public MultiStepVegasSuperTrendStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(2).TimeFrame())
.SetDisplay("Candle Type", "Timeframe", "Parameters");
_smaLength = Param(nameof(SmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("SMA Length", "SMA period", "Parameters");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Parameters");
_entryRsiLevel = Param(nameof(EntryRsiLevel), 55m)
.SetDisplay("Entry RSI", "RSI threshold for long entries", "Parameters");
_exitRsiLevel = Param(nameof(ExitRsiLevel), 45m)
.SetDisplay("Exit RSI", "RSI threshold for exits", "Parameters");
_signalCooldownBars = Param(nameof(SignalCooldownBars), 3)
.SetNotNegative()
.SetDisplay("Signal Cooldown Bars", "Closed candles to wait before a new entry", "Parameters");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = null;
_prevSma = null;
_cooldownRemaining = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = null;
_prevSma = null;
_cooldownRemaining = 0;
var sma = new SMA { Length = SmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, rsi, (candle, smaVal, rsiVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
if (!sma.IsFormed || !rsi.IsFormed || _prevClose is null || _prevSma is null)
{
_prevClose = candle.ClosePrice;
_prevSma = smaVal;
return;
}
var longEntry = _cooldownRemaining == 0 &&
_prevClose.Value <= _prevSma.Value &&
candle.ClosePrice > smaVal &&
rsiVal >= EntryRsiLevel &&
Position <= 0;
var longExit = Position > 0 &&
(candle.ClosePrice < smaVal || rsiVal <= ExitRsiLevel);
if (longExit)
{
SellMarket(Position);
_cooldownRemaining = SignalCooldownBars;
}
else if (longEntry)
{
BuyMarket(Volume + (Position < 0 ? -Position : 0m));
_cooldownRemaining = SignalCooldownBars;
}
_prevClose = candle.ClosePrice;
_prevSma = smaVal;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
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 SimpleMovingAverage, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class multi_step_vegas_super_trend_strategy(Strategy):
def __init__(self):
super(multi_step_vegas_super_trend_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(2))) \
.SetDisplay("Candle Type", "Timeframe", "Parameters")
self._sma_length = self.Param("SmaLength", 20) \
.SetGreaterThanZero() \
.SetDisplay("SMA Length", "SMA period", "Parameters")
self._rsi_length = self.Param("RsiLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("RSI Length", "RSI period", "Parameters")
self._entry_rsi_level = self.Param("EntryRsiLevel", 55.0) \
.SetDisplay("Entry RSI", "RSI threshold for long entries", "Parameters")
self._exit_rsi_level = self.Param("ExitRsiLevel", 45.0) \
.SetDisplay("Exit RSI", "RSI threshold for exits", "Parameters")
self._signal_cooldown_bars = self.Param("SignalCooldownBars", 3) \
.SetDisplay("Signal Cooldown Bars", "Closed candles to wait before a new entry", "Parameters")
self._prev_close = 0.0
self._prev_sma = 0.0
self._has_prev = False
self._cooldown_remaining = 0
@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_step_vegas_super_trend_strategy, self).OnReseted()
self._prev_close = 0.0
self._prev_sma = 0.0
self._has_prev = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(multi_step_vegas_super_trend_strategy, self).OnStarted2(time)
self._prev_close = 0.0
self._prev_sma = 0.0
self._has_prev = False
self._cooldown_remaining = 0
self._sma = SimpleMovingAverage()
self._sma.Length = self._sma_length.Value
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self._rsi_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._sma, self._rsi, self.OnProcess).Start()
def OnProcess(self, candle, sma_val, rsi_val):
if candle.State != CandleStates.Finished:
return
sv = float(sma_val)
rv = float(rsi_val)
close = float(candle.ClosePrice)
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
if not self._sma.IsFormed or not self._rsi.IsFormed or not self._has_prev:
self._prev_close = close
self._prev_sma = sv
self._has_prev = True
return
entry_rsi = float(self._entry_rsi_level.Value)
exit_rsi = float(self._exit_rsi_level.Value)
long_entry = self._cooldown_remaining == 0 and self._prev_close <= self._prev_sma and close > sv and rv >= entry_rsi and self.Position <= 0
long_exit = self.Position > 0 and (close < sv or rv <= exit_rsi)
if long_exit:
self.SellMarket()
self._cooldown_remaining = self._signal_cooldown_bars.Value
elif long_entry:
self.BuyMarket()
self._cooldown_remaining = self._signal_cooldown_bars.Value
self._prev_close = close
self._prev_sma = sv
def CreateClone(self):
return multi_step_vegas_super_trend_strategy()