STO M5xM15xM30 戦略
概要
この戦略は、MetaTrader 4 エキスパート アドバイザ「STO_m5xm15xm30」を忠実に C# 変換したものです。 M5、M15、M30 タイムフレームで計算された 3 つの確率オシレーターを使用して、同期した運動量の変化を特定します。 StockSharp 実装は、元の入口/出口構造を維持し、手動注文管理を高レベルの API に置き換え、すべてのキー定数を構成可能な StrategyParam として公開します。
取引ロジック
- マルチタイムフレームの確認
- プライマリ(デフォルト M5)ストキャスティックスは強気のクロスオーバー(
%K が %D を超える)を示す必要があります。
- ミドル (デフォルト M15) とスロー (デフォルト M30) の確率値は、すでに強気 (
%D を上回る %K) になっている必要があります。
- 弱気のセットアップには、ミラーリングされた条件 (
%D の下の %K) が必要です。
- シフトフィルター
- プライマリ ストキャスティクスは、状態
ShiftBars キャンドルもチェックします。買いシグナルでは、過去の %K が %D を下回っており、新たなクロスオーバーが確実に発生する必要があります。売りシグナルにはその逆が必要です。
- 価格モメンタムフィルター
- 最新の終値は、以前に完了したローソク足の終値よりも高い (買いの場合) か、低い (売りの場合) 必要があります。これは、MT4 スクリプトの
Close[0] > Close[1] ルールを反映しています。
- エントリールール
- オープンなポジションがなく、強気の基準が満たされている場合、戦略は設定された
TradeVolume でロング成行注文をオープンします。
- 強気シグナルが到着したときにショート ポジションが存在する場合、最初にフラット化され、その後ロング ポジションがオープンされます。弱気シグナルの場合はその逆が当てはまります。
- 退出ルール
- 期間
ExitKPeriod の専用 M5 ストキャスティクスは、前のローソク足 (shift = 1) をチェックします。ロングポジションは、%K が %D を下回るとクローズされます。 %K が %D を上回るとショートがクローズされます。
- イグジットがトリガーされた後、この戦略は同じローソク足での即時再エントリーをスキップし、MT4 注文ループの動作を再現します。
インジケーターとデータサブスクリプション
- プライマリーローソク足: デフォルトの 5 分間の時間枠 (
CandleType)。
- 中間の確認ローソク足: デフォルトの 15 分の時間枠 (
MiddleCandleType)。
- 遅い確認ローソク足: デフォルトの 30 分の時間枠 (
SlowCandleType)。
- Stochastic オシレーター: すべては %K スムージング = 3 および %D スムージング = 3 を使用し、元のパラメーターと一致します。
パラメーター
| 名前 |
デフォルト |
説明 |
CandleType |
5分キャンドル |
エントリーとエグジットの作業時間枠。 |
MiddleCandleType |
15分キャンドル |
確認期間 #1。 |
SlowCandleType |
30分キャンドル |
確認期限 #2。 |
FastKPeriod |
5 |
プライマリ ストキャスティクスの %K 期間。 |
MiddleKPeriod |
5 |
中間確率の %K 期間。 |
SlowKPeriod |
5 |
スローストキャスティックの %K 期間。 |
ExitKPeriod |
5 |
前のバーで動作する出口ストキャスティックの %K 期間。 |
ShiftBars |
3 |
基準クロスオーバーと現在のバーの間のバーの数。 |
TakeProfitPoints |
30 |
プロテクティブテイクプロフィットディスタンス(ポイント)。 |
StopLossPoints |
10 |
保護ストップロス距離 (ポイント)。 |
TradeVolume |
0.1 |
新規エントリーに使用される注文量。 |
すべてのパラメータは StrategyParam<T> を通じて公開され、StockSharp デザイナー内で最適化できるようになります。
リスク管理
StartProtection() は、MT4 の TP および SL 入力を StockSharp の保護命令に変換します。対応するパラメータをゼロに設定することで、両方を無効にできます。
実装メモ
- インジケーター値は、
SubscribeCandles(...).BindEx(...) を通じてのみ取得され、高レベルの API ガイドラインに準拠し、手動によるインジケーター収集を回避します。
StochasticShiftBuffer ヘルパーは、GetValue を呼び出さずに MT4 の shift 引数を模倣し、必要なバー履歴のみを保持します。
- エントリー処理は完了したキャンドルごとに 1 回発生します。終了評価は開始ロジックの前に行われ、元の EA の処理順序と一致します。
- インライン コメントは各処理ステップを説明し、MQL ロジックが StockSharp コードにどのようにマッピングされるかを明確にします。
使用法
- 戦略を StockSharp スキームまたはデザイナー プロジェクトに追加します。
- 目的のシンボルを構成し、M5、M15、および M30 ローソク足の履歴データが利用可能であることを確認します。
- ターゲット市場または最適化シナリオに合わせてパラメーターを調整します。
- 戦略を開始します。保護的なストップロス/テイクプロフィットレベルはポジションごとに自動的に登録されます。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// STO M5xM15xM30: RSI momentum with dual EMA confirmation.
/// Uses RSI crossover of 50 level with fast/slow EMA alignment.
/// </summary>
public class StoM5xM15xM30Strategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _atrLength;
private decimal _prevRsi;
private decimal _entryPrice;
public StoM5xM15xM30Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_rsiLength = Param(nameof(RsiLength), 14)
.SetDisplay("RSI Length", "RSI period.", "Indicators");
_fastLength = Param(nameof(FastLength), 10)
.SetDisplay("Fast EMA", "Fast EMA period.", "Indicators");
_slowLength = Param(nameof(SlowLength), 30)
.SetDisplay("Slow EMA", "Slow EMA period.", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period for stops.", "Indicators");
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
public int AtrLength
{
get => _atrLength.Value;
set => _atrLength.Value = value;
}
/// <inheritdoc />
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevRsi = 0;
_entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevRsi = 0;
_entryPrice = 0;
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var fast = new ExponentialMovingAverage { Length = FastLength };
var slow = new ExponentialMovingAverage { Length = SlowLength };
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, fast, slow, atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal rsiVal, decimal fastVal, decimal slowVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevRsi == 0 || atrVal <= 0)
{
_prevRsi = rsiVal;
return;
}
var close = candle.ClosePrice;
// Exit management
if (Position > 0)
{
if (close <= _entryPrice - atrVal * 2m || close >= _entryPrice + atrVal * 3m)
{
SellMarket();
_entryPrice = 0;
}
else if (rsiVal < 40 && fastVal < slowVal)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0)
{
if (close >= _entryPrice + atrVal * 2m || close <= _entryPrice - atrVal * 3m)
{
BuyMarket();
_entryPrice = 0;
}
else if (rsiVal > 60 && fastVal > slowVal)
{
BuyMarket();
_entryPrice = 0;
}
}
// Entry: RSI crosses 50 with EMA alignment
if (Position == 0)
{
if (_prevRsi <= 50 && rsiVal > 50 && fastVal > slowVal)
{
_entryPrice = close;
BuyMarket();
}
else if (_prevRsi >= 50 && rsiVal < 50 && fastVal < slowVal)
{
_entryPrice = close;
SellMarket();
}
}
_prevRsi = rsiVal;
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import RelativeStrengthIndex, ExponentialMovingAverage, AverageTrueRange
class sto_m5x_m15x_m30_strategy(Strategy):
def __init__(self):
super(sto_m5x_m15x_m30_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._fast_length = self.Param("FastLength", 10) \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators")
self._slow_length = self.Param("SlowLength", 30) \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period for stops", "Indicators")
self._prev_rsi = 0.0
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def RsiLength(self):
return self._rsi_length.Value
@property
def FastLength(self):
return self._fast_length.Value
@property
def SlowLength(self):
return self._slow_length.Value
@property
def AtrLength(self):
return self._atr_length.Value
def OnStarted2(self, time):
super(sto_m5x_m15x_m30_strategy, self).OnStarted2(time)
self._prev_rsi = 0.0
self._entry_price = 0.0
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self.RsiLength
self._fast = ExponentialMovingAverage()
self._fast.Length = self.FastLength
self._slow = ExponentialMovingAverage()
self._slow.Length = self.SlowLength
self._atr = AverageTrueRange()
self._atr.Length = self.AtrLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._rsi, self._fast, self._slow, self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, rsi_val, fast_val, slow_val, atr_val):
if candle.State != CandleStates.Finished:
return
rv = float(rsi_val)
fv = float(fast_val)
sv = float(slow_val)
av = float(atr_val)
if self._prev_rsi == 0 or av <= 0:
self._prev_rsi = rv
return
close = float(candle.ClosePrice)
# Exit management
if self.Position > 0:
if close <= self._entry_price - av * 2.0 or close >= self._entry_price + av * 3.0:
self.SellMarket()
self._entry_price = 0.0
elif rv < 40 and fv < sv:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if close >= self._entry_price + av * 2.0 or close <= self._entry_price - av * 3.0:
self.BuyMarket()
self._entry_price = 0.0
elif rv > 60 and fv > sv:
self.BuyMarket()
self._entry_price = 0.0
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_rsi = rv
return
# Entry: RSI crosses 50 with EMA alignment
if self.Position == 0:
if self._prev_rsi <= 50 and rv > 50 and fv > sv:
self._entry_price = close
self.BuyMarket()
elif self._prev_rsi >= 50 and rv < 50 and fv < sv:
self._entry_price = close
self.SellMarket()
self._prev_rsi = rv
def OnReseted(self):
super(sto_m5x_m15x_m30_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._entry_price = 0.0
def CreateClone(self):
return sto_m5x_m15x_m30_strategy()