Стратегия WPR Histogram
Стратегия торгует на основе индикатора Williams %R. Когда индикатор выходит из зоны перекупленности или перепроданности, открывается позиция в противоположную сторону.
Логика
- Если Williams %R поднимается выше верхнего уровня, а затем опускается обратно, считается, что рынок выходит из зоны перекупленности — открывается длинная позиция.
- Если Williams %R падает ниже нижнего уровня, а затем поднимается обратно, рынок выходит из зоны перепроданности — открывается короткая позиция.
- Перед открытием новой позиции противоположные позиции закрываются.
Параметры
- WPR Period – период расчёта индикатора Williams %R.
- High Level – порог зоны перекупленности.
- Low Level – порог зоны перепроданности.
- Candle Type – тип и таймфрейм свечей, используемых для расчётов.
Примечания
Стратегия использует только рыночные заявки и не устанавливает уровни стоп-лосса или тейк-профита. Размер позиции определяется свойством Volume.
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 Williams %R histogram indicator.
/// Opens a long position when price leaves overbought zone.
/// Opens a short position when price leaves oversold zone.
/// </summary>
public class WprHistogramStrategy : Strategy
{
private readonly StrategyParam<int> _wprPeriod;
private readonly StrategyParam<decimal> _highLevel;
private readonly StrategyParam<decimal> _lowLevel;
private readonly StrategyParam<DataType> _candleType;
// Previous zone state: 0 - overbought, 1 - neutral, 2 - oversold
private int? _previousZone;
/// <summary>
/// Williams %R period.
/// </summary>
public int WprPeriod
{
get => _wprPeriod.Value;
set => _wprPeriod.Value = value;
}
/// <summary>
/// High level threshold.
/// </summary>
public decimal HighLevel
{
get => _highLevel.Value;
set => _highLevel.Value = value;
}
/// <summary>
/// Low level threshold.
/// </summary>
public decimal LowLevel
{
get => _lowLevel.Value;
set => _lowLevel.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public WprHistogramStrategy()
{
_wprPeriod = Param(nameof(WprPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("WPR Period", "Period for Williams %R", "Indicator")
.SetOptimize(7, 28, 7);
_highLevel = Param(nameof(HighLevel), -30m)
.SetDisplay("High Level", "Overbought threshold", "Indicator")
.SetOptimize(-40m, -20m, 10m);
_lowLevel = Param(nameof(LowLevel), -70m)
.SetDisplay("Low Level", "Oversold threshold", "Indicator")
.SetOptimize(-80m, -60m, 10m);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_previousZone = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
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)
{
// Only finished candles are processed
if (candle.State != CandleStates.Finished)
return;
var currentZone = 1;
if (wprValue > HighLevel)
currentZone = 0;
else if (wprValue < LowLevel)
currentZone = 2;
if (!IsFormedAndOnlineAndAllowTrading())
{
_previousZone = currentZone;
return;
}
if (_previousZone == null)
{
_previousZone = currentZone;
return;
}
// Leaving overbought zone - open long
if (_previousZone == 0 && currentZone != 0 && Position <= 0)
{
BuyMarket();
}
// Leaving oversold zone - open short
else if (_previousZone == 2 && currentZone != 2 && Position >= 0)
{
SellMarket();
}
_previousZone = currentZone;
}
}
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 wpr_histogram_strategy(Strategy):
def __init__(self):
super(wpr_histogram_strategy, self).__init__()
self._wpr_period = self.Param("WprPeriod", 14).SetDisplay("WPR Period", "Period for Williams %R", "Indicator")
self._high_level = self.Param("HighLevel", -30.0).SetDisplay("High Level", "Overbought threshold", "Indicator")
self._low_level = self.Param("LowLevel", -70.0).SetDisplay("Low Level", "Oversold threshold", "Indicator")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Type of candles", "General")
self._previous_zone = None
@property
def wpr_period(self): return self._wpr_period.Value
@property
def high_level(self): return self._high_level.Value
@property
def low_level(self): return self._low_level.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self):
super(wpr_histogram_strategy, self).OnReseted()
self._previous_zone = None
def OnStarted2(self, time):
super(wpr_histogram_strategy, self).OnStarted2(time)
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
wv = float(wpr_value)
hl = float(self.high_level)
ll = float(self.low_level)
if wv > hl: current_zone = 0
elif wv < ll: current_zone = 2
else: current_zone = 1
if not self.IsFormedAndOnlineAndAllowTrading():
self._previous_zone = current_zone
return
if self._previous_zone is None:
self._previous_zone = current_zone
return
if self._previous_zone == 0 and current_zone != 0 and self.Position <= 0:
self.BuyMarket()
elif self._previous_zone == 2 and current_zone != 2 and self.Position >= 0:
self.SellMarket()
self._previous_zone = current_zone
def CreateClone(self): return wpr_histogram_strategy()