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;
using StockSharp.Algo;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Stochastic + Williams %R reversal system ported from the MetaTrader expert "TheMasterMind".
/// </summary>
public class TheMasterMindReversalStrategy : Strategy
{
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<int> _stochasticPeriod;
private readonly StrategyParam<int> _kPeriod;
private readonly StrategyParam<int> _dPeriod;
private readonly StrategyParam<int> _williamsPeriod;
private readonly StrategyParam<decimal> _stochasticBuyThreshold;
private readonly StrategyParam<decimal> _stochasticSellThreshold;
private readonly StrategyParam<decimal> _williamsBuyLevel;
private readonly StrategyParam<decimal> _williamsSellLevel;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<bool> _useTrailingStop;
private readonly StrategyParam<decimal> _trailingStop;
private readonly StrategyParam<decimal> _trailingStep;
private readonly StrategyParam<DataType> _candleType;
private StochasticOscillator _stochastic = null!;
private WilliamsR _williams = null!;
/// <summary>
/// Trade volume in lots.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set => _tradeVolume.Value = value;
}
/// <summary>
/// Total period for the stochastic oscillator.
/// </summary>
public int StochasticPeriod
{
get => _stochasticPeriod.Value;
set => _stochasticPeriod.Value = value;
}
/// <summary>
/// %K smoothing period.
/// </summary>
public int KPeriod
{
get => _kPeriod.Value;
set => _kPeriod.Value = value;
}
/// <summary>
/// %D signal period.
/// </summary>
public int DPeriod
{
get => _dPeriod.Value;
set => _dPeriod.Value = value;
}
/// <summary>
/// Williams %R lookback length.
/// </summary>
public int WilliamsPeriod
{
get => _williamsPeriod.Value;
set => _williamsPeriod.Value = value;
}
/// <summary>
/// Stochastic signal threshold for longs.
/// </summary>
public decimal StochasticBuyThreshold
{
get => _stochasticBuyThreshold.Value;
set => _stochasticBuyThreshold.Value = value;
}
/// <summary>
/// Stochastic signal threshold for shorts.
/// </summary>
public decimal StochasticSellThreshold
{
get => _stochasticSellThreshold.Value;
set => _stochasticSellThreshold.Value = value;
}
/// <summary>
/// Williams %R oversold level.
/// </summary>
public decimal WilliamsBuyLevel
{
get => _williamsBuyLevel.Value;
set => _williamsBuyLevel.Value = value;
}
/// <summary>
/// Williams %R overbought level.
/// </summary>
public decimal WilliamsSellLevel
{
get => _williamsSellLevel.Value;
set => _williamsSellLevel.Value = value;
}
/// <summary>
/// Stop-loss distance in absolute price units.
/// </summary>
public decimal StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Take-profit distance in absolute price units.
/// </summary>
public decimal TakeProfit
{
get => _takeProfit.Value;
set => _takeProfit.Value = value;
}
/// <summary>
/// Enables trailing stop management.
/// </summary>
public bool UseTrailingStop
{
get => _useTrailingStop.Value;
set => _useTrailingStop.Value = value;
}
/// <summary>
/// Trailing stop distance in absolute price units.
/// </summary>
public decimal TrailingStop
{
get => _trailingStop.Value;
set => _trailingStop.Value = value;
}
/// <summary>
/// Trailing step distance in absolute price units.
/// </summary>
public decimal TrailingStep
{
get => _trailingStep.Value;
set => _trailingStep.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="TheMasterMindReversalStrategy"/> class.
/// </summary>
public TheMasterMindReversalStrategy()
{
_tradeVolume = Param(nameof(TradeVolume), 1m)
.SetGreaterThanZero()
.SetDisplay("Volume", "Base order size", "Trading")
.SetOptimize(0.5m, 5m, 0.5m);
_stochasticPeriod = Param(nameof(StochasticPeriod), 100)
.SetGreaterThanZero()
.SetDisplay("Stochastic Length", "Total lookback for stochastic", "Indicators")
.SetOptimize(50, 150, 10);
_kPeriod = Param(nameof(KPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("%K Smoothing", "Stochastic %K smoothing length", "Indicators")
.SetOptimize(1, 5, 1);
_dPeriod = Param(nameof(DPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("%D Signal", "Stochastic %D signal length", "Indicators")
.SetOptimize(1, 5, 1);
_williamsPeriod = Param(nameof(WilliamsPeriod), 100)
.SetGreaterThanZero()
.SetDisplay("Williams %R Length", "Lookback period for Williams %R", "Indicators")
.SetOptimize(50, 150, 10);
_stochasticBuyThreshold = Param(nameof(StochasticBuyThreshold), 3m)
.SetDisplay("Stoch Buy Threshold", "%D level required to buy", "Signals");
_stochasticSellThreshold = Param(nameof(StochasticSellThreshold), 97m)
.SetDisplay("Stoch Sell Threshold", "%D level required to sell", "Signals");
_williamsBuyLevel = Param(nameof(WilliamsBuyLevel), -99.5m)
.SetDisplay("Williams Buy Level", "Williams %R oversold level", "Signals");
_williamsSellLevel = Param(nameof(WilliamsSellLevel), -0.5m)
.SetDisplay("Williams Sell Level", "Williams %R overbought level", "Signals");
_stopLoss = Param(nameof(StopLoss), 0m)
.SetDisplay("Stop Loss", "Protective stop distance", "Risk");
_takeProfit = Param(nameof(TakeProfit), 0m)
.SetDisplay("Take Profit", "Target distance", "Risk");
_useTrailingStop = Param(nameof(UseTrailingStop), false)
.SetDisplay("Use Trailing", "Enable trailing stop management", "Risk");
_trailingStop = Param(nameof(TrailingStop), 0m)
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk");
_trailingStep = Param(nameof(TrailingStep), 0m)
.SetDisplay("Trailing Step", "Trailing step distance", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Primary candle series", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
Volume = TradeVolume;
_stochastic = new StochasticOscillator();
_stochastic.K.Length = StochasticPeriod;
_stochastic.D.Length = DPeriod;
_williams = new WilliamsR
{
Length = WilliamsPeriod
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_stochastic, _williams, ProcessSignals)
.Start();
// Note: BindEx passes all indicator values as IIndicatorValue
var takeProfit = TakeProfit > 0m ? new Unit(TakeProfit, UnitTypes.Absolute) : null;
var stopLoss = StopLoss > 0m ? new Unit(StopLoss, UnitTypes.Absolute) : null;
if (takeProfit != null || stopLoss != null)
{
StartProtection(
takeProfit: takeProfit,
stopLoss: stopLoss,
isStopTrailing: UseTrailingStop);
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _stochastic);
DrawIndicator(area, _williams);
DrawOwnTrades(area);
}
}
private void ProcessSignals(ICandleMessage candle, IIndicatorValue stochasticValue, IIndicatorValue williamsRawValue)
{
if (candle.State != CandleStates.Finished)
return;
var stochasticTyped = (StochasticOscillatorValue)stochasticValue;
if (stochasticTyped.D is not decimal signalValue)
return;
var williamsValue = williamsRawValue.IsEmpty ? (decimal?)null : williamsRawValue.ToDecimal();
if (williamsValue is null)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var buySignal = signalValue <= StochasticBuyThreshold && williamsValue.Value <= WilliamsBuyLevel;
var sellSignal = signalValue >= StochasticSellThreshold && williamsValue.Value >= WilliamsSellLevel;
if (buySignal)
{
LogInfo($"Buy setup detected. %D={signalValue:F2}, WilliamsR={williamsValue.Value:F2}");
if (Position < 0)
{
BuyMarket(Math.Abs(Position));
}
if (Position <= 0)
{
BuyMarket(Volume);
}
return;
}
if (sellSignal)
{
LogInfo($"Sell setup detected. %D={signalValue:F2}, WilliamsR={williamsValue.Value:F2}");
if (Position > 0)
{
SellMarket(Math.Abs(Position));
}
if (Position >= 0)
{
SellMarket(Volume);
}
}
}
}
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, UnitTypes, Unit
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import StochasticOscillator, WilliamsR
class the_master_mind_reversal_strategy(Strategy):
def __init__(self):
super(the_master_mind_reversal_strategy, self).__init__()
self._trade_volume = self.Param("TradeVolume", 1.0).SetDisplay("Volume", "Base order size", "Trading")
self._stochastic_period = self.Param("StochasticPeriod", 100).SetDisplay("Stochastic Length", "Total lookback for stochastic", "Indicators")
self._k_period = self.Param("KPeriod", 3).SetDisplay("%K Smoothing", "Stochastic %K smoothing length", "Indicators")
self._d_period = self.Param("DPeriod", 3).SetDisplay("%D Signal", "Stochastic %D signal length", "Indicators")
self._williams_period = self.Param("WilliamsPeriod", 100).SetDisplay("Williams %R Length", "Lookback period for Williams %R", "Indicators")
self._stochastic_buy_threshold = self.Param("StochasticBuyThreshold", 3.0).SetDisplay("Stoch Buy Threshold", "%D level required to buy", "Signals")
self._stochastic_sell_threshold = self.Param("StochasticSellThreshold", 97.0).SetDisplay("Stoch Sell Threshold", "%D level required to sell", "Signals")
self._williams_buy_level = self.Param("WilliamsBuyLevel", -99.5).SetDisplay("Williams Buy Level", "Williams %R oversold level", "Signals")
self._williams_sell_level = self.Param("WilliamsSellLevel", -0.5).SetDisplay("Williams Sell Level", "Williams %R overbought level", "Signals")
self._stop_loss = self.Param("StopLoss", 0.0).SetDisplay("Stop Loss", "Protective stop distance", "Risk")
self._take_profit = self.Param("TakeProfit", 0.0).SetDisplay("Take Profit", "Target distance", "Risk")
self._use_trailing_stop = self.Param("UseTrailingStop", False).SetDisplay("Use Trailing", "Enable trailing stop management", "Risk")
self._trailing_stop = self.Param("TrailingStop", 0.0).SetDisplay("Trailing Stop", "Trailing stop distance", "Risk")
self._trailing_step = self.Param("TrailingStep", 0.0).SetDisplay("Trailing Step", "Trailing step distance", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))).SetDisplay("Candle Type", "Primary candle series", "Trading")
self._stochastic = None
self._williams = None
@property
def TradeVolume(self): return self._trade_volume.Value
@property
def StochasticPeriod(self): return self._stochastic_period.Value
@property
def KPeriod(self): return self._k_period.Value
@property
def DPeriod(self): return self._d_period.Value
@property
def WilliamsPeriod(self): return self._williams_period.Value
@property
def StochasticBuyThreshold(self): return self._stochastic_buy_threshold.Value
@property
def StochasticSellThreshold(self): return self._stochastic_sell_threshold.Value
@property
def WilliamsBuyLevel(self): return self._williams_buy_level.Value
@property
def WilliamsSellLevel(self): return self._williams_sell_level.Value
@property
def StopLoss(self): return self._stop_loss.Value
@property
def TakeProfit(self): return self._take_profit.Value
@property
def UseTrailingStop(self): return self._use_trailing_stop.Value
@property
def TrailingStop(self): return self._trailing_stop.Value
@property
def TrailingStep(self): return self._trailing_step.Value
@property
def CandleType(self): return self._candle_type.Value
def OnStarted2(self, time):
super(the_master_mind_reversal_strategy, self).OnStarted2(time)
self.Volume = self.TradeVolume
self._stochastic = StochasticOscillator()
self._stochastic.K.Length = self.StochasticPeriod
self._stochastic.D.Length = self.DPeriod
self._williams = WilliamsR()
self._williams.Length = self.WilliamsPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(self._stochastic, self._williams, self.ProcessSignals).Start()
tp = float(self.TakeProfit)
sl = float(self.StopLoss)
tp_unit = Unit(tp, UnitTypes.Absolute) if tp > 0 else None
sl_unit = Unit(sl, UnitTypes.Absolute) if sl > 0 else None
if tp_unit is not None or sl_unit is not None:
self.StartProtection(takeProfit=tp_unit, stopLoss=sl_unit, isStopTrailing=self.UseTrailingStop)
def ProcessSignals(self, candle, stochastic_value, williams_raw_value):
if candle.State != CandleStates.Finished:
return
signal_value = stochastic_value.D
if signal_value is None:
return
signal_val = float(signal_value)
williams_value = None
if not williams_raw_value.IsEmpty:
williams_value = float(williams_raw_value)
if williams_value is None:
return
buy_threshold = float(self.StochasticBuyThreshold)
sell_threshold = float(self.StochasticSellThreshold)
williams_buy = float(self.WilliamsBuyLevel)
williams_sell = float(self.WilliamsSellLevel)
buy_signal = signal_val <= buy_threshold and williams_value <= williams_buy
sell_signal = signal_val >= sell_threshold and williams_value >= williams_sell
if buy_signal:
if self.Position < 0:
self.BuyMarket(abs(self.Position))
if self.Position <= 0:
self.BuyMarket(self.Volume)
return
if sell_signal:
if self.Position > 0:
self.SellMarket(abs(self.Position))
if self.Position >= 0:
self.SellMarket(self.Volume)
def CreateClone(self):
return the_master_mind_reversal_strategy()