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>
/// Moving Average Oscillator Histogram strategy.
/// Generates signals when the oscillator forms local minima or maxima.
/// </summary>
public class MaOscillatorHistogramStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<bool> _enableBuyOpen;
private readonly StrategyParam<bool> _enableSellOpen;
private readonly StrategyParam<bool> _enableBuyClose;
private readonly StrategyParam<bool> _enableSellClose;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevOsc1;
private decimal _prevOsc2;
private bool _isWarmup;
/// <summary>
/// Fast MA period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow MA period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Enable opening long positions.
/// </summary>
public bool EnableBuyOpen
{
get => _enableBuyOpen.Value;
set => _enableBuyOpen.Value = value;
}
/// <summary>
/// Enable opening short positions.
/// </summary>
public bool EnableSellOpen
{
get => _enableSellOpen.Value;
set => _enableSellOpen.Value = value;
}
/// <summary>
/// Enable closing long positions.
/// </summary>
public bool EnableBuyClose
{
get => _enableBuyClose.Value;
set => _enableBuyClose.Value = value;
}
/// <summary>
/// Enable closing short positions.
/// </summary>
public bool EnableSellClose
{
get => _enableSellClose.Value;
set => _enableSellClose.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="MaOscillatorHistogramStrategy"/>.
/// </summary>
public MaOscillatorHistogramStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 13)
.SetDisplay("Fast Period", "Period of fast moving average", "Indicators")
;
_slowPeriod = Param(nameof(SlowPeriod), 24)
.SetDisplay("Slow Period", "Period of slow moving average", "Indicators")
;
_enableBuyOpen = Param(nameof(EnableBuyOpen), true)
.SetDisplay("Enable Buy Open", "Allow opening long positions", "Signals");
_enableSellOpen = Param(nameof(EnableSellOpen), true)
.SetDisplay("Enable Sell Open", "Allow opening short positions", "Signals");
_enableBuyClose = Param(nameof(EnableBuyClose), true)
.SetDisplay("Enable Buy Close", "Allow closing long positions", "Signals");
_enableSellClose = Param(nameof(EnableSellClose), true)
.SetDisplay("Enable Sell Close", "Allow closing short positions", "Signals");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevOsc1 = default;
_prevOsc2 = default;
_isWarmup = true;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Create moving averages
var fastMa = new ExponentialMovingAverage { Length = FastPeriod };
var slowMa = new ExponentialMovingAverage { Length = SlowPeriod };
// Subscribe to candles and bind indicators
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastMa, slowMa, ProcessCandle)
.Start();
// Chart visualization
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastMa);
DrawIndicator(area, slowMa);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
// Process only finished candles
if (candle.State != CandleStates.Finished)
return;
// Ensure indicators are formed and trading is allowed
if (!IsFormedAndOnlineAndAllowTrading())
return;
var osc = fastValue - slowValue;
if (_isWarmup)
{
_prevOsc1 = osc;
_prevOsc2 = osc;
_isWarmup = false;
return;
}
var buySignal = _prevOsc2 > _prevOsc1 && _prevOsc1 < osc;
var sellSignal = _prevOsc2 < _prevOsc1 && _prevOsc1 > osc;
if (buySignal)
{
if (EnableSellClose && Position < 0)
BuyMarket();
if (EnableBuyOpen && Position <= 0)
BuyMarket();
}
else if (sellSignal)
{
if (EnableBuyClose && Position > 0)
SellMarket();
if (EnableSellOpen && Position >= 0)
SellMarket();
}
_prevOsc2 = _prevOsc1;
_prevOsc1 = osc;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ma_oscillator_histogram_strategy(Strategy):
def __init__(self):
super(ma_oscillator_histogram_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 13).SetDisplay("Fast Period", "Period of fast moving average", "Indicators")
self._slow_period = self.Param("SlowPeriod", 24).SetDisplay("Slow Period", "Period of slow moving average", "Indicators")
self._enable_buy_open = self.Param("EnableBuyOpen", True).SetDisplay("Enable Buy Open", "Allow opening long positions", "Signals")
self._enable_sell_open = self.Param("EnableSellOpen", True).SetDisplay("Enable Sell Open", "Allow opening short positions", "Signals")
self._enable_buy_close = self.Param("EnableBuyClose", True).SetDisplay("Enable Buy Close", "Allow closing long positions", "Signals")
self._enable_sell_close = self.Param("EnableSellClose", True).SetDisplay("Enable Sell Close", "Allow closing short positions", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_osc1 = 0.0
self._prev_osc2 = 0.0
self._is_warmup = True
@property
def fast_period(self): return self._fast_period.Value
@property
def slow_period(self): return self._slow_period.Value
@property
def enable_buy_open(self): return self._enable_buy_open.Value
@property
def enable_sell_open(self): return self._enable_sell_open.Value
@property
def enable_buy_close(self): return self._enable_buy_close.Value
@property
def enable_sell_close(self): return self._enable_sell_close.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self):
super(ma_oscillator_histogram_strategy, self).OnReseted()
self._prev_osc1 = 0.0
self._prev_osc2 = 0.0
self._is_warmup = True
def OnStarted2(self, time):
super(ma_oscillator_histogram_strategy, self).OnStarted2(time)
fast_ma = ExponentialMovingAverage()
fast_ma.Length = self.fast_period
slow_ma = ExponentialMovingAverage()
slow_ma.Length = self.slow_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ma, slow_ma, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ma)
self.DrawIndicator(area, slow_ma)
self.DrawOwnTrades(area)
def process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished: return
if not self.IsFormedAndOnlineAndAllowTrading(): return
osc = float(fast_value) - float(slow_value)
if self._is_warmup:
self._prev_osc1 = osc
self._prev_osc2 = osc
self._is_warmup = False
return
buy_signal = self._prev_osc2 > self._prev_osc1 and self._prev_osc1 < osc
sell_signal = self._prev_osc2 < self._prev_osc1 and self._prev_osc1 > osc
if buy_signal:
if self.enable_sell_close and self.Position < 0:
self.BuyMarket()
if self.enable_buy_open and self.Position <= 0:
self.BuyMarket()
elif sell_signal:
if self.enable_buy_close and self.Position > 0:
self.SellMarket()
if self.enable_sell_open and self.Position >= 0:
self.SellMarket()
self._prev_osc2 = self._prev_osc1
self._prev_osc1 = osc
def CreateClone(self): return ma_oscillator_histogram_strategy()