using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Williams %R strategy with EMA trend filter and retracement gating.
/// Buys when WPR oversold and EMA trending up, sells when WPR overbought and EMA trending down.
/// </summary>
public class EmaWprRetracementStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _wprPeriod;
private readonly StrategyParam<decimal> _wprRetracement;
private readonly StrategyParam<DataType> _candleType;
private bool _canBuy = true;
private bool _canSell = true;
private decimal _prevEma;
private bool _hasPrevEma;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public int WprPeriod { get => _wprPeriod.Value; set => _wprPeriod.Value = value; }
public decimal WprRetracement { get => _wprRetracement.Value; set => _wprRetracement.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EmaWprRetracementStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA period for trend", "Trend");
_wprPeriod = Param(nameof(WprPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("WPR Period", "Williams %R period", "Signals");
_wprRetracement = Param(nameof(WprRetracement), 30m)
.SetDisplay("WPR Retracement", "Retracement needed for next trade", "Signals");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_canBuy = true;
_canSell = true;
_prevEma = 0;
_hasPrevEma = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var wpr = new WilliamsR { Length = WprPeriod };
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(wpr, ema, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal wpr, decimal ema)
{
if (candle.State != CandleStates.Finished)
return;
var emaUp = _hasPrevEma && ema > _prevEma;
var emaDown = _hasPrevEma && ema < _prevEma;
// Retracement gating: after a buy at oversold, require WPR to retrace above threshold before next buy
if (wpr > -100 + WprRetracement)
_canBuy = true;
if (wpr < -WprRetracement)
_canSell = true;
// Oversold buy with uptrend
if (wpr <= -80 && _canBuy && emaUp && Position <= 0)
{
BuyMarket();
_canBuy = false;
}
// Overbought sell with downtrend
else if (wpr >= -20 && _canSell && emaDown && Position >= 0)
{
SellMarket();
_canSell = false;
}
_prevEma = ema;
_hasPrevEma = true;
}
}
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, WilliamsR
from StockSharp.Algo.Strategies import Strategy
class ema_wpr_retracement_strategy(Strategy):
def __init__(self):
super(ema_wpr_retracement_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 50) \
.SetDisplay("EMA Period", "EMA period for trend", "Trend")
self._wpr_period = self.Param("WprPeriod", 14) \
.SetDisplay("WPR Period", "Williams %R period", "Signals")
self._wpr_retracement = self.Param("WprRetracement", 30.0) \
.SetDisplay("WPR Retracement", "Retracement needed for next trade", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._can_buy = True
self._can_sell = True
self._prev_ema = 0.0
self._has_prev_ema = False
@property
def ema_period(self):
return self._ema_period.Value
@property
def wpr_period(self):
return self._wpr_period.Value
@property
def wpr_retracement(self):
return self._wpr_retracement.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_wpr_retracement_strategy, self).OnReseted()
self._can_buy = True
self._can_sell = True
self._prev_ema = 0.0
self._has_prev_ema = False
def OnStarted2(self, time):
super(ema_wpr_retracement_strategy, self).OnStarted2(time)
wpr = WilliamsR()
wpr.Length = self.wpr_period
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(wpr, ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def on_process(self, candle, wpr, ema):
if candle.State != CandleStates.Finished:
return
ema_up = self._has_prev_ema and ema > self._prev_ema
ema_down = self._has_prev_ema and ema < self._prev_ema
# Retracement gating: after a buy at oversold, require WPR to retrace above threshold before next buy
if wpr > -100 + self.wpr_retracement:
self._can_buy = True
if wpr < -self.wpr_retracement:
self._can_sell = True
# Oversold buy with uptrend
if wpr <= -80 and self._can_buy and ema_up and self.Position <= 0:
self.BuyMarket()
self._can_buy = False
# Overbought sell with downtrend
elif wpr >= -20 and self._can_sell and ema_down and self.Position >= 0:
self.SellMarket()
self._can_sell = False
self._prev_ema = ema
self._has_prev_ema = True
def CreateClone(self):
return ema_wpr_retracement_strategy()