GitHub で見る

ローソク足戦略 (Candle)

概要

ローソク足戦略 (Candle) は、MT5の古典的エキスパート「Candle.mq5」の直接移植版です。選択した時間軸上の完成したローソク足の色を評価し、最新の終値に合わせてポジションを維持します。強気のローソク足はロングポジションへ、弱気のローソク足はショートポジションへ、十字線はポジションをそのままにします。リスクはpip単位のテイクプロフィットとトレーリングストップの距離で管理され、インストゥルメントのティックサイズを通じて絶対価格に換算されます。

戦略はバー内のノイズを避けるため、ローソク足が完全に形成された後にのみ反応します。必須のルックバック(MinBars * 2本の完成したローソク足)によりチャートに十分な履歴があることを検証し、設定可能なクールダウンが取引操作の間に待機します。これにより、低レベルシリーズアクセスに依存することなく、オリジナルのMetaTraderロジックを忠実にStockSharpで実装できます。

トレーディングロジック

準備

  • CandleTypeが提供するローソク足を処理します。他のデータソースは不要です。
  • エントリーを許可する前に、少なくとも2 * MinBars本の完成したローソク足が処理されるまで待機します。
  • 戦略がオンライン状態で、形成されており、注文実行が許可されている場合にのみ取引します。
  • 任意の2つの取引操作の間にTradeCooldownインターバル(デフォルト: 10秒)を強制します。

エントリーと反転のルール

  1. フラット状態:
    • ローソク足が始値より高く終値した場合、ロング(BuyMarket)エントリー。
    • ローソク足が始値より低く終値した場合、ショート(SellMarket)エントリー。
  2. 既存ポジション:
    • ロングポジション保有中に弱気のローソク足が出たら、|Position| + Volumeを売却してポジションを閉じ、すぐにVolumeサイズのショートポジションに反転。
    • ショートポジション保有中に強気のローソク足が出たら、|Position| + Volumeを購入してポジションを閉じ、すぐにVolumeサイズのロングポジションに反転。
  3. ニュートラルなローソク足:
    • 終値が始値と同じ場合、手動操作は行わず、保護注文のみが取引を終了できます。

リスク管理とエグジット

  • StartProtectionはpipで測定されたテイクプロフィットとトレーリングストップを設定します。戦略は各pip値に(PriceStep * 10)を掛けて、3桁および5桁クォートに対するMetaTraderの調整に合わせます。
  • トレーリングストップはTrailingStopPipsがゼロより大きい場合にのみ有効化され、取引が有利な方向に動くと自動的に価格を追跡します。
  • テイクプロフィットは設定された距離に達するとポジションを閉じます。いずれかの保護レベルが執行された後、反対の注文はキャンセルされます。
  • ローソク足の色による手動反転も、新しいポジションを開く前に以前のエクスポージャーを解消します。

パラメーター

  • CandleType – 分析するローソク足シリーズの時間軸(デフォルト: 15分ローソク足)。
  • TakeProfitPips – テイクプロフィット目標までの距離(pip単位、デフォルト: 50)。
  • TrailingStopPips – トレーリングストップの距離(pip単位、デフォルト: 30)。
  • MinBars – 最初の取引前に必要な最小バー数(デフォルト: 26; 戦略は52本の完成したローソク足を待機)。
  • TradeCooldown – 任意の取引アクション後の待機期間(デフォルト: 10秒)。

戦略のVolumeプロパティを希望の注文サイズに設定します。市場が反転した場合、戦略は前のポジションを終了し、新しいポジションを確立するのに十分なボリュームを自動的に送信します。

実装メモ

  • 完成したローソク足(CandleStates.Finished)のみが処理されます。これはCopyOpen/CopyCloseで取得した終値バーのデータに依存したMetaTraderエキスパートを反映しています。
  • コードはStockSharpの高レベルAPIを使用します: データにはSubscribeCandles、受信バーの処理にはBind、注文執行にはBuyMarket/SellMarket
  • 保護注文はStartProtectionによって管理されるため、手動でのストップリミット注文の管理は不要です。
  • pip サイズ計算PriceStep * 10は、3桁または5桁の小数点以下で表示されるシンボルに対するMQLの「digits adjust」ロジックを再現します。
  • エントリーは最新のローソク足の実体によって引き起こされるため、戦略は継続的に市場に存在し、ローソク足の色が変わるたびにサイドを交互に変える傾向があります。

取引するインストゥルメントに合わせてpip距離、クールダウン、時間軸を調整してください。デフォルト設定はオリジナルのMT5サンプルを反映していますが、StockSharpのパラメーターフレームワークを通じて最適化できます。

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>
/// Candle color reversal strategy with pip-based protection and trade cooldown.
/// </summary>
public class CandleStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<int> _minBars;
	private readonly StrategyParam<TimeSpan> _tradeCooldown;

	private decimal _pipSize;
	private int _finishedCandles;
	private DateTimeOffset _nextAllowedTime;

	/// <summary>
	/// Initializes a new instance of the <see cref="CandleStrategy"/>.
	/// </summary>
	public CandleStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General");

		_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
			.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
			.SetGreaterThanZero();

		_trailingStopPips = Param(nameof(TrailingStopPips), 30m)
			.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
			.SetGreaterThanZero();

		_minBars = Param(nameof(MinBars), 26)
			.SetDisplay("Minimum Bars", "History length required before trading", "General")
			.SetGreaterThanZero();

		_tradeCooldown = Param(nameof(TradeCooldown), TimeSpan.FromSeconds(10))
			.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk");
	}

	/// <summary>
	/// Candle type and timeframe used by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Take profit distance expressed in pips.
	/// </summary>
	public decimal TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Trailing stop distance expressed in pips.
	/// </summary>
	public decimal TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	/// <summary>
	/// Minimum number of bars required on the chart.
	/// </summary>
	public int MinBars
	{
		get => _minBars.Value;
		set => _minBars.Value = value;
	}

	/// <summary>
	/// Cooldown between consecutive trading operations.
	/// </summary>
	public TimeSpan TradeCooldown
	{
		get => _tradeCooldown.Value;
		set => _tradeCooldown.Value = value;
	}

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

		_pipSize = 0m;
		_finishedCandles = 0;
		_nextAllowedTime = DateTimeOffset.MinValue;
	}

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

		_pipSize = (Security?.PriceStep ?? 1m) * 10m;

		Unit takeProfit = TakeProfitPips > 0m && _pipSize > 0m
			? new Unit(TakeProfitPips * _pipSize, UnitTypes.Absolute)
			: null;

		Unit trailingStop = TrailingStopPips > 0m && _pipSize > 0m
			? new Unit(TrailingStopPips * _pipSize, UnitTypes.Absolute)
			: null;

		// Enable automatic protective orders and trailing stop handling.
		if (trailingStop != null || takeProfit != null)
			StartProtection(takeProfit, trailingStop);

		// Subscribe to candle data for the configured timeframe.
		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(ProcessCandle)
			.Start();

		// Draw candles and executions on the chart if visualization is available.
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle)
	{
		// Skip unfinished candles to work only with final prices.
		if (candle.State != CandleStates.Finished)
			return;

		_finishedCandles++;

		// Wait until the chart has enough historical data.
		if (_finishedCandles < MinBars * 2)
			return;

		var time = candle.CloseTime;

		// Enforce cooldown between trading operations.
		if (time < _nextAllowedTime)
			return;

		var isBullish = candle.ClosePrice > candle.OpenPrice;
		var isBearish = candle.ClosePrice < candle.OpenPrice;

		var tradeExecuted = false;

		if (Position > 0 && isBearish)
		{
			// Reverse from long to short when a bearish candle appears.
			var volume = Math.Abs(Position) + Volume;
			if (volume > 0m)
			{
				SellMarket();
				tradeExecuted = true;
			}
		}
		else if (Position < 0 && isBullish)
		{
			// Reverse from short to long when a bullish candle appears.
			var volume = Math.Abs(Position) + Volume;
			if (volume > 0m)
			{
				BuyMarket();
				tradeExecuted = true;
			}
		}
		else if (Position == 0)
		{
			if (isBullish)
			{
				// Enter long on bullish close.
				if (Volume > 0m)
				{
					BuyMarket();
					tradeExecuted = true;
				}
			}
			else if (isBearish)
			{
				// Enter short on bearish close.
				if (Volume > 0m)
				{
					SellMarket();
					tradeExecuted = true;
				}
			}
		}

		if (tradeExecuted)
		{
			_nextAllowedTime = time + TradeCooldown;
		}
	}
}