ホーム
/
戦略のサンプル
GitHub で見る
Ilan iMA戦略
概要
Ilan iMA戦略 は、MetaTrader 5のエキスパートアドバイザーIlan iMA.mq5のStockSharp移植版です。このアドバイザーは、シフトされた移動平均のトレンドフィルターとマーティンゲールスタイルの平均化グリッドを組み合わせています。StockSharpバージョンは高水準APIで同じアイデアを再実装しています:加重移動平均がトレンドを確認すると、戦略はマーケット注文を開き、価格が設定可能なステップだけポジションに逆行するたびに取引を追加し続けます。利益目標、トレーリングストップ、または明示的なストップロスに達すると、バスケット全体が閉じられ、元のEAのマネー管理モデルを再現します。
トレーディングロジック
選択されたタイムフレーム(CandleType)を購読し、設定可能な移動平均(MaMethod、MaPeriod、PriceMode)をフィードします。正のMaShiftはインジケーターを前にシフトするので、戦略はMT5の動作を模倣するために過去の値を評価します。
ローソク足のクローズを待ちます。完了したバーのみがシグナルを生成し、トレーリング/ストップロジックを更新します。
MaShiftバーでシフトされた4つの連続した移動平均値を比較してトレンドを検出します:
厳密に減少する値は下降トレンドを示します;
厳密に増加する値は上昇トレンドを示します。
バスケットが開いていない場合:
下降トレンドでクローズが移動平均値を上回っている場合、StartVolumeでショートを開きます;
上昇トレンドでクローズが移動平均値を下回っている場合、StartVolumeでロングを開きます。
バスケットが存在する場合:
価格がポジションに対して少なくともGridStepPips動いた場合、サイズがLotExponentで成長するがLotMaximumと取引所ボリューム制限で制限される別の注文を開きます;
平均エントリー価格、最低買い価格、最高売り価格はMT5ロジックに近い動作を維持するために内部的に追跡されます。
クローズ条件:
複数の取引を持つバスケットの浮動利益がProfitMinimum(口座通貨)に達すると、その方向のすべての注文を閉じます;
浮動利益がTakeProfitPipsに達するか損失がStopLossPipsに達すると、バスケットを閉じます;
トレーリング保護はTrailingStopPips + TrailingStepPipsポイントの有利な動きの後に有効になり、TrailingStepPipsのステップで動きます。
リスク管理とサイジング
StartVolumeはMT5のStartLotsパラメーターを再現します。各追加注文はLotMaximumと会場の制限(Security.MinVolume、Security.VolumeStep、Security.MaxVolume)を尊重しながら前のサイズをLotExponent倍にします。
ProfitMinimumはMT5バージョンの「ロック解除」動作を保持します:グリッドがヘッジから回復して要求された利益を印刷すると、その方向のすべての取引が閉じられます。
ストップロスとテイクプロフィット距離はpipで測定されます(StopLossPips、TakeProfitPips)。ヘルパーメソッドはSecurity.PriceStepを使用してpipを取引所価格ステップに変換します。
トレーリングブロックはMT5実装を模倣します:トレーリングは価格がTrailingStopPips + TrailingStepPipsを超えた後にのみ始まり、早期のストップ調整を避けるために離散ステップで更新されます。
パラメーター
名前
型
デフォルト
MT5対応
説明
MaPeriod
int
15
Inp_MA_ma_period
トレンドフィルター移動平均の期間。
MaShift
int
5
Inp_MA_ma_shift
バーでの移動平均線の前方シフト。
MaMethod
MovingAverageMethod
Weighted
Inp_MA_ma_method
平滑化アルゴリズム(SMA、EMA、SMMA、LWMA)。
PriceMode
CandlePrice
Weighted
Inp_MA_applied_price
インジケーターに投入するローソク足の価格。
StartVolume
decimal
1
InpStartLots
バスケットの最初の取引のベース注文ボリューム。
GridStepPips
decimal
30
InpStep
平均化エントリー間の距離(pip単位)。
LotExponent
decimal
1.6
InpLotExponent
前の注文サイズに適用される乗数。
LotMaximum
decimal
15
InpLotMaximum
単一注文ボリュームのハード上限。
ProfitMinimum
decimal
15
InpProfitMinimum
複数の取引を持つバスケットを閉じるために必要な最小浮動利益。
StopLossPips
decimal
0
InpStopLoss
pipで表したストップロス距離(0でストップを無効化)。
TakeProfitPips
decimal
100
InpTakeProfit
pipで表したテイクプロフィット距離。
TrailingStopPips
decimal
15
InpTrailingStop
トレーリングストップを有効にする利益閾値。
TrailingStepPips
decimal
5
InpTrailingStep
トレーリングストップが再び動く前の最小追加利益。
CandleType
DataType
15分足
チャート期間
シグナル計算に使用するタイムフレーム。
元のEAとの違い
StockSharpはネッティング環境で動作するため、方向ごとに1つのネットポジションのみが存在します。戦略はMT5のバスケット会計を模倣するためにエントリー価格とボリュームの内部リストを保持します。
取引所固有のボリューム制限はボリュームを丸める際に常に尊重されますが、MT5コードは手動チェックに依存していました。これによりブローカーコネクターによって拒否される注文を防ぎます。
ストップロス、テイクプロフィット、トレーリングロジックは既存のMT5ポジションを変更するのではなく、マーケット出口を通じて表現されます。機能的な動作は同じですが、注文管理はStockSharpによって処理されます。
使用上の注意
pipから価格への変換とボリュームの丸めが正しく機能するように、コネクターにインストゥルメントのメタデータ(PriceStep、StepPrice、MinVolume、VolumeStep、MaxVolume)が入力されていることを確認してください。
トレーリングブロックはpipサイズが取引所価格ステップと等しいと仮定します。非従来型のティックサイズを持つインストゥルメントにはGridStepPips、StopLossPips、TrailingStopPipsを調整してください。
マーティンゲールグリッドは本質的にリスクが高いです。本番環境に展開する前に歴史データで戦略をテストし、現実的な手数料/スリッページ設定を使用してください。
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 IlanImaStrategy : 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 IlanImaStrategy()
{
_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 ilan_ima_strategy(Strategy):
def __init__(self):
super(ilan_ima_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(ilan_ima_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(ilan_ima_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 ilan_ima_strategy()