Стратегия External Level
Отрисовывает уровни поддержки и сопротивления, когда значение источника равно 1 или -1. Линия рисуется по максимуму предыдущей свечи при 1 и по минимуму при -1.
Подробности
- Критерии входа: отсутствуют
- Длинная/короткая: нет
- Критерии выхода: нет
- Стопы: нет
- Значения по умолчанию:
CandleType= 1 мин
- Фильтры:
- Категория: Графика
- Направление: нет
- Индикаторы: нет
- Стопы: нет
- Сложность: базовая
- Таймфрейм: внутридневной
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: низкий
using System;
using System.Linq;
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>
/// Support/resistance level breakout strategy.
/// Tracks highest high and lowest low over a lookback period.
/// Buys on breakout above resistance, sells on breakdown below support.
/// </summary>
public class ExternalLevelStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevResistance;
private decimal _prevSupport;
public int Lookback { get => _lookback.Value; set => _lookback.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ExternalLevelStrategy()
{
_lookback = Param(nameof(Lookback), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Support/resistance lookback period", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Source candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevResistance = 0;
_prevSupport = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var highest = new Highest { Length = Lookback };
var lowest = new Lowest { Length = Lookback };
_prevResistance = 0;
_prevSupport = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(highest, lowest, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal resistance, decimal support)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevResistance == 0)
{
_prevResistance = resistance;
_prevSupport = support;
return;
}
if (candle.ClosePrice > _prevResistance && Position <= 0)
BuyMarket();
else if (candle.ClosePrice < _prevSupport && Position >= 0)
SellMarket();
_prevResistance = resistance;
_prevSupport = support;
}
}
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 Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class external_level_strategy(Strategy):
def __init__(self):
super(external_level_strategy, self).__init__()
self._lookback = self.Param("Lookback", 20) \
.SetDisplay("Lookback", "Support/resistance lookback period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Source candle timeframe", "General")
self._prev_resistance = 0.0
self._prev_support = 0.0
@property
def lookback(self):
return self._lookback.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(external_level_strategy, self).OnReseted()
self._prev_resistance = 0.0
self._prev_support = 0.0
def OnStarted2(self, time):
super(external_level_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self.lookback
lowest = Lowest()
lowest.Length = self.lookback
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(highest, lowest, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, resistance, support):
if candle.State != CandleStates.Finished:
return
if self._prev_resistance == 0:
self._prev_resistance = resistance
self._prev_support = support
return
if candle.ClosePrice > self._prev_resistance and self.Position <= 0:
self.BuyMarket()
elif candle.ClosePrice < self._prev_support and self.Position >= 0:
self.SellMarket()
self._prev_resistance = resistance
self._prev_support = support
def CreateClone(self):
return external_level_strategy()