在 GitHub 上查看

箭头与曲线策略

概述

该策略是 MQL5 专家顾问 Exp_Arrows_Curves 的移植版本。 它使用最近的最高价和最低价构建动态价格通道,并对突破做出 反应。策略可根据用户权限和趋势方向开仓或平仓。

策略逻辑

  • 在设定周期内计算最高价和最低价。
  • 按百分比扩展区间以形成外部通道线。
  • 使用额外的百分比创建内部止损线。
  • 当价格突破上轨时做多,跌破下轨时做空。
  • 当价格穿越内部止损线的另一侧时平仓。

参数

  • SspPeriod – 计算高低点的周期。
  • Channel – 主要通道线的扩展百分比。
  • StopChannel – 内部止损线的附加百分比。
  • CandleType – K 线时间框架。
  • BuyPosOpen / SellPosOpen – 允许开多/开空。
  • BuyPosClose / SellPosClose – 允许平多/平空。

指标

  • Highest
  • Lowest

说明

策略仅在已完成的 K 线上运行。未包含止损和止盈管理,退出依靠 通道穿越信号。

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 midpoint crossing.
/// </summary>
public class ArrowsCurvesStrategy : Strategy
{
	private readonly StrategyParam<int> _period;
	private readonly StrategyParam<DataType> _candleType;

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

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

	public ArrowsCurvesStrategy()
	{
		_period = Param(nameof(Period), 20)
			.SetGreaterThanZero()
			.SetDisplay("Period", "Channel period", "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 = Period };
		var lowest = new Lowest { Length = Period };

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

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

		if (!_hasPrev)
		{
			_prevHigh = high;
			_prevLow = low;
			_hasPrev = true;
			return;
		}

		var close = candle.ClosePrice;

		if (close > _prevHigh && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (close < _prevLow && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevHigh = high;
		_prevLow = low;
	}
}