在 GitHub 上查看

自适应市场水平

基于自适应市场水平(Adaptive Market Level,AML)指标的策略。该指标根据当前波动率动态调整价格水平。当AML线转向上时开多单,转向下时开空单。出现反向颜色变化或触发止损/止盈时平仓。

系统跟随中期趋势,默认在较高时间框架上运行。

细节

  • 入场条件:AML线向上转折做多,向下转折做空。
  • 多空方向:双向。
  • 退出条件:AML方向改变或到达止损/止盈。
  • 止损:有。
  • 默认参数
    • Fractal = 6
    • Lag = 7
    • StopLossTicks = 1000
    • TakeProfitTicks = 2000
    • BuyPosOpen = true
    • SellPosOpen = true
    • BuyPosClose = true
    • SellPosClose = true
    • CandleType = TimeSpan.FromHours(4)
  • 过滤器
    • 类别: 趋势
    • 方向: 双向
    • 指标: Adaptive Market Level
    • 止损: 有
    • 复杂度: 中等
    • 时间框架: H4
    • 季节性: 无
    • 神经网络: 无
    • 背离: 无
    • 风险级别: 中等
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>
/// Adaptive market level strategy using SMA slope direction changes.
/// </summary>
public class AdaptiveMarketLevelStrategy : Strategy
{
	private readonly StrategyParam<int> _period;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevSma;
	private decimal _prevPrevSma;
	private int _count;

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

	public AdaptiveMarketLevelStrategy()
	{
		_period = Param(nameof(Period), 14)
			.SetGreaterThanZero()
			.SetDisplay("Period", "SMA period", "Indicator");

		_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();
		_prevSma = 0;
		_prevPrevSma = 0;
		_count = 0;
	}

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

		var sma = new SimpleMovingAverage { Length = Period };

		SubscribeCandles(CandleType)
			.Bind(sma, ProcessCandle)
			.Start();
	}

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

		_count++;

		if (_count < 3)
		{
			_prevPrevSma = _prevSma;
			_prevSma = smaValue;
			return;
		}

		var turnUp = _prevSma < _prevPrevSma && smaValue > _prevSma;
		var turnDown = _prevSma > _prevPrevSma && smaValue < _prevSma;

		if (turnUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (turnDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevPrevSma = _prevSma;
		_prevSma = smaValue;
	}
}