在 GitHub 上查看

XRVI Crossover 策略

XRVI Crossover 策略基于扩展的相对活力指数 XRVI。 XRVI 通过对 RVI 进行平滑处理并再次应用移动平均来生成信号线。 当 XRVI 向上穿越信号线时做多,向下穿越时做空。 出现反向信号时会反转持仓。

细节

  • 入场条件:XRVI 与信号线的交叉
  • 多/空:双向
  • 出场条件:反向交叉
  • 止损:无
  • 默认参数
    • RviLength = 10
    • SignalLength = 5
    • CandleType = H4 时间框
  • 过滤器
    • 分类:震荡指标
    • 方向:双向
    • 指标:Relative Vigor Index, Simple Moving Average
    • 止损:无
    • 复杂度:基础
    • 时间框:日内
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险等级:中等
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>
/// XRVI crossover strategy.
/// Buys when RVI Average crosses above Signal, sells when it crosses below.
/// </summary>
public class XrviCrossoverStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevAvg;
	private decimal? _prevSig;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public XrviCrossoverStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevAvg = null;
		_prevSig = null;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rvi = new RelativeVigorIndex();

		SubscribeCandles(CandleType)
			.BindEx(rvi, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue rviValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		var value = (IRelativeVigorIndexValue)rviValue;
		if (value.Average is not decimal avg || value.Signal is not decimal sig)
			return;

		if (_prevAvg is not null && _prevSig is not null)
		{
			var crossUp = _prevAvg <= _prevSig && avg > sig;
			var crossDown = _prevAvg >= _prevSig && avg < sig;

			if (crossUp && Position <= 0)
			{
				if (Position < 0) BuyMarket();
				BuyMarket();
			}
			else if (crossDown && Position >= 0)
			{
				if (Position > 0) SellMarket();
				SellMarket();
			}
		}

		_prevAvg = avg;
		_prevSig = sig;
	}
}