GitHub で見る

Ichimoku雲リトレース戦略

この戦略は、MetaTraderのエキスパート「ichimok2005」のStockSharpポートです。Ichimoku雲へのプルバックを探し、優勢な雲(kumo)の傾きの方向にトレードします。シグナルは完成した足のみで評価されます。

概要

  • ローソク足データを提供するあらゆる銘柄と時間軸で機能します。
  • デフォルトでは標準的なIchimoku設定(9/26/52)を使用しますが、完全に設定可能です。
  • ロングとショートの両方でトレードします。ポジションサイズは戦略のVolumeプロパティで定義されます。
  • オプションのストップロスとテイクプロフィットは絶対価格単位で設定できます。

インジケーターとパラメーター

  • Ichimoku: TenkanKijunSenkou Span Bの長さはパラメーターとして公開されています。
  • 足タイプ: 接続でサポートされている任意の集約足タイプを選択してください(デフォルト: 1時間の時間軸)。
  • Stop Loss Offset: エントリー価格より下/上のオプションの距離で、エグジットを強制します。無効にするには0に設定してください。
  • Take Profit Offset: エントリー価格からのオプションの利益目標距離。無効にするには0に設定してください。

エントリー条件

ロング設定

  1. Senkou Span ASenkou Span Bより上にあり、強気の雲を示しています。
  2. 現在の完成した足は強気(Close > Open)。
  3. 足が雲の内部でクローズします(Closeが2つのスパンの間にある)。
  4. すべての条件が揃い、戦略がフラットまたはショートの場合、ショートエクスポージャーを閉じて新しいロングを開くようにサイジングされたマーケット買い注文を送信します。

ショート設定

  1. Senkou Span BSenkou Span Aより上にあり、弱気の雲を示しています。
  2. 現在の完成した足は弱気(Open > Close)。
  3. 足が雲の内部でクローズします(Closeが2つのスパンの間にある)。
  4. 条件が揃い、戦略がフラットまたはロングの場合、ロングエクスポージャーを閉じて新しいショートを開くようにサイジングされたマーケット売り注文を送信します。

エグジット条件

  • 反対のシグナルは、クローズと新しいエントリーを単一のマーケット注文に組み合わせることでポジションを自動的に反転させます。
  • 有効になっている場合、Stop Loss Offsetはロングに対してEntryPrice - Offset、ショートに対してEntryPrice + Offsetでエグジットします(足のクローズ価格を使用)。
  • 有効になっている場合、Take Profit Offsetはロングに対してEntryPrice + Offset、ショートに対してEntryPrice - Offsetでエグジットします。
  • 手動フラット化(戦略のクローズ)も内部エントリー価格トラッカーをリセットします。

リスク管理メモ

  • オフセットは絶対価格単位で表現されます。設定前にピップまたはティック距離を価格に変換してください。
  • 戦略はリスクチェックに足のクローズ価格を使用するため、低い時間軸では狭いオフセットを検討してください。
  • トレーリングや部分エグジットは実装されていません。戦略は常にポジション全体をエグジットします。

追加実装の詳細

  • 戦略は高レベルAPIを通じて足をサブスクライブし、BindExでIchimokuインジケーターをバインドします。
  • 完成した足のみがロジックをトリガーします。中間更新は無視されます。
  • チャートエリアは(利用可能な場合)自動的に作成され、価格、Ichimoku雲、実行されたトレードを表示します。
  • ManageRiskは新しいエントリーを探す前に実行されるため、保護エグジットが優先されます。
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>
/// Ichimoku cloud retrace strategy.
/// Takes trades when price pulls back inside the cloud in the direction of the kumo slope.
/// Uses optional fixed offsets for stop-loss and take-profit management.
/// </summary>
public class IchimokuCloudRetraceStrategy : Strategy
{
	private readonly StrategyParam<int> _tenkanPeriod;
	private readonly StrategyParam<int> _kijunPeriod;
	private readonly StrategyParam<int> _senkouSpanBPeriod;
	private readonly StrategyParam<decimal> _stopLossOffset;
	private readonly StrategyParam<decimal> _takeProfitOffset;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _entryPrice;

	/// <summary>
	/// Tenkan-sen period.
	/// </summary>
	public int TenkanPeriod
	{
		get => _tenkanPeriod.Value;
		set => _tenkanPeriod.Value = value;
	}

	/// <summary>
	/// Kijun-sen period.
	/// </summary>
	public int KijunPeriod
	{
		get => _kijunPeriod.Value;
		set => _kijunPeriod.Value = value;
	}

	/// <summary>
	/// Senkou Span B period.
	/// </summary>
	public int SenkouSpanBPeriod
	{
		get => _senkouSpanBPeriod.Value;
		set => _senkouSpanBPeriod.Value = value;
	}

	/// <summary>
	/// Stop-loss offset in price units. Set to zero to disable.
	/// </summary>
	public decimal StopLossOffset
	{
		get => _stopLossOffset.Value;
		set => _stopLossOffset.Value = value;
	}

	/// <summary>
	/// Take-profit offset in price units. Set to zero to disable.
	/// </summary>
	public decimal TakeProfitOffset
	{
		get => _takeProfitOffset.Value;
		set => _takeProfitOffset.Value = value;
	}

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

	/// <summary>
	/// Initializes strategy parameters.
	/// </summary>
	public IchimokuCloudRetraceStrategy()
	{
		_tenkanPeriod = Param(nameof(TenkanPeriod), 9)
			.SetGreaterThanZero()
			.SetDisplay("Tenkan Period", "Tenkan-sen length", "Ichimoku Settings")
			
			.SetOptimize(5, 15, 1);

		_kijunPeriod = Param(nameof(KijunPeriod), 26)
			.SetGreaterThanZero()
			.SetDisplay("Kijun Period", "Kijun-sen length", "Ichimoku Settings")
			
			.SetOptimize(20, 40, 2);

		_senkouSpanBPeriod = Param(nameof(SenkouSpanBPeriod), 52)
			.SetGreaterThanZero()
			.SetDisplay("Senkou Span B Period", "Senkou Span B length", "Ichimoku Settings")
			
			.SetOptimize(40, 70, 5);

		_stopLossOffset = Param(nameof(StopLossOffset), 0m)
			.SetDisplay("Stop Loss Offset", "Distance from entry for stop-loss (price units)", "Risk Management");

		_takeProfitOffset = Param(nameof(TakeProfitOffset), 0m)
			.SetDisplay("Take Profit Offset", "Distance from entry for take-profit (price units)", "Risk Management");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles for analysis", "General");
	}

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

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

		// Reset internal state values.
		_entryPrice = 0m;
	}

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

		// Prepare Ichimoku indicator with user-defined lengths.
		var ichimoku = new Ichimoku
		{
			Tenkan = { Length = TenkanPeriod },
			Kijun = { Length = KijunPeriod },
			SenkouB = { Length = SenkouSpanBPeriod }
		};

		// Subscribe to candle data and bind the indicator for processing.
		var subscription = SubscribeCandles(CandleType);

		subscription
			.BindEx(ichimoku, ProcessCandle)
			.Start();

		// Draw helper visuals if a chart is available.
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, ichimoku);
			DrawOwnTrades(area);
		}
	}

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

		if (!ichimokuValue.IsFinal)
			return;

		// Manage open positions using the latest close before looking for new entries.
		ManageRisk(candle);

		if (Position == 0)
			_entryPrice = 0m;

		var ichimoku = (IchimokuValue)ichimokuValue;

		if (ichimoku.SenkouA is not decimal senkouA ||
			ichimoku.SenkouB is not decimal senkouB)
			return;

		var open = candle.OpenPrice;
		var close = candle.ClosePrice;

		var lowerSpan = Math.Min(senkouA, senkouB);
		var upperSpan = Math.Max(senkouA, senkouB);

		var priceInsideCloud = close > lowerSpan && close < upperSpan;

		var bullishCloud = senkouA > senkouB;
		var bearishCloud = senkouB > senkouA;

		var shouldBuy = bullishCloud && close > open && priceInsideCloud;
		var shouldSell = bearishCloud && open > close && priceInsideCloud;

		if (shouldBuy && Position <= 0)
		{
			// Combine reversal and new entry volume in a single market order.
			var volume = Volume + (Position < 0 ? Math.Abs(Position) : 0m);

			if (volume > 0)
			{
				_entryPrice = close;
				BuyMarket(volume);
			}
		}
		else if (shouldSell && Position >= 0)
		{
			// Combine reversal and new entry volume in a single market order.
			var volume = Volume + (Position > 0 ? Math.Abs(Position) : 0m);

			if (volume > 0)
			{
				_entryPrice = close;
				SellMarket(volume);
			}
		}
	}

	private void ManageRisk(ICandleMessage candle)
	{
		if (_entryPrice == 0m)
			return;

		var close = candle.ClosePrice;

		if (Position > 0)
		{
			if (StopLossOffset > 0m && close <= _entryPrice - StopLossOffset)
			{
				var volumeToClose = Math.Abs(Position);

				if (volumeToClose > 0m)
				{
					SellMarket(volumeToClose);
					_entryPrice = 0m;
					return;
				}
			}

			if (TakeProfitOffset > 0m && close >= _entryPrice + TakeProfitOffset)
			{
				var volumeToClose = Math.Abs(Position);

				if (volumeToClose > 0m)
				{
					SellMarket(volumeToClose);
					_entryPrice = 0m;
				}
			}
		}
		else if (Position < 0)
		{
			if (StopLossOffset > 0m && close >= _entryPrice + StopLossOffset)
			{
				var volumeToClose = Math.Abs(Position);

				if (volumeToClose > 0m)
				{
					BuyMarket(volumeToClose);
					_entryPrice = 0m;
					return;
				}
			}

			if (TakeProfitOffset > 0m && close <= _entryPrice - TakeProfitOffset)
			{
				var volumeToClose = Math.Abs(Position);

				if (volumeToClose > 0m)
				{
					BuyMarket(volumeToClose);
					_entryPrice = 0m;
				}
			}
		}
	}
}