GitHub で見る

Trend Line戦略

概要

Trend Line戦略は、高速および低速の線形加重移動平均、Momentumフィルター、MACD確認を組み合わせることで、オリジナルのMetaTraderエキスパートのコアトレード管理ロジックを再現します。変換はStockSharpの高レベルコンポーネントに焦点を当て、エントリー前にトレンド方向のMomentum爆発を待つ同じ体系的なアプローチを維持します。価格ステップでの保護ストップ、利益目標、オプションのトレーリングストップがソースエキスパートと同様のリスク管理を提供します。

トレードロジック

  1. 設定されたキャンドルシリーズをサブスクライブし、以下のインジケーターを計算します:
    • 設定可能なFastMaPeriodを持つ高速線形加重移動平均(LWMA)。
    • 設定可能なSlowMaPeriodを持つ低速LWMA。
    • 期間MomentumPeriodのMomentumインジケーター。最近の3つのMomentum読み取りはMQLバージョンに存在するマルチバーMomentumチェックを模倣するために追跡されます。
    • 標準の高速/低速/シグナル長でのMACD(移動平均収束拡散)インジケーター。戦略は後で使用するためにMACDとシグナル値を格納します。
  2. 以下の場合にロングエントリー:
    • 高速LWMAが低速LWMAを上回っている。
    • 最後の3つのMomentum値の少なくとも1つがMomentumBuyThreshold以上である。
    • MACD主線がMACDシグナル線を上回っている。
    • オープンのショートポジションが存在しない(ロングポジションを開く前にショートエクスポージャーがフラット化される)。
  3. 以下の場合にショートエントリー:
    • 高速LWMAが低速LWMAを下回っている。
    • 最後の3つのMomentum値の少なくとも1つがMomentumSellThreshold以下である(下方加速を検出するには閾値は負である必要があります)。
    • MACD主線がMACDシグナル線を下回っている。
    • オープンのロングポジションが存在しない(ショートポジションを開く前にロングエクスポージャーがフラット化される)。
  4. 各エントリー後、戦略は価格ステップ距離で保護的なストップロスとテイクプロフィット注文を出します。両方の注文はポジションが変化するたびに再計算されます。
  5. トレーリングストップはTrailingStopStepsTrailingTriggerStepsで有効化できます。オープンポジションが少なくともトリガー距離を獲得すると、ストップロスが処理されたキャンドルの現在のクローズ価格からTrailingStopStepsに移動されます。

パラメーター

  • CandleType – 各インジケーターが使用するキャンドルシリーズのデータタイプ(デフォルト1時間時間軸)。
  • FastMaPeriod – 高速LWMAの期間(デフォルト6)。
  • SlowMaPeriod – 低速LWMAの期間(デフォルト85)。
  • MomentumPeriod – Momentum計算のキャンドル数(デフォルト14)。
  • MomentumBuyThreshold – 新しいロングポジションを許可するために必要な最小正Momentum(デフォルト0.3)。
  • MomentumSellThreshold – 新しいショートポジションを開く前に許可される最大(負)Momentum(デフォルト-0.3)。
  • MacdFastLength – MACDの高速EMA長(デフォルト12)。
  • MacdSlowLength – MACDの低速EMA長(デフォルト26)。
  • MacdSignalLength – MACDのシグナルEMA長(デフォルト9)。
  • StopLossSteps – インストゥルメントステップで表された保護ストップ距離(デフォルト20)。
  • TakeProfitSteps – ステップ単位の保護利益目標距離(デフォルト50)。
  • TrailingStopSteps – ステップ単位のトレーリングストップ距離(デフォルト40、ゼロの場合無効)。
  • TrailingTriggerSteps – トレーリングストップが有効になる前に必要なステップ単位の利益(デフォルト40)。

注意事項

  • インジケーターバインディングは完了したキャンドルのみに依存し、未完のデータは早期シグナルを避けるために無視されます。
  • SetStopLossSetTakeProfitは価格ステップでの距離で動作し、異なるティックサイズのインストゥルメントで動作を一貫させます。
  • MomentumSellThresholdが正に保たれている場合、デフォルトの比較(<= threshold)はその値が負であることを期待します。戦略を最適化する際は符号を調整してください。
  • トレーリングストップは各完了キャンドルの処理時に更新されるためバーエンドモードで動作し、新しいバーでストップを再計算したオリジナルスクリプトを反映します。
  • 変換はStockSharpで利用できないインタラクティブなターミナル機能に依存していたため、手動トレンドライン描画とエクイティベースの清算ルールを意図的に省略しています。他のすべてのコアエントリーとリスクルールは保存されています。
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;

public class TrendLineStrategy : 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;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public TrendLineStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).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");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	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;

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

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

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}