GitHub で見る
移動平均シフト戦略
概要
この戦略は、MetaTrader 4 に同梱されている従来の 移動平均 エキスパート アドバイザーの StockSharp の高レベル ポートです。システムは完成したローソク足を観察し、それらをシフトされた単純移動平均 (SMA) と比較して、方向の変化を検出します。注文は常に市場で執行され、戦略は常に最大 1 つのオープンポジションで市場に留まります。
取引ロジック
- 構成可能な時間枠 (デフォルト: 5 分) のローソク足を購読し、要求された期間で SMA を計算します。
- 元の
iMA 関数の動作をエミュレートするには、指定された完成したキャンドルの数だけ SMA をシフトします。
- 以前に完成したキャンドルを評価します。
- 強気のクロス (シフトされた SMA の下で開き、上で閉じる) は、オープン ポジションがない場合にロング エントリーをトリガーします。
- 弱気クロス (シフトされた SMA の上で開き、下で閉じる) は、オープン ポジションがない場合にショート エントリーをトリガーします。
- 同じ相互ルールを使用して出口を管理します。
- ロングポジションは、最後のローソク足がシフトされた SMA を下回ったときにクローズされます。
- 最後のローソク足がシフトされた SMA の上を通過すると、ショート ポジションが閉じられます。
- いつでも存在できるポジションは 1 つだけで、買い注文と売り注文を交互に行った元の EA の動作と一致します。
パラメーター
| 名前 |
説明 |
デフォルト |
CandleType |
計算に使用されるローソク足シリーズ。任意の時間枠 DataType を選択できます。 |
5分の時間枠 |
MovingPeriod |
SMA の長さのキャンドルの数。 |
12 |
MovingShift |
完成したローソク足の SMA 値のオフセット。 iMA の shift 引数をエミュレートします。 |
6 |
BaseVolume |
エントリーのデフォルトの注文量。ロングトレードとショートトレードの両方に同じボリュームが使用されます。 |
1 |
インジケーターの処理
SimpleMovingAverage インジケーターは OnStarted で作成され、高レベルの Bind API を通じてローソク足サブスクリプションにバインドされます。
- 生の SMA 出力は小さな FIFO キューにバッファリングされ、
MovingShift キャンドル前の値を取得します。手動インジケーターの再計算は実行されません。
- キューには
MovingShift + 1 値のみが保持されるため、大きなシフトがあってもメモリ使用量は一定に保たれます。
注文とリスクの管理
- 注文は
BuyMarket/SellMarket で行われ、BaseVolume パラメータによってサイズが決定されます。閉じるときは、完全な終了を保証するために現在の絶対位置サイズが使用されます。
- 元の MetaTrader 実装では、無料証拠金と最近の損失に基づいてロット サイズが動的に調整されました。 StockSharp ポートはロジックを決定論的に保ち、
BaseVolume パラメータを通じて位置のサイジングをユーザーに委任します。これにより、エントリー/エグジットルールを維持しながら、ブローカー固有のアカウントメトリクスに依存することが回避されます。
変換メモ
- シグナルは前のローソク足で評価され、反応する前に新しいバーを待機したMetaTraderからの
Volume[0] == 1チェックと一致します。
- 時期尚早の取引を避けるために、完了したローソク足 (
CandleStates.Finished) のみが処理されます。
- この戦略は、チャート領域が使用可能な場合、StockSharp チャート ヘルパーを使用して、ローソク足、インジケーター値、取引マーカーをプロットします。
使用法
- StockSharp デザイナー、シェル、またはランナー内で戦略をコンパイルします。
- 目的の商品を選択し、ポートフォリオを割り当てます。
- 異なる時間枠、長さ、または量が必要な場合は、パラメーターを構成します。
- 戦略を開始します。選択したローソク足シリーズを購読し、SMA のクロスを監視し、それに応じて取引します。
さらなるアイデア
- 基本的な反転出口を超えたリスク管理が必要な場合は、
StartProtection を使用して保護ストップまたは利益確定レベルを追加します。
- 既存のサブスクリプション ワークフローを維持しながらインジケーター インスタンスを変更することで、単純な SMA を別のインジケーター (EMA、LWMA など) に置き換えます。
GetEntryVolume メソッドを調整して、位置スケーリング ルールを導入します。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public class MovingAverageShiftStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _cooldownCandles;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevClose;
private decimal _prevEma;
private bool _hasPrev;
private int _cooldownRemaining;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public int CooldownCandles { get => _cooldownCandles.Value; set => _cooldownCandles.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MovingAverageShiftStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 50).SetDisplay("EMA Period", "EMA lookback", "Indicators");
_cooldownCandles = Param(nameof(CooldownCandles), 200).SetDisplay("Cooldown", "Candles between signals", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame()).SetDisplay("Candle Type", "Candle timeframe", "General");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = default;
_prevEma = default;
_hasPrev = default;
_cooldownRemaining = default;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = 0;
_prevEma = 0;
_hasPrev = false;
_cooldownRemaining = 0;
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ema, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal ema)
{
if (candle.State != CandleStates.Finished) return;
var close = candle.ClosePrice;
if (!_hasPrev) { _prevClose = close; _prevEma = ema; _hasPrev = true; return; }
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
_prevClose = close;
_prevEma = ema;
return;
}
if (_prevClose <= _prevEma && close > ema && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_cooldownRemaining = CooldownCandles;
}
else if (_prevClose >= _prevEma && close < ema && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
_cooldownRemaining = CooldownCandles;
}
_prevClose = close;
_prevEma = ema;
}
}
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 moving_average_shift_strategy(Strategy):
def __init__(self):
super(moving_average_shift_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 50) \
.SetDisplay("EMA Period", "EMA lookback", "Indicators")
self._cooldown_candles = self.Param("CooldownCandles", 200) \
.SetDisplay("Cooldown", "Candles between signals", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
self._cooldown_remaining = 0
@property
def ema_period(self):
return self._ema_period.Value
@property
def cooldown_candles(self):
return self._cooldown_candles.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(moving_average_shift_strategy, self).OnReseted()
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(moving_average_shift_strategy, self).OnStarted2(time)
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
self._cooldown_remaining = 0
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.process_candle).Start()
def process_candle(self, candle, ema):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
ema_val = float(ema)
if not self._has_prev:
self._prev_close = close
self._prev_ema = ema_val
self._has_prev = True
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
self._prev_close = close
self._prev_ema = ema_val
return
if self._prev_close <= self._prev_ema and close > ema_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown_remaining = self.cooldown_candles
elif self._prev_close >= self._prev_ema and close < ema_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown_remaining = self.cooldown_candles
self._prev_close = close
self._prev_ema = ema_val
def CreateClone(self):
return moving_average_shift_strategy()