IU Break of Any Session Strategy
该策略在自定义时段内记录最高价和最低价, 在交易窗口中突破该区间时入场。止损设在进场K线的极值, 盈利目标基于可配置的风险回报比。到达设定的退出时间后所有仓位都会被平掉。
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Breakout from custom session high or low.
/// Enters once per day when price breaks session range.
/// </summary>
public class IUBreakOfAnySessionStrategy : Strategy
{
private readonly StrategyParam<int> _sessionBars;
private readonly StrategyParam<decimal> _profitFactor;
private readonly StrategyParam<int> _maxEntries;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private decimal _sessionHigh;
private decimal _sessionLow;
private int _barCount;
private int _entriesExecuted;
private int _cooldown;
private decimal _stopPrice;
private decimal _targetPrice;
public int SessionBars { get => _sessionBars.Value; set => _sessionBars.Value = value; }
public decimal ProfitFactor { get => _profitFactor.Value; set => _profitFactor.Value = value; }
public int MaxEntries { get => _maxEntries.Value; set => _maxEntries.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public IUBreakOfAnySessionStrategy()
{
_sessionBars = Param(nameof(SessionBars), 24)
.SetGreaterThanZero()
.SetDisplay("Session Bars", "Number of bars to form session range", "Session")
.SetOptimize(24, 96, 24);
_profitFactor = Param(nameof(ProfitFactor), 2m)
.SetGreaterThanZero()
.SetDisplay("Profit Factor", "Risk to reward ratio", "Risk")
.SetOptimize(1m, 4m, 1m);
_maxEntries = Param(nameof(MaxEntries), 45)
.SetDisplay("Max Entries", "Maximum number of entries per test", "Trading");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetGreaterThanZero()
.SetDisplay("Cooldown Bars", "Minimum bars between entries", "Trading");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_sessionHigh = 0m;
_sessionLow = 0m;
_barCount = 0;
_entriesExecuted = 0;
_cooldown = 0;
_stopPrice = 0m;
_targetPrice = 0m;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var dummyEma1 = new StockSharp.Algo.Indicators.ExponentialMovingAverage { Length = 10 };
var dummyEma2 = new StockSharp.Algo.Indicators.ExponentialMovingAverage { Length = 20 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(dummyEma1, dummyEma2, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal d1, decimal d2)
{
if (candle.State != CandleStates.Finished)
return;
_barCount++;
_cooldown++;
if (_barCount <= SessionBars)
{
if (_sessionLow == 0m)
{
_sessionHigh = candle.HighPrice;
_sessionLow = candle.LowPrice;
}
else
{
_sessionHigh = Math.Max(_sessionHigh, candle.HighPrice);
_sessionLow = Math.Min(_sessionLow, candle.LowPrice);
}
return;
}
if (Position > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _targetPrice)
{
SellMarket();
_sessionHigh = candle.HighPrice;
_sessionLow = candle.LowPrice;
_barCount = 1;
}
}
else if (Position < 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _targetPrice)
{
BuyMarket();
_sessionHigh = candle.HighPrice;
_sessionLow = candle.LowPrice;
_barCount = 1;
}
}
else if (_entriesExecuted < MaxEntries && _cooldown >= CooldownBars)
{
if (candle.ClosePrice > _sessionHigh)
{
_stopPrice = _sessionLow;
var risk = candle.ClosePrice - _stopPrice;
_targetPrice = candle.ClosePrice + risk * ProfitFactor;
BuyMarket();
_entriesExecuted++;
_cooldown = 0;
}
else if (candle.ClosePrice < _sessionLow)
{
_stopPrice = _sessionHigh;
var risk = _stopPrice - candle.ClosePrice;
_targetPrice = candle.ClosePrice - risk * ProfitFactor;
SellMarket();
_entriesExecuted++;
_cooldown = 0;
}
}
}
}
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 iu_break_of_any_session_strategy(Strategy):
"""
Breakout from custom session high/low.
Enters when price breaks session range with risk/reward management.
"""
def __init__(self):
super(iu_break_of_any_session_strategy, self).__init__()
self._session_bars = self.Param("SessionBars", 24) \
.SetDisplay("Session Bars", "Number of bars to form session range", "Session")
self._profit_factor = self.Param("ProfitFactor", 2.0) \
.SetDisplay("Profit Factor", "Risk to reward ratio", "Risk")
self._max_entries = self.Param("MaxEntries", 45) \
.SetDisplay("Max Entries", "Maximum number of entries per test", "Trading")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Minimum bars between entries", "Trading")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._session_high = 0.0
self._session_low = 0.0
self._bar_count = 0
self._entries_executed = 0
self._cooldown = 0
self._stop_price = 0.0
self._target_price = 0.0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(iu_break_of_any_session_strategy, self).OnReseted()
self._session_high = 0.0
self._session_low = 0.0
self._bar_count = 0
self._entries_executed = 0
self._cooldown = 0
self._stop_price = 0.0
self._target_price = 0.0
def OnStarted2(self, time):
super(iu_break_of_any_session_strategy, self).OnStarted2(time)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
high = float(candle.HighPrice)
low = float(candle.LowPrice)
close = float(candle.ClosePrice)
self._bar_count += 1
self._cooldown += 1
if self._bar_count <= self._session_bars.Value:
if self._session_low == 0.0:
self._session_high = high
self._session_low = low
else:
self._session_high = max(self._session_high, high)
self._session_low = min(self._session_low, low)
return
if self.Position > 0:
if low <= self._stop_price or high >= self._target_price:
self.SellMarket()
self._session_high = high
self._session_low = low
self._bar_count = 1
elif self.Position < 0:
if high >= self._stop_price or low <= self._target_price:
self.BuyMarket()
self._session_high = high
self._session_low = low
self._bar_count = 1
elif self._entries_executed < self._max_entries.Value and self._cooldown >= self._cooldown_bars.Value:
if close > self._session_high:
self._stop_price = self._session_low
risk = close - self._stop_price
self._target_price = close + risk * self._profit_factor.Value
self.BuyMarket()
self._entries_executed += 1
self._cooldown = 0
elif close < self._session_low:
self._stop_price = self._session_high
risk = self._stop_price - close
self._target_price = close - risk * self._profit_factor.Value
self.SellMarket()
self._entries_executed += 1
self._cooldown = 0
def CreateClone(self):
return iu_break_of_any_session_strategy()