GitHub で見る
前のローソク足のブレイクアウトレベル戦略
概要
この戦略はMetaTraderエキスパートアドバイザー「Previous Candle Breakdown」を再現します。価格が設定可能な価格ステップで測定されたインデントを持つ前の参照ローソク足の上または下に突破するのを待ちます。実装はレベル計算のためのローソク足サブスクリプションと実行決定のためのティックサブスクリプションを使用したStockSharp高レベルAPIに依存しています。
トレードロジック
- 各参照ローソク足(デフォルト4時間)のクローズ時に、戦略は前のローソク足の高値と安値を保存し、ブレイクアウトレベルを構築するために
IndentSteps * Security.PriceStepでオフセットします。
- ティック価格(最後の取引)が監視されます。価格が上位レベルに達するとロングエントリーがトリガーされ、価格が下位レベルを下回るとショートエントリーがトリガーされます。
- オプションの移動平均フィルターは、ロング取引では高速MA(オプションの前向きシフト付き)が低速MAより上にあり、ショート取引では下にあることを要求します。いずれかのMA期間をゼロに設定するとフィルターが無効になります。
- 取引は
StartTimeとEndTime間の設定されたセッションウィンドウ内でのみ許可されます。真夜中をまたぐセッションがサポートされています。
- フローティング利益は継続的に監視されます:ストップ、ターゲット、トレーリングルールはブレイクアウトシグナルが反転をトリガーできる前に既存のポジションをクローズします。
リスク管理
- StopLossSteps / TakeProfitSteps — エントリー価格からの価格ステップでの距離。ステップは
distance = steps * Security.PriceStepで変換されます。
- TrailingStopSteps / TrailingStepSteps — ポジションが少なくともトレーリング距離分有利に動いた後、トレーリング終了を有効にします。ストップはトレーリングステップ分利益が進んだ時にのみさらに移動します。
- ProfitClose — 未実現利益(
Position * (最後の価格 - PositionPrice))が閾値を超えたらすべてのポジションをクローズします。無効にするには0に設定。
- MaxNetPosition — 戦略がその量を超えてピラミッディングできないように絶対純ポジションを制限します。ポジションサイズ自体は戦略の
Volumeプロパティによって制御されます。
パラメーター
| パラメーター |
説明 |
CandleType |
ブレイクアウトレベルを計算するために使用する参照時間軸。 |
IndentSteps |
価格ステップで表された前のローソク足の高値/安値の上/下のオフセット。 |
FastMaPeriod / FastMaShift |
高速MA長とオプションの前向きシフト(バー)。 |
SlowMaPeriod / SlowMaShift |
低速MA長とオプションの前向きシフト(バー)。 |
StopLossSteps |
価格ステップでのストップロス距離。 |
TakeProfitSteps |
価格ステップでのテイクプロフィット距離。 |
TrailingStopSteps |
トレーリングストップ距離(0でトレーリングを無効化)。 |
TrailingStepSteps |
トレーリングストップが進む前に必要な最小利益。トレーリング使用時は > 0でなければなりません。 |
ProfitClose |
すべてのポジションをクローズするフローティング利益ターゲット。 |
MaxNetPosition |
許可される最大絶対純ポジション。 |
StartTime / EndTime |
取引ウィンドウの境界。 |
使用上の注意
- 注文サイズを制御するために戦略インスタンスの
Volumeプロパティを設定してください。MetaTraderバージョンのリスクベースのポジションサイジングは意図的にポートされていません。
- 移動平均は単純移動平均(
SMA)を使用します。他の平滑化モードが必要な場合は、それに応じて戦略を拡張してください。
- 利益クローズ閾値はブローカー固有のスワップ/コミッションデータが直接利用できないため、口座通貨の代わりに平均ポジション価格から計算された未実現PnLを使用します。
- 戦略はネッティング環境で動作します;反転取引は反対方向にマーケット注文を送信し、自動的に最初に現在のエクスポージャーをクローズします。
- トレーリングストップは正の
TrailingStepSteps値が必要です;そうでなければ戦略は起動時に例外をスローします。
元のMQLバージョンとの違い
- 固定ロットまたはリスクパーセンテージに基づくマネーマネジメントは実装されていません;StockSharpユーザーは
Volumeプロパティまたは外部ポートフォリオマネージャーを通じてサイズを管理する必要があります。
- 単純移動平均のみがサポートされています;元のバージョンは異なるMAタイプを許可していました。
- 利益クローズロジックはブローカー固有のスワップ/コミッションデータが直接利用できないため、口座通貨の代わりに平均ポジション価格からの未実現PnLを使用します。
- ログはStockSharpによって処理されます;MetaTraderからの詳細な取引結果メッセージは省略されます。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public class PreviousCandleBreakdownLevelsStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private decimal? _prevHigh, _prevLow;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public PreviousCandleBreakdownLevelsStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame()).SetDisplay("Candle Type", "Timeframe", "General");
_fastPeriod = Param(nameof(FastPeriod), 8).SetGreaterThanZero().SetDisplay("Fast EMA", "Fast period", "Indicators");
_slowPeriod = Param(nameof(SlowPeriod), 21).SetGreaterThanZero().SetDisplay("Slow EMA", "Slow period", "Indicators");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevHigh = null;
_prevLow = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevHigh = null; _prevLow = null;
var fast = new ExponentialMovingAverage { Length = FastPeriod };
var slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fast, slow, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null) { DrawCandles(area, subscription); DrawIndicator(area, fast); DrawIndicator(area, slow); DrawOwnTrades(area); }
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished) return;
if (!IsFormedAndOnlineAndAllowTrading()) { _prevHigh = candle.HighPrice; _prevLow = candle.LowPrice; return; }
if (_prevHigh == null) { _prevHigh = candle.HighPrice; _prevLow = candle.LowPrice; return; }
var close = candle.ClosePrice;
if (fast > slow && close > _prevHigh.Value && Position <= 0) { if (Position < 0) BuyMarket(); BuyMarket(); }
else if (fast < slow && close < _prevLow.Value && Position >= 0) { if (Position > 0) SellMarket(); SellMarket(); }
_prevHigh = candle.HighPrice; _prevLow = candle.LowPrice;
}
}
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 previous_candle_breakdown_levels_strategy(Strategy):
def __init__(self):
super(previous_candle_breakdown_levels_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._fast_period = self.Param("FastPeriod", 8) \
.SetDisplay("Fast EMA", "Fast period", "Indicators")
self._slow_period = self.Param("SlowPeriod", 21) \
.SetDisplay("Slow EMA", "Slow period", "Indicators")
self._prev_high = None
self._prev_low = None
@property
def CandleType(self):
return self._candle_type.Value
@property
def FastPeriod(self):
return self._fast_period.Value
@property
def SlowPeriod(self):
return self._slow_period.Value
def OnReseted(self):
super(previous_candle_breakdown_levels_strategy, self).OnReseted()
self._prev_high = None
self._prev_low = None
def OnStarted2(self, time):
super(previous_candle_breakdown_levels_strategy, self).OnStarted2(time)
self._prev_high = None
self._prev_low = None
fast = ExponentialMovingAverage()
fast.Length = self.FastPeriod
slow = ExponentialMovingAverage()
slow.Length = self.SlowPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast, slow, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def _on_process(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fv = float(fast_value)
sv = float(slow_value)
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
return
if self._prev_high is None:
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
return
close = float(candle.ClosePrice)
if fv > sv and close > self._prev_high and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif fv < sv and close < self._prev_low and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
def CreateClone(self):
return previous_candle_breakdown_levels_strategy()