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 – 移動平均アルゴリズム: SimpleExponentialSmma、または Weighted。デフォルトは 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;
	}
}