在 GitHub 上查看

BrakeExp通道策略

该策略基于 BrakeExp 指标进行交易,该指标在价格周围构建指数通道。当价格突破动态通道边界时,指标在多空模式之间切换并生成买入或卖出信号。

工作原理

  • 指标维护一条跟随价格的指数曲线。
  • 当曲线位于价格下方(上升趋势)时,策略寻找买入信号。
  • 当曲线位于价格上方(下降趋势)时,策略寻找卖出信号。
  • 从一个模式切换到另一个模式时,会在新方向生成入场信号并平掉相反头寸。

参数

  • Candle Type – 处理的K线周期。
  • Volume – 市价单的下单量。
  • AB – 决定BrakeExp曲线形状的参数。
  • Buy Open / Sell Open – 是否允许开多或开空。
  • Buy Close / Sell Close – 是否允许平空或平多。

说明

本实现仅关注BrakeExp指标的核心逻辑,不包含止损或止盈管理。如有需要,可增加额外的风险控制。

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 EMA and price crossover.
/// </summary>
public class BrakeExpChannelStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _emaPeriod;

	private decimal _prevClose;
	private decimal _prevEma;
	private bool _hasPrev;

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

	public BrakeExpChannelStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA period", "Indicators");
	}

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

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

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

		var ema = new ExponentialMovingAverage { Length = EmaPeriod };

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

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevEma = emaVal;
			_hasPrev = true;
			return;
		}

		var crossUp = _prevClose <= _prevEma && close > emaVal;
		var crossDown = _prevClose >= _prevEma && close < emaVal;

		if (crossUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (crossDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevClose = close;
		_prevEma = emaVal;
	}
}