GitHub で見る

Nevalyashkaフリップ戦略

MetaTraderエキスパート「Nevalyashka」の直接的なStockSharpポート。戦略は常にロングとショートのトレードを交互に行います。売り成行注文から始め、ストップロスまたはテイクプロフィットによってポジションがクローズされるのを待ち、直後に反対方向の成行注文を開きます。保護注文はオリジナルコードと同じpipsベースのオフセットを使用して各エントリーで再作成されます。

戦略ロジック

  1. 初期化
    • インストゥルメントの価格ステップと小数点を検出してMQLバージョンと同一のpipサイズを導出する(3/5桁ペアは10を掛ける)。
    • 取引所のMinVolumeLotMultiplierパラメーターを掛けて注文サイズを取得し、必要に応じてボリュームステップに丸める。
  2. 価格処理
    • 最新の最良bid/ask価格を取得するためにオーダーブックの更新をサブスクライブし、エキスパートのRefreshRates()呼び出しをミラーリングする。
  3. 注文フロー
    • 最良のbid/ask価格が利用可能になったら初期売り成行注文を配置する。
    • ポジションがクローズされたら、サイドを反転させ(売りの後に買い、買いの後に売り)、同じボリュームで新しい成行注文を発行する。
    • 約定したエントリーごとに、pips距離パラメーターを使用して個別のストップロスとテイクプロフィット注文を配置する。

リスク管理

  • ストップロス: オプション。StopLossPipsがゼロより大きい場合、戦略はエントリー ± StopLossPips * pipに保護ストップ注文(ロングポジションにはSellStop、ショートポジションにはBuyStop)を送信する。
  • テイクプロフィット: オプション。TakeProfitPipsがゼロより大きい場合、戦略はエントリー ± TakeProfitPips * pipに保護リミット注文(ロングポジションにはSellLimit、ショートポジションにはBuyLimit)を送信する。
  • 両方の保護注文は、ポジションがフラットな場合は常にキャンセルされ、次のフリップの前に未解決注文が残らないようにする。

パラメーター

名前 説明 デフォルト
LotMultiplier インストゥルメントの最小ボリュームに適用される乗数。結果は取引所のボリュームステップに丸められる。 1
StopLossPips pipsでのストップロス距離。ストップを無効にするには0に設定。 50
TakeProfitPips pipsでのテイクプロフィット距離。ターゲットを無効にするには0に設定。 50

操作上の注意事項

  • このアプローチはエクスポージャーを継続的に交互に切り替えるため、完了した動きが反転しやすい平均回帰相場に適している。
  • 最良気配値を提供するシンボルであれば機能する。pip計算は価格精度に基づいて自動的に適応する。
  • スリッページ処理は取引所に委任されており、オリジナルエキスパートと同様に追加チェックなしでマーケット注文が送信される。
  • 戦略には取引時間フィルター、ニュースフィルター、またはトレーリングストップは含まれていない。そのようなロジックはTryOpenNextPositionまたはRegisterProtectionOrdersを拡張することで追加できる。
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>
/// Alternating long-short strategy that mirrors the original Nevalyashka MQL logic.
/// Opens an initial sell position and flips direction each time the position is closed.
/// </summary>
public class NevalyashkaFlipStrategy : Strategy
{
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _entryPrice;
	private Sides? _currentSide;
	private Sides? _lastCompletedSide;

	/// <summary>
	/// Stop loss distance in price steps.
	/// </summary>
	public int StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take profit distance in price steps.
	/// </summary>
	public int TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

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

	/// <summary>
	/// Initializes a new instance of the <see cref="NevalyashkaFlipStrategy"/> class.
	/// </summary>
	public NevalyashkaFlipStrategy()
	{
		_stopLossPoints = Param(nameof(StopLossPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pts)", "Stop loss distance in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit (pts)", "Take profit distance in price steps", "Risk");

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

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

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

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

		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;

		var step = Security?.PriceStep ?? 1m;
		var stopDistance = StopLossPoints * step;
		var takeDistance = TakeProfitPoints * step;
		var price = candle.ClosePrice;

		// Check SL/TP for current position
		if (Position != 0 && _entryPrice > 0)
		{
			var hit = false;

			if (_currentSide == Sides.Buy)
			{
				if (stopDistance > 0 && candle.LowPrice <= _entryPrice - stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.HighPrice >= _entryPrice + takeDistance)
					hit = true;
			}
			else if (_currentSide == Sides.Sell)
			{
				if (stopDistance > 0 && candle.HighPrice >= _entryPrice + stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.LowPrice <= _entryPrice - takeDistance)
					hit = true;
			}

			if (hit)
			{
				// Close position
				if (Position > 0)
					SellMarket();
				else if (Position < 0)
					BuyMarket();

				_lastCompletedSide = _currentSide;
				_currentSide = null;
				_entryPrice = 0m;
			}
		}

		// If flat, open next position
		if (Position == 0 && _currentSide == null)
		{
			// Alternate direction: start with sell, then flip
			var sideToOpen = _lastCompletedSide switch
			{
				Sides.Buy => Sides.Sell,
				Sides.Sell => Sides.Buy,
				_ => Sides.Sell,
			};

			if (sideToOpen == Sides.Buy)
				BuyMarket();
			else
				SellMarket();

			_currentSide = sideToOpen;
			_entryPrice = price;
		}
	}
}