在 GitHub 上查看

PZ Reversal Trend Following 反转趋势跟踪

该策略跟随长期高点和低点的突破。当收盘价超过设定周期内的最高点时做多,当收盘价跌破最低点时做空。出现相反信号时头寸会反转,因此策略始终保持在市场中。

该方法试图在显著突破后捕捉持续趋势。由于只在关键极值附近交易,它能够过滤部分噪音,但在震荡市中可能出现较大回撤。

详情

  • 入场条件: 突破前 Period 根K线的高/低点
  • 多空方向: 双向,始终在场
  • 退出条件: 相反的突破信号
  • 止损: 无
  • 默认值:
    • Period = 100
    • Volume = 1m
    • CandleType = TimeSpan.FromDays(1)
  • 过滤器:
    • 类型: 趋势
    • 方向: 双向
    • 指标: Highest, Lowest
    • 止损: 无
    • 复杂度: 基础
    • 时间框架: 日线
    • 季节性: 无
    • 神经网络: 无
    • 背离: 无
    • 风险等级: 中
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>
/// Breakout strategy using Highest/Lowest channels.
/// </summary>
public class PzReversalTrendFollowingStrategy : Strategy
{
	private readonly StrategyParam<int> _period;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevHighest;
	private decimal _prevLowest;
	private bool _hasPrev;

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

	public PzReversalTrendFollowingStrategy()
	{
		_period = Param(nameof(Period), 30)
			.SetGreaterThanZero()
			.SetDisplay("Period", "Lookback period for breakout", "General");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevHighest = 0;
		_prevLowest = 0;
		_hasPrev = false;
	}

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

		var highest = new Highest { Length = Period };
		var lowest = new Lowest { Length = Period };

		SubscribeCandles(CandleType)
			.Bind(highest, lowest, ProcessCandle)
			.Start();
	}

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

		if (!_hasPrev)
		{
			_prevHighest = highestValue;
			_prevLowest = lowestValue;
			_hasPrev = true;
			return;
		}

		if (candle.ClosePrice > _prevHighest && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (candle.ClosePrice < _prevLowest && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevHighest = highestValue;
		_prevLowest = lowestValue;
	}
}