GitHub で見る

NRTR トレーリングストップ戦略

この戦略は NRTR (Nick R's Trend Reverse) インジケーターを使用して市場トレンドを追跡します。アルゴリズムは最近のローソク足の平均レンジから導き出されたトレーリングストップレベルを計算します。価格がトレーリングレベルを突破すると、ポジションはブレイクアウトの方向に反転します。システムはロングとショートの両サイドで機能し、オプションのストップロスとテイクプロフィット保護を含みます。

NRTRの長さはトレーリングストップの感度を定義します:短い期間は速く反応しますが、ダマシが多くなる可能性があり、長い期間はノイズをフィルタリングします。追加の桁シフトパラメーターは、異なる価格スケールの商品にインジケーターを調整します。戦略は選択した時間軸のローソク足をサブスクライブし、各完成したバーでNRTR値を計算します。

詳細

  • エントリーロジック:
    • ロング: 下降トレンド後、価格がNRTRレベルを上抜け。
    • ショート: 上昇トレンド後、価格がNRTRレベルを下抜け。
  • エグジットロジック:
    • 反対のブレイクアウトが発生するとポジションが反転。
  • ストップ: StartProtection によるオプションのストップロスとテイクプロフィット。
  • デフォルト値:
    • Length = 10
    • DigitsShift = 0
    • TakeProfit = 2000ポイント
    • StopLoss = 1000ポイント
    • CandleType = 1時間ローソク足
  • フィルター:
    • カテゴリ: トレンドフォロー
    • 方向: 両方
    • インジケーター: NRTR, ATR
    • ストップ: はい
    • 複雑さ: 中程度
    • 時間軸: 柔軟
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中
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>
/// NRTR trailing stop strategy based on the NRTR indicator.
/// Opens long when trend turns up and short when trend turns down.
/// Includes optional stop-loss and take-profit.
/// </summary>
public class NrtrTrailingStopStrategy : Strategy
{
	private readonly StrategyParam<int> _length;
	private readonly StrategyParam<int> _digitsShift;
	private readonly StrategyParam<decimal> _takeProfit;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _price;
	private decimal _value;
	private int _trend;
	private bool _isInitialized;

	/// <summary>
	/// Number of bars for average range calculation.
	/// </summary>
	public int Length
	{
		get => _length.Value;
		set => _length.Value = value;
	}

	/// <summary>
	/// Digits adjustment for indicator sensitivity.
	/// </summary>
	public int DigitsShift
	{
		get => _digitsShift.Value;
		set => _digitsShift.Value = value;
	}

	/// <summary>
	/// Take-profit in price points.
	/// </summary>
	public decimal TakeProfit
	{
		get => _takeProfit.Value;
		set => _takeProfit.Value = value;
	}

	/// <summary>
	/// Stop-loss in price points.
	/// </summary>
	public decimal StopLoss
	{
		get => _stopLoss.Value;
		set => _stopLoss.Value = value;
	}

	/// <summary>
	/// Type of candles used for calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of <see cref="NrtrTrailingStopStrategy"/>.
	/// </summary>
	public NrtrTrailingStopStrategy()
	{
		_length = Param(nameof(Length), 20)
			.SetGreaterThanZero()
			.SetDisplay("NRTR Length", "Number of bars for average range", "Indicator")
			
			.SetOptimize(5, 20, 5);

		_digitsShift = Param(nameof(DigitsShift), 0)
			.SetDisplay("Digits Shift", "Adjustment for price digits", "Indicator");

		_takeProfit = Param(nameof(TakeProfit), 2000m)
			.SetNotNegative()
			.SetDisplay("Take Profit (pts)", "Take profit level in points", "Risk")
			
			.SetOptimize(500m, 3000m, 500m);

		_stopLoss = Param(nameof(StopLoss), 1000m)
			.SetNotNegative()
			.SetDisplay("Stop Loss (pts)", "Stop loss level in points", "Risk")
			
			.SetOptimize(500m, 3000m, 500m);

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_price = 0m;
		_value = 0m;
		_trend = 0;
		_isInitialized = false;
	}

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

		var atr = new AverageTrueRange { Length = Length };
		var subscription = SubscribeCandles(CandleType);
		subscription.BindEx(atr, ProcessCandle).Start();

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

	}

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

		if (!atrValue.IsFormed)
			return;

		var atr = atrValue.GetValue<decimal>();
		var dK = atr / Length * (decimal)Math.Pow(10, -DigitsShift);

		if (!_isInitialized)
		{
			_price = candle.ClosePrice;
			_value = _price;
			_trend = 0;
			_isInitialized = true;
			return;
		}

		var isOnline = IsFormedAndOnlineAndAllowTrading();

		if (_trend >= 0)
		{
			_price = Math.Max(_price, candle.ClosePrice);
			_value = Math.Max(_value, _price * (1m - dK));
			if (candle.ClosePrice < _value)
			{
				_price = candle.ClosePrice;
				_value = _price * (1m + dK);
				_trend = -1;
				if (isOnline && Position >= 0)
					SellMarket();
			}
		}
		else
		{
			_price = Math.Min(_price, candle.ClosePrice);
			_value = Math.Min(_value, _price * (1m + dK));
			if (candle.ClosePrice > _value)
			{
				_price = candle.ClosePrice;
				_value = _price * (1m - dK);
				_trend = 1;
				if (isOnline && Position <= 0)
					BuyMarket();
			}
		}
	}
}