GitHub で見る

Precipice 戦略

概要

Precipice 戦略は MetaTrader エキスパートアドバイザー Precipice (barabashkakvn's edition) の直接変換です。このシステムは市場構造を分析したりインジケーターを使用したりしません。代わりに、前のポジションがクローズするのを待ってからコインを投げてロングかショートかを決定します。トレーダーが両方向を有効にすると、アカウントが現在フラットである場合、すべての完了したローソク足は50%の確率で新しいポジションを生成します。オプションの保護注文は各取引に同じストップロスとテイクプロフィット距離(「ピップス」単位)を付加することでMetaTraderの動作をミラーします。

StockSharp の実装は元のコードのランダムな性質を維持し、そのマネー管理設定を再現します。ストップロスとテイクプロフィットが有価証券が使用する小数点以下の桁数に関係なく対称であり続けるよう、MetaTrader のピップ距離を楽器のネイティブ価格ステップに自動的に変換します。

取引ロジック

  1. CandleType で定義された主要ローソク足シリーズをサブスクライブし、バーのクローズ後の MetaTrader OnTick ロジックに合わせるために完了したローソク足のみを処理します。
  2. ポジションが開いている間はすべてのシグナルを無視します。エキスパートは一度に最大1つの取引を配置します。
  3. ストラテジーがフラットのとき、買いブランチの乱数を生成します。UseBuy が有効で結果が 0.5 未満の場合、TradeVolume ロットの買い成行注文を送信します。
  4. ロングポジションが開かれなかった場合、売りブランチの別の乱数を生成します。UseSell が有効で結果が 0.5 を超える場合、売り成行注文を送信します。
  5. エントリー後、オプションのストップロスとテイクプロフィット注文をローソク足クローズから MetaTrader の StopLossTakeProfitPips ピップのところに付加します。保護注文はポジションがゼロに戻ると自動的にキャンセルされます。

パラメーター

名前 デフォルト 説明
CandleType DataType 1分の時間軸 ストラテジーが処理する主要時間軸。
TradeVolume decimal 1 すべての成行エントリーに使用される注文サイズ。
StopLossTakeProfitPips int 100 エントリー価格と両方の保護注文の間の距離(MetaTrader ピップス単位)。ストップロスとテイクプロフィットの配置を無効にするには 0 に設定します。
UseBuy bool true ランダムなロングエントリーを有効にします。
UseSell bool true ランダムなショートエントリーを有効にします。

元の MetaTrader エキスパートとの違い

  • MetaTrader は楽器のフリーズおよびストップレベルを公開します。StockSharp ポートはピップ距離変換のみをエミュレートし、必要に応じてブローカーに無効なストップ距離の拒否を任せます。
  • 元の EA は現在の Bid/Ask クォートを使用します。StockSharp ストラテジーは高レベル API が集計されたローソク足データを受信するため、保護注文をローソク足のクローズ価格に基づかせます。スリッページとスプレッドの影響は外部で処理する必要があります。
  • MetaTrader は個々のチケットで動作しますが、StockSharp はネットポジションを管理します。変換は最大1つのネットポジションを保持し、エクスポージャーがゼロに戻るとすぐに保護注文を削除します。

使用上のヒント

  • 有価証券のロットステップに合ったリアルな TradeVolume を選択してください。コンストラクターもこの値を Strategy.Volume に適用するため、ヘルパーメソッドは意図した量で注文を送信します。
  • 楽器のボラティリティに合わせて StopLossTakeProfitPips を調整してください。ストラテジーはネイティブ価格距離を得るために有価証券の価格ステップでピップを掛けます(3/5桁クォートに対してスケーリングされます)。
  • ランダムジェネレーターが1つの方向だけでトレードを開くようにしたい場合は、UseBuy または UseSell のみを有効にします。
  • エントリーがランダムであるため、確定的な終了条件が必要な場合は追加のリスク制限または最大ポジション期間でストラテジーを監視してください。

インジケーター

  • なし。ストラテジーは純粋にランダムなトレード生成とオプションの保護注文に依存しています。
using System;
using System.Collections.Generic;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Precipice strategy using EMA crossover for trend direction.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class PrecipiceStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	/// <summary>
	/// Fast EMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <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>
	/// Initializes a new instance of the <see cref="PrecipiceStrategy"/> class.
	/// </summary>
	public PrecipiceStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast EMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 80)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow EMA period", "Indicator");

		_stopLossPoints = Param(nameof(StopLossPoints), 200)
			.SetNotNegative()
			.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

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

		_fast = null;
		_slow = null;
		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
		_cooldown = 0;
	}

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

		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

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

		if (!_fast.IsFormed || !_slow.IsFormed)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		// Check SL/TP
		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}

		// EMA crossover
		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();

			BuyMarket();
			_entryPrice = close;
			_cooldown = 80;
		}
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();

			SellMarket();
			_entryPrice = close;
			_cooldown = 80;
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}