Williams %Rダイバージェンス戦略
Williams %Rオシレーターは買われ過ぎと売られ過ぎの状態を測定します。価格が新しい安値を付けるが%Rがより高い安値を形成する場合、または価格が新しい高値を付けるが%Rが下向きに転じる場合、モメンタムが反転する可能性があります。この戦略はインジケーターの極値でそのようなダイバージェンスを探します。
テストでは年平均リターンが約109%であることが示されています。暗号資産市場で最も良いパフォーマンスを発揮します。
毎バー、システムは最新の終値と%Rの値を記録して前回の読みと比較します。-80以下の売られ過ぎレベルと組み合わせた強気のダイバージェンスがロングエントリーを起動し、-20以上の弱気のダイバージェンスがショートを生み出します。ストップは価格のパーセントを使って設定されます。
オシレーターが反対の極値に戻った時点でポジションを決済し、ダイバージェンスシグナルからの反発を捉えます。
詳細
- エントリー条件: 価格/Williams %Rのダイバージェンスで、ロングには%Rが-80以下、ショートには-20以上。
- ロング/ショート: 両方。
- エグジット条件: Williams %Rが反対の極値に達するか、ストップロス。
- ストップ: はい、パーセントベース。
- デフォルト値:
WilliamsRPeriod= 14DivergencePeriod= 5CandleType= 5 minuteStopLossPercent= 2
- フィルター:
- カテゴリ: ダイバージェンス
- 方向: 両方
- インジケーター: Williams %R
- ストップ: はい
- 複雑さ: 中級
- 時間軸: イントラデイ
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: はい
- リスクレベル: 中
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 Divergence strategy.
/// Detects divergences between price and Williams %R for reversal signals.
/// Bullish: price falling but Williams %R rising (oversold zone).
/// Bearish: price rising but Williams %R falling (overbought zone).
/// </summary>
public class WilliamsPercentRDivergenceStrategy : Strategy
{
private readonly StrategyParam<int> _williamsRPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private decimal _prevPrice;
private decimal _prevWR;
private int _cooldown;
/// <summary>
/// Williams %R period.
/// </summary>
public int WilliamsRPeriod
{
get => _williamsRPeriod.Value;
set => _williamsRPeriod.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Cooldown bars.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public WilliamsPercentRDivergenceStrategy()
{
_williamsRPeriod = Param(nameof(WilliamsRPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Williams %R Period", "Period for Williams %R", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_cooldownBars = Param(nameof(CooldownBars), 500)
.SetRange(1, 1000)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevPrice = default;
_prevWR = default;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevPrice = 0;
_prevWR = 0;
_cooldown = 0;
var williamsR = new WilliamsR { Length = WilliamsRPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(williamsR, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, williamsR);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal wrValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_prevPrice == 0)
{
_prevPrice = candle.ClosePrice;
_prevWR = wrValue;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevPrice = candle.ClosePrice;
_prevWR = wrValue;
return;
}
// Bullish divergence: price lower but WR higher (in oversold zone)
var bullishDiv = candle.ClosePrice < _prevPrice && wrValue > _prevWR;
// Bearish divergence: price higher but WR lower (in overbought zone)
var bearishDiv = candle.ClosePrice > _prevPrice && wrValue < _prevWR;
if (Position == 0 && bullishDiv && wrValue < -80)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (Position == 0 && bearishDiv && wrValue > -20)
{
SellMarket();
_cooldown = CooldownBars;
}
else if (Position > 0 && wrValue > -20)
{
SellMarket();
_cooldown = CooldownBars;
}
else if (Position < 0 && wrValue < -80)
{
BuyMarket();
_cooldown = CooldownBars;
}
_prevPrice = candle.ClosePrice;
_prevWR = wrValue;
}
}
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 williams_percent_r_divergence_strategy(Strategy):
"""
Williams %R Divergence strategy.
Detects divergences between price and Williams %R for reversal signals.
Bullish: price falling but Williams %R rising (oversold zone).
Bearish: price rising but Williams %R falling (overbought zone).
"""
def __init__(self):
super(williams_percent_r_divergence_strategy, self).__init__()
self._wr_period = self.Param("WilliamsRPeriod", 14).SetDisplay("Williams %R Period", "Period for Williams %R", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown_bars = self.Param("CooldownBars", 500).SetDisplay("Cooldown Bars", "Bars to wait between trades", "General")
self._prev_price = 0.0
self._prev_wr = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(williams_percent_r_divergence_strategy, self).OnReseted()
self._prev_price = 0.0
self._prev_wr = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(williams_percent_r_divergence_strategy, self).OnStarted2(time)
self._prev_price = 0.0
self._prev_wr = 0.0
self._cooldown = 0
wr = WilliamsR()
wr.Length = self._wr_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(wr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, wr)
self.DrawOwnTrades(area)
def _process_candle(self, candle, wr_val):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
wv = float(wr_val)
if self._prev_price == 0:
self._prev_price = close
self._prev_wr = wv
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_price = close
self._prev_wr = wv
return
cd = self._cooldown_bars.Value
# Bullish divergence: price lower but WR higher (in oversold zone)
bullish_div = close < self._prev_price and wv > self._prev_wr
# Bearish divergence: price higher but WR lower (in overbought zone)
bearish_div = close > self._prev_price and wv < self._prev_wr
if self.Position == 0 and bullish_div and wv < -80:
self.BuyMarket()
self._cooldown = cd
elif self.Position == 0 and bearish_div and wv > -20:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0 and wv > -20:
self.SellMarket()
self._cooldown = cd
elif self.Position < 0 and wv < -80:
self.BuyMarket()
self._cooldown = cd
self._prev_price = close
self._prev_wr = wv
def CreateClone(self):
return williams_percent_r_divergence_strategy()