在 GitHub 上查看

Hardcore FX Breakout

该策略改编自 MetaTrader 的 "HardcoreFX" 专家顾问。策略跟踪 ZigZag 的高点和低点,当价格突破这些水平时开仓。它使用固定的止损和止盈,并通过跟踪止损来保护已有利润。

细节

  • 入场条件:收盘价突破最近的 ZigZag 高点做多;收盘价跌破最近的 ZigZag 低点做空。
  • 方向:双向。
  • 出场条件:触发止损、止盈或跟踪止损。
  • 止损:固定止损、止盈和跟踪止损。
  • 默认值
    • ZigzagLength = 17
    • StopLoss = 1400
    • TakeProfit = 5400
    • TrailingStop = 500
    • CandleType = TimeSpan.FromMinutes(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>
/// Channel breakout strategy using Highest/Lowest.
/// </summary>
public class HardcoreFxStrategy : Strategy
{
	private readonly StrategyParam<int> _channelPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevHigh;
	private decimal _prevLow;
	private bool _hasPrev;

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

	public HardcoreFxStrategy()
	{
		_channelPeriod = Param(nameof(ChannelPeriod), 12)
			.SetGreaterThanZero()
			.SetDisplay("Channel Period", "Highest/Lowest lookback", "Parameters");
		_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();
		_prevHigh = 0;
		_prevLow = 0;
		_hasPrev = false;
	}

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

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

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

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

		if (!_hasPrev)
		{
			_prevHigh = highVal;
			_prevLow = lowVal;
			_hasPrev = true;
			return;
		}

		// Buy when close breaks above previous channel high
		if (candle.ClosePrice > _prevHigh && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Sell when close breaks below previous channel low
		else if (candle.ClosePrice < _prevLow && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevHigh = highVal;
		_prevLow = lowVal;
	}
}