GitHub で見る

Crypto SR戦略

Crypto SR戦略は、MetaTrader 4のエキスパートアドバイザー「Crypto S&R」をStockSharpの高レベルAPIへ移植したものです。実装は元のシステムの階層的な確認ロジックを維持します。線形加重移動平均(LWMA)に基づくトレンドフィルター、上位時間軸のモメンタム確認、長期MACDトレンドフィルター、フラクタル由来のサポート/レジスタンス水準を組み合わせます。注文は成行で送信され、ポジションは固定のストップロス/テイクプロフィット、ブレイクイーブン調整、pips単位のトレーリングストップで管理されます。

取引ロジック

  1. 主要時間軸の分析: 戦略は設定されたローソク足系列を購読し、典型価格 (high + low + close) / 3 を使って2本のLWMAを更新します。ロング(ショート)を許可するには、高速LWMAが低速LWMAの上(下)にある必要があります。
  2. 上位時間軸のモメンタム: Momentum指標を2つ目のローソク足系列で評価します。中立値(100)からの直近3つのモメンタム値の絶対距離が、買い/売りのしきい値を超える必要があります。
  3. 長期MACDフィルター: 別のローソク足ストリームでMACD(12, 26, 9)を計算します。ロングではMACDラインがシグナルを上回る必要があり、ショートでは下回る必要があります。既定の長期時間軸は日足で、EAが使う月足系列を近似します。実際の月足が利用できる場合は調整できます。
  4. フラクタルのサポート/レジスタンス: 完了したローソク足をローリングバッファーに保存します。古典的なBill Williamsフラクタルパターン(両側に2本ずつ)が現れると、対応する高値/安値が有効なレジスタンスまたはサポートになります。元のエキスパートが描く水平線を再現するため、設定可能なpipバッファーを水準の周囲に適用します。
  5. エントリールール:
    • 買い: オープン中のロングがなく、高速LWMAが低速LWMAの上、モメンタム偏差が買いしきい値以上、MACDが強気、現在のローソク足がバッファー付きサポートを試して前回終値より上で閉じる。
    • 売り: レジスタンス水準、モメンタム売りしきい値、弱気MACD確認を使った反対条件。
  6. リスク管理: 新しい各ポジションには、pips単位の初期ストップロスとテイクプロフィットを設定します。価格がトリガー距離に達するとブレイクイーブンロジックでストップを移動でき、任意のトレーリングストップはローソク足の高値/安値を使って価格を追跡します。MACDフィルターが取引と逆方向へ反転した場合、ロング/ショートのエクスポージャーを閉じます。

実装メモ

  • MetaTrader版の月次MACDフィルターは、StockSharpがカレンダー月のローソク足を標準提供しないため、既定では日足系列で近似されます。データソースが対応している場合は、独自の月次アグリゲーターへ切り替えられます。
  • 保護水準が破られた場合、注文は成行リクエストで閉じられます。これはMQLのOrderClose呼び出しを反映し、取引所側のストップ注文への依存を避けます。
  • すべての指標バインディングは高レベル購読APIで行われ、GetValueへの直接呼び出しは不要です。

パラメーター

名前 説明 既定値
FastMaPeriod 主要時間軸の高速LWMAの長さ。 6
SlowMaPeriod 主要時間軸の低速LWMAの長さ。 85
MomentumPeriod 上位時間軸のモメンタム期間。 14
MomentumBuyThreshold ロングエントリーを有効にするための、100からの最小絶対モメンタム偏差。 0.3
MomentumSellThreshold ショートエントリーを有効にするための、100からの最小絶対モメンタム偏差。 0.3
MacdFastPeriod 長期MACDフィルターの高速EMA長。 12
MacdSlowPeriod 長期MACDフィルターの低速EMA長。 26
MacdSignalPeriod 長期MACDフィルターのシグナルEMA長。 9
StopLossPips pipsで表すハードストップロス距離。 20
TakeProfitPips pipsで表す固定テイクプロフィット距離。 50
TrailingStopPips pipsで表すトレーリングストップ距離(0で無効)。 40
UseBreakEven 利益トリガー後にストップをブレイクイーブンへ移動するかどうか。 true
BreakEvenTriggerPips ブレイクイーブン調整前に必要な利益pips。 30
BreakEvenOffsetPips ストップをブレイクイーブンへ移動するときに加えるオフセット。 30
FractalWindowLength フラクタル高値/安値を確認するために保持する完了済みローソク足数。 7
FractalBufferPips フラクタル水準周辺に加える追加バッファー(pips)。 10
TradeVolume 各成行注文で送信する数量。 1
CandleType LWMAとフラクタルロジック用の主要ローソク足系列。 15m時間軸
HigherCandleType モメンタムフィルター用の上位時間軸。 1h時間軸
LongTermCandleType MACDトレンドフィルター用の時間軸。 1d時間軸
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 CryptoSrStrategy : 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 CryptoSrStrategy()
	{
		_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;
	}
}