在 GitHub 上查看

Averaged Stoch & WPR 策略

该策略将随机指标 (Stochastic) 与威廉指标 (Williams %R) 结合,用于识别市场的极端超买和超卖状态。 当随机指标低于 0.1 且 Williams %R 低于 -90 时开多单,表示市场严重超卖。 当随机指标高于 99.9 且 Williams %R 高于 -5 时开空单,表示市场严重超买。

策略适用于所选蜡烛类型支持的任何品种和周期,可进行多空交易,并提供可选的百分比止损以控制风险。

细节

  • 入场条件
    • 做多:Stochastic < 0.1 且 Williams %R < -90。
    • 做空:Stochastic > 99.9 且 Williams %R > -5。
  • 多空方向:双向。
  • 出场条件:反向信号或触发止损。
  • 止损:可选百分比止损。
  • 指标
    • 随机指标(默认周期 26)。
    • Williams %R(默认周期 26)。

参数

  • StochPeriod – 随机指标周期。
  • WprPeriod – Williams %R 周期。
  • StopLossPercent – 百分比止损大小。
  • CandleType – 用于计算指标的蜡烛类型。
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 using RSI and Williams %R for oversold/overbought entries.
/// </summary>
public class AveragedStochWprStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<int> _wprPeriod;
	private readonly StrategyParam<DataType> _candleType;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public int WprPeriod { get => _wprPeriod.Value; set => _wprPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public AveragedStochWprStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI period", "Indicators");
		_wprPeriod = Param(nameof(WprPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("WPR Period", "Williams %R period", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		var wpr = new WilliamsR { Length = WprPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(rsi, wpr, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal wpr)
	{
		if (candle.State != CandleStates.Finished)
			return;

		// Buy: RSI oversold + WPR oversold
		if (rsi < 30 && wpr < -80 && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Sell: RSI overbought + WPR overbought
		else if (rsi > 70 && wpr > -20 && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}
		// Exit
		else if (Position > 0 && rsi > 65)
			SellMarket();
		else if (Position < 0 && rsi < 35)
			BuyMarket();
	}
}