在 GitHub 上查看

MLTrendE 策略

该策略沿加权移动平均线(WMA)的方向交易,并在价格有利时加仓。

逻辑

  • 计算所选 K 线序列的 WMA。
  • 当没有持仓时:
    • 类型 0:收盘价高于 WMA 时做多,低于 WMA 时做空。
    • 类型 1:始终做多。
    • 类型 2:始终做空。
  • 当持仓达到设定的盈利目标时,按比例增加新的交易。
  • 达到最大交易数量后,在下一次达到盈利目标时全部平仓。

参数

  • Volume – 基础交易量。
  • Multiplier1 – 第二笔交易的量倍数。
  • Multiplier2 – 第三笔交易的量倍数。
  • TakeProfit – 触发加仓或平仓的盈利点数。
  • Map – 加权移动平均的周期。
  • MaxTrades – 连续交易的最大数量。
  • TradeType – 0 顺势,1 只做多,2 只做空。
  • CandleType – 分析所用 K 线的时间框架。

备注

该策略仅使用收盘完成的 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>
/// Weighted moving average trend strategy.
/// Buys when close crosses above WMA, sells when below.
/// </summary>
public class MLTrendEStrategy : Strategy
{
	private readonly StrategyParam<int> _wmaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevWma;
	private bool _hasPrev;

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

	public MLTrendEStrategy()
	{
		_wmaPeriod = Param(nameof(WmaPeriod), 34)
			.SetGreaterThanZero()
			.SetDisplay("WMA Length", "Weighted moving average period", "Indicators");

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

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevClose = 0;
		_prevWma = 0;
		_hasPrev = false;
	}

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

		var wma = new WeightedMovingAverage { Length = WmaPeriod };
		SubscribeCandles(CandleType).Bind(wma, ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevWma = wmaValue;
			_hasPrev = true;
			return;
		}

		// Cross above WMA
		if (_prevClose <= _prevWma && close > wmaValue && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Cross below WMA
		else if (_prevClose >= _prevWma && close < wmaValue && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevClose = close;
		_prevWma = wmaValue;
	}
}