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>
/// Larry Connors RSI-2 strategy with a 200-period SMA filter and optional stop management.
/// </summary>
public class LarryConnersRsi2Strategy : Strategy
{
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<int> _fastSmaPeriod;
private readonly StrategyParam<int> _slowSmaPeriod;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _rsiLongEntry;
private readonly StrategyParam<decimal> _rsiShortEntry;
private readonly StrategyParam<bool> _useStopLoss;
private readonly StrategyParam<decimal> _stopLossPips;
private readonly StrategyParam<bool> _useTakeProfit;
private readonly StrategyParam<decimal> _takeProfitPips;
private readonly StrategyParam<DataType> _candleType;
private decimal _pipSize;
private decimal? _longEntryPrice;
private decimal? _shortEntryPrice;
/// <summary>
/// Order volume for entries.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set
{
_tradeVolume.Value = value;
Volume = value;
}
}
/// <summary>
/// Fast SMA period used for timing exits.
/// </summary>
public int FastSmaPeriod
{
get => _fastSmaPeriod.Value;
set => _fastSmaPeriod.Value = value;
}
/// <summary>
/// Slow SMA period used as a trend filter.
/// </summary>
public int SlowSmaPeriod
{
get => _slowSmaPeriod.Value;
set => _slowSmaPeriod.Value = value;
}
/// <summary>
/// RSI lookback length.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// RSI threshold for long entries.
/// </summary>
public decimal RsiLongEntry
{
get => _rsiLongEntry.Value;
set => _rsiLongEntry.Value = value;
}
/// <summary>
/// RSI threshold for short entries.
/// </summary>
public decimal RsiShortEntry
{
get => _rsiShortEntry.Value;
set => _rsiShortEntry.Value = value;
}
/// <summary>
/// Enables stop-loss handling in price pips.
/// </summary>
public bool UseStopLoss
{
get => _useStopLoss.Value;
set => _useStopLoss.Value = value;
}
/// <summary>
/// Stop-loss size expressed in pips.
/// </summary>
public decimal StopLossPips
{
get => _stopLossPips.Value;
set => _stopLossPips.Value = value;
}
/// <summary>
/// Enables take-profit handling in price pips.
/// </summary>
public bool UseTakeProfit
{
get => _useTakeProfit.Value;
set => _useTakeProfit.Value = value;
}
/// <summary>
/// Take-profit size expressed in pips.
/// </summary>
public decimal TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
/// <summary>
/// Timeframe used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes <see cref="LarryConnersRsi2Strategy"/>.
/// </summary>
public LarryConnersRsi2Strategy()
{
_tradeVolume = Param(nameof(TradeVolume), 1m)
.SetGreaterThanZero()
.SetDisplay("Trade Volume", "Order volume", "Trading")
;
_fastSmaPeriod = Param(nameof(FastSmaPeriod), 5)
.SetGreaterThanZero()
.SetDisplay("Fast SMA Period", "Fast SMA length", "Indicators")
;
_slowSmaPeriod = Param(nameof(SlowSmaPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("Slow SMA Period", "Slow SMA length", "Indicators")
;
_rsiPeriod = Param(nameof(RsiPeriod), 2)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI lookback", "Indicators")
;
_rsiLongEntry = Param(nameof(RsiLongEntry), 6m)
.SetDisplay("RSI Long Entry", "RSI threshold for longs", "Signals")
;
_rsiShortEntry = Param(nameof(RsiShortEntry), 95m)
.SetDisplay("RSI Short Entry", "RSI threshold for shorts", "Signals")
;
_useStopLoss = Param(nameof(UseStopLoss), true)
.SetDisplay("Use Stop Loss", "Enable stop-loss management", "Risk");
_stopLossPips = Param(nameof(StopLossPips), 30m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss (pips)", "Stop-loss distance in pips", "Risk")
;
_useTakeProfit = Param(nameof(UseTakeProfit), true)
.SetDisplay("Use Take Profit", "Enable take-profit management", "Risk");
_takeProfitPips = Param(nameof(TakeProfitPips), 60m)
.SetGreaterThanZero()
.SetDisplay("Take Profit (pips)", "Take-profit distance in pips", "Risk")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
// Clear internal state between runs.
_pipSize = 0m;
_longEntryPrice = null;
_shortEntryPrice = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Use configured trade volume for default order size.
Volume = TradeVolume;
// Pre-compute pip size multiplier for risk management calculations.
var priceStep = Security?.PriceStep ?? 1m;
var decimals = Security?.Decimals ?? 0;
var pipMultiplier = decimals is 1 or 3 or 5 ? 10m : 1m;
_pipSize = priceStep * pipMultiplier;
if (_pipSize <= 0m)
_pipSize = priceStep;
// Prepare technical indicators.
var fastSma = new SMA { Length = FastSmaPeriod };
var slowSma = new SMA { Length = SlowSmaPeriod };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
// Subscribe to candles and bind indicators for combined processing.
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastSma, slowSma, rsi, ProcessCandle)
.Start();
// Build optional chart visuals to monitor the strategy.
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastSma);
DrawIndicator(area, slowSma);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fastSma, decimal slowSma, decimal rsi)
{
// Act only on fully formed candles to mimic MQL bar-close execution.
if (candle.State != CandleStates.Finished)
return;
// Manage open long position exits before generating new signals.
if (Position > 0)
{
if (UseStopLoss && _longEntryPrice.HasValue)
{
var stopPrice = _longEntryPrice.Value - StopLossPips * _pipSize;
if (candle.LowPrice <= stopPrice)
{
SellMarket();
ResetLongState();
return;
}
}
if (UseTakeProfit && _longEntryPrice.HasValue)
{
var targetPrice = _longEntryPrice.Value + TakeProfitPips * _pipSize;
if (candle.HighPrice >= targetPrice)
{
SellMarket();
ResetLongState();
return;
}
}
if (candle.ClosePrice > fastSma)
{
SellMarket();
ResetLongState();
return;
}
}
else if (Position < 0)
{
if (UseStopLoss && _shortEntryPrice.HasValue)
{
var stopPrice = _shortEntryPrice.Value + StopLossPips * _pipSize;
if (candle.HighPrice >= stopPrice)
{
BuyMarket();
ResetShortState();
return;
}
}
if (UseTakeProfit && _shortEntryPrice.HasValue)
{
var targetPrice = _shortEntryPrice.Value - TakeProfitPips * _pipSize;
if (candle.LowPrice <= targetPrice)
{
BuyMarket();
ResetShortState();
return;
}
}
if (candle.ClosePrice < fastSma)
{
BuyMarket();
ResetShortState();
return;
}
}
if (!IsFormedAndOnlineAndAllowTrading())
return;
// Generate new entries only when flat to match the MQL logic.
if (Position == 0)
{
var canGoLong = rsi < RsiLongEntry && candle.ClosePrice > slowSma;
if (canGoLong)
{
BuyMarket();
_longEntryPrice = candle.ClosePrice;
_shortEntryPrice = null;
return;
}
var canGoShort = rsi > RsiShortEntry && candle.ClosePrice < slowSma;
if (canGoShort)
{
SellMarket();
_shortEntryPrice = candle.ClosePrice;
_longEntryPrice = null;
}
}
}
private void ResetLongState()
{
// Drop long tracking data after an exit.
_longEntryPrice = null;
}
private void ResetShortState()
{
// Drop short tracking data after an exit.
_shortEntryPrice = null;
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import (
SimpleMovingAverage,
RelativeStrengthIndex,
)
class larry_conners_rsi2_strategy(Strategy):
"""Larry Connors RSI-2: mean-reversion with SMA trend filter and optional pip-based SL/TP."""
def __init__(self):
super(larry_conners_rsi2_strategy, self).__init__()
self._trade_volume = self.Param("TradeVolume", 1.0) \
.SetGreaterThanZero() \
.SetDisplay("Trade Volume", "Order volume", "Trading")
self._fast_sma_period = self.Param("FastSmaPeriod", 5) \
.SetGreaterThanZero() \
.SetDisplay("Fast SMA Period", "Fast SMA length", "Indicators")
self._slow_sma_period = self.Param("SlowSmaPeriod", 50) \
.SetGreaterThanZero() \
.SetDisplay("Slow SMA Period", "Slow SMA length", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 2) \
.SetGreaterThanZero() \
.SetDisplay("RSI Period", "RSI lookback", "Indicators")
self._rsi_long_entry = self.Param("RsiLongEntry", 6.0) \
.SetDisplay("RSI Long Entry", "RSI threshold for longs", "Signals")
self._rsi_short_entry = self.Param("RsiShortEntry", 95.0) \
.SetDisplay("RSI Short Entry", "RSI threshold for shorts", "Signals")
self._use_stop_loss = self.Param("UseStopLoss", True) \
.SetDisplay("Use Stop Loss", "Enable stop-loss management", "Risk")
self._stop_loss_pips = self.Param("StopLossPips", 30.0) \
.SetGreaterThanZero() \
.SetDisplay("Stop Loss (pips)", "Stop-loss distance in pips", "Risk")
self._use_take_profit = self.Param("UseTakeProfit", True) \
.SetDisplay("Use Take Profit", "Enable take-profit management", "Risk")
self._take_profit_pips = self.Param("TakeProfitPips", 60.0) \
.SetGreaterThanZero() \
.SetDisplay("Take Profit (pips)", "Take-profit distance in pips", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for candles", "General")
self._pip_size = 0.0
self._long_entry_price = None
self._short_entry_price = None
@property
def TradeVolume(self):
return float(self._trade_volume.Value)
@property
def FastSmaPeriod(self):
return int(self._fast_sma_period.Value)
@property
def SlowSmaPeriod(self):
return int(self._slow_sma_period.Value)
@property
def RsiPeriod(self):
return int(self._rsi_period.Value)
@property
def RsiLongEntry(self):
return float(self._rsi_long_entry.Value)
@property
def RsiShortEntry(self):
return float(self._rsi_short_entry.Value)
@property
def UseStopLoss(self):
return self._use_stop_loss.Value
@property
def StopLossPips(self):
return float(self._stop_loss_pips.Value)
@property
def UseTakeProfit(self):
return self._use_take_profit.Value
@property
def TakeProfitPips(self):
return float(self._take_profit_pips.Value)
@property
def CandleType(self):
return self._candle_type.Value
def _calc_pip_size(self):
sec = self.Security
if sec is None or sec.PriceStep is None:
return 1.0
step = float(sec.PriceStep)
if step <= 0:
return 1.0
decimals = 0
if sec.Decimals is not None:
decimals = int(sec.Decimals)
pip_multiplier = 10.0 if decimals in (1, 3, 5) else 1.0
result = step * pip_multiplier
if result <= 0:
result = step
return result
def OnStarted2(self, time):
super(larry_conners_rsi2_strategy, self).OnStarted2(time)
self._pip_size = self._calc_pip_size()
self._long_entry_price = None
self._short_entry_price = None
fast_sma = SimpleMovingAverage()
fast_sma.Length = self.FastSmaPeriod
slow_sma = SimpleMovingAverage()
slow_sma.Length = self.SlowSmaPeriod
rsi = RelativeStrengthIndex()
rsi.Length = self.RsiPeriod
self._fast_sma_ind = fast_sma
self._slow_sma_ind = slow_sma
self._rsi_ind = rsi
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast_sma, slow_sma, rsi, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_sma)
self.DrawIndicator(area, slow_sma)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def process_candle(self, candle, fast_sma, slow_sma, rsi):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
h = float(candle.HighPrice)
lo = float(candle.LowPrice)
fast_sma_val = float(fast_sma)
slow_sma_val = float(slow_sma)
rsi_val = float(rsi)
# Manage open long position exits
if self.Position > 0:
if self.UseStopLoss and self._long_entry_price is not None:
stop_price = self._long_entry_price - self.StopLossPips * self._pip_size
if lo <= stop_price:
self.SellMarket()
self._long_entry_price = None
return
if self.UseTakeProfit and self._long_entry_price is not None:
target_price = self._long_entry_price + self.TakeProfitPips * self._pip_size
if h >= target_price:
self.SellMarket()
self._long_entry_price = None
return
if close > fast_sma_val:
self.SellMarket()
self._long_entry_price = None
return
elif self.Position < 0:
if self.UseStopLoss and self._short_entry_price is not None:
stop_price = self._short_entry_price + self.StopLossPips * self._pip_size
if h >= stop_price:
self.BuyMarket()
self._short_entry_price = None
return
if self.UseTakeProfit and self._short_entry_price is not None:
target_price = self._short_entry_price - self.TakeProfitPips * self._pip_size
if lo <= target_price:
self.BuyMarket()
self._short_entry_price = None
return
if close < fast_sma_val:
self.BuyMarket()
self._short_entry_price = None
return
# New entries only when flat
if self.Position == 0:
can_go_long = rsi_val < self.RsiLongEntry and close > slow_sma_val
if can_go_long:
self.BuyMarket()
self._long_entry_price = close
self._short_entry_price = None
return
can_go_short = rsi_val > self.RsiShortEntry and close < slow_sma_val
if can_go_short:
self.SellMarket()
self._short_entry_price = close
self._long_entry_price = None
def OnReseted(self):
super(larry_conners_rsi2_strategy, self).OnReseted()
self._pip_size = 0.0
self._long_entry_price = None
self._short_entry_price = None
def CreateClone(self):
return larry_conners_rsi2_strategy()