GitHub で見る

NUp1Down戦略

概要

NUp1Down戦略は、MetaTrader 5エキスパート「N bars up, then one bar down」(ファイルNUp1Down.mq5)を直接変換したものです。StockSharpが提供する完成したローソク足をスキャンし、設定可能な数の強気ローソク足(より高い終値を継続的に更新)の後に弱気ローソク足が現れると、ショート取引に入ります。StockSharp Designer、Shell、またはRunnerの中でクラシックなスイングリバーサルパターンを自動化したい裁量トレーダー向けに設計されています。

取引ロジック

  1. CandleTypeパラメーターで提供された完成したローソク足のみで動作します。
  2. 最新のBarsCount + 1本のローソク足をメモリに保持します。最も新しいローソク足は始値を下回って終わる必要があります(弱気セットアップローソク足)。
  3. 前のBarsCount本のローソク足はすべて始値を上回って終わる必要があります。これらの強気ローソク足(最も古いものを除く)はそれぞれ、直前のローソク足の終値を上回って終わる必要があり、「階段状」の上昇動きを強制します。
  4. パターンが検証され、アクティブなショートポジションがない場合、戦略は成行売り注文を送信します。
  5. ポジションサイジングはRiskPercentパラメーターを使用します。アルゴリズムは、リスク資本(ストップロスまでの距離を金銭価値に変換したもの)がポートフォリオの選択されたパーセントを超えないように開けるコントラクト数を推定します。基本Volumeプロパティは最小ロットサイズのままで、リスクモデルは取引サイズを増加させることしかできません。

ポジション管理

  • エントリー時に、エントリー価格から保護的なストップロスとテイクプロフィットレベルが計算されます。両方の距離はpipsで表現され、インストゥルメントのPriceStepを使用して価格に変換されます。3桁または5桁の小数を持つシンボルの場合、MetaTraderのpip定義に合わせてpipサイズが自動的に調整されます。
  • トレーリングストップは完成したローソク足ごとに再計算されます。トレーリング距離はTrailingStopPipsと同等で、価格が取引の有利方向に少なくともTrailingStepPips動いた場合のみストップが移動します。トレーリングロジックは元のエキスパートをエミュレートします:ショート取引ではアスク価格の下落に追従し、このストラテジーはロング取引を生成しません。
  • 終了条件はすべてのローソク足で新しいエントリーを探す前に評価されます。ストップロスまたはテイクプロフィットがヒットしたとき、またはトレーリングロジックが現在のアスク価格を超えてストップを締め付けたときに、戦略はポジションを閉じます。

パラメーター

名前 説明
BarsCount 弱気セットアップローソク足の前に必要な強気ローソク足の数(デフォルト:3)。
TakeProfitPips エントリー価格に適用されるpips単位のテイクプロフィット距離(デフォルト:50)。
StopLossPips エントリー価格に適用されるpips単位のストップロス距離(デフォルト:50)。
TrailingStopPips 市場価格とトレーリングストップの間の距離(デフォルト:10)。
TrailingStepPips トレーリングストップが前進する前の最小有利移動(デフォルト:5)。
RiskPercent 各取引でリスクにさらすポートフォリオ資本の割合(デフォルト:5)。
CandleType パターン検出に使用するローソク足データタイプ/時間軸(デフォルト:1時間)。

使用上の注意

  • Volumeプロパティをブローカーが許可する最小注文サイズに設定してください。リスクベースのサイジングは取引サイズを上げることがありますが、Volumeを下回ることはありません。
  • 戦略は常に一つの集約されたショートポジションのみを保持します。ロングポジションが存在する場合、ショートポジションを開く前に閉じられます。
  • アルゴリズムはローソク足データで動作します。バー内のストップロスまたはテイクプロフィットヒットはローソク足の高値/安値を使用して検出されるため、実際の約定タイミングはティックレベルの執行とは異なる可能性があります。
  • このリリースではPythonバージョンは提供されていません。API/2574/CS/NUp1DownStrategy.cs内のC#実装のみが利用可能です。
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;

using System.Globalization;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy that sells after a sequence of bullish candles followed by a bearish candle.
/// </summary>
public class NUp1DownStrategy : Strategy
{
	private readonly StrategyParam<int> _barsCount;
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<decimal> _trailingStepPips;
	private readonly StrategyParam<decimal> _riskPercent;
	private readonly StrategyParam<DataType> _candleType;

	private readonly Queue<(decimal Open, decimal Close)> _recentCandles = new();

	private decimal _pipSize;
	private decimal? _entryPrice;
	private decimal? _activeStopPrice;
	private decimal? _activeTakePrice;

	/// <summary>
	/// Number of consecutive bullish bars required before the bearish setup candle.
	/// </summary>
	public int BarsCount
	{
		get => _barsCount.Value;
		set => _barsCount.Value = value;
	}

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

	/// <summary>
	/// Stop loss distance in pips.
	/// </summary>
	public decimal StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

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

	/// <summary>
	/// Trailing stop step in pips.
	/// </summary>
	public decimal TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <summary>
	/// Risk percentage used to size the position.
	/// </summary>
	public decimal RiskPercent
	{
		get => _riskPercent.Value;
		set => _riskPercent.Value = value;
	}

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

	/// <summary>
	/// Initializes a new instance of the <see cref="NUp1DownStrategy"/> class.
	/// </summary>
	public NUp1DownStrategy()
	{
		Volume = 1m;

		_barsCount = Param(nameof(BarsCount), 3)
			.SetGreaterThanZero()
			.SetDisplay("Bullish Bars", "Number of bullish bars before the down bar", "General")
			
			.SetOptimize(2, 6, 1);

		_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk")
			
			.SetOptimize(20m, 120m, 10m);

		_stopLossPips = Param(nameof(StopLossPips), 50m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk")
			
			.SetOptimize(20m, 120m, 10m);

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

		_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
			.SetGreaterThanZero()
			.SetDisplay("Trailing Step (pips)", "Trailing step before adjusting stop", "Risk")
			
			.SetOptimize(1m, 20m, 1m);

		_riskPercent = Param(nameof(RiskPercent), 5m)
			.SetGreaterThanZero()
			.SetDisplay("Risk %", "Portfolio risk percentage per trade", "Money Management")
			
			.SetOptimize(1m, 10m, 1m);

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Time frame for candle analysis", "General");
	}

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

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

		_recentCandles.Clear();
		_pipSize = 0m;
		ResetPositionState();
	}

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

		_pipSize = CalculatePipSize();

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

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

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

		UpdateTrailingAndExits(candle);

		_recentCandles.Enqueue((candle.OpenPrice, candle.ClosePrice));
		while (_recentCandles.Count > BarsCount + 1)
			_recentCandles.Dequeue();

		if (_recentCandles.Count < BarsCount + 1)
			return;

		var candles = _recentCandles.ToArray();
		var last = candles[^1];

		if (last.Close >= last.Open)
			return;

		var isPattern = true;

		for (var i = 1; i <= BarsCount; i++)
		{
			var index = candles.Length - 1 - i;
			var bar = candles[index];

			if (bar.Close <= bar.Open)
			{
				isPattern = false;
				break;
			}

			if (i < BarsCount)
			{
				var prev = candles[index - 1];
				if (bar.Close <= prev.Close)
				{
					isPattern = false;
					break;
				}
			}
		}

		if (!isPattern)
			return;

		if (Position < 0)
			return;

		SellMarket();

		_entryPrice = candle.ClosePrice;
		_activeStopPrice = _entryPrice + StopLossPips * _pipSize;
		_activeTakePrice = _entryPrice - TakeProfitPips * _pipSize;

		this.LogInfo($"Short entry after {BarsCount} bullish bars at {_entryPrice:0.#####}");
	}

	private void UpdateTrailingAndExits(ICandleMessage candle)
	{
		if (Position < 0)
		{
			var volumeToClose = Math.Abs(Position);
			if (volumeToClose <= 0m)
				return;

			if (_activeStopPrice is decimal stop && candle.HighPrice >= stop)
			{
				BuyMarket();
				this.LogInfo($"Short exit by stop-loss at {stop:0.#####}");
				ResetPositionState();
				return;
			}

			if (_activeTakePrice is decimal take && candle.LowPrice <= take)
			{
				BuyMarket();
				this.LogInfo($"Short exit by take-profit at {take:0.#####}");
				ResetPositionState();
				return;
			}

			if (_activeStopPrice is decimal trailingStop)
			{
				var trailingDistance = TrailingStopPips * _pipSize;
				var trailingStep = TrailingStepPips * _pipSize;

				if (trailingDistance <= 0m)
					return;

				var currentAsk = candle.ClosePrice;
				var newStopCandidate = currentAsk + trailingDistance;

				if (newStopCandidate + trailingStep < trailingStop)
				{
					_activeStopPrice = newStopCandidate;
					this.LogInfo($"Short trailing stop moved to {_activeStopPrice:0.#####}");
				}
			}
		}
		else if (Position == 0)
		{
			ResetPositionState();
		}
	}

	private decimal CalculatePipSize()
	{
		if (Security?.PriceStep is decimal step && step > 0m)
		{
			var decimals = CountDecimalPlaces(step);
			return decimals is 3 or 5 ? step * 10m : step;
		}

		return 1m;
	}

	private static int CountDecimalPlaces(decimal value)
	{
		var text = value.ToString(CultureInfo.InvariantCulture);
		var separatorIndex = text.IndexOf('.');
		return separatorIndex >= 0 ? text.Length - separatorIndex - 1 : 0;
	}

	private decimal CalculateOrderVolume()
	{
		var baseVolume = Volume;
		var stopDistance = StopLossPips * _pipSize;

		if (Portfolio == null || stopDistance <= 0m)
			return baseVolume;

		var priceStep = Security?.PriceStep ?? 0m;

		if (priceStep <= 0m)
			return baseVolume;

		var capital = Portfolio?.CurrentValue ?? Portfolio?.BeginValue ?? 0m;
		if (capital <= 0m)
			return baseVolume;

		var riskAmount = capital * (RiskPercent / 100m);
		if (riskAmount <= 0m)
			return baseVolume;

		var riskPerUnit = stopDistance;
		if (riskPerUnit <= 0m)
			return baseVolume;

		var volumeFromRisk = riskAmount / riskPerUnit;
		if (volumeFromRisk <= 0m)
			return baseVolume;

		return Math.Max(baseVolume, volumeFromRisk);
	}

	private void ResetPositionState()
	{
		_entryPrice = null;
		_activeStopPrice = null;
		_activeTakePrice = null;
	}
}