在 GitHub 上查看

平滑蜡烛策略

该策略基于平滑蜡烛的颜色进行交易。对于每个完成的蜡烛,计算收盘价与开盘价之差并通过移动平均线平滑。当平滑后的差值改变符号时,蜡烛颜色发生切换,策略相应反转头寸。

逻辑

  1. 订阅可配置的蜡烛序列。
  2. 计算每个完成蜡烛的 diff = close - open
  3. 使用选定的移动平均线平滑 diff
  4. 判断颜色:
    • smoothed diff > 0 时为 颜色 0(收盘高于开盘)。
    • 否则为 颜色 1
  5. 生成信号:
    • 颜色从 0 变为 1 时 买入
    • 颜色从 1 变为 0 时 卖出
  6. 开仓前先平掉当前持仓。

参数

  • CandleType – 处理蜡烛的时间框架,默认 1 小时。
  • MaLength – 平滑移动平均的长度,默认 30。
  • MaMethods – 移动平均算法:SimpleExponentialSmmaWeighted,默认 Weighted

说明

  • 策略通过 BuyMarketSellMarket 发送市价单。
  • 使用高级 API 进行蜡烛订阅和图表可视化。
  • 指标值通过 TryGetValue 获取,避免直接访问缓冲区。
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy based on smoothed candle body direction.
/// Smooths (close-open) with WMA, trades on color changes.
/// </summary>
public class CandlesSmoothedStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _maLength;

	private WeightedMovingAverage _ma;
	private int? _prevColor;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }

	public CandlesSmoothedStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Time frame", "General");

		_maLength = Param(nameof(MaLength), 30)
			.SetGreaterThanZero()
			.SetDisplay("MA Length", "Moving average smoothing length", "Indicator");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_ma = null;
		_prevColor = null;
	}

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

		_ma = new WeightedMovingAverage { Length = MaLength };
		Indicators.Add(_ma);

		// Use a dummy EMA for warmup binding
		var warmup = new ExponentialMovingAverage { Length = MaLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(warmup, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);
		}
	}

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

		// Calculate close-open diff and smooth with WMA
		var diff = candle.ClosePrice - candle.OpenPrice;
		var maResult = _ma.Process(new DecimalIndicatorValue(_ma, diff, candle.OpenTime) { IsFinal = true });

		if (!maResult.IsFormed)
			return;

		var smoothed = maResult.GetValue<decimal>();
		var color = smoothed > 0m ? 0 : 1;

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_prevColor = color;
			return;
		}

		if (_prevColor is int prev)
		{
			// Color change from negative to positive -> buy
			if (color == 1 && prev == 0 && Position <= 0)
				BuyMarket();
			// Color change from positive to negative -> sell
			else if (color == 0 && prev == 1 && Position >= 0)
				SellMarket();
		}

		_prevColor = color;
	}
}