Ma Williams R 戦略
戦略の実装 - MA + Williams %R。価格が MA を上回り、Williams %R が -80 を下回っている(売られすぎ)場合に買い。価格が MA を下回り、Williams %R が -20 を上回っている(買われすぎ)場合に売り。
テストでは年平均収益率は約 79% を示しています。株式市場で最もパフォーマンスが優れています。
移動平均は優勢なトレンドの方向を示します。Williams %R はそのトレンドに対して買われすぎまたは売られすぎのポイントを探します。
平均に向けた押し目を待つスイングトレーダーに適しています。ストップロスの距離はエントリー価格の一定割合です。
詳細
- エントリー条件:
- ロング:
Close > MA && WilliamsR < WilliamsROversold - ショート:
Close < MA && WilliamsR > WilliamsROverbought
- ロング:
- ロング/ショート: 両方
- エグジット条件:
- Williams %R が中間に戻る
- ストップ:
StopLossPercentを使用したパーセントベース - デフォルト値:
MaPeriod= 20MaType= MovingAverageTypeEnum.SimpleWilliamsRPeriod= 14WilliamsROversold= -80mWilliamsROverbought= -20mStopLossPercent= 2CandleType= TimeSpan.FromMinutes(5).TimeFrame() MaTypeで単純・指数・加重・平滑・Hullの移動平均を選びます。Williams %Rの中央は-50で、ロングは%Rがそこまで上昇したら、ショートはそこまで下落したら決済します。 保有ポジションと逆方向のエントリーシグナルはドテンになります。
- フィルター:
- カテゴリ: 平均回帰
- 方向: 両方
- インジケーター: Moving Average, Williams %R, 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>
/// MA Williams %R strategy.
/// A close above the MaPeriod moving average of type MaType with Williams %R below WilliamsROversold goes long and a close below it with
/// %R above WilliamsROverbought goes short, reversing an opposite position. A long closes once %R returns to the -50 middle from below
/// and a short once it returns from above, and a percent stop limits the loss.
/// </summary>
public class MaWilliamsRStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<MovingAverageTypes> _maType;
private readonly StrategyParam<int> _williamsRPeriod;
private readonly StrategyParam<decimal> _williamsROversold;
private readonly StrategyParam<decimal> _williamsROverbought;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Period of the moving average.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Type of the moving average.
/// </summary>
public MovingAverageTypes MaType
{
get => _maType.Value;
set => _maType.Value = value;
}
/// <summary>
/// Period of Williams %R.
/// </summary>
public int WilliamsRPeriod
{
get => _williamsRPeriod.Value;
set => _williamsRPeriod.Value = value;
}
/// <summary>
/// Williams %R level for longs.
/// </summary>
public decimal WilliamsROversold
{
get => _williamsROversold.Value;
set => _williamsROversold.Value = value;
}
/// <summary>
/// Williams %R level for shorts.
/// </summary>
public decimal WilliamsROverbought
{
get => _williamsROverbought.Value;
set => _williamsROverbought.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public MaWilliamsRStrategy()
{
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Period of the moving average", "Indicators");
_maType = Param(nameof(MaType), MovingAverageTypes.Simple)
.SetDisplay("MA Type", "Type of the moving average", "Indicators");
_williamsRPeriod = Param(nameof(WilliamsRPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Williams %R Period", "Period of Williams %R", "Indicators");
_williamsROversold = Param(nameof(WilliamsROversold), -80m)
.SetDisplay("Williams %R Oversold", "Williams %R level for longs", "Indicators");
_williamsROverbought = Param(nameof(WilliamsROverbought), -20m)
.SetDisplay("Williams %R Overbought", "Williams %R level for shorts", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ma = CreateMovingAverage();
var williams = new WilliamsR { Length = WilliamsRPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(ma, williams, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ma);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
DrawIndicator(oscillators, williams);
}
}
}
private DecimalLengthIndicator CreateMovingAverage()
{
return MaType switch
{
MovingAverageTypes.Exponential => new ExponentialMovingAverage { Length = MaPeriod },
MovingAverageTypes.Weighted => new WeightedMovingAverage { Length = MaPeriod },
MovingAverageTypes.Smoothed => new SmoothedMovingAverage { Length = MaPeriod },
MovingAverageTypes.HullMA => new HullMovingAverage { Length = MaPeriod },
_ => new SimpleMovingAverage { Length = MaPeriod },
};
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue maValue, IIndicatorValue williamsValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!maValue.IsFormed || !williamsValue.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var ma = maValue.GetValue<decimal>();
var williams = williamsValue.GetValue<decimal>();
var close = candle.ClosePrice;
if (close > ma && williams < WilliamsROversold && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < ma && williams > WilliamsROverbought && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && williams >= -50m)
SellMarket(Position);
else if (Position < 0 && williams <= -50m)
BuyMarket(-Position);
}
/// <summary>
/// Moving average types.
/// </summary>
public enum MovingAverageTypes
{
/// <summary>
/// Simple moving average.
/// </summary>
Simple,
/// <summary>
/// Exponential moving average.
/// </summary>
Exponential,
/// <summary>
/// Weighted moving average.
/// </summary>
Weighted,
/// <summary>
/// Smoothed moving average.
/// </summary>
Smoothed,
/// <summary>
/// Hull moving average.
/// </summary>
HullMA,
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import SimpleMovingAverage, ExponentialMovingAverage, WeightedMovingAverage, SmoothedMovingAverage, HullMovingAverage, WilliamsR
from StockSharp.Algo.Strategies import Strategy
class MovingAverageTypeEnum:
"""Moving average types."""
Simple = 0
Exponential = 1
Weighted = 2
Smoothed = 3
HullMA = 4
class ma_williams_r_strategy(Strategy):
"""
MA Williams %R strategy.
A close above the MaPeriod moving average of type MaType with Williams %R below WilliamsROversold goes long and a close below it with
%R above WilliamsROverbought goes short, reversing an opposite position. A long closes once %R returns to the -50 middle from below
and a short once it returns from above, and a percent stop limits the loss.
"""
def __init__(self):
super(ma_williams_r_strategy, self).__init__()
self._ma_period = self.Param("MaPeriod", 20).SetGreaterThanZero().SetDisplay("MA Period", "Period of the moving average", "Indicators")
self._ma_type = self.Param("MaType", MovingAverageTypeEnum.Simple).SetDisplay("MA Type", "Type of the moving average", "Indicators")
self._williams_r_period = self.Param("WilliamsRPeriod", 14).SetGreaterThanZero().SetDisplay("Williams %R Period", "Period of Williams %R", "Indicators")
self._williams_r_oversold = self.Param("WilliamsROversold", -80.0).SetDisplay("Williams %R Oversold", "Williams %R level for longs", "Indicators")
self._williams_r_overbought = self.Param("WilliamsROverbought", -20.0).SetDisplay("Williams %R Overbought", "Williams %R level for shorts", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(ma_williams_r_strategy, self).OnStarted2(time)
ma = self._create_moving_average()
williams = WilliamsR()
williams.Length = self._williams_r_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(ma, williams, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ma)
self.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, williams)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _create_moving_average(self):
ma_type = self._ma_type.Value
if ma_type == MovingAverageTypeEnum.Exponential:
ma = ExponentialMovingAverage()
elif ma_type == MovingAverageTypeEnum.Weighted:
ma = WeightedMovingAverage()
elif ma_type == MovingAverageTypeEnum.Smoothed:
ma = SmoothedMovingAverage()
elif ma_type == MovingAverageTypeEnum.HullMA:
ma = HullMovingAverage()
else:
ma = SimpleMovingAverage()
ma.Length = self._ma_period.Value
return ma
def _process_candle(self, candle, ma_value, williams_value):
if candle.State != CandleStates.Finished:
return
if not ma_value.IsFormed or not williams_value.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
ma = ma_value.GetValue[Decimal](None)
williams = williams_value.GetValue[Decimal](None)
close = candle.ClosePrice
middle = Decimal(-50)
if close > ma and williams < Decimal(self._williams_r_oversold.Value) and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < ma and williams > Decimal(self._williams_r_overbought.Value) and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and williams >= middle:
self.SellMarket(self.Position)
elif self.Position < 0 and williams <= middle:
self.BuyMarket(-self.Position)
def CreateClone(self):
return ma_williams_r_strategy()