WPR柱状图策略
该策略基于威廉指标 %R 的行为。当指标离开超买或超卖区域时,策略在相反方向开仓。
逻辑
- 当威廉指标 %R 超过高位后再次下穿时,被视为市场离开超买区域的信号,策略开多仓。
- 当威廉指标 %R 跌破低位后再次上穿时,被视为市场离开超卖区域的信号,策略开空仓。
- 在开新仓位之前,策略会关闭现有的反向仓位。
参数
- WPR Period – 威廉指标 %R 的计算周期。
- High Level – 超买区域阈值。
- Low Level – 超卖区域阈值。
- Candle Type – 用于计算的K线类型和时间周期。
说明
该策略仅使用市价单,不设置止损或止盈。仓位大小由用户设置的 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()