Ema612CrossoverStrategy 戦略
概要
- MetaTrader 5のエキスパートアドバイザー**"EMA 6.12 (barabashkakvn版)"**のStockSharp高レベルAPIへのポート。
- 高速と低速の単純移動平均のクロスオーバーを取引します(オリジナルスクリプトはEMAという名前にもかかわらずMODE_SMAも使用していました)。
- 絶対価格単位で表されたオプションのテイクプロフィットとトレーリングストップ管理を追加し、インストゥルメントごとに動作を調整できます。
取引ロジック
データ準備
- 戦略は
CandleTypeで定義されたタイプのローソク足を購読します(デフォルトは15分時間軸)。 - 2つの単純移動平均が計算されます:高速カーブ用の
FastPeriod長と低速カーブ用のSlowPeriod長。低速期間は高速期間より大きくなければなりません。
エントリールール
- シグナルは各完了ローソク足のクローズで評価されます。
- 強気クロスオーバーは、前のローソク足で低速SMAが高速SMAより上にあり、現在のローソク足でその下に落ちるときに発生します。オープンしているショートポジションはクローズされ、設定された
Volumeでロングポジションが開かれます。 - 弱気クロスオーバーは、前のローソク足で低速SMAが高速SMAより下にあり、現在のローソク足でその上に上昇するときに発生します。オープンしているロングポジションはクローズされ、設定された
Volumeでショートポジションが開かれます。
エグジットルール
- オープンポジションは上記で説明した反対のクロスオーバーでクローズされます。
- オプションのテイクプロフィット:
TakeProfitOffsetがゼロより大きい場合、戦略はエントリー価格から固定価格目標を計算します。ロング取引は価格がエントリー + TakeProfitOffsetに達したときに出口し、ショート取引は価格がエントリー - TakeProfitOffsetに達したときに出口します。 - オプションのトレーリングストップ:
TrailingStopOffsetがゼロより大きい場合、戦略は未実現利益がTrailingStopOffset + TrailingStepOffsetを超えるまで待ちます。その閾値を超えると、ストップ価格は最後のクローズからTrailingStopOffset距離を保つように引き締められますが、新しいレベルが前のストップより少なくともTrailingStepOffset価格に近い場合のみです。ロング取引はストップを発動するために安値を使用し、ショートは高値を使用します。
パラメーター
| パラメーター | デフォルト | 説明 |
|---|---|---|
CandleType |
15分時間軸 | SMA計算とシグナル評価に使用されるローソク足の解像度。 |
FastPeriod |
6 | 高速単純移動平均の期間。> 0かつSlowPeriodより小さくなければならない。 |
SlowPeriod |
54 | 低速単純移動平均の期間。> 0かつFastPeriodより大きくなければならない。 |
Volume |
1 | 新規エントリーに使用される注文ボリューム。 |
TakeProfitOffset |
0.001 | テイクプロフィット目標のオプションの絶対価格距離。無効にするには0に設定。 |
TrailingStopOffset |
0.005 | 価格とトレーリングストップ間の絶対距離。トレーリングを無効にするには0に設定。 |
TrailingStepOffset |
0.0005 | トレーリングストップが移動する前に必要な追加の有利な動き。 |
重要: オフセットは絶対価格単位で指定されます。インストゥルメントのティックサイズに合わせて調整してください(例えば、0.0001ステップのEURUSDでは、デフォルト値はそれぞれ10、50、5 pipsに対応します)。
実装ノート
- プロジェクトガイドラインで要求される高レベルの
SubscribeCandles().Bind()ワークフローを使用しています。 - チャート出力は、環境でチャートが利用可能な場合、両方のSMAと取引マーカーをプロットします。
- 状態変数はMQLバージョンとまったく同じようにエントリー価格、トレーリングストップレベル、テイクプロフィット目標を追跡します。
- C#実装は無効なインジケーター構成を避けるために起動時に
SlowPeriod > FastPeriodを強制します。
使用のヒント
- 取引される市場に合わせてローソク足の時間軸とSMA期間を最適化します(例:イントラデイ先物には短い期間、スイングトレードには長い期間)。
- 戦略を実行する前にpipsまたはティックから絶対価格単位にオフセットを変換してください。
TrailingStopOffsetをゼロに設定することでトレーリングを無効にできます;その場合、戦略は出口に反対のクロスオーバーまたはオプションのテイクプロフィットのみに依存します。
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// EMA 6/12 crossover strategy with trailing stop management.
/// </summary>
public class Ema612CrossoverStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<decimal> _takeProfitOffset;
private readonly StrategyParam<decimal> _trailingStopOffset;
private readonly StrategyParam<decimal> _trailingStepOffset;
private ExponentialMovingAverage _fastSma;
private ExponentialMovingAverage _slowSma;
private decimal? _prevFast;
private decimal? _prevSlow;
private decimal? _entryPrice;
private decimal? _stopPrice;
private decimal? _takeProfitPrice;
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Fast moving average period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow moving average period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Take profit distance in absolute price units.
/// </summary>
public decimal TakeProfitOffset
{
get => _takeProfitOffset.Value;
set => _takeProfitOffset.Value = value;
}
/// <summary>
/// Trailing stop distance in absolute price units.
/// </summary>
public decimal TrailingStopOffset
{
get => _trailingStopOffset.Value;
set => _trailingStopOffset.Value = value;
}
/// <summary>
/// Additional distance required to move the trailing stop.
/// </summary>
public decimal TrailingStepOffset
{
get => _trailingStepOffset.Value;
set => _trailingStepOffset.Value = value;
}
/// <summary>
/// Initializes <see cref="Ema612CrossoverStrategy"/>.
/// </summary>
public Ema612CrossoverStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Candle resolution", "General");
_fastPeriod = Param(nameof(FastPeriod), 6)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Fast SMA length", "Moving Averages");
_slowPeriod = Param(nameof(SlowPeriod), 54)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Slow SMA length", "Moving Averages");
_takeProfitOffset = Param(nameof(TakeProfitOffset), 0.001m)
.SetNotNegative()
.SetDisplay("Take Profit", "Target distance in price units", "Risk");
_trailingStopOffset = Param(nameof(TrailingStopOffset), 0.005m)
.SetNotNegative()
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk");
_trailingStepOffset = Param(nameof(TrailingStepOffset), 0.0005m)
.SetNotNegative()
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetPositionState();
_prevFast = null;
_prevSlow = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (SlowPeriod <= FastPeriod)
throw new InvalidOperationException("Slow period must be greater than fast period.");
_fastSma = new ExponentialMovingAverage { Length = FastPeriod };
_slowSma = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastSma, _slowSma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastSma);
DrawIndicator(area, _slowSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastSma.IsFormed || !_slowSma.IsFormed)
return;
var bullishCross = false;
var bearishCross = false;
if (_prevFast.HasValue && _prevSlow.HasValue)
{
// Detect crossovers using previous candle values.
bullishCross = _prevSlow > _prevFast && slow < fast;
bearishCross = _prevSlow < _prevFast && slow > fast;
}
HandleExistingPosition(candle, bullishCross, bearishCross);
if (Position == 0)
{
if (bullishCross)
{
// Slow MA crossed below the fast MA - go long.
EnterLong(candle);
}
else if (bearishCross)
{
// Slow MA crossed above the fast MA - go short.
EnterShort(candle);
}
}
_prevFast = fast;
_prevSlow = slow;
}
private void HandleExistingPosition(ICandleMessage candle, bool bullishCross, bool bearishCross)
{
if (Position > 0)
{
// Update trailing stop for the long position before evaluating exits.
UpdateLongTrailing(candle);
var exit = bearishCross;
if (!exit && _takeProfitPrice.HasValue && candle.HighPrice >= _takeProfitPrice.Value)
{
// Price reached the take profit objective.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
{
// Price retraced to the trailing stop.
exit = true;
}
if (exit)
{
SellMarket(Position);
ResetPositionState();
}
}
else if (Position < 0)
{
// Update trailing stop for the short position before evaluating exits.
UpdateShortTrailing(candle);
var exit = bullishCross;
if (!exit && _takeProfitPrice.HasValue && candle.LowPrice <= _takeProfitPrice.Value)
{
// Price reached the take profit objective for the short trade.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
{
// Price rallied back to the trailing stop level.
exit = true;
}
if (exit)
{
BuyMarket(Math.Abs(Position));
ResetPositionState();
}
}
}
private void EnterLong(ICandleMessage candle)
{
BuyMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice + TakeProfitOffset : null;
_stopPrice = null;
}
private void EnterShort(ICandleMessage candle)
{
SellMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice - TakeProfitOffset : null;
_stopPrice = null;
}
private void UpdateLongTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = candle.ClosePrice - _entryPrice.Value;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice - TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || candidate - _stopPrice.Value > minAdvance)
{
// Move stop loss closer only when price progressed enough.
_stopPrice = candidate;
}
}
private void UpdateShortTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = _entryPrice.Value - candle.ClosePrice;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice + TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || _stopPrice.Value - candidate > minAdvance)
{
// Move stop loss for the short only after sufficient favorable movement.
_stopPrice = candidate;
}
}
private void ResetPositionState()
{
_entryPrice = null;
_stopPrice = null;
_takeProfitPrice = null;
}
}
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 ema_612_crossover_strategy(Strategy):
"""
EMA 6/12 crossover strategy with trailing stop management.
Enters on EMA crossover, manages position with take profit and trailing stop.
"""
def __init__(self):
super(ema_612_crossover_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Candle resolution", "General")
self._fast_period = self.Param("FastPeriod", 6) \
.SetDisplay("Fast Period", "Fast EMA length", "Moving Averages")
self._slow_period = self.Param("SlowPeriod", 54) \
.SetDisplay("Slow Period", "Slow EMA length", "Moving Averages")
self._take_profit_offset = self.Param("TakeProfitOffset", 0.001) \
.SetDisplay("Take Profit", "Target distance in price units", "Risk")
self._trailing_stop_offset = self.Param("TrailingStopOffset", 0.005) \
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk")
self._trailing_step_offset = self.Param("TrailingStepOffset", 0.0005) \
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk")
self._prev_fast = None
self._prev_slow = None
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
self._fast_ema = None
self._slow_ema = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_612_crossover_strategy, self).OnReseted()
self._reset_position_state()
self._prev_fast = None
self._prev_slow = None
def OnStarted2(self, time):
super(ema_612_crossover_strategy, self).OnStarted2(time)
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_period.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._fast_ema)
self.DrawIndicator(area, self._slow_ema)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed:
return
fast_val = float(fast_val)
slow_val = float(slow_val)
bullish_cross = False
bearish_cross = False
if self._prev_fast is not None and self._prev_slow is not None:
bullish_cross = self._prev_slow > self._prev_fast and slow_val < fast_val
bearish_cross = self._prev_slow < self._prev_fast and slow_val > fast_val
self._handle_existing_position(candle, bullish_cross, bearish_cross)
if self.Position == 0:
if bullish_cross:
self._enter_long(candle)
elif bearish_cross:
self._enter_short(candle)
self._prev_fast = fast_val
self._prev_slow = slow_val
def _handle_existing_position(self, candle, bullish_cross, bearish_cross):
if self.Position > 0:
self._update_long_trailing(candle)
do_exit = bearish_cross
if not do_exit and self._take_profit_price is not None and float(candle.HighPrice) >= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
do_exit = True
if do_exit:
self.SellMarket()
self._reset_position_state()
elif self.Position < 0:
self._update_short_trailing(candle)
do_exit = bullish_cross
if not do_exit and self._take_profit_price is not None and float(candle.LowPrice) <= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
do_exit = True
if do_exit:
self.BuyMarket()
self._reset_position_state()
def _enter_long(self, candle):
self.BuyMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close + tp if tp > 0 else None
self._stop_price = None
def _enter_short(self, candle):
self.SellMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close - tp if tp > 0 else None
self._stop_price = None
def _update_long_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = close - self._entry_price
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close - trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or candidate - self._stop_price > min_advance:
self._stop_price = candidate
def _update_short_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = self._entry_price - close
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close + trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or self._stop_price - candidate > min_advance:
self._stop_price = candidate
def _reset_position_state(self):
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
def CreateClone(self):
return ema_612_crossover_strategy()