GitHub で見る
Stochastic Momentum Filter 戦略
概要
Stochastic Momentum Filter 戦略は、MetaTraderのエキスパートアドバイザーStochastic.mq4(フォルダMQL/23473)のStockSharpポートです。元のロボットは2つのストキャスティクスオシレーター、線形加重移動平均(LWMA)、Momentumの偏差フィルター、および上位タイムフレームのMACDトレンドチェックを組み合わせます。このC#バージョンはStockSharpの高レベルAPIの上で同じ構成要素を再現し、多層確認ワークフローを維持します:
- トレンドフィルター – ロングトレード(またはショートトレード)が許可される前に、速いLWMAが遅いLWMAより上(または下)にある必要があります。
- オシレーター確認 – 速いストキャスティクス(5/2/2)と遅いストキャスティクス(21/4/10)の両方が売られ過ぎ/買われ過ぎゾーンで一致する必要があります。
- Momentumの偏差 – 最近の3つのMomentum読み取り値のうち少なくとも1つが設定可能な閾値を超えて100のベースラインから偏差しなければならず、エキスパートによるMT4の
iMomentum関数の使用に対応します。
- 上位タイムフレームMACD – 設定可能な上位タイムフレームのMACDメインラインはロングのシグナルラインより上(ショートでは下)に留まる必要があります。デフォルトの30日タイムフレームは元の月次フィルターに近似します。
- リスクロジック – ストップロス、テイクプロフィット、およびオプションのトレーリングは
StartProtectionを通じて処理され、EAの保護パラメーターを反映します。ポジションのフリップは新しいネットポジションを確立する前に反対の露出を自動的に閉じます。
戦略は2つのローソク足ストリームを購読します:トレードタイムフレームとMACDフィルターを供給する上位タイムフレーム。すべての計算はStockSharpインジケーターで実行され、高レベルのBindヘルパーを通じて処理されます。
パラメーター
| 名前 |
デフォルト |
説明 |
StochasticBuyLevel |
30 |
ロングセットアップのために両方のストキャスティクスオシレーターが破るべき売られ過ぎレベル。 |
StochasticSellLevel |
80 |
ショートセットアップのために両方のストキャスティクスオシレーターが達するべき買われ過ぎレベル。 |
FastMaPeriod |
6 |
速いLWMAトレンドフィルターの長さ。 |
SlowMaPeriod |
85 |
遅いLWMAトレンドフィルターの長さ。 |
FastStochasticPeriod |
5 |
速いストキャスティクスオシレーターの%K期間。 |
FastStochasticSignal |
2 |
速いストキャスティクスの%Dスムージング期間。 |
FastStochasticSmoothing |
2 |
速いストキャスティクスに適用される追加スムージング(MT4の「slowing」に対応)。 |
SlowStochasticPeriod |
21 |
遅いストキャスティクスオシレーターの%K期間。 |
SlowStochasticSignal |
4 |
遅いストキャスティクスの%Dスムージング期間。 |
SlowStochasticSmoothing |
10 |
遅いストキャスティクスに適用される追加スムージング。 |
MomentumPeriod |
14 |
Momentumオシレーターのルックバック(MT4のiMomentumと同じ)。 |
MomentumThreshold |
0.3 |
最後の3つのMomentum値内で必要な100ベースラインからの最小絶対偏差。 |
MacdFastPeriod |
12 |
上位タイムフレームMACDの速いEMA期間。 |
MacdSlowPeriod |
26 |
上位タイムフレームMACDの遅いEMA期間。 |
MacdSignalPeriod |
9 |
上位タイムフレームMACDのシグナルEMA期間。 |
TakeProfitPoints |
50 |
テイクプロフィット距離(価格ポイント)。無効にするには0に設定。 |
StopLossPoints |
20 |
ストップロス距離(価格ポイント)。無効にするには0に設定。 |
EnableTrailing |
true |
保護ストップのStockSharpトレーリングを有効にする。 |
TradeVolume |
1 |
各シグナルでターゲットとするネットポジションサイズ。 |
MaxNetPositions |
1 |
スタックされたネット露出を制限する(TradeVolumeを乗算)。 |
CandleType |
15mタイムフレーム |
メインのトレードタイムフレーム。 |
HigherTimeframe |
30dタイムフレーム |
MACD確認に使用するタイムフレーム。 |
トレードロジック
- インジケーターの準備 – 戦略は両方のLWMA、両方のストキャスティクスオシレーター、Momentumインジケーター、およびMACDをそれぞれのローソク足ストリームにバインドします。
- Momentumの履歴 – Momentumオシレーターの100からの絶対距離は最後の3本の完了したバーに保存されます。これはEAの
MomLevelB/MomLevelS配列を再現します。
- エントリールール
- ロング:速いLWMAが遅いLWMAより上、両方のストキャスティクスの
%Kと%D値がStochasticBuyLevelより下、Momentumの偏差がMomentumThresholdより上、そしてMACDメインラインがシグナルラインより上。
- ショート:速いLWMAが遅いLWMAより下、両方のストキャスティクスの
%Kと%D値がStochasticSellLevelより上、Momentumの偏差が閾値より上、そしてMACDメインラインがシグナルラインより下。
- ポジション処理 – 注文は
BuyMarket/SellMarketで送信されます。反転シグナルが現れると、戦略は新しい方向を確立する前に反対のネット露出を自動的に閉じます。
- 保護 –
StartProtectionは設定されたテイクプロフィットとストップロス距離(ポイント)を適用します。EnableTrailingがtrueの場合、StockSharpはEAのトレーリングルーティンと同様にストップのトレーリングを管理します。
MQLバージョンとの違い
- ボリュームスケーリング:EAは
LotExponentを使用してロットサイズをスケールし、複数の同時チケットを許可します。StockSharpポートはネット露出に焦点を当て、方向ごとに単一のTradeVolumeをターゲットとします(MaxNetPositionsで制限)。
- マージン管理:元のスクリプトのマージンチェック、エクイティストップ、および通知機能はMT4アカウントAPIに依存するため再現されません。
- フリーズレベル:ブローカー固有の低レベルフリーズレベルチェックは省略されます;StockSharpの注文ルーティングが取引所の制約を処理します。
- ブレークイーブントグル:MT4の「break-evenへ移動」ヘルパーはStockSharpのトレーリング保護に置き換えられます。
使用上の注記
- 証券とコネクターを割り当て、戦略を開始します。トレードタイムフレームとMACDフィルターに必要な上位タイムフレームの両方を自動的に購読します。
- データソースが30日のローソク足タイプをサポートしない場合は、
HigherTimeframeをサポートされている間隔(例:週次または日次)に調整してください。
- ポートフォリオユニットに合わせて
TradeVolumeを設定します。
- 保護注文を無効にする場合は
TakeProfitPoints/StopLossPointsをゼロに設定します。
- コード内のすべてのコメントは英語で記述され、インデントにはタブを使用します。
ファイル
CS/StochasticMomentumFilterStrategy.cs – 戦略ロジックのStockSharp実装。
README.md – 英語ドキュメント(このファイル)。
README_ru.md – ロシア語ドキュメント。
README_zh.md – 中国語ドキュメント。
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 StochasticMomentumFilterStrategy : 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 StochasticMomentumFilterStrategy()
{
_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;
}
}
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
class stochastic_momentum_filter_strategy(Strategy):
def __init__(self):
super(stochastic_momentum_filter_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(stochastic_momentum_filter_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(stochastic_momentum_filter_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return stochastic_momentum_filter_strategy()