GitHub で見る
ギャップ回復戦略
概要
ギャップ復帰戦略は、MetaTrader 4 エキスパート アドバイザー gaps.mq4 を直接移植したものです。システムは15分間のロウソクとトイレを監視します
ks は、前のローソク足の高値/安値の範囲外で発生するギャップを開くためのものです。このようなギャップが現れた場合、すぐに戦略を立てることができます。
予想される平均回帰の方向に市場を誘導します。
StockSharp バージョンは、高レベルのキャンドル サブスクリプション API に依存しながら、元のロジックに従います。あらゆる貿易管理は、
成行注文で行われ、固定の保護注文は発注されません。これは、MQL コードで見られる動作を反映しています。
取引ルール
- 15 分のローソク足を購読します (
CandleType パラメータで設定可能)。
- 前回完成したローソクの高値と安値を維持します。
- 新しいキャンドルが始まると:
- ギャップ バッファを計算します:
(MinGapSize + spreadInSteps) * pointValue。
- 始値が
previousHigh + gapBuffer を 上 にしている場合は、ショート ポジションをオープンします。
- 始値が
previousLow - gapBuffer を**下回る場合は、ロング ポジションをオープンします。
- キャンドルごとに 1 つの取引のみが許可されます。注文が出されると、ストラテジーは次のローソク足を待ってから新しい注文を生成します。
点火する。
スプレッド コンポーネントは、利用可能な場合、現在の最良の買値/売値を使用します。相場データが提供されない場合、戦略は罪に戻ります。
保守的なバッファーとしての gle 価格ステップ。
パラメーター
| パラメータ |
デフォルト |
説明 |
MinGapSize |
1 |
注文を送信する前に超える必要がある価格ステップの最小ギャップ サイズ。 |
GapVolume |
0.1 |
ギャップによって引き起こされる市場エントリーの注文量。 |
CandleType |
15m TimeFrame |
計算に使用されるローソク足のタイプ (デフォルトは 15 分足ローソク足)。 |
すべてのパラメータは StrategyParam<T> として登録され、StockSharp デザイナーまたはその他のツール内での最適化をサポートします。
実装メモ
SubscribeCandles を Bind とともに使用して、完成したキャンドルのみを処理します。
- データ系列の再計算を避けるために、前のローソク足の範囲を記憶します。
- 取引をトリガーしたバーのオープン時間を追跡することで、同じローソク足での重複注文をブロックします。
- チャート出力は登録されたローソク足を描画し、戦略は迅速な視覚的検査のために取引されます。
MQL バージョンとの違い
- 元の EA でテイクプロフィットとストップロスのレベルが正しく設定されていませんでした (MQL コードが間違ったパラメータに値を渡しました)
。したがって、StockSharp ポートは、保護命令なしで実行される動作を維持します。
- スプレッド処理は、利用可能な場合にリアルタイムの買値/売値をチェックするようになり、より適応性の高いバッファーを提供します。
要件
- StockSharp API は、選択した商品のローソク足データにアクセスできます。
- レベル 1 の引用はオプションですが、スプレッドの検出が向上します。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Gap Reversion strategy - detects gap openings and trades mean reversion.
/// Buys when candle opens below previous low (gap down reversion).
/// Sells when candle opens above previous high (gap up reversion).
/// Uses EMA as trend filter for exits.
/// </summary>
public class GapReversionStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevHigh;
private decimal _prevLow;
private bool _hasPrev;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public GapReversionStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetDisplay("EMA Period", "EMA trend filter", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
protected override void OnReseted() { base.OnReseted(); _prevHigh = 0m; _prevLow = 0m; _hasPrev = false; }
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_hasPrev = false;
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(2, UnitTypes.Percent),
stopLoss: new Unit(1, UnitTypes.Percent)
);
}
private void ProcessCandle(ICandleMessage candle, decimal ema)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrev)
{
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
_hasPrev = true;
return;
}
var open = candle.OpenPrice;
var close = candle.ClosePrice;
// Gap down reversion - open below previous low, expect bounce
if (open < _prevLow && close > ema && Position == 0)
BuyMarket();
// Gap up reversion - open above previous high, expect pullback
else if (open > _prevHigh && close < ema && Position == 0)
SellMarket();
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Messages import Unit, UnitTypes
class gap_reversion_strategy(Strategy):
def __init__(self):
super(gap_reversion_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20).SetDisplay("EMA Period", "EMA trend filter", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
@property
def ema_period(self): return self._ema_period.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self):
super(gap_reversion_strategy, self).OnReseted()
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(gap_reversion_strategy, self).OnStarted2(time)
self._has_prev = False
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.process_candle).Start()
self.StartProtection(takeProfit=Unit(2, UnitTypes.Percent), stopLoss=Unit(1, UnitTypes.Percent))
def process_candle(self, candle, ema):
if candle.State != CandleStates.Finished:
return
if not self._has_prev:
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
self._has_prev = True
return
op = float(candle.OpenPrice)
close = float(candle.ClosePrice)
ema_val = float(ema)
if op < self._prev_low and close > ema_val and self.Position == 0:
self.BuyMarket()
elif op > self._prev_high and close < ema_val and self.Position == 0:
self.SellMarket()
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
def CreateClone(self):
return gap_reversion_strategy()