初期のトップ比例配分 V1 戦略
このドキュメントでは、MetaTrader エキスパート アドバイザー earlyTopProrate_V1 の StockSharp ポートについて説明します。この戦略は、日次の始値から離れる日中の動きを検索し、3 つの利益目標を使用してポジションをスケールアウトします。元の資金管理と貿易管理のアイデアを維持しながら、高レベルの StockSharp API を使用して変換されました。
中核ロジック
- 毎日のコンテキスト – この戦略は、処理されたローソク足から当日の始値、高値、安値を再構築します。支配的な方向は、
high - open と open - low を比較することによって定義されます。
- エントリーウィンドウ – 新しい取引は、
StartHour (この値を含む) と EndHour (この値を含む) の間でのみ開始できます。デフォルト設定では、初期のヨーロッパセッションがトレードされます。
- エントリー条件 –
- 支配的な方向が強気で、最新の終値が毎日の始値を上回っている場合、戦略はロングポジションをオープンします。
- 支配的な方向が弱気で、最新の終値が毎日の始値を下回っている場合、戦略はショートポジションをオープンします。
- 同時に許可される市場ポジションは 1 つだけです (デフォルトでは
MaxPositions = 1)。
- 資金管理 – 各エントリの量は、選択した資金管理モードから取得されます (以下を参照)。値は機器の音量ステップを使用して四捨五入され、交換の最小音量と最大音量の間にクランプされます。
- ポジション処理 – ポジションにエントリーした後、戦略は次のセクションにリストされている階層化されたエグジット ルールを適用します。このルールは元のエキスパートアドバイザーを反映していますが、ストップロス/テイクプロフィットの直接的な変更ではなく、高レベルの StockSharp 注文を使用して実装されています。
- セッションクローズ –
ClosingHour に達したときにポジションが残っている場合、戦略は市場で強制的にエグジットします。
貿易管理の詳細
元の MQL エキスパート アドバイザーは手動のストップとテイクプロフィット調整に依存しています。 StockSharp ポートは、完成した各キャンドルを明示的にチェックして動作を再現します。
- 損益分岐点救済 (
BreakEvenTrigger) – 価格が設定されたポイント数だけエントリーに対して動いた場合、戦略はエントリー価格まで回復するのを待ち、損益分岐点でエグジットします。
- 緊急停止 (
StopLoss0) – 逆偏位がこの距離を超えると、ポジションは直ちにクローズされます。
- ストップからエントリーまで (
StopLoss1) – 指定された距離をプラスに移動した後、保護ストップがエントリー価格に移動します。
- 利益のストップ (
StopLoss2) – 利益がこのしきい値に達すると、保護ストップはエントリーの上(ロング)または下(ショート)に押し込まれます。オフセットは StopLoss2 - StopLoss1 に等しく、MetaTrader から setSL2-35 ロジックを再現します。
- スケールアウト (
TakeProfit1/2/3 および Ratio1/2/3) – 3 つの利益目標により、残りのポジション量の部分的な決済がトリガーされます。比率は現在の位置のパーセンテージを表し、後続のターゲットが露出を減らして動作するようにします。 3 番目のターゲットは残り全体をクローズします。
すべての距離ベースのパラメータは ポイント で動作します。ヘルパー パラメータ PointMultiplier は、インストゥルメント PriceStep を乗算して、元のスクリプトからの value * 10 * Point 演算を再現します (デフォルトの乗数 = 10)。
資金管理モード
パラメータ MoneyManagementType は、4 つのサイジング モデルのいずれかを選択します。
| モード |
説明 |
0 or 1 |
ロットサイズを BaseVolume に固定しました (モード 0 と 1 が同一である場合の MQL の動作を反映します)。 |
2 |
平方根モデル – 0.1 * sqrt(balance / 1000) * MoneyManagementFactor を使用します。利用可能な場合は、現在のポートフォリオ値が使用されます。 |
3 |
株式リスク モデル – MetaTrader から AccountEquity/Close[0] 式を近似して、equity / price / 1000 * MoneyManagementRiskPercent / 100 を計算します。 |
各結果は、機器の音量ステップと交換の最小/最大音量を使用して正規化されます。
パラメーター
| 名前 |
説明 |
CandleType |
決断に使うキャンドルシリーズ。デフォルトは 5 分足のローソク足です。 |
StartHour / EndHour |
時間単位の取引ウィンドウ (0 ~ 23)。 |
ClosingHour |
オープンポジションがクローズされたときの時間。 |
TimeZoneShift |
互換性のために保持されている情報タイム ゾーン オフセット。 |
BaseVolume |
資金管理調整前の基本ロットサイズ。 |
MaxPositions |
最大同時ポジション数 (デフォルト = 1)。 |
TakeProfit1, TakeProfit2, TakeProfit3 |
3 つの利益目標間の距離 (ポイント単位)。 |
BreakEvenTrigger |
損益分岐点の救済出口を有効にする損失 (ポイント単位)。 |
StopLoss0, StopLoss1, StopLoss2 |
保護停止ロジックを制御する不利/有利なしきい値。 |
Ratio1, Ratio2, Ratio3 |
各ターゲットで現在ポジションがクローズされた割合。 |
MoneyManagementType |
資金管理モード (0 ~ 3)。 |
MoneyManagementFactor |
平方根モデルの乗数。 |
MoneyManagementRiskPercent |
株式モデルのリスクの割合。 |
PointMultiplier |
ポイントを実際の価格オフセットに変換するときに商品価格ステップに適用される乗数。 |
使用上の注意
- 選択した会場で利用可能なデータ粒度に一致するキャンドル タイプを選択します。デフォルトの 5 分間のシリーズは、応答性とノイズ フィルターのバランスを提供します。
- ポイントベースの距離を実際の価格に変換すると、戦略は
PriceStep * PointMultiplier を乗算します。ブローカーが元の MetaTrader 環境とは異なるポイントを定義する場合は、乗数を調整します。
- 損益分岐点ロジックとトレーリング ロジックには完了したローソク足が必要であるため、バー内での動作はティックベースの MetaTrader 実行とは若干異なる場合があります。 README では、テスト中に考慮できるように、この近似値が強調表示されています。
TimeZoneShift はドキュメント用に保存されています。取引時間自体は、StartHour、EndHour、および ClosingHour を使用して設定する必要があります。
はじめに
- 戦略を StockSharp プロジェクトに追加するか、デザイナー/ランナー内で実行します。
- 取引する商品のローソク足シリーズ (
CandleType) と取引時間を設定します。
- 商品のボラティリティに応じて、ポイントベースのしきい値と比率を調整します。
- 資金管理モードを選択し、対応するパラメータ (
BaseVolume、MoneyManagementFactor、MoneyManagementRiskPercent) を設定します。
- ライブキャピタルで使用する前に、まず紙取引で戦略を実行して、その動作が期待と一致することを検証します。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Early Top Prorate V1: EMA crossover with RSI filter and ATR stops.
/// </summary>
public class EarlyTopProrateV1Strategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastEmaLength;
private readonly StrategyParam<int> _slowEmaLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _atrLength;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
public EarlyTopProrateV1Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_fastEmaLength = Param(nameof(FastEmaLength), 10)
.SetDisplay("Fast EMA Length", "Fast EMA period.", "Indicators");
_slowEmaLength = Param(nameof(SlowEmaLength), 25)
.SetDisplay("Slow EMA Length", "Slow EMA period.", "Indicators");
_rsiLength = Param(nameof(RsiLength), 14)
.SetDisplay("RSI Length", "RSI period.", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period.", "Indicators");
}
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0; _prevSlow = 0; _entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = 0; _prevSlow = 0; _entryPrice = 0;
var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fastEma, slowEma, rsi, atr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null) { DrawCandles(area, subscription); DrawIndicator(area, fastEma); DrawIndicator(area, slowEma); DrawOwnTrades(area); }
}
private void ProcessCandle(ICandleMessage candle, decimal fastVal, decimal slowVal, decimal rsiVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished) return;
if (_prevFast == 0 || _prevSlow == 0 || atrVal <= 0) { _prevFast = fastVal; _prevSlow = slowVal; return; }
var close = candle.ClosePrice;
if (Position > 0)
{
if ((fastVal < slowVal && _prevFast >= _prevSlow) || close <= _entryPrice - atrVal * 1.5m) { SellMarket(); _entryPrice = 0; }
}
else if (Position < 0)
{
if ((fastVal > slowVal && _prevFast <= _prevSlow) || close >= _entryPrice + atrVal * 1.5m) { BuyMarket(); _entryPrice = 0; }
}
if (Position == 0)
{
if (fastVal > slowVal && _prevFast <= _prevSlow && rsiVal > 55) { _entryPrice = close; BuyMarket(); }
else if (fastVal < slowVal && _prevFast >= _prevSlow && rsiVal < 45) { _entryPrice = close; SellMarket(); }
}
_prevFast = fastVal; _prevSlow = slowVal;
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import ExponentialMovingAverage, RelativeStrengthIndex, AverageTrueRange
class early_top_prorate_v1_strategy(Strategy):
def __init__(self):
super(early_top_prorate_v1_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe.", "General")
self._fast_ema_length = self.Param("FastEmaLength", 10) \
.SetDisplay("Fast EMA Length", "Fast EMA period.", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 25) \
.SetDisplay("Slow EMA Length", "Slow EMA period.", "Indicators")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period.", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period.", "Indicators")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def FastEmaLength(self):
return self._fast_ema_length.Value
@property
def SlowEmaLength(self):
return self._slow_ema_length.Value
@property
def RsiLength(self):
return self._rsi_length.Value
@property
def AtrLength(self):
return self._atr_length.Value
def OnStarted2(self, time):
super(early_top_prorate_v1_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self.FastEmaLength
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self.SlowEmaLength
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self.RsiLength
self._atr = AverageTrueRange()
self._atr.Length = self.AtrLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._fast_ema, self._slow_ema, self._rsi, self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, fast_val, slow_val, rsi_val, atr_val):
if candle.State != CandleStates.Finished:
return
fv = float(fast_val)
sv = float(slow_val)
rv = float(rsi_val)
av = float(atr_val)
if self._prev_fast == 0 or self._prev_slow == 0 or av <= 0:
self._prev_fast = fv
self._prev_slow = sv
return
close = float(candle.ClosePrice)
if self.Position > 0:
if (fv < sv and self._prev_fast >= self._prev_slow) or close <= self._entry_price - av * 1.5:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if (fv > sv and self._prev_fast <= self._prev_slow) or close >= self._entry_price + av * 1.5:
self.BuyMarket()
self._entry_price = 0.0
if self.Position == 0:
if fv > sv and self._prev_fast <= self._prev_slow and rv > 55:
self._entry_price = close
self.BuyMarket()
elif fv < sv and self._prev_fast >= self._prev_slow and rv < 45:
self._entry_price = close
self.SellMarket()
self._prev_fast = fv
self._prev_slow = sv
def OnReseted(self):
super(early_top_prorate_v1_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
def CreateClone(self):
return early_top_prorate_v1_strategy()