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>
/// Strategy based on MACD and Williams %R indicators.
/// Enters long when MACD > Signal and Williams %R is oversold (< -80)
/// Enters short when MACD < Signal and Williams %R is overbought (> -20)
/// </summary>
public class MacdWilliamsRStrategy : Strategy
{
private readonly StrategyParam<int> _macdFast;
private readonly StrategyParam<int> _macdSlow;
private readonly StrategyParam<int> _macdSignal;
private readonly StrategyParam<int> _williamsRPeriod;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private int _cooldown;
private bool _hasPrevState;
private bool _prevBull;
/// <summary>
/// MACD fast period
/// </summary>
public int MacdFast
{
get => _macdFast.Value;
set => _macdFast.Value = value;
}
/// <summary>
/// MACD slow period
/// </summary>
public int MacdSlow
{
get => _macdSlow.Value;
set => _macdSlow.Value = value;
}
/// <summary>
/// MACD signal period
/// </summary>
public int MacdSignal
{
get => _macdSignal.Value;
set => _macdSignal.Value = value;
}
/// <summary>
/// Williams %R period
/// </summary>
public int WilliamsRPeriod
{
get => _williamsRPeriod.Value;
set => _williamsRPeriod.Value = value;
}
/// <summary>
/// Bars to wait between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Stop-loss percentage
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type for strategy calculation
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor
/// </summary>
public MacdWilliamsRStrategy()
{
_macdFast = Param(nameof(MacdFast), 12)
.SetGreaterThanZero()
.SetDisplay("MACD Fast Period", "Fast EMA period for MACD", "Indicators")
.SetOptimize(8, 16, 2);
_macdSlow = Param(nameof(MacdSlow), 26)
.SetGreaterThanZero()
.SetDisplay("MACD Slow Period", "Slow EMA period for MACD", "Indicators")
.SetOptimize(20, 30, 2);
_macdSignal = Param(nameof(MacdSignal), 9)
.SetGreaterThanZero()
.SetDisplay("MACD Signal Period", "Signal line period for MACD", "Indicators")
.SetOptimize(7, 12, 1);
_williamsRPeriod = Param(nameof(WilliamsRPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Williams %R Period", "Period for Williams %R indicator", "Indicators")
.SetOptimize(10, 20, 2);
_cooldownBars = Param(nameof(CooldownBars), 120)
.SetRange(5, 500)
.SetDisplay("Cooldown Bars", "Bars between trades", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2.0m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss as percentage of entry price", "Risk Management")
.SetOptimize(1.0m, 3.0m, 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for strategy", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cooldown = 0;
_hasPrevState = false;
_prevBull = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Create indicators
var macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = MacdFast },
LongMa = { Length = MacdSlow },
},
SignalMa = { Length = MacdSignal }
};
var williamsR = new WilliamsR { Length = WilliamsRPeriod };
// Subscribe to candles and bind indicators
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macd, williamsR, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, macd);
// Create a separate area for Williams %R
var williamsArea = CreateChartArea();
if (williamsArea != null)
{
DrawIndicator(williamsArea, williamsR);
}
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue, IIndicatorValue williamsRValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Check if strategy is ready to trade
if (!IsFormedAndOnlineAndAllowTrading())
return;
// Get additional values from MACD (signal line)
var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
var macd = macdTyped.Macd;
var signal = macdTyped.Signal;
var williamsR = williamsRValue.ToDecimal();
var bull = macd > signal;
if (!_hasPrevState)
{
_hasPrevState = true;
_prevBull = bull;
return;
}
if (_cooldown > 0)
{
_cooldown--;
return;
}
var crossedUp = !_prevBull && bull;
var crossedDown = _prevBull && !bull;
// Trading logic
if (crossedUp && Position == 0)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (crossedDown && Position == 0)
{
SellMarket();
_cooldown = CooldownBars;
}
else if (macd < signal) // MACD below signal line - bearish
{
if (Position > 0) // Already long, exit on MACD crossing down
{
// Exit long position
SellMarket();
_cooldown = CooldownBars;
}
}
else if (macd > signal && Position < 0) // Already short, exit on MACD crossing up
{
// Exit short position
BuyMarket();
_cooldown = CooldownBars;
}
_prevBull = bull;
}
}
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 MovingAverageConvergenceDivergenceSignal, WilliamsR
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
class macd_williams_r_strategy(Strategy):
"""
MACD + Williams %R strategy.
Enters on MACD crossover with Williams %R confirmation.
"""
def __init__(self):
super(macd_williams_r_strategy, self).__init__()
self._macd_fast = self.Param("MacdFast", 12) \
.SetDisplay("MACD Fast Period", "Fast EMA period for MACD", "Indicators")
self._macd_slow = self.Param("MacdSlow", 26) \
.SetDisplay("MACD Slow Period", "Slow EMA period for MACD", "Indicators")
self._macd_signal = self.Param("MacdSignal", 9) \
.SetDisplay("MACD Signal Period", "Signal line period for MACD", "Indicators")
self._williams_r_period = self.Param("WilliamsRPeriod", 14) \
.SetDisplay("Williams %R Period", "Period for Williams %R indicator", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 120) \
.SetRange(5, 500) \
.SetDisplay("Cooldown Bars", "Bars between trades", "General")
self._candle_type = self.Param("CandleType", tf(5)) \
.SetDisplay("Candle Type", "Timeframe for strategy", "General")
self._cooldown = 0
self._has_prev_state = False
self._prev_bull = False
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(macd_williams_r_strategy, self).OnStarted2(time)
self._cooldown = 0
self._has_prev_state = False
self._prev_bull = False
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self._macd_fast.Value
macd.Macd.LongMa.Length = self._macd_slow.Value
macd.SignalMa.Length = self._macd_signal.Value
williams_r = WilliamsR()
williams_r.Length = self._williams_r_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(macd, williams_r, self.ProcessCandle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, macd)
wr_area = self.CreateChartArea()
if wr_area is not None:
self.DrawIndicator(wr_area, williams_r)
self.DrawOwnTrades(area)
def ProcessCandle(self, candle, macd_value, williams_r_value):
if candle.State != CandleStates.Finished:
return
if macd_value.Macd is None or macd_value.Signal is None:
return
macd_line = float(macd_value.Macd)
signal_line = float(macd_value.Signal)
williams_r = float(williams_r_value)
bull = macd_line > signal_line
if not self._has_prev_state:
self._has_prev_state = True
self._prev_bull = bull
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_bull = bull
return
crossed_up = not self._prev_bull and bull
crossed_down = self._prev_bull and not bull
cd = self._cooldown_bars.Value
if crossed_up and self.Position == 0:
self.BuyMarket()
self._cooldown = cd
elif crossed_down and self.Position == 0:
self.SellMarket()
self._cooldown = cd
elif macd_line < signal_line and self.Position > 0:
self.SellMarket()
self._cooldown = cd
elif macd_line > signal_line and self.Position < 0:
self.BuyMarket()
self._cooldown = cd
self._prev_bull = bull
def OnReseted(self):
super(macd_williams_r_strategy, self).OnReseted()
self._cooldown = 0
self._has_prev_state = False
self._prev_bull = False
def CreateClone(self):
return macd_williams_r_strategy()