GitHub で見る
エリー戦略
概要
Elli 戦略は、MetaTrader 4 エキスパート アドバイザー「Elli」を StockSharp の高レベル API に移植します。元のロボットは、H1 タイムフレームの Ichimoku Kinko Hyo 構造を、より低いタイムフレーム ADX フィルターと厳格なリスク パラメーターと組み合わせました。この変換では、同じ方向ロジックが維持され、手動の注文管理が StartProtection に置き換えられ、すべての調整ノブが最適化可能な StrategyParam<T> として公開されるため、動作をさまざまな市場に適応させることができます。
取引ロジック
- Ichimoku のトレンド構造
- この戦略は、
CandleType で定義されたタイムフレーム (デフォルトでは H1) をサブスクライブし、元の期間 (19、60、120) を使用して天下線、基準線、および線香スパンを計算します。
- 強気のセットアップには、テンカン > キジュン > センコウ スパン A > センコウ スパン B が必要で、ローソク足がキジュンのすぐ上にあります。弱気のセットアップはこの状況を反映しています。
- 平らな雲や広範囲にわたる雲を避けるには、テンカンとキジュンの間の絶対距離が
TenkanKijunGapPips ピップスを超える必要があります。
- 方向移動の確認
- 2 番目のローソク足サブスクリプションは、
AdxCandleType で指定された時間枠 (デフォルトでは M1) で平均方向性インデックスを実行します。
- ロングシグナルは、以前の +DI 値が
ConvertLow を下回っており、現在の +DI が ConvertHigh を超えている場合にのみ許可されます。 Short は、MT4 コードに存在する加速フィルターを複製する、-DI コンポーネントに対して同じ関係を必要とします。
- エントリー実行
- すべてのフィルターが一致すると、ストラテジーは数量
OrderVolume + |Position| の成行注文を発行します。これにより、トレンドに加わる前に反対のエクスポージャが自動的にクローズされます。
- 元の
OrdersTotal() < 1 ガードに従って、一度に 1 つの方向の露出のみが維持されます。
- リスク管理
StartProtection は、商品のピップサイズを使用してピップ距離から変換された対称的なストップロス注文とテイクプロフィット注文を添付します。
- それ以外の場合、ポジションは受動的に管理され、保護命令が MT4 エキスパートアドバイザーと同じようにエグジットを処理できるようになります。
インジケーターとデータサブスクリプション
- プライマリ ローソク足: Ichimoku 処理用の
CandleType (デフォルトの 1 時間足ローソク足)。
- ADX ローソク足:
AdxCandleType (デフォルトの 1 分ローソク足)、DI 加速チェック用。
- インジケーター:
Ichimoku (テンカン、キジュン、センコウ スパン B) および AverageDirectionalIndex (+DI/−DI を提供)。
- どちらのサブスクリプションも、グラフ領域が利用可能な場合、
DrawCandles、DrawIndicator、および DrawOwnTrades を介したグラフのレンダリングをサポートします。
パラメーター
| 名前 |
デフォルト |
説明 |
OrderVolume |
1 |
基本市場注文量。 |
TakeProfitPips |
60 |
ピップスで表されるテイクプロフィット距離。 |
StopLossPips |
30 |
ピップスで表されるストップロス距離。 |
TenkanPeriod |
19 |
Ichimoku インジケーターのテンカンセン期間。 |
KijunPeriod |
60 |
Ichimoku インジケーターの基準線期間。 |
SenkouSpanBPeriod |
120 |
Ichimoku クラウドの閃光スパン B 期間。 |
TenkanKijunGapPips |
20 |
取引前に必要な最小 Tenkan/Kijun 距離 (pips 単位)。 |
ConvertHigh |
13 |
勢いを確認するには、現在の値が DI しきい値を超える必要があります。 |
ConvertLow |
6 |
新しい取引を行う前に、以前の値が DI しきい値を下回っていなければなりません。 |
AdxPeriod |
10 |
ADX の計算に使用される期間。 |
CandleType |
H1 |
Ichimoku の計算を行う時間枠。 |
AdxCandleType |
M1 |
ADX と DI モニタリングに使用される時間枠。 |
すべてのパラメータは StrategyParam<T> ヘルパーを使用して実装されており、StockSharp デザイナー内での最適化とランタイム調整が可能になります。
実装メモ
- pip 変換は標準の外国為替規則 (5 桁の相場の場合は 0.0001、3 桁の金融商品の場合は 0.01) に従って、元の pip ベースのしきい値が保持されます。
- ADX の値は
_latestPlusDi、_previousPlusDi、_latestMinusDi、および _previousMinusDi にキャッシュされ、DI アクセラレーション チェックがシフト 0 および 1 の MQL iADX 呼び出しと一致することが保証されます。
IsFormedAndOnlineAndAllowTrading() は、戦略、インジケーター、データ フィードの準備ができるまでシグナルをブロックし、ウォームアップ中の時期尚早な取引を防ぎます。
- 市場エントリーは
Volume + Math.Abs(Position) に依存するため、方向の変更により既存の取引が即座に平坦化され、MT4 スクリプトの単一ポジションの動作がエミュレートされます。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Elli: EMA crossover with ATR momentum confirmation.
/// Fast EMA above slow EMA = bullish, below = bearish.
/// Entry when ATR expansion confirms trend strength.
/// </summary>
public class ElliStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _atrLength;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _prevAtr;
private decimal _entryPrice;
public ElliStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_fastLength = Param(nameof(FastLength), 19)
.SetDisplay("Fast EMA", "Fast EMA period.", "Indicators");
_slowLength = Param(nameof(SlowLength), 60)
.SetDisplay("Slow EMA", "Slow EMA period.", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period for momentum.", "Indicators");
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.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();
_prevFast = 0;
_prevSlow = 0;
_prevAtr = 0;
_entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = 0;
_prevSlow = 0;
_prevAtr = 0;
_entryPrice = 0;
var fast = new ExponentialMovingAverage { Length = FastLength };
var slow = new ExponentialMovingAverage { Length = SlowLength };
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(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 fastVal, decimal slowVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevFast == 0 || _prevSlow == 0 || atrVal <= 0)
{
_prevFast = fastVal;
_prevSlow = slowVal;
_prevAtr = atrVal;
return;
}
var close = candle.ClosePrice;
// Exit: stop or take based on ATR
if (Position > 0)
{
if (close <= _entryPrice - atrVal * 2m || close >= _entryPrice + atrVal * 3m)
{
SellMarket();
_entryPrice = 0;
}
else if (fastVal < slowVal)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0)
{
if (close >= _entryPrice + atrVal * 2m || close <= _entryPrice - atrVal * 3m)
{
BuyMarket();
_entryPrice = 0;
}
else if (fastVal > slowVal)
{
BuyMarket();
_entryPrice = 0;
}
}
// Entry: EMA crossover with ATR expansion
if (Position == 0)
{
var atrRising = atrVal > _prevAtr;
if (_prevFast <= _prevSlow && fastVal > slowVal && atrRising)
{
_entryPrice = close;
BuyMarket();
}
else if (_prevFast >= _prevSlow && fastVal < slowVal && atrRising)
{
_entryPrice = close;
SellMarket();
}
}
_prevFast = fastVal;
_prevSlow = slowVal;
_prevAtr = atrVal;
}
}
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 ExponentialMovingAverage, AverageTrueRange
class elli_strategy(Strategy):
def __init__(self):
super(elli_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._fast_length = self.Param("FastLength", 19) \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators")
self._slow_length = self.Param("SlowLength", 60) \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period for momentum", "Indicators")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_atr = 0.0
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.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(elli_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_atr = 0.0
self._entry_price = 0.0
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._fast, self._slow, self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, fast_val, slow_val, atr_val):
if candle.State != CandleStates.Finished:
return
fv = float(fast_val)
sv = float(slow_val)
av = float(atr_val)
if self._prev_fast == 0 or self._prev_slow == 0 or av <= 0:
self._prev_fast = fv
self._prev_slow = sv
self._prev_atr = av
return
close = float(candle.ClosePrice)
# Exit: stop or take based on ATR
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 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 fv > sv:
self.BuyMarket()
self._entry_price = 0.0
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_fast = fv
self._prev_slow = sv
self._prev_atr = av
return
# Entry: EMA crossover with ATR expansion
if self.Position == 0:
atr_rising = av > self._prev_atr
if self._prev_fast <= self._prev_slow and fv > sv and atr_rising:
self._entry_price = close
self.BuyMarket()
elif self._prev_fast >= self._prev_slow and fv < sv and atr_rising:
self._entry_price = close
self.SellMarket()
self._prev_fast = fv
self._prev_slow = sv
self._prev_atr = av
def OnReseted(self):
super(elli_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_atr = 0.0
self._entry_price = 0.0
def CreateClone(self):
return elli_strategy()