SpectrAnalysis WPR Strategy
This strategy is converted from the MQL5 expert Exp_i-SpectrAnalysis_WPR.
It analyzes the direction of the Williams %R indicator and opens or closes
positions according to indicator turns.
Logic
- Subscribe to candles of the selected timeframe.
- Calculate Williams %R with the configured period.
- Keep the last two indicator values to detect upward or downward direction.
- When the indicator turns upward and long entries are allowed:
- Close short positions if enabled.
- Open a new long position.
- When the indicator turns downward and short entries are allowed:
- Close long positions if enabled.
- Open a new short position.
Only finished candles are processed. The strategy does not use complex
historical queries and relies on high-level API bindings.
Parameters
| Name |
Description |
Default |
Candle Type |
Timeframe of the candles used for calculations |
4h |
WPR Period |
Period of the Williams %R indicator |
13 |
Allow Long Entry |
Permit opening long positions |
true |
Allow Short Entry |
Permit opening short positions |
true |
Allow Long Exit |
Permit closing long positions |
true |
Allow Short Exit |
Permit closing short positions |
true |
Notes
The original MQL version applied spectral analysis to the Williams %R output.
This C# conversion uses the standard Williams %R indicator and replicates the
signal logic by tracking recent indicator values.
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>
/// Strategy based on Williams %R trend direction.
/// </summary>
public class SpectrAnalysisWprStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _wprPeriod;
private readonly StrategyParam<bool> _buyPosOpen;
private readonly StrategyParam<bool> _sellPosOpen;
private readonly StrategyParam<bool> _buyPosClose;
private readonly StrategyParam<bool> _sellPosClose;
private decimal? _prev;
private decimal? _prev2;
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Williams %R period.
/// </summary>
public int WprPeriod
{
get => _wprPeriod.Value;
set => _wprPeriod.Value = value;
}
/// <summary>
/// Allow opening long positions.
/// </summary>
public bool BuyPosOpen
{
get => _buyPosOpen.Value;
set => _buyPosOpen.Value = value;
}
/// <summary>
/// Allow opening short positions.
/// </summary>
public bool SellPosOpen
{
get => _sellPosOpen.Value;
set => _sellPosOpen.Value = value;
}
/// <summary>
/// Allow closing long positions.
/// </summary>
public bool BuyPosClose
{
get => _buyPosClose.Value;
set => _buyPosClose.Value = value;
}
/// <summary>
/// Allow closing short positions.
/// </summary>
public bool SellPosClose
{
get => _sellPosClose.Value;
set => _sellPosClose.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public SpectrAnalysisWprStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for indicator", "General");
_wprPeriod = Param(nameof(WprPeriod), 13)
.SetGreaterThanZero()
.SetDisplay("WPR Period", "Williams %R period", "Indicator");
_buyPosOpen = Param(nameof(BuyPosOpen), true)
.SetDisplay("Allow Long Entry", "Enable long position opening", "Trading");
_sellPosOpen = Param(nameof(SellPosOpen), true)
.SetDisplay("Allow Short Entry", "Enable short position opening", "Trading");
_buyPosClose = Param(nameof(BuyPosClose), true)
.SetDisplay("Allow Long Exit", "Enable closing of long positions", "Trading");
_sellPosClose = Param(nameof(SellPosClose), true)
.SetDisplay("Allow Short Exit", "Enable closing of short positions", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prev = null;
_prev2 = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prev = null;
_prev2 = null;
var wpr = new WilliamsR { Length = WprPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(wpr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, wpr);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal wprValue)
{
if (candle.State != CandleStates.Finished || !IsFormedAndOnlineAndAllowTrading())
return;
if (_prev is null || _prev2 is null)
{
_prev2 = _prev;
_prev = wprValue;
return;
}
// Upward direction detected (WPR was falling, now turning up)
if (_prev < _prev2 && wprValue >= _prev)
{
if (BuyPosOpen && Position <= 0)
BuyMarket(Position < 0 ? Volume + Math.Abs(Position) : Volume);
else if (SellPosClose && Position < 0)
BuyMarket(Math.Abs(Position));
}
// Downward direction detected (WPR was rising, now turning down)
else if (_prev > _prev2 && wprValue <= _prev)
{
if (SellPosOpen && Position >= 0)
SellMarket(Position > 0 ? Volume + Position : Volume);
else if (BuyPosClose && Position > 0)
SellMarket(Position);
}
_prev2 = _prev;
_prev = wprValue;
}
}
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 WilliamsR
from StockSharp.Algo.Strategies import Strategy
class spectr_analysis_wpr_strategy(Strategy):
def __init__(self):
super(spectr_analysis_wpr_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for indicator", "General")
self._wpr_period = self.Param("WprPeriod", 13) \
.SetDisplay("WPR Period", "Williams %R period", "Indicator")
self._buy_pos_open = self.Param("BuyPosOpen", True) \
.SetDisplay("Allow Long Entry", "Enable long position opening", "Trading")
self._sell_pos_open = self.Param("SellPosOpen", True) \
.SetDisplay("Allow Short Entry", "Enable short position opening", "Trading")
self._buy_pos_close = self.Param("BuyPosClose", True) \
.SetDisplay("Allow Long Exit", "Enable closing of long positions", "Trading")
self._sell_pos_close = self.Param("SellPosClose", True) \
.SetDisplay("Allow Short Exit", "Enable closing of short positions", "Trading")
self._prev = None
self._prev2 = None
@property
def candle_type(self):
return self._candle_type.Value
@property
def wpr_period(self):
return self._wpr_period.Value
@property
def buy_pos_open(self):
return self._buy_pos_open.Value
@property
def sell_pos_open(self):
return self._sell_pos_open.Value
@property
def buy_pos_close(self):
return self._buy_pos_close.Value
@property
def sell_pos_close(self):
return self._sell_pos_close.Value
def OnReseted(self):
super(spectr_analysis_wpr_strategy, self).OnReseted()
self._prev = None
self._prev2 = None
def OnStarted2(self, time):
super(spectr_analysis_wpr_strategy, self).OnStarted2(time)
self._prev = None
self._prev2 = None
wpr = WilliamsR()
wpr.Length = self.wpr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(wpr, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, wpr)
self.DrawOwnTrades(area)
def process_candle(self, candle, wpr_value):
if candle.State != CandleStates.Finished:
return
wpr_value = float(wpr_value)
if self._prev is None or self._prev2 is None:
self._prev2 = self._prev
self._prev = wpr_value
return
if self._prev < self._prev2 and wpr_value >= self._prev:
if self.buy_pos_open and self.Position <= 0:
self.BuyMarket()
elif self.sell_pos_close and self.Position < 0:
self.BuyMarket()
elif self._prev > self._prev2 and wpr_value <= self._prev:
if self.sell_pos_open and self.Position >= 0:
self.SellMarket()
elif self.buy_pos_close and self.Position > 0:
self.SellMarket()
self._prev2 = self._prev
self._prev = wpr_value
def CreateClone(self):
return spectr_analysis_wpr_strategy()