GitHub で見る

ChannelEA2戦略

概要

ChannelEA2戦略はStockSharpでMetaTraderのエキスパート「ChannelEA2」を再現します。戦略は設定されたセッション開始時と終了時刻の間のイントラデイ価格チャネルを構築します。セッション終了時、チャネルの高値の上と安値の下にストップ注文を出します。各ストップ注文は、チャネルの反対側の端で定義された保護ストップロスを持ちます。このアプローチはセッションウィンドウ中の統合期間後のブレイクアウトを捉えることを目指しています。

取引ロジック

  • 開始時刻が BeginHour を超える最初の完了したローソク足で、戦略はセッションをリセットします。
    • 全てのオープンポジションは成行注文でクローズされます。
    • 以前のストップエントリーや保護ストップを含む全てのアクティブな注文がキャンセルされます。
    • セッションの高値と安値は新しいセッション内の最初のローソク足を使って初期化されます。
  • セッション中(BeginHour から EndHour まで)、完了した各ローソク足の高値と安値がチャネルの境界を更新します。
  • セッション終了(EndHour)後に開く最初のローソク足で、戦略は以下を計算します:
    • 記録されたセッション高値に価格ステップで測定されたオプションのバッファを加えた位置での買いストップ注文。
    • 記録されたセッション安値から同じバッファを引いた位置での売りストップ注文。
    • 買い注文のストップロスはセッション安値で、売り注文のストップロスはセッション高値です。
  • ポジションが開かれると、反対側のエントリー注文がキャンセルされ、格納されたストップレベルを使って市場に保護ストップが登録されます。
  • 注文は次のセッション開始まで有効で、その時にすべてがリセットされます。

パラメーター

名前 説明 デフォルト
BeginHour セッションがリセットされてチャネルがデータ収集を開始する時刻(0-23)。 1
EndHour ストップ注文がスケジュールされる時刻(0-23)。BeginHour > EndHour の場合は夜間セッションをサポートします。 10
TradeVolume 各エントリー注文に使用されるボリューム。 1
CandleType チャネルを構築するために使用されるローソク足シリーズ(デフォルト1時間ローソク足)。 1時間
StopBufferMultiplier エントリー有効化と保護ストップのための安全バッファとして使用される銘柄価格ステップの乗数。 2

リスク管理

  • 戦略は自動的に StartProtection() を呼び出し、StockSharpに予期しないポジションを管理させます。
  • 保護ストップ注文はポジションが出現した直後に送信されます。ポジションがゼロに戻るとキャンセルされます。
  • ストップ価格は取引所のストップ距離制限に違反しないよう StopBufferMultiplier * PriceStep だけオフセットされます。

追加メモ

  • チャネルレンジはストップ注文が生成されると凍結されます。後続のローソク足は次のセッション開始までエントリーレベルに影響しません。
  • 銘柄に PriceStep が定義されていない場合、バッファは無視されてチャネルの正確なレベルで注文が出されます。
  • ボリューム値は小数で、ブローカーがサポートする場合は分数コントラクトまたはロットを許可します。
  • 戦略はビジュアルトラッキングのためにチャートエリアにローソク足と実行済みトレードを描画します。
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>
/// Breakout strategy that places stop orders at the extremes of the intraday channel.
/// </summary>
public class ChannelEa2Strategy : Strategy
{
	private readonly StrategyParam<int> _beginHour;
	private readonly StrategyParam<int> _endHour;
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _stopBufferMultiplier;

	private decimal? _sessionHigh;
	private decimal? _sessionLow;
	private bool _channelReady;
	private decimal? _entryPrice;
	private decimal? _stopLossPrice;

	/// <summary>
	/// Trading session start hour.
	/// </summary>
	public int BeginHour
	{
		get => _beginHour.Value;
		set => _beginHour.Value = value;
	}

	/// <summary>
	/// Trading session end hour.
	/// </summary>
	public int EndHour
	{
		get => _endHour.Value;
		set => _endHour.Value = value;
	}

	/// <summary>
	/// Order volume.
	/// </summary>
	public decimal TradeVolume
	{
		get => _tradeVolume.Value;
		set => _tradeVolume.Value = value;
	}

	/// <summary>
	/// Candle type used for channel detection.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Number of price steps added as a buffer to entry and protective orders.
	/// </summary>
	public decimal StopBufferMultiplier
	{
		get => _stopBufferMultiplier.Value;
		set => _stopBufferMultiplier.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="ChannelEa2Strategy"/> class.
	/// </summary>
	public ChannelEa2Strategy()
	{
		_beginHour = Param(nameof(BeginHour), 1)
			.SetDisplay("Begin Hour", "Hour when the session resets", "Trading")
			
			.SetOptimize(0, 23, 1);

		_endHour = Param(nameof(EndHour), 10)
			.SetDisplay("End Hour", "Hour when breakout orders are scheduled", "Trading")
			
			.SetOptimize(0, 23, 1);

		_tradeVolume = Param(nameof(TradeVolume), 1m)
			.SetDisplay("Volume", "Order volume", "Trading")
			.SetGreaterThanZero();

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Time frame used for the channel", "General");

		_stopBufferMultiplier = Param(nameof(StopBufferMultiplier), 2m)
			.SetDisplay("Stop Buffer", "Price step multiplier for safety offsets", "Risk")
			.SetNotNegative();
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_sessionHigh = null;
		_sessionLow = null;
		_channelReady = false;
		_entryPrice = null;
		_stopLossPrice = null;
	}

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

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

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

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

		var hour = candle.OpenTime.Hour;

		// During channel-building hours, accumulate the range.
		if (hour >= BeginHour && hour < EndHour)
		{
			if (_sessionHigh is null || candle.HighPrice > _sessionHigh)
				_sessionHigh = candle.HighPrice;
			if (_sessionLow is null || candle.LowPrice < _sessionLow)
				_sessionLow = candle.LowPrice;
			_channelReady = true;
			return;
		}

		// Outside the channel window, attempt breakout entries.
		if (!_channelReady || _sessionHigh is not decimal high || _sessionLow is not decimal low || high <= low)
			return;

		var buffer = GetPriceBuffer();

		// Manage existing positions.
		if (Position > 0)
		{
			if (_stopLossPrice.HasValue && candle.LowPrice <= _stopLossPrice.Value)
			{
				SellMarket(Position);
				_entryPrice = null;
				_stopLossPrice = null;
			}
			return;
		}
		else if (Position < 0)
		{
			if (_stopLossPrice.HasValue && candle.HighPrice >= _stopLossPrice.Value)
			{
				BuyMarket(Math.Abs(Position));
				_entryPrice = null;
				_stopLossPrice = null;
			}
			return;
		}

		// Long breakout: price exceeds channel high.
		if (candle.HighPrice > high + buffer)
		{
			BuyMarket(TradeVolume > 0 ? TradeVolume : Volume);
			_entryPrice = candle.ClosePrice;
			_stopLossPrice = low - buffer;
			// Reset channel for next session.
			_sessionHigh = null;
			_sessionLow = null;
			_channelReady = false;
			return;
		}

		// Short breakout: price drops below channel low.
		if (candle.LowPrice < low - buffer)
		{
			SellMarket(TradeVolume > 0 ? TradeVolume : Volume);
			_entryPrice = candle.ClosePrice;
			_stopLossPrice = high + buffer;
			_sessionHigh = null;
			_sessionLow = null;
			_channelReady = false;
		}
	}

	private decimal GetPriceBuffer()
	{
		var step = Security?.PriceStep ?? 0m;
		if (step <= 0m || StopBufferMultiplier <= 0m)
			return 0m;

		return step * StopBufferMultiplier;
	}
}