GitHub で見る

Probe 戦略

概要

Probe 戦略は、StockSharp 高レベルフレームワーク内で MetaTrader 5 エキスパートアドバイザー "Probe" を再現します。設定可能な時間軸で Commodity Channel Index (CCI) を監視し、オシレーターが対称チャネルを突破したときに反応します。ブレイクアウトが発生すると、戦略は現在の市場価格からピップベースのインデントでオフセットされたストップ注文を発注します。このアプローチは、ブレイクアウト後のモメンタム継続を捉えることを目指しつつ、ピップベースの保護レベルと適応型トレーリングストップでリスクを制限します。

取引ロジック

  1. 設定されたローソク足タイプで CCI を計算します。
  2. インジケーターが下限または上限のチャネル境界を出るタイミングを検出するために、前の CCI 値と現在の CCI 値を追跡します。
  3. CCI が -CCI Channel を上向きに突破したとき、Indent (pips) 距離を使用して最後のクローズより上に買いストップ注文を提出します。
  4. CCI が +CCI Channel を下向きに突破したとき、同じピップインデントを使用して最後のクローズより下に売りストップ注文を提出します。
  5. 一度に1つの保留中のストップ注文のみがアクティブのままでいられます。反対の注文はキャンセルされ、注文がアクティブな間は新しいシグナルが無視されます。

注文管理

  • 保留中のストップ注文は、市場がエントリー価格から 1.5 * Indent (pips) より遠くに移動した場合に撤回されます。これは、モメンタムが薄れた際に古い注文が帳簿に残るのを防ぐ MetaTrader のロジックを反映します。
  • ストップ注文が執行されると、戦略は執行価格をエントリー参照として保存します。反対の保留中注文は即座にキャンセルされます。

リスク管理

  • 初期ストップロスは Stop Loss (pips) から導出され、内部監視を使用してアクティブポジションに添付されます。価格がストップに触れると、ポジションは成行注文で決済されます。
  • トレーリング動作は、フローティング利益が Trailing Stop (pips) + Trailing Step (pips) を超えた後に始まります。その後、最小トレーリング距離を尊重しながら利益を確定するためにストップが移動されます。
  • すべてのピップベースの距離は、取引所のティックサイズをスケーリングすることで、3 桁および 5 桁の気配値に対して自動的に調整されます。

パラメーター

パラメーター 説明
CandleType ローソク足を構築し CCI を計算するために使用するプライマリの時間軸。
CciLength CCI オシレーターの平均期間。
CciChannelLevel 対称ブレイクアウトチャネルを形成する絶対 CCI 閾値。
IndentPips 保留中のストップ注文を配置する際に最後のクローズに追加するピップ距離。
StopLossPips ピップ単位で測定した保護ストップロス距離。
TrailingStopPips トレーリングストップが有効になる前に必要な利益閾値 (ピップ)。
TrailingStepPips トレーリングストップが再び動く前に必要な追加利益距離。

注意事項

  • 取引サイズを制御するには、戦略の Volume プロパティを使用してください。
  • 戦略はシングルポジションネッティング向けに設計されており、オリジナルのエキスパートアドバイザーの動作に対応しています。
  • チャートエリアが利用可能な場合、チャートレンダリングはローソク足、CCI インジケーター、および実行された取引を描画します。
using System;
using System.Collections.Generic;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Probe CCI breakout strategy converted from the original MetaTrader 5 expert advisor.
/// Listens for Commodity Channel Index threshold crossovers and enters with market orders.
/// </summary>
public class ProbeStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _cciLength;
	private readonly StrategyParam<decimal> _cciChannelLevel;
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<decimal> _trailingStepPips;

	private decimal? _previousCci;
	private decimal? _entryPrice;
	private decimal? _stopPrice;
	private decimal _pipSize;

	public ProbeStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Primary timeframe used for indicator calculations", "General");

		_cciLength = Param(nameof(CciLength), 60)
			.SetGreaterThanZero()
			.SetDisplay("CCI Length", "Averaging period of the Commodity Channel Index", "Indicators");

		_cciChannelLevel = Param(nameof(CciChannelLevel), 120m)
			.SetGreaterThanZero()
			.SetDisplay("CCI Channel", "Absolute CCI level used as the channel boundary", "Indicators");

		_stopLossPips = Param(nameof(StopLossPips), 50m)
			.SetNotNegative()
			.SetDisplay("Stop Loss (pips)", "Protective stop loss distance expressed in pips", "Risk");

		_trailingStopPips = Param(nameof(TrailingStopPips), 5m)
			.SetNotNegative()
			.SetDisplay("Trailing Stop (pips)", "Minimum profit required before trailing activates", "Risk");

		_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
			.SetNotNegative()
			.SetDisplay("Trailing Step (pips)", "Additional profit required before the stop is moved again", "Risk");
	}

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

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

	public int CciLength
	{
		get => _cciLength.Value;
		set => _cciLength.Value = value;
	}

	public decimal CciChannelLevel
	{
		get => _cciChannelLevel.Value;
		set => _cciChannelLevel.Value = value;
	}

	public decimal StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	public decimal TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	public decimal TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_previousCci = null;
		_entryPrice = null;
		_stopPrice = null;
		_pipSize = 0m;
	}

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

		_pipSize = CalculatePipSize();
		_previousCci = null;
		_entryPrice = null;
		_stopPrice = null;

		var cci = new CommodityChannelIndex { Length = CciLength };

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

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

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

		if (_pipSize <= 0m)
			_pipSize = CalculatePipSize();

		// Manage existing position (stop loss / trailing)
		var exited = ManagePosition(candle);
		if (exited)
		{
			_previousCci = cciValue;
			return;
		}

		// Check for CCI crossover signals
		if (_previousCci.HasValue && Position == 0m)
		{
			var channel = CciChannelLevel;
			var lower = -channel;

			// CCI crosses up from below -channel -> buy signal
			var crossUp = _previousCci.Value < lower && cciValue > lower;
			// CCI crosses down from above +channel -> sell signal
			var crossDown = _previousCci.Value > channel && cciValue < channel;

			if (crossUp)
			{
				BuyMarket();
				_entryPrice = candle.ClosePrice;

				var stopDistance = StopLossPips * _pipSize;
				_stopPrice = stopDistance > 0m ? candle.ClosePrice - stopDistance : null;
			}
			else if (crossDown)
			{
				SellMarket();
				_entryPrice = candle.ClosePrice;

				var stopDistance = StopLossPips * _pipSize;
				_stopPrice = stopDistance > 0m ? candle.ClosePrice + stopDistance : null;
			}
		}

		_previousCci = cciValue;
	}

	private bool ManagePosition(ICandleMessage candle)
	{
		if (Position == 0m)
		{
			_entryPrice = null;
			_stopPrice = null;
			return false;
		}

		var trailingStop = TrailingStopPips * _pipSize;
		var trailingStep = TrailingStepPips * _pipSize;

		if (Position > 0m)
		{
			if (_entryPrice == null)
				_entryPrice = candle.ClosePrice;

			// Check stop loss
			if (_stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
			{
				SellMarket();
				ResetTradeState();
				return true;
			}

			// Trailing stop logic
			if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
			{
				var profit = candle.ClosePrice - _entryPrice.Value;
				var threshold = trailingStop + trailingStep;

				if (profit > threshold)
				{
					var desiredStop = candle.ClosePrice - trailingStop;
					if (!_stopPrice.HasValue || desiredStop > _stopPrice.Value)
						_stopPrice = desiredStop;
				}
			}
		}
		else if (Position < 0m)
		{
			if (_entryPrice == null)
				_entryPrice = candle.ClosePrice;

			// Check stop loss
			if (_stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
			{
				BuyMarket();
				ResetTradeState();
				return true;
			}

			// Trailing stop logic
			if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
			{
				var profit = _entryPrice.Value - candle.ClosePrice;
				var threshold = trailingStop + trailingStep;

				if (profit > threshold)
				{
					var desiredStop = candle.ClosePrice + trailingStop;
					if (!_stopPrice.HasValue || desiredStop < _stopPrice.Value)
						_stopPrice = desiredStop;
				}
			}
		}

		return false;
	}

	private void ResetTradeState()
	{
		_entryPrice = null;
		_stopPrice = null;
	}

	private decimal CalculatePipSize()
	{
		var step = Security?.PriceStep ?? 0m;
		if (step <= 0m)
			return 0.01m;

		return step;
	}
}