トゥユルギャップ 週末
概要
Tuyul Gap の週末には、MetaTrader 5 エキスパート アドバイザー TuyulGAP が StockSharp に移植されます。この戦略は、金曜日の夜に設定可能な数の最近のローソク足をスキャンし、最高高値と最低安値の周囲にブレイクアウト ストップ注文のペアを配置することで、毎週の市場開始に備えます。許可される取引セッションは週に 1 回だけです。注文がステージングされると、戦略は価格がいずれかのレベルを通過するのを待ちます。口座通貨で安全な利益目標に達したオープンポジションはすぐにクローズされ、残りの未決注文はすべて月曜日にキャンセルされ、翌週のワークフローがリセットされます。
戦略ロジック
- 毎週のセッション トリガー – セットアップは、設定可能な平日 (デフォルトでは金曜日) に、交換クロックが設定された時間に達すると実行されます。 1 分間のウィンドウ (デフォルトでは 23:00 ~ 23:15) の間、ストラテジーはセッションごとに 1 回ブレイクアウト レベルを準備します。
- 動的ブレイクアウト レベル – 過去の
Lookback Bars終了ローソク足の最高高値と最低安値がトリガー価格を定義します。買いストップは高値より 1 ティック上に配置され、売りストップは安値より 1 ティック下に配置され、MetaTrader ポイント オフセットを模倣します。 - 未決注文の健全性 – その週の逆指値注文がすでに存在する場合、その注文は再作成されません。一方の側がトリガーされた後も、反対側の未決注文はアクティブなままであるため、戦略はギャップのどちらの方向でも取引できます。
- 安全な利益の出口 – 完了したすべてのローソク足でオープンポジションが監視されます。ポジションの未実現利益が確実な利益目標(ポートフォリオ通貨で)に達すると、方向に関係なく市場でフラット化されます。
- 毎週のリセット – 最初の月曜日のローソク足で、戦略はまだアクティブな未決注文をキャンセルし、セッション フラグを再設定して、次の金曜日のセットアップをステージングできるようにします。
パラメーター
- 出来高 – ブレイクアウトストップ注文の注文量。
- ストップロス (ポイント) – エントリー価格からの距離。商品ポイントで表され、ポジションがオープンした後に保護ストップを置くために使用されます。停止を無効にするには、
0に設定します。 - ルックバックバー – 毎週の高値と安値を計算するために検査された完成したローソク足の数。
- 曜日の設定 – 毎週の設定をトリガーする日のインデックス (0=日曜日 ... 6=土曜日)。デフォルト値の
5は、金曜日の元の動作を維持します。 - セットアップ時間 – ブレイクアウト注文をステージングするためのアンカーとして使用される取引時間。
- セットアップ時間枠 –
Setup Hour以降、セットアップが有効なままになる分数。デフォルト値15を使用すると、戦略は 23:00 から 23:15 までの間で実行されます。 - 安全な利益目標 – 即時市場撤退を引き起こす、ポジションごとの最小未実現利益 (ポートフォリオ通貨)。
- ローソク足タイプ – 高値/低値スキャンと監視ループに使用される時間枠。
追加の注意事項
- StockSharp は保留中のストップ注文に直接保護ストップを付けることをサポートしていないため、ストップロス注文はポジションがオープンした後にのみ送信されます。
- 出来高、価格、ストップレベルは、StockSharp が提供する証券のステップと精度の情報を使用して正規化されます。
- この戦略の Python 翻訳はありません。このパッケージには C# 実装のみが含まれています。
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Port of the MetaTrader 5 expert advisor TuyulGAP.
/// Places weekly breakout stop orders around the recent high/low range and closes positions once secure profit is reached.
/// </summary>
public class TuyulGapEndOfWeekStrategy : Strategy
{
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _lookbackBars;
private readonly StrategyParam<int> _setupDayOfWeek;
private readonly StrategyParam<int> _setupHour;
private readonly StrategyParam<int> _setupMinuteWindow;
private readonly StrategyParam<decimal> _secureProfitTarget;
private readonly StrategyParam<DataType> _candleType;
private Highest _highestHigh;
private Lowest _lowestLow;
private decimal _tickSize;
private decimal _entryPrice;
private decimal? _virtualStopPrice;
private decimal _prevHighest;
private decimal _prevLowest;
/// <summary>
/// Initializes a new instance of the <see cref="TuyulGapEndOfWeekStrategy"/> class.
/// </summary>
public TuyulGapEndOfWeekStrategy()
{
_stopLossPoints = Param(nameof(StopLossPoints), 60)
.SetRange(0, 5000)
.SetDisplay("Stop Loss (points)", "Distance from entry used for protective stops", "Risk");
_lookbackBars = Param(nameof(LookbackBars), 12)
.SetRange(2, 500)
.SetDisplay("Lookback Bars", "Number of finished candles inspected for highs/lows", "Setup");
_setupDayOfWeek = Param(nameof(SetupDayOfWeek), 5)
.SetRange(0, 6)
.SetDisplay("Setup Day Of Week", "Day index (0=Sunday) that stages the weekly orders", "Setup");
_setupHour = Param(nameof(SetupHour), 23)
.SetRange(0, 23)
.SetDisplay("Setup Hour", "Exchange hour when the weekly setup is evaluated", "Setup");
_setupMinuteWindow = Param(nameof(SetupMinuteWindow), 15)
.SetRange(0, 59)
.SetDisplay("Setup Minute Window", "Minutes after the setup hour when staging is allowed", "Setup");
_secureProfitTarget = Param(nameof(SecureProfitTarget), 5m)
.SetRange(0m, 100000m)
.SetDisplay("Secure Profit Target", "Unrealized profit per position that triggers an immediate exit", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for the high/low scan and monitoring", "Data");
}
/// <summary>
/// Distance from entry used for protective stops, measured in instrument points.
/// </summary>
public int StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Number of finished candles inspected for highs and lows.
/// </summary>
public int LookbackBars
{
get => _lookbackBars.Value;
set => _lookbackBars.Value = value;
}
/// <summary>
/// Day index (0=Sunday … 6=Saturday) that stages the weekly setup.
/// </summary>
public int SetupDayOfWeek
{
get => _setupDayOfWeek.Value;
set => _setupDayOfWeek.Value = value;
}
/// <summary>
/// Exchange hour when the weekly setup is evaluated.
/// </summary>
public int SetupHour
{
get => _setupHour.Value;
set => _setupHour.Value = value;
}
/// <summary>
/// Minutes after the setup hour when staging is allowed.
/// </summary>
public int SetupMinuteWindow
{
get => _setupMinuteWindow.Value;
set => _setupMinuteWindow.Value = value;
}
/// <summary>
/// Unrealized profit per position that triggers an immediate exit.
/// </summary>
public decimal SecureProfitTarget
{
get => _secureProfitTarget.Value;
set => _secureProfitTarget.Value = value;
}
/// <summary>
/// Timeframe used for the high/low scan and monitoring.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_highestHigh = null;
_lowestLow = null;
_tickSize = 0m;
_entryPrice = 0m;
_virtualStopPrice = null;
_prevHighest = 0m;
_prevLowest = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_tickSize = Security?.PriceStep ?? 0m;
_highestHigh = new Highest
{
Length = Math.Max(2, LookbackBars)
};
_lowestLow = new Lowest
{
Length = Math.Max(2, LookbackBars)
};
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_highestHigh, _lowestLow, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal highestValue, decimal lowestValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_highestHigh.IsFormed || !_lowestLow.IsFormed)
return;
// Check virtual stop
if (Position > 0m && _virtualStopPrice.HasValue && candle.LowPrice <= _virtualStopPrice.Value)
{
SellMarket(Math.Abs(Position));
_virtualStopPrice = null;
_entryPrice = 0m;
return;
}
if (Position < 0m && _virtualStopPrice.HasValue && candle.HighPrice >= _virtualStopPrice.Value)
{
BuyMarket(Math.Abs(Position));
_virtualStopPrice = null;
_entryPrice = 0m;
return;
}
// Close on profit
if (Position != 0m && SecureProfitTarget > 0m && PnL >= SecureProfitTarget)
{
if (Position > 0m)
SellMarket(Math.Abs(Position));
else
BuyMarket(Math.Abs(Position));
_virtualStopPrice = null;
_entryPrice = 0m;
return;
}
if (Position == 0m && _prevHighest > 0m && _prevLowest > 0m)
{
// Breakout above previous highest
if (candle.ClosePrice > _prevHighest)
{
BuyMarket(Volume);
_entryPrice = candle.ClosePrice;
var stopDist = GetStopLossDistance();
if (stopDist > 0m)
_virtualStopPrice = _entryPrice - stopDist;
}
// Breakout below previous lowest
else if (candle.ClosePrice < _prevLowest)
{
SellMarket(Volume);
_entryPrice = candle.ClosePrice;
var stopDist = GetStopLossDistance();
if (stopDist > 0m)
_virtualStopPrice = _entryPrice + stopDist;
}
}
_prevHighest = highestValue;
_prevLowest = lowestValue;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
private decimal GetStopLossDistance()
{
var tick = _tickSize > 0m ? _tickSize : Security?.PriceStep ?? 0m;
if (tick <= 0m)
return 0m;
return StopLossPoints > 0 ? StopLossPoints * tick : 0m;
}
private decimal NormalizePrice(decimal price)
{
var tick = _tickSize > 0m ? _tickSize : Security?.PriceStep ?? 0m;
if (tick <= 0m)
return price;
return Math.Round(price / tick, MidpointRounding.AwayFromZero) * tick;
}
private decimal NormalizeVolume(decimal volume)
{
var security = Security;
if (security == null)
return volume;
if (security.VolumeStep is { } volumeStep && volumeStep > 0m)
volume = Math.Round(volume / volumeStep, MidpointRounding.AwayFromZero) * volumeStep;
if (security.MinVolume is { } minVolume && minVolume > 0m && volume < minVolume)
volume = minVolume;
if (security.MaxVolume is { } maxVolume && maxVolume > 0m && volume > maxVolume)
volume = maxVolume;
return volume;
}
private DayOfWeek GetSetupDay()
{
var day = SetupDayOfWeek % 7;
if (day < 0)
day += 7;
return (DayOfWeek)day;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class tuyul_gap_end_of_week_strategy(Strategy):
"""Breakout above highest / below lowest with stop loss management."""
def __init__(self):
super(tuyul_gap_end_of_week_strategy, self).__init__()
self._sl_points = self.Param("StopLossPoints", 60).SetDisplay("Stop Loss", "SL in points", "Risk")
self._lookback = self.Param("LookbackBars", 12).SetDisplay("Lookback", "Bars for high/low", "Setup")
self._secure_profit = self.Param("SecureProfitTarget", 5.0).SetDisplay("Secure Profit", "Profit target for exit", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))).SetDisplay("Candle Type", "Timeframe", "Data")
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, value): self._candle_type.Value = value
def OnReseted(self):
super(tuyul_gap_end_of_week_strategy, self).OnReseted()
self._entry_price = 0
self._virtual_stop = None
self._prev_highest = 0
self._prev_lowest = 0
self._tick_size = 0
def OnStarted2(self, time):
super(tuyul_gap_end_of_week_strategy, self).OnStarted2(time)
self._entry_price = 0
self._virtual_stop = None
self._prev_highest = 0
self._prev_lowest = 0
self._tick_size = 0.0
if self.Security is not None and self.Security.PriceStep is not None:
self._tick_size = float(self.Security.PriceStep)
hi = Highest()
hi.Length = max(2, self._lookback.Value)
lo = Lowest()
lo.Length = max(2, self._lookback.Value)
self._hi = hi
self._lo = lo
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(hi, lo, self.OnProcess).Start()
def OnProcess(self, candle, hi_val, lo_val):
if candle.State != CandleStates.Finished:
return
if not self._hi.IsFormed or not self._lo.IsFormed:
return
highest = float(hi_val)
lowest = float(lo_val)
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
# Check virtual stop
if self.Position > 0 and self._virtual_stop is not None and low <= self._virtual_stop:
self.SellMarket(abs(float(self.Position)))
self._virtual_stop = None
self._entry_price = 0
return
if self.Position < 0 and self._virtual_stop is not None and high >= self._virtual_stop:
self.BuyMarket(abs(float(self.Position)))
self._virtual_stop = None
self._entry_price = 0
return
# Close on profit
if self.Position != 0 and self._secure_profit.Value > 0 and float(self.PnL) >= self._secure_profit.Value:
if self.Position > 0:
self.SellMarket(abs(float(self.Position)))
else:
self.BuyMarket(abs(float(self.Position)))
self._virtual_stop = None
self._entry_price = 0
return
# Entry on breakout
if self.Position == 0 and self._prev_highest > 0 and self._prev_lowest > 0:
stop_dist = self._get_stop_distance()
if close > self._prev_highest:
self.BuyMarket()
self._entry_price = close
if stop_dist > 0:
self._virtual_stop = close - stop_dist
elif close < self._prev_lowest:
self.SellMarket()
self._entry_price = close
if stop_dist > 0:
self._virtual_stop = close + stop_dist
self._prev_highest = highest
self._prev_lowest = lowest
def _get_stop_distance(self):
tick = self._tick_size
if tick <= 0:
if self.Security is not None and self.Security.PriceStep is not None:
tick = float(self.Security.PriceStep)
if tick <= 0:
return 0
if self._sl_points.Value > 0:
return self._sl_points.Value * tick
return 0
def CreateClone(self):
return tuyul_gap_end_of_week_strategy()