在 GitHub 上查看

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;
	}
}