Estratégia Williams R
Estratégia baseada no indicador Williams %R
Os testes indicam um retorno anual médio de aproximadamente 88%. Funciona melhor no mercado de ações.
Williams %R identifica zonas de sobrecompra e sobrevenda. Quando o indicador sobe acima do limite superior sinaliza fraqueza potencial para posições vendidas; leituras abaixo do limite inferior sugerem posições compradas. As posições fecham quando %R se move em direção à zona neutra.
Como %R oscila rapidamente, a estratégia pode gerar muitos sinais em mercados voláteis. Alguns traders o combinam com outros filtros para reduzir o ruído.
Detalhes
- Critérios de entrada: Sinais baseados em Williams.
- Comprado/Vendido: Ambas as direções.
- Critérios de saída: Sinal oposto ou stop.
- Stops: Sim.
- Valores padrão:
Period= 14StopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- Filtros:
- Categoria: Tendência
- Direção: Ambos
- Indicadores: Williams
- Stops: Sim
- Complexidade: Básico
- Período: Intradiário (5m)
- Sazonalidade: Não
- Neural Networks: Não
- Divergência: Não
- Nível de risco: Médio
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 indicator.
/// Buys when Williams %R drops below the oversold level (-80),
/// sells when it rises above the overbought level (-20).
/// Closes at the neutral midpoint (-50) and protects actual fills with a native percent stop.
/// </summary>
public class WilliamsPercentRStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private decimal _prevWR;
private bool _hasPrevValues;
private Order _pendingOrder;
/// <summary>
/// Williams %R period.
/// </summary>
public int Period
{
get => _period.Value;
set => _period.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <summary>
/// Initializes a new instance of the <see cref="WilliamsPercentRStrategy"/>.
/// </summary>
public WilliamsPercentRStrategy()
{
_period = Param(nameof(Period), 14)
.SetDisplay("Period", "Period for Williams %R calculation", "Indicators")
.SetOptimize(10, 20, 2);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, DataType.Level1)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevWR = default;
_hasPrevValues = default;
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var williams = new WilliamsR { Length = Period };
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
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 subscription = SubscribeCandles(CandleType);
subscription
.Bind(williams, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, williams);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, decimal wrValue)
{
if (candle.State != CandleStates.Finished || !IsFormedAndOnlineAndAllowTrading())
return;
if (!_hasPrevValues)
{
_hasPrevValues = true;
_prevWR = wrValue;
return;
}
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
{
_prevWR = wrValue;
return;
}
// Williams %R drops into the oversold zone below -80 - buy signal
if (_prevWR >= -80m && wrValue < -80m && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
// Williams %R rises into the overbought zone above -20 - sell signal
else if (_prevWR <= -20m && wrValue > -20m && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
else if (Position > 0m && wrValue >= -50m)
SellMarket(Position);
else if (Position < 0m && wrValue <= -50m)
BuyMarket(Math.Abs(Position));
_prevWR = wrValue;
}
}
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, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, OrderStates, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import WilliamsR
from StockSharp.Algo.Strategies import Strategy
class williams_percent_r_strategy(Strategy):
"""
Strategy based on Williams %R indicator.
Buys when Williams %R drops below the oversold level (-80),
sells when it rises above the overbought level (-20).
Closes at the neutral midpoint (-50) and protects actual fills with a native percent stop.
"""
def __init__(self):
super(williams_percent_r_strategy, self).__init__()
self._period = self.Param("Period", 14) \
.SetDisplay("Period", "Period for Williams %R calculation", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._prev_wr = Decimal.Zero
self._has_prev_values = False
self._pending_order = None
self.OrderRegistering += self._track_pending
def GetWorkingSecurities(self):
return [(self.Security, self.candle_type), (self.Security, DataType.Level1)]
def _track_pending(self, order):
self._pending_order = order
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(williams_percent_r_strategy, self).OnReseted()
self._prev_wr = Decimal.Zero
self._has_prev_values = False
self._pending_order = None
def OnStarted2(self, time):
super(williams_percent_r_strategy, self).OnStarted2(time)
williams = WilliamsR()
williams.Length = self._period.Value
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
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()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(williams, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, williams)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, wr):
if candle.State != CandleStates.Finished or not self.IsFormedAndOnlineAndAllowTrading():
return
if not self._has_prev_values:
self._has_prev_values = True
self._prev_wr = wr
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
self._prev_wr = wr
return
if self._prev_wr >= -80 and wr < -80 and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif self._prev_wr <= -20 and wr > -20 and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
elif self.Position > 0 and wr >= -50:
self.SellMarket(self.Position)
elif self.Position < 0 and wr <= -50:
self.BuyMarket(Math.Abs(self.Position))
self._prev_wr = wr
def CreateClone(self):
return williams_percent_r_strategy()