GitHub で見る
バーチャル・トレーリング・ストップ Level1 戦略
概要
バーチャル・トレーリング・ストップ戦略は、MetaTraderエキスパートアドバイザー Virtual Trailing Stop.mq5(MQL ID 21362)をC#に直接移植したものです。オリジナルのエキスパートは、他の場所で開かれたポジションの保護ストップのみを管理します。このC#ポートはStockSharpの高レベルAPIの上で同じ動作を再現します。最良のbid/askレートを監視し、ストップロス、テイクプロフィット、またはトレーリングストップの条件が満たされたときに現在のポジションを閉じます。
エントリー主導の戦略とは異なり、この実装は自分では新しいポジションを開くことはありません。StockSharp内でMetaTraderスタイルの「バーチャル」トレーリングストップを適用する必要がある場合に、他の自動エントリーや手動取引セッションと組み合わせることを目的としています。
取引ロジック
- Level1フィード – 戦略はLevel1データを購読し、最新のbid/ask値を継続的に保存します。
- Pip変換 – ユーザー入力はpipで定義されます。戦略は、値を銘柄の
PriceStepで乗算することで価格オフセットに変換します。3桁と5桁の外為クォートには、MetaTraderのpip定義に合わせるために10倍の乗数が適用されます。
- ストップロス確認 – ロングポジションのbidが
エントリー価格 − StopLossを下回る場合、またはショートポジションのaskがエントリー価格 + StopLossを上回る場合、ポジションは成行で決済されます。
- テイクプロフィット確認 – ロングポジションのbidが
エントリー価格 + TakeProfitを上回る場合、またはショートポジションのaskがエントリー価格 − TakeProfitを下回る場合、ポジションが決済されます。
- トレーリング活性化 – 価格がポジションに有利な方向に
TrailingStart pip動くと、Bid − TrailingStop(ロング)またはAsk + TrailingStop(ショート)でトレーリングレベルが作成されます。
- トレーリング更新 – 未実現利益が少なくとも
TrailingStep pip増加するたびに、トレーリングレベルがそれに応じてシフトします。ステップをゼロに設定すると、トレーリングはすべての有利なティックに追随します。
- トレーリング決済 – ソースEAの
Profit()>0セーフガードを反映して、取引が引き続き利益を上げている間にトレーリングレベルに価格が触れたとき、ポジションが決済されます。
保留中の注文は置かれません。すべての決済は、MQL実装の「バーチャル」な性質を模倣するために成行注文で実行されます。
パラメーター
| パラメーター |
説明 |
デフォルト値 |
StopLossPips |
pip単位のストップロス距離。ハードストップロス管理を無効にするには0に設定します。 |
0 |
TakeProfitPips |
pip単位のテイクプロフィット距離。テイクプロフィット管理を無効にするには0に設定します。 |
0 |
TrailingStopPips |
現在の価格とトレーリングレベルの間の距離(pip単位)。 |
5 |
TrailingStartPips |
トレーリングが活性化される前に到達する必要がある利益閾値(pip単位)。 |
5 |
TrailingStepPips |
トレーリングレベルが再び移動する前に必要な最小pip増分。連続トレーリングには0を使用します。 |
1 |
すべてのパラメーターは、StockSharpのStrategyParamヘルパーのおかげで最適化をサポートしています。
実装上の注意
- 戦略はLevel1データ(
DataType.Level1)のみを使用し、StockSharpがMetaTraderとは異なる方法で可視化を処理するため、チャートオブジェクトを登録しません。
- 価格変換は
Security.PriceStepとSecurity.Decimalsに依存します。取引所がこのメタデータを提供しない場合、フォールバックのpipサイズは1です。
- 保護はロングポジションとショートポジションに対して対称的です。トレーリング値は両方向で別々に保存されます。
- オリジナルのEAのテスターモードに存在していた自動ポジションシードは、StockSharp戦略がネットポジションで操作するため、意図的に省略されています。
使用上のヒント
- すでに建玉があるか、別のコンポーネントから受け取ることが予想されるポートフォリオ/銘柄ペアに戦略を割り当てます。
- 裁量取引や自動エントリー戦略と組み合わせて、StockSharp Designer、Shell、またはRunnerでMetaTraderスタイルのトレード管理を模倣します。
- 外為以外の銘柄を取引する場合は、銘柄のティックサイズに合わせてpipベースの入力を調整します。
TrailingStopPips = 1を設定すると、実質的に1つのPriceStepでトレーリングされます。
ファイル
CS/VirtualTrailingStopLevel1Strategy.cs – 戦略の実装。
README.md、README_zh.md、README_ru.md – 戦略の多言語ドキュメント。
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;
/// <summary>
/// Virtual Trailing Stop Level1 strategy (simplified). Uses EMA with
/// percentage-based trailing stop for position management.
/// </summary>
public class VirtualTrailingStopLevel1Strategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<decimal> _trailingPercent;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
public decimal TrailingPercent
{
get => _trailingPercent.Value;
set => _trailingPercent.Value = value;
}
public VirtualTrailingStopLevel1Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
_emaLength = Param(nameof(EmaLength), 15)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period", "Indicators");
_trailingPercent = Param(nameof(TrailingPercent), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Trailing %", "Trailing stop percent", "Risk");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaLength };
decimal highSinceEntry = 0;
decimal lowSinceEntry = decimal.MaxValue;
decimal prevClose = 0;
decimal prevEma = 0;
var hasPrev = false;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, (ICandleMessage candle, decimal emaVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!hasPrev)
{
prevClose = candle.ClosePrice;
prevEma = emaVal;
hasPrev = true;
return;
}
if (!IsFormedAndOnlineAndAllowTrading())
{
prevClose = candle.ClosePrice;
prevEma = emaVal;
return;
}
var close = candle.ClosePrice;
// Trailing stop management
if (Position > 0)
{
if (candle.HighPrice > highSinceEntry) highSinceEntry = candle.HighPrice;
if (close < highSinceEntry * (1m - TrailingPercent / 100m))
{
SellMarket();
highSinceEntry = 0;
lowSinceEntry = decimal.MaxValue;
return;
}
}
else if (Position < 0)
{
if (candle.LowPrice < lowSinceEntry) lowSinceEntry = candle.LowPrice;
if (close > lowSinceEntry * (1m + TrailingPercent / 100m))
{
BuyMarket();
highSinceEntry = 0;
lowSinceEntry = decimal.MaxValue;
return;
}
}
// Entry based on EMA
var bullishCross = prevClose <= prevEma && close > emaVal;
var bearishCross = prevClose >= prevEma && close < emaVal;
if (bullishCross && Position <= 0)
{
BuyMarket();
highSinceEntry = candle.HighPrice;
lowSinceEntry = decimal.MaxValue;
}
else if (bearishCross && Position >= 0)
{
SellMarket();
lowSinceEntry = candle.LowPrice;
highSinceEntry = 0;
}
prevClose = close;
prevEma = emaVal;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
}
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 virtual_trailing_stop_level1_strategy(Strategy):
def __init__(self):
super(virtual_trailing_stop_level1_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candles", "General")
self._ema_length = self.Param("EmaLength", 15) \
.SetDisplay("EMA Length", "EMA period", "Indicators")
self._trailing_percent = self.Param("TrailingPercent", 1.5) \
.SetDisplay("Trailing %", "Trailing stop percent", "Risk")
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@property
def EmaLength(self):
return self._ema_length.Value
@property
def TrailingPercent(self):
return self._trailing_percent.Value
def OnReseted(self):
super(virtual_trailing_stop_level1_strategy, self).OnReseted()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(virtual_trailing_stop_level1_strategy, self).OnStarted2(time)
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
ema = ExponentialMovingAverage()
ema.Length = self.EmaLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, ema_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
ev = float(ema_value)
if not self._has_prev:
self._prev_close = close
self._prev_ema = ev
self._has_prev = True
return
if self.Position > 0:
if high > self._high_since_entry:
self._high_since_entry = high
if close < self._high_since_entry * (1.0 - self.TrailingPercent / 100.0):
self.SellMarket()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = close
self._prev_ema = ev
return
elif self.Position < 0:
if low < self._low_since_entry:
self._low_since_entry = low
if close > self._low_since_entry * (1.0 + self.TrailingPercent / 100.0):
self.BuyMarket()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = close
self._prev_ema = ev
return
bullish_cross = self._prev_close <= self._prev_ema and close > ev
bearish_cross = self._prev_close >= self._prev_ema and close < ev
if bullish_cross and self.Position <= 0:
self.BuyMarket()
self._high_since_entry = high
self._low_since_entry = 1e18
elif bearish_cross and self.Position >= 0:
self.SellMarket()
self._low_since_entry = low
self._high_since_entry = 0.0
self._prev_close = close
self._prev_ema = ev
def CreateClone(self):
return virtual_trailing_stop_level1_strategy()