GitHub で見る
上 下 MA 再結合戦略
概要
Above Below MA 再結合戦略は、MetaTrader 4 エキスパート アドバイザー「AboveBelowMA」の StockSharp 変換です。元のスクリプトは GBP/USD の 15 分足チャートを監視し、現在の価格を典型的な価格に基づいて計算された 1 期間の指数移動平均 (EMA) と比較します。価格が上昇または下降平均の反対側で取引される場合、この戦略はその変動を弱め、EMAの基本的な方向に再び加わることを試みます。このポートは、StockSharp の高レベル API (SubscribeCandles + Bind) を活用しながら、信号構造をそのまま維持します。
取引ロジック
- 構成されたローソク足タイプ (デフォルトでは 15 分) をサブスクライブし、典型的な価格
(High + Low + Close) / 3 を使用する指数移動平均をフィードします。
- 最新および以前の EMA の値を追跡して、短期的な傾きを理解します。強気バイアスでは EMA が上昇する必要があり、弱気バイアスでは低下する必要があります。
- ロングセットアップ: ローソク足が EMA より少なくとも 1 価格ステップ下で開始し、EMA より下で終了し、前の EMA の値が現在の EMA の値よりも低い場合、短期エクスポージャーを閉じて購入の準備をします。ポジションが残っていない場合は、成行買い注文を送信します。
- 短い設定: ローソク足が EMA より少なくとも 1 価格ステップ上で始まり、EMA より上で終値し、前の EMA の値が現在の EMA の値より高い場合、長時間露光を閉じて売りの準備をします。ポジションが横ばいの場合は、成行売り注文を送信します。
- 部分的に形成されたバーでの時期尚早のシグナルを避けるために、注文は完成したローソク足に対してのみ発行されます。
ポジションサイジング
- MetaTrader のバージョン サイズは、5 ロットを上限とする
AccountFreeMargin / 10000 を使用して取引されます。 StockSharp 実装は同等の動作を提供します。UseDynamicVolume が有効な場合、戦略は現在のポートフォリオ値を BalanceToVolumeDivider (デフォルトは 10000) で除算します。
- 計算されたサイズは、エキスパートアドバイザーからのハード 5 ロット キャップを反映して、
MaxVolume によって制限されます。動的サイジングが無効になっている場合、InitialVolume パラメータは固定ボリュームとして使用されます。
- すべてのボリュームは、ブローカーまたはシミュレーターによる拒否を避けるために、機器のボリュームステップと最小/最大ボリューム制約に合わせて調整されます。
パラメーター
| パラメータ |
説明 |
EmaLength |
指数移動平均の期間 (デフォルトは 1、EA と一致)。 |
CandleType |
EMA に供給するキャンドルを構築するために使用される時間枠(デフォルトは 15 分)。 |
InitialVolume |
動的サイジングが無効になっている場合の注文量を修正しました。 |
UseDynamicVolume |
ポートフォリオベースのポジションサイジング (Balance / BalanceToVolumeDivider) を有効にします。 |
BalanceToVolumeDivider |
AccountFreeMargin / 10000 をエミュレートするためにポートフォリオ値に適用される除算器。 |
MaxVolume |
戦略によって許可される最大注文量。 |
注意事項
- この戦略は、反対方向の取引を開始する前に
ClosePosition() を使用し、CheckOrders を介して反対の注文を閉じる MetaTrader ロジックと一致します。
- シグナルは完成したローソク足で評価されるため、エントリーはティックベースの MetaTrader バージョンよりわずかに遅れて発生する可能性があります。この変更により、バックテストやローソク足データを使用したライブ取引で実行する際の安定性が向上します。
- 選択したセキュリティが、ダイナミック ボリューム ブロックが期待どおりに機能するための意味のある
PriceStep、VolumeStep、およびポートフォリオ評価情報を提供していることを確認してください。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Above/Below MA Rejoin strategy.
/// Buys when price is below a rising EMA (pullback in uptrend).
/// Sells when price is above a falling EMA (pullback in downtrend).
/// </summary>
public class AboveBelowMaRejoinStrategy : Strategy
{
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevEma;
private decimal _prevClose;
private bool _hasPrev;
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public AboveBelowMaRejoinStrategy()
{
_emaLength = Param(nameof(EmaLength), 20)
.SetDisplay("EMA Period", "EMA lookback period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevEma = 0m;
_prevClose = 0m;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_hasPrev = false;
var ema = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
if (!_hasPrev)
{
_prevEma = emaValue;
_prevClose = close;
_hasPrev = true;
return;
}
var emaRising = emaValue > _prevEma;
var emaFalling = emaValue < _prevEma;
// Price rejoins from below in uptrend - buy
if (emaRising && _prevClose < _prevEma && close >= emaValue && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Price rejoins from above in downtrend - sell
else if (emaFalling && _prevClose > _prevEma && close <= emaValue && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevEma = emaValue;
_prevClose = close;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class above_below_ma_rejoin_strategy(Strategy):
"""Above/Below MA Rejoin strategy.
Buys when price rejoins from below a rising EMA (pullback in uptrend).
Sells when price rejoins from above a falling EMA (pullback in downtrend)."""
def __init__(self):
super(above_below_ma_rejoin_strategy, self).__init__()
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Period", "EMA lookback period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_ema = 0.0
self._prev_close = 0.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def EmaLength(self):
return self._ema_length.Value
def OnReseted(self):
super(above_below_ma_rejoin_strategy, self).OnReseted()
self._prev_ema = 0.0
self._prev_close = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(above_below_ma_rejoin_strategy, self).OnStarted2(time)
self._has_prev = False
ema = ExponentialMovingAverage()
ema.Length = self.EmaLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(ema, self._process_candle).Start()
def _process_candle(self, candle, ema_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
ema_val = float(ema_value)
if not self._has_prev:
self._prev_ema = ema_val
self._prev_close = close
self._has_prev = True
return
ema_rising = ema_val > self._prev_ema
ema_falling = ema_val < self._prev_ema
# Price rejoins from below in uptrend - buy
if ema_rising and self._prev_close < self._prev_ema and close >= ema_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Price rejoins from above in downtrend - sell
elif ema_falling and self._prev_close > self._prev_ema and close <= ema_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_ema = ema_val
self._prev_close = close
def CreateClone(self):
return above_below_ma_rejoin_strategy()