在 GitHub 上查看

高级多季节性策略

该策略根据预设的季节性周期进行交易。最多可配置四个周期,每个周期拥有独立的入场日期、持有天数和方向。

详情

  • 入场条件:日历日期与设置的周期匹配
  • 多空方向:双向
  • 出场条件:达到持有天数
  • 止损:无
  • 默认值
    • CandleType = 1 day
  • 过滤器
    • 类别:季节性
    • 方向:双向
    • 指标:无
    • 止损:无
    • 复杂度:初级
    • 时间框架:日线
    • 季节性:是
    • 神经网络:否
    • 背离:否
    • 风险级别:中等
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>
/// Strategy that trades during predefined seasonal periods.
/// Enters periodically and holds for a configured number of bars.
/// </summary>
public class AdvancedMultiSeasonalityStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _holdingBars;
	private readonly StrategyParam<int> _cooldownBars;

	private ExponentialMovingAverage _ema1;
	private ExponentialMovingAverage _ema2;
	private int _barIndex;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int HoldingBars { get => _holdingBars.Value; set => _holdingBars.Value = value; }
	public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }

	public AdvancedMultiSeasonalityStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
		_holdingBars = Param(nameof(HoldingBars), 100)
			.SetGreaterThanZero()
			.SetDisplay("Holding Bars", "Bars to hold position", "General");
		_cooldownBars = Param(nameof(CooldownBars), 50)
			.SetGreaterThanZero()
			.SetDisplay("Cooldown Bars", "Bars between trades", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_ema1 = null;
		_ema2 = null;
		_barIndex = 0;
	}

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

		_ema1 = new ExponentialMovingAverage { Length = 10 };
		_ema2 = new ExponentialMovingAverage { Length = 30 };

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(_ema1, _ema2, ProcessCandle).Start();
	}

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

		_barIndex++;

		if (_barIndex > HoldingBars && Position > 0)
		{
			SellMarket();
			return;
		}

		if (Position == 0 && _barIndex > CooldownBars)
		{
			BuyMarket();
			_barIndex = 0;
		}
	}
}