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>
/// OsMA histogram pattern strategy converted from the "OsMaSter v0" MQL expert.
/// Enters on four-bar momentum reversals identified by the MACD histogram.
/// </summary>
public class OsMaSterV0Strategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _signalPeriod;
private readonly StrategyParam<int> _stopLossPips;
private readonly StrategyParam<int> _takeProfitPips;
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<DataType> _candleType;
private decimal? _histCurrent;
private decimal? _histPrev1;
private decimal? _histPrev2;
private decimal? _histPrev3;
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public OsMaSterV0Strategy()
{
_fastPeriod = Param(nameof(FastPeriod), 9)
.SetDisplay("Fast EMA", "Fast EMA period for MACD histogram", "Indicators")
.SetGreaterThanZero();
_slowPeriod = Param(nameof(SlowPeriod), 26)
.SetDisplay("Slow EMA", "Slow EMA period for MACD histogram", "Indicators")
.SetGreaterThanZero();
_signalPeriod = Param(nameof(SignalPeriod), 5)
.SetDisplay("Signal Smoothing", "Signal moving average period", "Indicators")
.SetGreaterThanZero();
_stopLossPips = Param(nameof(StopLossPips), 500)
.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk");
_takeProfitPips = Param(nameof(TakeProfitPips), 1000)
.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk");
_tradeVolume = Param(nameof(TradeVolume), 1m)
.SetDisplay("Trade Volume", "Order volume in lots", "Trading")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles for calculations", "General");
Volume = TradeVolume;
}
/// <summary>
/// Fast EMA period used in MACD histogram calculation.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period used in MACD histogram calculation.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Signal moving average period.
/// </summary>
public int SignalPeriod
{
get => _signalPeriod.Value;
set => _signalPeriod.Value = value;
}
/// <summary>
/// Stop loss size expressed in pips.
/// </summary>
public int StopLossPips
{
get => _stopLossPips.Value;
set => _stopLossPips.Value = value;
}
/// <summary>
/// Take profit size expressed in pips.
/// </summary>
public int TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
/// <summary>
/// Trading volume used for market orders.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set
{
_tradeVolume.Value = value;
Volume = value;
}
}
/// <summary>
/// Candle type used for indicator calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_histCurrent = null;
_histPrev1 = null;
_histPrev2 = null;
_histPrev3 = null;
Volume = TradeVolume;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
Volume = TradeVolume;
var macd = new MovingAverageConvergenceDivergenceHistogram
{
Macd =
{
ShortMa = { Length = FastPeriod },
LongMa = { Length = SlowPeriod }
},
SignalMa = { Length = SignalPeriod }
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macd, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, macd);
DrawOwnTrades(area);
}
var step = Security?.PriceStep ?? 1m;
var decimals = Security?.Decimals ?? 0;
var pipSize = (decimals == 3 || decimals == 5) ? step * 10m : step;
// Convert pip-based risk controls into absolute price offsets.
StartProtection(
takeProfit: TakeProfitPips > 0 ? new Unit(TakeProfitPips * pipSize, UnitTypes.Absolute) : null,
stopLoss: StopLossPips > 0 ? new Unit(StopLossPips * pipSize, UnitTypes.Absolute) : null);
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
{
// Ignore incomplete candles because signals rely on closed data.
if (candle.State != CandleStates.Finished)
return;
// Ensure the strategy is synchronized with the market and permitted to trade.
if (!macdValue.IsFormed)
return;
var macdTyped = (MovingAverageConvergenceDivergenceHistogramValue)macdValue;
if (macdTyped.Macd is not decimal histogram)
return;
// Shift stored histogram values to maintain the last four observations.
_histPrev3 = _histPrev2;
_histPrev2 = _histPrev1;
_histPrev1 = _histCurrent;
_histCurrent = histogram;
if (_histCurrent is not decimal hist0 ||
_histPrev1 is not decimal hist1 ||
_histPrev2 is not decimal hist2 ||
_histPrev3 is not decimal hist3)
{
return;
}
// Detect the specific four-bar rising pattern used for long entries.
var bullishPattern = hist3 > hist2 && hist2 < hist1 && hist1 < hist0;
// Detect the mirrored falling pattern used for short entries.
var bearishPattern = hist3 < hist2 && hist2 > hist1 && hist1 > hist0;
// The original expert opens a position only when no trades are active.
if (Position != 0)
return;
if (bullishPattern)
{
// Enter long when the histogram forms a higher-low sequence.
BuyMarket();
}
else if (bearishPattern)
{
// Enter short when the histogram forms a lower-high sequence.
SellMarket();
}
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import (
MovingAverageConvergenceDivergenceHistogram,
MovingAverageConvergenceDivergenceHistogramValue,
)
class os_ma_ster_v0_strategy(Strategy):
"""OsMaSter v0: four-bar MACD histogram pattern entries with pip-based SL/TP."""
def __init__(self):
super(os_ma_ster_v0_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 9) \
.SetGreaterThanZero() \
.SetDisplay("Fast EMA", "Fast EMA period for MACD histogram", "Indicators")
self._slow_period = self.Param("SlowPeriod", 26) \
.SetGreaterThanZero() \
.SetDisplay("Slow EMA", "Slow EMA period for MACD histogram", "Indicators")
self._signal_period = self.Param("SignalPeriod", 5) \
.SetGreaterThanZero() \
.SetDisplay("Signal Smoothing", "Signal moving average period", "Indicators")
self._stop_loss_pips = self.Param("StopLossPips", 500) \
.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk")
self._take_profit_pips = self.Param("TakeProfitPips", 1000) \
.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk")
self._trade_volume = self.Param("TradeVolume", 1.0) \
.SetGreaterThanZero() \
.SetDisplay("Trade Volume", "Order volume in lots", "Trading")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles for calculations", "General")
self._hist_current = None
self._hist_prev1 = None
self._hist_prev2 = None
self._hist_prev3 = None
@property
def FastPeriod(self):
return int(self._fast_period.Value)
@property
def SlowPeriod(self):
return int(self._slow_period.Value)
@property
def SignalPeriod(self):
return int(self._signal_period.Value)
@property
def StopLossPips(self):
return int(self._stop_loss_pips.Value)
@property
def TakeProfitPips(self):
return int(self._take_profit_pips.Value)
@property
def TradeVolume(self):
return float(self._trade_volume.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)
else:
v = abs(step)
while v != int(v) and decimals < 10:
v *= 10
decimals += 1
return step * 10.0 if (decimals == 3 or decimals == 5) else step
def OnStarted2(self, time):
super(os_ma_ster_v0_strategy, self).OnStarted2(time)
self._hist_current = None
self._hist_prev1 = None
self._hist_prev2 = None
self._hist_prev3 = None
macd = MovingAverageConvergenceDivergenceHistogram()
macd.Macd.ShortMa.Length = self.FastPeriod
macd.Macd.LongMa.Length = self.SlowPeriod
macd.SignalMa.Length = self.SignalPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(macd, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, macd)
self.DrawOwnTrades(area)
pip_size = self._calc_pip_size()
tp = Unit(self.TakeProfitPips * pip_size, UnitTypes.Absolute) if self.TakeProfitPips > 0 else None
sl = Unit(self.StopLossPips * pip_size, UnitTypes.Absolute) if self.StopLossPips > 0 else None
if tp is not None and sl is not None:
self.StartProtection(takeProfit=tp, stopLoss=sl)
elif tp is not None:
self.StartProtection(takeProfit=tp)
elif sl is not None:
self.StartProtection(stopLoss=sl)
def process_candle(self, candle, macd_value):
if candle.State != CandleStates.Finished:
return
if not macd_value.IsFormed:
return
histogram = macd_value.Macd
if histogram is None:
return
hist = float(histogram)
self._hist_prev3 = self._hist_prev2
self._hist_prev2 = self._hist_prev1
self._hist_prev1 = self._hist_current
self._hist_current = hist
if (self._hist_current is None or self._hist_prev1 is None
or self._hist_prev2 is None or self._hist_prev3 is None):
return
h0 = self._hist_current
h1 = self._hist_prev1
h2 = self._hist_prev2
h3 = self._hist_prev3
bullish = h3 > h2 and h2 < h1 and h1 < h0
bearish = h3 < h2 and h2 > h1 and h1 > h0
if self.Position != 0:
return
if bullish:
self.BuyMarket()
elif bearish:
self.SellMarket()
def OnReseted(self):
super(os_ma_ster_v0_strategy, self).OnReseted()
self._hist_current = None
self._hist_prev1 = None
self._hist_prev2 = None
self._hist_prev3 = None
def CreateClone(self):
return os_ma_ster_v0_strategy()