GitHub で見る
Flat Channel Breakout戦略
Flat Channel Strategy は MetaTrader 5 エキスパートアドバイザー Flat Channel (barabashkakvn の版) の C# 翻訳です。元のワークフローを維持します:平滑化された標準偏差がボラティリティスクイーズを強調し、スクイーズ内の最高値と最低値が水平チャネルを定義し、そのレンジのすぐ外にペンディングストップ注文が置かれます。市場がブレイクアウトすると、戦略は事前定義されたストップロスとテイクプロフィットレベルで動きに乗り、ポジションが利益を得るとオプションでストップをトレールできます。
動作原理
- ボラティリティスクイーズ検出 – 長さ
StdDevPeriod の StandardDeviation インジケーターが SmoothingLength の短い SimpleMovingAverage で平滑化されます。平滑化されたシリーズが FlatBars 個の連続した非増加値を出力するたびに、市場はフラットとして扱われ、注文フラグが再アームされます。
- チャネル構築 – フラットが確認されると、戦略は組み込みの
Highest/Lowest インジケーターを使用して、最後の max(ChannelLookback, FlatBars + 1) ローソク足にわたる最高値と最低値を要求します。チャネルの高さは PipSize を通じて pips を価格単位に変換した後、ChannelMinPips/ChannelMaxPips でフィルタリングされます(パラメーターをゼロに残した場合は検出されたティックサイズを使用)。
- ペンディング注文 – 現在のポジションがフラットで取引が許可されている場合、戦略は
high + IndentPips で買いストップ注文を、low − IndentPips で売りストップ注文を送ります。各注文は提出時に計算された保護レベルを記憶します。
- ブレイクアウト実行 – ペンディング注文がフィルされると、逆のペンディング注文が自動的にキャンセルされます。フィルされた価格はトレーリングストップロジックのエントリーアンカーとなり、記憶されたストップロス/テイクプロフィット距離が有効になります。
- ポジション管理 – アクティブポジションは完成したローソク足ごとに監視されます。価格がストップロスまたはテイクプロフィットレベルに触れると、戦略は成行エグジットを発動します。
TrailingStopPips がゼロより大きい場合、終値がフィル価格から少なくとも TrailingStopPips + TrailingStepPips 動くとストップが前進します。
- セッションフィルター –
UseTradingHours が有効な場合、ブレイクアウトロジックは StartHour(含む)と EndHour(含まない)の間でのみ機能します。StartHour > EndHour を許可することで夜間セッションがサポートされます。
リスク管理
- 動的または固定の保護 – 固定距離(pips 単位)を使用するには
StopLossPips / TakeProfitPips を正の値に設定します。ゼロに保つと、チャネルの高さと DynamicStopMultiplier / DynamicTakeMultiplier 係数に基づく動的サイジングに切り替わります。
- トレーリングストップ –
TrailingStopPips を有効にして、取引が利益になったら動きに従います。トレーリングロジックはマイクロ調整を避けるために TrailingStepPips を尊重します。
- ポジションキャップ –
MaxPositions は集計エクスポージャーを MaxPositions × TradeVolume に制限します。その閾値に達した場合、エクスポージャーが減少するまで新しいペンディング注文は送られません。
- 方向性フィルター –
UseBuy と UseSell で戦略をブレイクアウトのみ、ブレイクダウンのみ、または双方向モードで動作させることができます。
パラメーター
| パラメーター |
デフォルト |
説明 |
TradeVolume |
1 |
各ペンディング注文で送られる出来高。 |
PipSize |
0.0001 |
手動 pip サイズ上書き。ゼロに残すとインストゥルメントのティックサイズを使用(3/5 桁自動調整付き)。 |
StdDevPeriod |
46 |
ベース StandardDeviation のルックバック。 |
SmoothingLength |
3 |
ボラティリティシリーズに適用する移動平均長。 |
FlatBars |
3 |
ブレイクアウト注文を再アームするために必要な連続する非増加の平滑化ボラティリティ値の数。 |
ChannelLookback |
5 |
フラット検出後に最高値と最低値を測定するために使用するローソク足数。FlatBars + 1 と自動的に比較されます。 |
ChannelMinPips |
15 |
チャネルの最小高さ(pips 単位)。下限を無効にするには 0 に設定。 |
ChannelMaxPips |
105 |
チャネルの最大高さ(pips 単位)。上限を無効にするには 0 に設定。 |
DynamicStopMultiplier |
1 |
StopLossPips = 0 のとき動的ストップロス計算のチャネル高さ乗数。 |
DynamicTakeMultiplier |
1 |
TakeProfitPips = 0 のとき動的テイクプロフィット計算のチャネル高さ乗数。 |
StopLossPips |
0 |
pips 単位の固定ストップロス距離。正のとき動的数式を上書き。 |
TakeProfitPips |
0 |
pips 単位の固定テイクプロフィット距離。正のとき動的数式を上書き。 |
IndentPips |
0 |
ペンディング注文のチャネル境界を超えた追加オフセット(pips 単位)。 |
TrailingStopPips |
5 |
pips 単位のトレーリングストップ距離。トレーリングを無効にするには 0 に設定。 |
TrailingStepPips |
5 |
トレーリングストップを移動するために必要な最小ステップ(pips 単位)。 |
UseBuy |
true |
ロング(買いストップ)ブレイクアウトを有効にする。 |
UseSell |
true |
ショート(売りストップ)ブレイクアウトを有効にする。 |
MaxPositions |
5 |
集計ポジションで許可される基本出来高の最大数。 |
UseTradingHours |
true |
取引セッションフィルターを有効にする。 |
StartHour |
0 |
セッション開始時刻(含む)。 |
EndHour |
23 |
セッション終了時刻(含まない)。 |
CandleType |
H1 |
計算に使用するローソク足シリーズ(デフォルト: 1 時間足)。 |
ノート
- 戦略は高レベルの
SubscribeCandles().Bind(...) API を通じて完成したローソク足のみで動作し、元の EA に期待される決定論的な動作に一致します。
- 保護価格は
Security.ShrinkPrice を通じて正規化され、取引所のティックサイズを尊重します。
- 両方のペンディング注文がアクティブで一方がフィルされると、逆の注文は即座にキャンセルされ、一度に 1 つのブレイクアウトポジションのみが開いていることができます。
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>
/// Flat Channel Breakout strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class FlatChannelBreakoutStrategy : 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 FlatChannelBreakoutStrategy()
{
_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 flat_channel_breakout_strategy(Strategy):
def __init__(self):
super(flat_channel_breakout_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(flat_channel_breakout_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(flat_channel_breakout_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 flat_channel_breakout_strategy()