GitHub で見る
Trend Reversal戦略
概要
Trend Reversal戦略は、既存トレンド内の短期的な押し戻し後のブレイクアウトを捉えようとする方向性システムです。MetaTrader の "Trend Reversal" エキスパートアドバイザーから移植され、StockSharp の高レベル API を使うように書き直されました。この変換では、中心となる確認スタック (移動平均、momentum、MACD) を維持しつつ、元のグラフィカルなラインフィルターを、プログラムで再現しやすい価格重なりチェックに置き換えています。
インジケータースタック
- 線形加重移動平均 (LWMA) は典型価格上で計算され、高速と低速の長さをカスタマイズできます。高速ラインは直近のスイングを追跡し、低速ラインは支配的なトレンドを識別します。
- Momentumオシレーター は同じ時間枠で計算されます。戦略は MetaTrader ロジックを模倣するため、直近 3 本の確定ローソク足について中立レベル 100 からの絶対距離を記録します。
- MACDシグナルラインペア は、独立した高速、低速、シグナル長で設定されます。ヒストグラム方向は、ロングとショートの両方で上位時間枠確認として使われます。
取引ロジック
- 設定時間枠の確定ローソク足を待ちます。部分的に形成されたバーは無視します。
- 両方の LWMA と momentum インジケーターが完全に形成されていることを確認します。履歴が不足している間、システムはフラットのままです。
- 100 からの直近 3 つの momentum 偏差をローリングキューに保持します。これらの値の少なくとも 1 つが対応する買いまたは売りしきい値を超える場合にのみ、セットアップは有効です。
- 2 バー前のローソク足が、前のローソク足の高値より低い安値を持つことを要求します。これは、ブレイクアウト前の狭い保ち合いを検出するために元の EA が使っていた「重なり」構造を再現します。
- 方向フィルターを評価します。
- ロング: 高速 LWMA が低速 LWMA より上、かつ MACD メイン値がシグナルラインより上。
- ショート: 高速 LWMA が低速 LWMA より下、かつ MACD メイン値がシグナルラインより下。
- ネットポジション制限を尊重します。絶対エクスポージャー (現在ポジションを取引数量で割った値) が設定された
MaxPositions 値を下回る場合にのみ、戦略はエントリーまたは追加を行います。
- 注文は
BuyMarket() または SellMarket() で送信され、現在のエクスポージャーに応じて部分的または完全な反転が可能です。
リスク管理
- 任意の take profit と stop loss 距離 (価格単位) は、StockSharp の組み込み保護ブロックを通じて付与できます。パラメーターがゼロに設定されると、両水準は無効になります。
- この移植版には、自動 trailing stop や break-even 調整は含まれていません。必要な場合は追加のイベントハンドラーで実装できます。
パラメーター
| 名前 |
説明 |
デフォルト |
CandleType |
ローソク足を構築する主要時間枠。 |
15 分時間枠 |
FastLength |
高速 LWMA の期間。 |
6 |
SlowLength |
低速 LWMA の期間。 |
85 |
MomentumLength |
momentum オシレーターの期間。 |
14 |
MomentumBuyThreshold |
ロングセットアップを検証する最小絶対 momentum 偏差 (100 から)。 |
0.3 |
MomentumSellThreshold |
ショートセットアップを検証する最小絶対 momentum 偏差 (100 から)。 |
0.3 |
MacdFastLength |
MACD フィルター内で使う高速 EMA 期間。 |
12 |
MacdSlowLength |
MACD フィルター内で使う低速 EMA 期間。 |
26 |
MacdSignalLength |
MACD フィルター内で使うシグナル EMA 期間。 |
9 |
TakeProfit |
価格単位の take profit 距離。無効にするには 0 に設定します。 |
50 |
StopLoss |
価格単位の stop loss 距離。無効にするには 0 に設定します。 |
20 |
TradeVolume |
ロットで表される注文数量。 |
1 |
MaxPositions |
ネットポジションで許可される取引数量単位の最大数。 |
1 |
使用上の注意
- 保護注文が正しく動作するよう、ステップと価格情報が有効な銘柄に戦略を接続してください。
- 複数方向の取引 (ピラミッディングまたは積み増し) を行うには、
MaxPositions を増やします。フィルターが有効で、エクスポージャーがこの制限内にある限り、戦略はポジションを追加し続けます。
- バックテストは、
CandleType パラメーターが指定する同じローソク足時間枠で実行する必要があります。StockSharp は戦略開始時に適切なデータを自動的に要求します。
- MetaTrader 版は手描きのトレンドラインに依存していたため、この書き直しではそれらを決定論的なローソク足重なり条件に置き換えています。これにより、バックテストとライブ実行で動作が一貫します。
元のEAとの違い
- サンプルを中核的なシグナル生成に集中させるため、trailing stop、break-even 移動、equity ベースの緊急エグジットは実装していません。
- ロット乗算や Magic Number フィルターなどの資金管理機能は StockSharp では不要なため削除されました。
- MACD 確認は、元の月次集計ではなく、取引ローソク足と同じ時間枠を使います。必要であれば、より遅いローソク足タイプを購読し、その購読へ MACD フィルターをバインドすることでマルチタイムフレーム設定を模倣できます。
最適化のヒント
- まず移動平均の長さを市場の支配的サイクルに合わせて最適化し、その後 momentum しきい値を微調整します。
- ボラティリティの高い商品を取引する場合は、より広い stop-loss と take-profit 距離を試してください。ロジックはトレンドフォローなので、出口バッファーを広げると収益性が改善することがよくあります。
- 最適化実行中は drawdown 統計を監視してください。
MaxPositions を増やすと応答性が向上する可能性がありますが、リスクも拡大します。
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 TrendReversalStrategy : 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 TrendReversalStrategy()
{
_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 trend_reversal_strategy(Strategy):
def __init__(self):
super(trend_reversal_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(trend_reversal_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(trend_reversal_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 trend_reversal_strategy()