GitHub で見る
SRブレイクアウト戦略
概要
SR ブレイクアウト戦略は、2 つの時間枠 (H1 と H4) で Donchian チャネルから得られるサポートとレジスタンスのレベルを監視します。完了したローソク足がレジスタンスを上回ったりサポートを下回って終了すると、ストラテジーは情報ログ メッセージを書き込みます。この実装は、注文を行わずに、元の MQL4 エキスパートのアラート ロジックを反映しています。
仕組み
- 2 つのキャンドル サブスクリプションが作成されます。1 つは 1 時間の時間枠用で、もう 1 つは 4 時間の時間枠用です。
- 各サブスクリプションは、構成可能なルックバック長 (デフォルトは
26) を持つ独自の DonchianChannels インジケーターにバインドされます。
- インジケーターが形成されると、戦略は各時間枠の前のローソク足の終値を追跡します。
- 終了したすべてのローソク足で、現在の終値が Donchian の上部バンドと下部バンドと比較されます。
- 終値が上部バンドの下から上に移動すると、「レジスタンスを超えた」メッセージが記録されます。
- 終値が下限バンドの上から下に移動すると、「サポートを下回るクロス」メッセージが記録されます。
- このロジックは、
LogInfo エントリをアラートとして使用して、MQL4 スクリプトの通知動作を再現します。
パラメーター
| 名前 |
説明 |
デフォルト |
LookbackLength |
Donchian サポート/レジスタンスを計算するために使用されるローソク足の数。 |
26 |
Hour1CandleType |
1時間単位のキャンドルタイプ。 |
TimeFrame(1h) |
Hour4CandleType |
4時間予約のキャンドルタイプ。 |
TimeFrame(4h) |
信号
- H1 ブレイクアウト – 1 時間足のローソク足の終値がレジスタンスを上回ったとき、またはサポートを下回ったときのログです。
- H4 ブレイクアウト – 4 時間足のローソク足終値がレジスタンスを上回ったとき、またはサポートを下回ったときのログです。
注意事項
- この戦略はアラートのみを目的としています。取引は実行されません。
- Donchian インジケーターが正しく動作するには、両方のローソク足サブスクリプションが高値と安値のデータを提供する必要があります。
- 他の取引セッションや商品に合わせてルックバックの長さやローソク足の種類を調整します。
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Support and resistance breakout strategy using Donchian channels.
/// Buys when price breaks above resistance (upper band), sells when breaks below support (lower band).
/// </summary>
public class SrBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _lookbackLength;
private readonly StrategyParam<DataType> _candleType;
private readonly Queue<decimal> _highHistory = new();
private readonly Queue<decimal> _lowHistory = new();
public int LookbackLength
{
get => _lookbackLength.Value;
set => _lookbackLength.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public SrBreakoutStrategy()
{
_lookbackLength = Param(nameof(LookbackLength), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Number of candles for Donchian channel", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(60).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for analysis", "General");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_highHistory.Clear();
_lowHistory.Clear();
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (_highHistory.Count < LookbackLength)
{
EnqueueCandle(candle);
return;
}
var highs = _highHistory.ToArray();
var lows = _lowHistory.ToArray();
var upper = GetMax(highs);
var lower = GetMin(lows);
var close = candle.ClosePrice;
var range = upper - lower;
var volume = Volume;
if (volume <= 0)
volume = 1;
var breakoutPadding = range * 0.05m;
// Break above resistance
if (close > upper + breakoutPadding)
{
if (Position <= 0)
BuyMarket(Position < 0 ? Math.Abs(Position) + volume : volume);
}
// Break below support
else if (close < lower - breakoutPadding)
{
if (Position >= 0)
SellMarket(Position > 0 ? Math.Abs(Position) + volume : volume);
}
EnqueueCandle(candle);
}
private void EnqueueCandle(ICandleMessage candle)
{
_highHistory.Enqueue(candle.HighPrice);
_lowHistory.Enqueue(candle.LowPrice);
if (_highHistory.Count > LookbackLength)
{
_highHistory.Dequeue();
_lowHistory.Dequeue();
}
}
private static decimal GetMax(IEnumerable<decimal> values)
{
var max = decimal.MinValue;
foreach (var value in values)
{
if (value > max)
max = value;
}
return max;
}
private static decimal GetMin(IEnumerable<decimal> values)
{
var min = decimal.MaxValue;
foreach (var value in values)
{
if (value < min)
min = value;
}
return min;
}
/// <inheritdoc />
protected override void OnReseted()
{
_highHistory.Clear();
_lowHistory.Clear();
base.OnReseted();
}
}
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
class sr_breakout_strategy(Strategy):
def __init__(self):
super(sr_breakout_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(60)))
self._lookback_length = self.Param("LookbackLength", 20)
self._highs = []
self._lows = []
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def LookbackLength(self):
return self._lookback_length.Value
@LookbackLength.setter
def LookbackLength(self, value):
self._lookback_length.Value = value
def OnReseted(self):
super(sr_breakout_strategy, self).OnReseted()
self._highs = []
self._lows = []
def OnStarted2(self, time):
super(sr_breakout_strategy, self).OnStarted2(time)
self._highs = []
self._lows = []
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._process_candle).Start()
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
lookback = self.LookbackLength
if len(self._highs) < lookback:
self._enqueue_candle(candle)
return
upper = max(self._highs)
lower = min(self._lows)
close = float(candle.ClosePrice)
range_val = upper - lower
breakout_padding = range_val * 0.05
if close > upper + breakout_padding:
if self.Position <= 0:
self.BuyMarket()
elif close < lower - breakout_padding:
if self.Position >= 0:
self.SellMarket()
self._enqueue_candle(candle)
def _enqueue_candle(self, candle):
self._highs.append(float(candle.HighPrice))
self._lows.append(float(candle.LowPrice))
lookback = self.LookbackLength
while len(self._highs) > lookback:
self._highs.pop(0)
self._lows.pop(0)
def CreateClone(self):
return sr_breakout_strategy()