Стратегия EPSI Multi SET
Стратегия пробоя, конвертированная из MQL4 эксперта e-PSI@MultiSET. Она отслеживает каждую свечу и входит в позицию, когда цена уходит на заданное расстояние от открытия. Позиции защищаются уровнями тейк-профита и стоп-лосса, а торговля разрешена только в пределах заданного временного окна.
Подробности
- Условия входа:
- Длинная:
High - Open >= MinDistance - Короткая:
Open - Low >= MinDistance
- Длинная:
- Long/Short: Оба
- Условия выхода: TakeProfit или StopLoss
- Стопы: Да
- Параметры по умолчанию:
MinDistance= 20TakeProfit= 20StopLoss= 200CandleType= TimeSpan.FromHours(1).TimeFrame()OpenHour= 2CloseHour= 20
- Фильтры:
- Категория: Breakout
- Направление: Оба
- Индикаторы: Нет
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Breakout strategy. Opens a position when price moves significantly from candle open.
/// </summary>
public class EPSIMultiSetStrategy : Strategy
{
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _breakoutMult;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public decimal BreakoutMult { get => _breakoutMult.Value; set => _breakoutMult.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EPSIMultiSetStrategy()
{
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "ATR period", "Indicators");
_breakoutMult = Param(nameof(BreakoutMult), 0.5m)
.SetDisplay("Breakout Mult", "ATR multiplier for breakout", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var atr = new StandardDeviation { Length = AtrPeriod };
SubscribeCandles(CandleType).Bind(atr, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal atrValue)
{
if (candle.State != CandleStates.Finished) return;
if (atrValue <= 0) return;
var minDist = atrValue * BreakoutMult;
if (Position == 0)
{
if (candle.HighPrice - candle.OpenPrice >= minDist)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
}
else if (candle.OpenPrice - candle.LowPrice >= minDist)
{
SellMarket();
_entryPrice = candle.ClosePrice;
}
}
else if (Position > 0)
{
if (candle.ClosePrice <= _entryPrice - atrValue * 2 || candle.ClosePrice >= _entryPrice + atrValue * 1.5m)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0)
{
if (candle.ClosePrice >= _entryPrice + atrValue * 2 || candle.ClosePrice <= _entryPrice - atrValue * 1.5m)
{
BuyMarket();
_entryPrice = 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.Indicators import StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class epsi_multi_set_strategy(Strategy):
"""
Breakout strategy. Opens a position when price moves significantly from candle open.
Uses StdDev as volatility measure for breakout confirmation and exit levels.
"""
def __init__(self):
super(epsi_multi_set_strategy, self).__init__()
self._atr_period = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "ATR period", "Indicators")
self._breakout_mult = self.Param("BreakoutMult", 0.5) \
.SetDisplay("Breakout Mult", "ATR multiplier for breakout", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._entry_price = 0.0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(epsi_multi_set_strategy, self).OnReseted()
self._entry_price = 0.0
def OnStarted2(self, time):
super(epsi_multi_set_strategy, self).OnStarted2(time)
atr = StandardDeviation()
atr.Length = self._atr_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(atr, self._process_candle).Start()
def _process_candle(self, candle, atr_val):
if candle.State != CandleStates.Finished:
return
atr_val = float(atr_val)
if atr_val <= 0.0:
return
min_dist = atr_val * self._breakout_mult.Value
high = float(candle.HighPrice)
low = float(candle.LowPrice)
open_p = float(candle.OpenPrice)
close = float(candle.ClosePrice)
if self.Position == 0:
if high - open_p >= min_dist:
self.BuyMarket()
self._entry_price = close
elif open_p - low >= min_dist:
self.SellMarket()
self._entry_price = close
elif self.Position > 0:
if close <= self._entry_price - atr_val * 2.0 or close >= self._entry_price + atr_val * 1.5:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if close >= self._entry_price + atr_val * 2.0 or close <= self._entry_price - atr_val * 1.5:
self.BuyMarket()
self._entry_price = 0.0
def CreateClone(self):
return epsi_multi_set_strategy()