在 GitHub 上查看

Close Cross MA Strategy

该策略监控简单移动平均线,当收盘价穿越均线时自动平掉当前持仓。它适用于使用其他系统或手动开仓的交易者,用于在趋势反转时自动退出。

策略跟踪收盘价与均线的关系。当新的已完成K线从均线上方穿到下方或相反时,策略发送市价单以平仓,不会开立新的仓位。

细节

  • 入场条件:无,仓位需外部建立。
  • 出场条件
    • 多头:前一根K线在均线上方,当前K线收盘于均线下方,则卖出平仓。
    • 空头:前一根K线在均线下方,当前K线收盘于均线上方,则买入平仓。
  • 多空:同时支持。
  • 止损:无,均线穿越即为退出信号。
  • 默认值
    • MA Period = 50。
    • Candle Type = 1分钟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>
/// Price cross MA strategy.
/// </summary>
public class CloseCrossMaStrategy : Strategy
{
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevDiff;
	private bool _hasPrev;

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

	public CloseCrossMaStrategy()
	{
		_maPeriod = Param(nameof(MaPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("MA Period", "EMA 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();
		_prevDiff = 0;
		_hasPrev = false;
	}

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

		var ema = new ExponentialMovingAverage { Length = MaPeriod };

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

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

		var diff = candle.ClosePrice - emaVal;

		if (!_hasPrev)
		{
			_prevDiff = diff;
			_hasPrev = true;
			return;
		}

		// Price crosses above EMA
		if (_prevDiff <= 0 && diff > 0 && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Price crosses below EMA
		else if (_prevDiff >= 0 && diff < 0 && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevDiff = diff;
	}
}