在 GitHub 上查看

Levels With Trail 策略

该策略根据用户设定的价格水平进行交易,并可选择在盈利时跟踪止损。此实现基于 MQL 脚本 levels_with_trail.mq4

工作原理

  • 订阅所选时间框的蜡烛。
  • 当没有持仓且收盘价上穿 Level Price 时买入,下穿时卖出。
  • 若启用 Trail Stop,当行情向有利方向发展时,止损价会跟随移动。
  • 持仓在达到止损、止盈或出现反向突破信号时平仓。

参数

  • Stop Loss – 止损距离(价格单位)。
  • Take Profit – 止盈距离(价格单位)。
  • Level Price – 用于触发进场的价格水平。
  • Trail Stop – 是否启用跟踪止损。
  • Candle Type – 用于分析的蜡烛类型。
using System;
using System.Collections.Generic;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy trading price level breakouts with trailing stop loss.
/// Uses SMA as dynamic level, enters on breakout, trails stop on winning positions.
/// </summary>
public class LevelsWithTrailStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<decimal> _trailPct;

	private decimal _entryPrice;
	private decimal _bestPrice;
	private decimal _prevPrice;
	private decimal _prevMa;
	private bool _hasPrev;

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

	public int MaPeriod
	{
		get => _maPeriod.Value;
		set => _maPeriod.Value = value;
	}

	public decimal TrailPct
	{
		get => _trailPct.Value;
		set => _trailPct.Value = value;
	}

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

		_maPeriod = Param(nameof(MaPeriod), 50)
			.SetDisplay("MA Period", "Moving average period for level", "Parameters");

		_trailPct = Param(nameof(TrailPct), 1m)
			.SetDisplay("Trail %", "Trailing stop percent", "Risk");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_entryPrice = 0;
		_bestPrice = 0;
		_prevPrice = 0;
		_prevMa = 0;
		_hasPrev = false;
	}

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

		_entryPrice = 0;
		_bestPrice = 0;
		_prevPrice = 0;
		_prevMa = 0;
		_hasPrev = false;

		var ma = new ExponentialMovingAverage { Length = MaPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(ma, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, ma);
			DrawOwnTrades(area);
		}
	}

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

		var price = candle.ClosePrice;

		// Trailing stop management
		if (Position > 0)
		{
			if (price > _bestPrice)
				_bestPrice = price;

			var stopLevel = _bestPrice * (1 - TrailPct / 100m);
			if (price <= stopLevel)
			{
				SellMarket();
				_entryPrice = 0;
			}
		}
		else if (Position < 0)
		{
			if (price < _bestPrice)
				_bestPrice = price;

			var stopLevel = _bestPrice * (1 + TrailPct / 100m);
			if (price >= stopLevel)
			{
				BuyMarket();
				_entryPrice = 0;
			}
		}

		if (!_hasPrev)
		{
			_prevPrice = price;
			_prevMa = maValue;
			_hasPrev = true;
			return;
		}

		// Entry: price crosses above MA
		if (_prevPrice < _prevMa && price >= maValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();
			BuyMarket();
			_entryPrice = price;
			_bestPrice = price;
		}
		// Entry: price crosses below MA
		else if (_prevPrice > _prevMa && price <= maValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();
			SellMarket();
			_entryPrice = price;
			_bestPrice = price;
		}

		_prevPrice = price;
		_prevMa = maValue;
	}
}