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>
/// Conversion of the "MartingailExpert v1.0 Stochastic" MetaTrader expert advisor.
/// Implements stochastic based entries with martingale averaging and cluster take profits.
/// </summary>
public class MartingailExpertV10StochasticStrategy : Strategy
{
private readonly StrategyParam<decimal> _stepPoints;
private readonly StrategyParam<int> _stepMode;
private readonly StrategyParam<decimal> _profitFactorPoints;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<int> _kPeriod;
private readonly StrategyParam<int> _dPeriod;
private readonly StrategyParam<decimal> _zoneBuy;
private readonly StrategyParam<decimal> _zoneSell;
private readonly StrategyParam<DataType> _candleType;
private StochasticOscillator _stochastic;
private decimal _pointSize;
private decimal? _prevK;
private decimal? _prevD;
private decimal _buyLastPrice;
private decimal _buyLastVolume;
private decimal _buyTotalVolume;
private decimal _buyWeightedSum;
private int _buyOrderCount;
private decimal _buyTakeProfit;
private decimal _sellLastPrice;
private decimal _sellLastVolume;
private decimal _sellTotalVolume;
private decimal _sellWeightedSum;
private int _sellOrderCount;
private decimal _sellTakeProfit;
/// <summary>
/// Distance in points that price has to travel against the latest entry before adding.
/// </summary>
public decimal StepPoints
{
get => _stepPoints.Value;
set => _stepPoints.Value = value;
}
/// <summary>
/// Step mode: 0 - fixed, 1 - fixed plus extra points per filled order.
/// </summary>
public int StepMode
{
get => _stepMode.Value;
set => _stepMode.Value = value;
}
/// <summary>
/// Profit target in points applied to every open order.
/// </summary>
public decimal ProfitFactorPoints
{
get => _profitFactorPoints.Value;
set => _profitFactorPoints.Value = value;
}
/// <summary>
/// Martingale multiplier for the next averaging order.
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Stochastic %K lookback period.
/// </summary>
public int KPeriod
{
get => _kPeriod.Value;
set => _kPeriod.Value = value;
}
/// <summary>
/// Stochastic %D smoothing length.
/// </summary>
public int DPeriod
{
get => _dPeriod.Value;
set => _dPeriod.Value = value;
}
/// <summary>
/// Minimum stochastic level that confirms long setups.
/// </summary>
public decimal ZoneBuy
{
get => _zoneBuy.Value;
set => _zoneBuy.Value = value;
}
/// <summary>
/// Maximum stochastic level that confirms short setups.
/// </summary>
public decimal ZoneSell
{
get => _zoneSell.Value;
set => _zoneSell.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 <see cref="MartingailExpertV10StochasticStrategy"/>.
/// </summary>
public MartingailExpertV10StochasticStrategy()
{
_stepPoints = Param(nameof(StepPoints), 500m)
.SetGreaterThanZero()
.SetDisplay("Step", "Price step in points before averaging", "Martingale");
_stepMode = Param(nameof(StepMode), 0)
.SetDisplay("Step Mode", "0 - fixed step, 1 - step plus extra points per order", "Martingale");
_profitFactorPoints = Param(nameof(ProfitFactorPoints), 300m)
.SetGreaterThanZero()
.SetDisplay("Profit Factor", "Points multiplied by order count for take profit", "Martingale");
_multiplier = Param(nameof(Multiplier), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Multiplier", "Martingale multiplier for averaging", "Martingale");
_kPeriod = Param(nameof(KPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("%K Period", "Stochastic %K lookback", "Indicators");
_dPeriod = Param(nameof(DPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators");
_zoneBuy = Param(nameof(ZoneBuy), 50m)
.SetDisplay("Zone Buy", "%D lower bound to allow buys", "Indicators");
_zoneSell = Param(nameof(ZoneSell), 50m)
.SetDisplay("Zone Sell", "%D upper bound to allow sells", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(10).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for processing", "General");
Volume = 1;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_stochastic = null;
_pointSize = 0m;
_prevK = null;
_prevD = null;
ResetLongState();
ResetShortState();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
_pointSize = Security?.PriceStep ?? 1m;
if (_pointSize <= 0m) _pointSize = 1m;
_stochastic = new StochasticOscillator();
_stochastic.K.Length = KPeriod;
_stochastic.D.Length = DPeriod;
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_stochastic, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
var indArea = CreateChartArea();
if (indArea != null)
DrawIndicator(indArea, _stochastic);
}
base.OnStarted2(time);
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stochasticValue)
{
if (candle.State != CandleStates.Finished)
return;
if (stochasticValue is not StochasticOscillatorValue stoch)
return;
if (stoch.K is not decimal currentK || stoch.D is not decimal currentD)
return;
if (!_stochastic.IsFormed)
{
_prevK = currentK;
_prevD = currentD;
return;
}
var tradingAllowed = IsFormedAndOnlineAndAllowTrading();
ManageClusters(candle, tradingAllowed);
if (!tradingAllowed)
{
_prevK = currentK;
_prevD = currentD;
return;
}
// Entry logic: stochastic crossover in oversold/overbought zones
if (Position == 0m && _buyOrderCount == 0 && _sellOrderCount == 0
&& _prevK is decimal prevK && _prevD is decimal prevD)
{
if (prevK > prevD && prevD > ZoneBuy)
{
OpenLong(candle.ClosePrice);
}
else if (prevK < prevD && prevD < ZoneSell)
{
OpenShort(candle.ClosePrice);
}
}
_prevK = currentK;
_prevD = currentD;
}
private void ManageClusters(ICandleMessage candle, bool tradingAllowed)
{
if (Position > 0m && _buyOrderCount > 0)
{
HandleLongCluster(candle, tradingAllowed);
}
else if (Position < 0m && _sellOrderCount > 0)
{
HandleShortCluster(candle, tradingAllowed);
}
else if (Position == 0m)
{
if (_buyOrderCount > 0 || _sellOrderCount > 0)
{
ResetLongState();
ResetShortState();
}
}
}
private void HandleLongCluster(ICandleMessage candle, bool tradingAllowed)
{
if (!tradingAllowed || _pointSize <= 0m)
return;
// Check take profit first
if (_buyTakeProfit > 0m && candle.HighPrice >= _buyTakeProfit)
{
SellMarket(Math.Abs(Position));
ResetLongState();
return;
}
// Average down
var currentCount = Math.Max(1, _buyOrderCount);
var stepPts = StepMode == 0
? StepPoints
: StepPoints + Math.Max(0m, currentCount * 2m - 2m);
var addTrigger = _buyLastPrice - stepPts * _pointSize;
if (_buyLastVolume > 0m && candle.LowPrice <= addTrigger)
{
var nextVolume = Math.Max(1m, Math.Round(_buyLastVolume * Multiplier));
BuyMarket(nextVolume);
var executionPrice = candle.ClosePrice;
_buyLastVolume = nextVolume;
_buyLastPrice = executionPrice;
_buyTotalVolume += nextVolume;
_buyWeightedSum += executionPrice * nextVolume;
_buyOrderCount++;
RecalcLongTp();
}
}
private void HandleShortCluster(ICandleMessage candle, bool tradingAllowed)
{
if (!tradingAllowed || _pointSize <= 0m)
return;
// Check take profit first
if (_sellTakeProfit > 0m && candle.LowPrice <= _sellTakeProfit)
{
BuyMarket(Math.Abs(Position));
ResetShortState();
return;
}
// Average up
var currentCount = Math.Max(1, _sellOrderCount);
var stepPts = StepMode == 0
? StepPoints
: StepPoints + Math.Max(0m, currentCount * 2m - 2m);
var addTrigger = _sellLastPrice + stepPts * _pointSize;
if (_sellLastVolume > 0m && candle.HighPrice >= addTrigger)
{
var nextVolume = Math.Max(1m, Math.Round(_sellLastVolume * Multiplier));
SellMarket(nextVolume);
var executionPrice = candle.ClosePrice;
_sellLastVolume = nextVolume;
_sellLastPrice = executionPrice;
_sellTotalVolume += nextVolume;
_sellWeightedSum += executionPrice * nextVolume;
_sellOrderCount++;
RecalcShortTp();
}
}
private void OpenLong(decimal price)
{
BuyMarket(Volume);
_buyLastPrice = price;
_buyLastVolume = Volume;
_buyTotalVolume = Volume;
_buyWeightedSum = price * Volume;
_buyOrderCount = 1;
RecalcLongTp();
ResetShortState();
}
private void OpenShort(decimal price)
{
SellMarket(Volume);
_sellLastPrice = price;
_sellLastVolume = Volume;
_sellTotalVolume = Volume;
_sellWeightedSum = price * Volume;
_sellOrderCount = 1;
RecalcShortTp();
ResetLongState();
}
private void RecalcLongTp()
{
var avg = _buyTotalVolume > 0 ? _buyWeightedSum / _buyTotalVolume : _buyLastPrice;
_buyTakeProfit = avg + ProfitFactorPoints * _pointSize;
}
private void RecalcShortTp()
{
var avg = _sellTotalVolume > 0 ? _sellWeightedSum / _sellTotalVolume : _sellLastPrice;
_sellTakeProfit = avg - ProfitFactorPoints * _pointSize;
}
private void ResetLongState()
{
_buyLastPrice = 0m;
_buyLastVolume = 0m;
_buyTotalVolume = 0m;
_buyWeightedSum = 0m;
_buyOrderCount = 0;
_buyTakeProfit = 0m;
}
private void ResetShortState()
{
_sellLastPrice = 0m;
_sellLastVolume = 0m;
_sellTotalVolume = 0m;
_sellWeightedSum = 0m;
_sellOrderCount = 0;
_sellTakeProfit = 0m;
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import StochasticOscillator
class martingail_expert_v10_stochastic_strategy(Strategy):
def __init__(self):
super(martingail_expert_v10_stochastic_strategy, self).__init__()
self._step_points = self.Param("StepPoints", 500.0) \
.SetDisplay("Step", "Price step in points before averaging", "Martingale")
self._step_mode = self.Param("StepMode", 0) \
.SetDisplay("Step Mode", "0 - fixed step, 1 - step plus extra points per order", "Martingale")
self._profit_factor_points = self.Param("ProfitFactorPoints", 300.0) \
.SetDisplay("Profit Factor", "Points multiplied by order count for take profit", "Martingale")
self._multiplier = self.Param("Multiplier", 1.5) \
.SetDisplay("Multiplier", "Martingale multiplier for averaging", "Martingale")
self._k_period = self.Param("KPeriod", 14) \
.SetDisplay("%K Period", "Stochastic %K lookback", "Indicators")
self._d_period = self.Param("DPeriod", 3) \
.SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators")
self._zone_buy = self.Param("ZoneBuy", 50.0) \
.SetDisplay("Zone Buy", "%D lower bound to allow buys", "Indicators")
self._zone_sell = self.Param("ZoneSell", 50.0) \
.SetDisplay("Zone Sell", "%D upper bound to allow sells", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(10))) \
.SetDisplay("Candle Type", "Timeframe used for processing", "General")
self.Volume = 1
self._point_size = 0.0
self._prev_k = None
self._prev_d = None
self._buy_last_price = 0.0
self._buy_last_volume = 0.0
self._buy_total_volume = 0.0
self._buy_weighted_sum = 0.0
self._buy_order_count = 0
self._buy_take_profit = 0.0
self._sell_last_price = 0.0
self._sell_last_volume = 0.0
self._sell_total_volume = 0.0
self._sell_weighted_sum = 0.0
self._sell_order_count = 0
self._sell_take_profit = 0.0
@property
def StepPoints(self):
return self._step_points.Value
@property
def StepMode(self):
return self._step_mode.Value
@property
def ProfitFactorPoints(self):
return self._profit_factor_points.Value
@property
def Multiplier(self):
return self._multiplier.Value
@property
def KPeriod(self):
return self._k_period.Value
@property
def DPeriod(self):
return self._d_period.Value
@property
def ZoneBuy(self):
return self._zone_buy.Value
@property
def ZoneSell(self):
return self._zone_sell.Value
@property
def CandleType(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(martingail_expert_v10_stochastic_strategy, self).OnStarted2(time)
ps = self.Security.PriceStep if self.Security is not None else None
self._point_size = float(ps) if ps is not None else 1.0
if self._point_size <= 0:
self._point_size = 1.0
self._stochastic = StochasticOscillator()
self._stochastic.K.Length = self.KPeriod
self._stochastic.D.Length = self.DPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(self._stochastic, self.ProcessCandle).Start()
def ProcessCandle(self, candle, stochastic_value):
if candle.State != CandleStates.Finished:
return
k_val = stochastic_value.K
d_val = stochastic_value.D
if k_val is None or d_val is None:
return
current_k = float(k_val)
current_d = float(d_val)
if not self._stochastic.IsFormed:
self._prev_k = current_k
self._prev_d = current_d
return
trading_allowed = self.IsFormedAndOnlineAndAllowTrading()
self._manage_clusters(candle, trading_allowed)
if not trading_allowed:
self._prev_k = current_k
self._prev_d = current_d
return
if self.Position == 0 and self._buy_order_count == 0 and self._sell_order_count == 0:
if self._prev_k is not None and self._prev_d is not None:
if self._prev_k > self._prev_d and self._prev_d > float(self.ZoneBuy):
self._open_long(float(candle.ClosePrice))
elif self._prev_k < self._prev_d and self._prev_d < float(self.ZoneSell):
self._open_short(float(candle.ClosePrice))
self._prev_k = current_k
self._prev_d = current_d
def _manage_clusters(self, candle, trading_allowed):
if self.Position > 0 and self._buy_order_count > 0:
self._handle_long_cluster(candle, trading_allowed)
elif self.Position < 0 and self._sell_order_count > 0:
self._handle_short_cluster(candle, trading_allowed)
elif self.Position == 0:
if self._buy_order_count > 0 or self._sell_order_count > 0:
self._reset_long_state()
self._reset_short_state()
def _handle_long_cluster(self, candle, trading_allowed):
if not trading_allowed or self._point_size <= 0:
return
if self._buy_take_profit > 0 and float(candle.HighPrice) >= self._buy_take_profit:
self.SellMarket(abs(self.Position))
self._reset_long_state()
return
current_count = max(1, self._buy_order_count)
step_pts = float(self.StepPoints)
if self.StepMode != 0:
step_pts = step_pts + max(0.0, current_count * 2.0 - 2.0)
add_trigger = self._buy_last_price - step_pts * self._point_size
if self._buy_last_volume > 0 and float(candle.LowPrice) <= add_trigger:
next_volume = max(1.0, float(round(float(self._buy_last_volume) * float(self.Multiplier))))
self.BuyMarket(next_volume)
execution_price = float(candle.ClosePrice)
self._buy_last_volume = next_volume
self._buy_last_price = execution_price
self._buy_total_volume += next_volume
self._buy_weighted_sum += execution_price * next_volume
self._buy_order_count += 1
self._recalc_long_tp()
def _handle_short_cluster(self, candle, trading_allowed):
if not trading_allowed or self._point_size <= 0:
return
if self._sell_take_profit > 0 and float(candle.LowPrice) <= self._sell_take_profit:
self.BuyMarket(abs(self.Position))
self._reset_short_state()
return
current_count = max(1, self._sell_order_count)
step_pts = float(self.StepPoints)
if self.StepMode != 0:
step_pts = step_pts + max(0.0, current_count * 2.0 - 2.0)
add_trigger = self._sell_last_price + step_pts * self._point_size
if self._sell_last_volume > 0 and float(candle.HighPrice) >= add_trigger:
next_volume = max(1.0, float(round(float(self._sell_last_volume) * float(self.Multiplier))))
self.SellMarket(next_volume)
execution_price = float(candle.ClosePrice)
self._sell_last_volume = next_volume
self._sell_last_price = execution_price
self._sell_total_volume += next_volume
self._sell_weighted_sum += execution_price * next_volume
self._sell_order_count += 1
self._recalc_short_tp()
def _open_long(self, price):
vol = self.Volume
self.BuyMarket(vol)
self._buy_last_price = price
self._buy_last_volume = vol
self._buy_total_volume = vol
self._buy_weighted_sum = price * vol
self._buy_order_count = 1
self._recalc_long_tp()
self._reset_short_state()
def _open_short(self, price):
vol = self.Volume
self.SellMarket(vol)
self._sell_last_price = price
self._sell_last_volume = vol
self._sell_total_volume = vol
self._sell_weighted_sum = price * vol
self._sell_order_count = 1
self._recalc_short_tp()
self._reset_long_state()
def _recalc_long_tp(self):
avg = self._buy_weighted_sum / self._buy_total_volume if self._buy_total_volume > 0 else self._buy_last_price
self._buy_take_profit = avg + float(self.ProfitFactorPoints) * self._point_size
def _recalc_short_tp(self):
avg = self._sell_weighted_sum / self._sell_total_volume if self._sell_total_volume > 0 else self._sell_last_price
self._sell_take_profit = avg - float(self.ProfitFactorPoints) * self._point_size
def _reset_long_state(self):
self._buy_last_price = 0.0
self._buy_last_volume = 0.0
self._buy_total_volume = 0.0
self._buy_weighted_sum = 0.0
self._buy_order_count = 0
self._buy_take_profit = 0.0
def _reset_short_state(self):
self._sell_last_price = 0.0
self._sell_last_volume = 0.0
self._sell_total_volume = 0.0
self._sell_weighted_sum = 0.0
self._sell_order_count = 0
self._sell_take_profit = 0.0
def OnReseted(self):
super(martingail_expert_v10_stochastic_strategy, self).OnReseted()
self._point_size = 0.0
self._prev_k = None
self._prev_d = None
self._reset_long_state()
self._reset_short_state()
def CreateClone(self):
return martingail_expert_v10_stochastic_strategy()