GitHub で見る

SAR RSI MTS 戦略

概要

SAR RSI MTS 戦略は、MetaTrader 5 のエキスパートアドバイザー「SAR RSI MTS」をStockSharp 高レベル API に直接移植したものです。システムはパラボリック SAR インジケーターの方向に従い、相対力指数(RSI)でエントリーを確認します。完成したローソク足のみで動作し(デフォルトの時間軸は 1 時間)、ネットポジションサイズに対して設定可能な上限を適用します。

インジケーターとデータ

  • パラボリック SAR (Acceleration = SarStepAccelerationStep = SarStepAccelerationMax = SarMax)。
  • 相対力指数:カスタマイズ可能な期間とニュートラルレベル(デフォルト 50)。
  • ローソク足は CandleType によって提供され、デフォルトは時間足データです。

内部的に、戦略はセキュリティのメタデータから pip 値を計算します。シンボルが 3 または 5 桁の小数点を持つ場合、価格ステップを 10 倍にして、元の MQL プログラムの pip 処理に合わせます。

エントリー条件

両方のインジケーターが有効な値を生成した後、完成した各ローソク足のクローズ時に新規トレードを評価します:

  • ロングセットアップ

    1. 前のバーのパラボリック SAR 値が現在のクローズを下回り、現在の SAR が前の値より上昇している。
    2. RSI がニュートラル閾値を上回り、前回の読み取り値より上昇している。
    3. 口座がすでにネットショートの場合、戦略はまずポジションを反転するのに十分な数量を買い、その後 Volume パラメーターに従ってサイズを設定した新規ロングを開き、MaxPosition 制限を遵守します。
  • ショートセットアップ

    1. 前のパラボリック SAR 値が現在のクローズを上回り、現在の SAR が減少している。
    2. RSI がニュートラル閾値を下回り、前回の値より下落している。
    3. 新規ショートを建てる前に既存のロングエクスポージャーをフラットにします。絶対ポジションが MaxPosition に達するまで追加ショートが許可されます。

すべての比較はインストゥルメントの精度を使用して、等価テストが MQL オリジナルの CompareDoubles ヘルパーに一致するようにします。

エグジット条件とリスク管理

完成した各ローソク足で新規エントリーを確認する前にリスクコントロールを評価します:

  • 固定ストップロス:pips で表され価格単位に変換され、現在のネットポジションの平均エントリー価格に適用されます。
  • 固定テイクプロフィット:pips 単位で、ストップロスと対称的に処理されます。
  • トレーリングストップ:含み益が TrailingStop + TrailingStep を超えた後にのみ有効になります。ストップは離散的なステップで移動し、MQL 戦略の「Trailing」ルーティンを模倣します。
  • 上記のいずれも該当しない場合、ポジションがフラットになるたびにトレーリング状態がリセットされます。

すべてのエグジットは全体のネットポジション(ロングまたはショート)をクローズします。保護ルールが発動すると、戦略は同じバーのシグナル評価をスキップし、元の実装におけるブローカー側ストップ注文の動作を反映します。

パラメーター

パラメーター 説明
StopLossPips pips で表されたストップロス距離。0 の値は保護ストップを無効にします。
TakeProfitPips pips 単位のテイクプロフィット距離。0 に設定すると無効になります。
TrailingStopPips トレーリングストップの距離。0 に設定すると無効になります。
TrailingStepPips トレーリングストップを進める前に必要な最小価格改善。
SarStep パラボリック SAR の加速ステップ;初期加速係数としても使用されます。
SarMax パラボリック SAR の最大加速係数。
RsiPeriod RSI インジケーターのルックバック期間。
RsiNeutralLevel 強気・弱気バイアスを分けるRSI閾値(デフォルト 50)。
CandleType 計算に使用されるローソク足サブスクリプション(デフォルト 1 時間)。
MaxPosition 戦略で許可される最大絶対ネットポジション。

補足事項

  • デフォルト設定は元の EA の入力を再現します:10 pip ストップ、40 pip 目標、15/5 pip トレーリングストップ、パラボリック SAR 0.05/0.5、RSI 期間 14
  • 数量はベース Strategy.Volume プロパティで制御されます。ポジションスケーリングは MaxPosition を遵守し、反転を自動的に処理します。
  • インジケーターのバインディングと注文ルーティングは、手動のシリーズアクセスなしに StockSharp 高レベル API に完全に依存し、プロジェクトガイドラインへの準拠を確保します。
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>
/// Parabolic SAR and RSI strategy translated from the original MQL implementation.
/// </summary>
public class SarRsiMtsStrategy : Strategy
{
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<decimal> _trailingStepPips;
	private readonly StrategyParam<decimal> _sarStep;
	private readonly StrategyParam<decimal> _sarMax;
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _rsiNeutralLevel;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _maxPosition;

	private decimal? _previousSar;
	private decimal? _previousRsi;
	private decimal? _longTrailingStop;
	private decimal? _shortTrailingStop;
	private decimal _pipSize;
	private decimal _entryPrice;
	private DateTimeOffset _lastTradeTime;

	/// <summary>
	/// Stop loss distance expressed in pips.
	/// </summary>
	public decimal StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.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>
	/// Trailing step distance expressed in pips.
	/// </summary>
	public decimal TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <summary>
	/// Parabolic SAR acceleration step.
	/// </summary>
	public decimal SarStep
	{
		get => _sarStep.Value;
		set => _sarStep.Value = value;
	}

	/// <summary>
	/// Parabolic SAR maximum acceleration.
	/// </summary>
	public decimal SarMax
	{
		get => _sarMax.Value;
		set => _sarMax.Value = value;
	}

	/// <summary>
	/// RSI lookback period.
	/// </summary>
	public int RsiPeriod
	{
		get => _rsiPeriod.Value;
		set => _rsiPeriod.Value = value;
	}

	/// <summary>
	/// RSI neutral level used for bullish or bearish confirmation.
	/// </summary>
	public decimal RsiNeutralLevel
	{
		get => _rsiNeutralLevel.Value;
		set => _rsiNeutralLevel.Value = value;
	}

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

	/// <summary>
	/// Maximum absolute net position allowed by the strategy.
	/// </summary>
	public decimal MaxPosition
	{
		get => _maxPosition.Value;
		set => _maxPosition.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="SarRsiMtsStrategy"/> class.
	/// </summary>
	public SarRsiMtsStrategy()
	{
		_stopLossPips = Param(nameof(StopLossPips), 10m)
			.SetNotNegative()
			.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk");

		_takeProfitPips = Param(nameof(TakeProfitPips), 40m)
			.SetNotNegative()
			.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk");

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

		_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
			.SetNotNegative()
			.SetDisplay("Trailing Step (pips)", "Trailing step distance in pips", "Risk");

		_sarStep = Param(nameof(SarStep), 0.05m)
			.SetGreaterThanZero()
			.SetDisplay("SAR Step", "Parabolic SAR acceleration step", "Indicators");

		_sarMax = Param(nameof(SarMax), 0.5m)
			.SetGreaterThanZero()
			.SetDisplay("SAR Maximum", "Parabolic SAR maximum acceleration", "Indicators");

		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "Lookback period for RSI", "Indicators");

		_rsiNeutralLevel = Param(nameof(RsiNeutralLevel), 50m)
			.SetDisplay("RSI Neutral", "Neutral RSI threshold separating bullish and bearish bias", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Candle type for indicator calculations", "General");

		_maxPosition = Param(nameof(MaxPosition), 5m)
			.SetGreaterThanZero()
			.SetDisplay("Max Position", "Maximum absolute net position allowed", "Risk");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_previousSar = null;
		_previousRsi = null;
		_longTrailingStop = null;
		_shortTrailingStop = null;
		_pipSize = 0;
		_entryPrice = 0;
		_lastTradeTime = default;
	}

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

		_pipSize = CalculatePipSize();

		var parabolicSar = new ParabolicSar
		{
			Acceleration = SarStep,
			AccelerationStep = SarStep,
			AccelerationMax = SarMax
		};

		var rsi = new RelativeStrengthIndex
		{
			Length = RsiPeriod
		};

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

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

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

		if (ManageRisk(candle))
			return;

		if (sarValue == 0m || rsiValue == 0m)
			return;

		if (!_previousSar.HasValue || !_previousRsi.HasValue)
		{
			_previousSar = sarValue;
			_previousRsi = rsiValue;
			return;
		}

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_previousSar = sarValue;
			_previousRsi = rsiValue;
			return;
		}

		// Cooldown: skip if a trade was placed within the last ~240 candles (5-min candles = ~1200 min)
		if (_lastTradeTime != default && (candle.OpenTime - _lastTradeTime) < TimeSpan.FromMinutes(1200))
		{
			_previousSar = sarValue;
			_previousRsi = rsiValue;
			return;
		}

		var sarPrev = _previousSar.Value;
		var rsiPrev = _previousRsi.Value;

		var price = candle.ClosePrice;
		var buySignal = sarPrev < price
			&& !AreClose(sarPrev, price)
			&& sarValue > sarPrev
			&& rsiValue > RsiNeutralLevel
			&& rsiValue > rsiPrev
			&& !AreClose(rsiValue, rsiPrev);

		if (buySignal)
		{
			EnterLong(candle);
		}
		else
		{
			var sellSignal = sarPrev > price
				&& !AreClose(sarPrev, price)
				&& sarValue < sarPrev
				&& rsiValue < RsiNeutralLevel
				&& rsiValue < rsiPrev
				&& !AreClose(rsiValue, rsiPrev);

			if (sellSignal)
				EnterShort(candle);
		}

		_previousSar = sarValue;
		_previousRsi = rsiValue;
	}

	private void EnterLong(ICandleMessage candle)
	{
		var tradeVolume = Volume;
		if (tradeVolume <= 0m)
			return;

		var maxPosition = MaxPosition;
		if (maxPosition <= 0m)
			return;

		var current = Position;
		var target = current < 0 ? Math.Min(maxPosition, tradeVolume) : Math.Min(maxPosition, current + tradeVolume);
		var required = target - current;
		if (required <= 0m)
			return;

		BuyMarket(required);
		_longTrailingStop = null;
		_shortTrailingStop = null;
		_lastTradeTime = candle.OpenTime;
	}

	private void EnterShort(ICandleMessage candle)
	{
		var tradeVolume = Volume;
		if (tradeVolume <= 0m)
			return;

		var maxPosition = MaxPosition;
		if (maxPosition <= 0m)
			return;

		var current = Position;
		var target = current > 0 ? -Math.Min(maxPosition, tradeVolume) : Math.Max(-maxPosition, current - tradeVolume);
		var required = current - target;
		if (required <= 0m)
			return;

		SellMarket(required);
		_longTrailingStop = null;
		_shortTrailingStop = null;
		_lastTradeTime = candle.OpenTime;
	}

	private bool ManageRisk(ICandleMessage candle)
	{
		if (Position > 0m)
		{
			var entryPrice = _entryPrice;
			if (entryPrice <= 0m)
				return false;

			var trailingTriggered = UpdateLongTrailing(candle, entryPrice);
			if (trailingTriggered)
				return true;

			var stopDistance = GetPriceOffset(StopLossPips);
			if (stopDistance > 0m)
			{
				var stopPrice = entryPrice - stopDistance;
				if (candle.LowPrice <= stopPrice)
				{
					SellMarket(Position);
					ResetTrailing();
					return true;
				}
			}

			var takeDistance = GetPriceOffset(TakeProfitPips);
			if (takeDistance > 0m)
			{
				var takePrice = entryPrice + takeDistance;
				if (candle.HighPrice >= takePrice)
				{
					SellMarket(Position);
					ResetTrailing();
					return true;
				}
			}
		}
		else if (Position < 0m)
		{
			var entryPrice = _entryPrice;
			if (entryPrice <= 0m)
				return false;

			var trailingTriggered = UpdateShortTrailing(candle, entryPrice);
			if (trailingTriggered)
				return true;

			var stopDistance = GetPriceOffset(StopLossPips);
			if (stopDistance > 0m)
			{
				var stopPrice = entryPrice + stopDistance;
				if (candle.HighPrice >= stopPrice)
				{
					BuyMarket(Math.Abs(Position));
					ResetTrailing();
					return true;
				}
			}

			var takeDistance = GetPriceOffset(TakeProfitPips);
			if (takeDistance > 0m)
			{
				var takePrice = entryPrice - takeDistance;
				if (candle.LowPrice <= takePrice)
				{
					BuyMarket(Math.Abs(Position));
					ResetTrailing();
					return true;
				}
			}
		}
		else
		{
			ResetTrailing();
		}

		return false;
	}

	private bool UpdateLongTrailing(ICandleMessage candle, decimal entryPrice)
	{
		var trailingDistance = GetPriceOffset(TrailingStopPips);
		if (trailingDistance <= 0m)
		{
			_longTrailingStop = null;
			return false;
		}

		var trailingStep = GetPriceOffset(TrailingStepPips);
		var profit = candle.ClosePrice - entryPrice;
		if (profit >= trailingDistance + trailingStep)
		{
			var candidate = candle.ClosePrice - trailingDistance;
			var threshold = candle.ClosePrice - (trailingDistance + trailingStep);
			if (!_longTrailingStop.HasValue || _longTrailingStop.Value < threshold)
				_longTrailingStop = candidate;
		}

		if (_longTrailingStop.HasValue && candle.LowPrice <= _longTrailingStop.Value)
		{
			SellMarket(Position);
			ResetTrailing();
			return true;
		}

		return false;
	}

	private bool UpdateShortTrailing(ICandleMessage candle, decimal entryPrice)
	{
		var trailingDistance = GetPriceOffset(TrailingStopPips);
		if (trailingDistance <= 0m)
		{
			_shortTrailingStop = null;
			return false;
		}

		var trailingStep = GetPriceOffset(TrailingStepPips);
		var profit = entryPrice - candle.ClosePrice;
		if (profit >= trailingDistance + trailingStep)
		{
			var candidate = candle.ClosePrice + trailingDistance;
			var threshold = candle.ClosePrice + (trailingDistance + trailingStep);
			if (!_shortTrailingStop.HasValue || _shortTrailingStop.Value > threshold)
				_shortTrailingStop = candidate;
		}

		if (_shortTrailingStop.HasValue && candle.HighPrice >= _shortTrailingStop.Value)
		{
			BuyMarket(Math.Abs(Position));
			ResetTrailing();
			return true;
		}

		return false;
	}

	private decimal GetPriceOffset(decimal pips)
	{
		if (pips <= 0m)
			return 0m;

		var pip = _pipSize;
		if (pip <= 0m)
			pip = Security?.PriceStep ?? 1m;

		return pip * pips;
	}

	private decimal CalculatePipSize()
	{
		var priceStep = Security?.PriceStep ?? 0m;
		if (priceStep <= 0m)
			priceStep = 1m;

		var decimals = Security?.Decimals;
		var adjust = decimals == 3 || decimals == 5 ? 10m : 1m;

		return priceStep * adjust;
	}

	private void ResetTrailing()
	{
		_longTrailingStop = null;
		_shortTrailingStop = null;
	}

	/// <inheritdoc />
	protected override void OnOwnTradeReceived(MyTrade trade)
	{
		base.OnOwnTradeReceived(trade);
		if (trade?.Trade == null) return;
		if (Position != 0 && _entryPrice == 0m)
			_entryPrice = trade.Trade.Price;
		if (Position == 0)
			_entryPrice = 0m;
	}

	private bool AreClose(decimal value1, decimal value2)
	{
		var decimals = Security?.Decimals ?? 4;
		return Math.Round(value1 - value2, decimals) == 0m;
	}
}