Стратегия Renko Trend Reversal
Стратегия Renko Trend Reversal входит, когда открытие ренко пересекает закрытие. Стоп-лосс и тейк-профит можно включить. Используются кирпичи ренко на основе ATR.
Детали
- Критерий входа: пересечение открытия и закрытия ренко с учётом времени
- Длин/Шорт: обе стороны
- Критерий выхода: опциональный стоп-лосс или тейк-профит
- Стопы: опционально
- Значения по умолчанию:
RenkoAtrLength= 10StopLossPct= 10TakeProfitPct= 50
- Фильтры:
- Категория: Тренд
- Направление: Обе стороны
- Индикаторы: ATR
- Стопы: Опционально
- Сложность: Базовая
- Таймфрейм: Renko
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Volatility-based trend reversal strategy simulating renko brick logic on regular candles.
/// Uses StandardDeviation for brick sizing with stop loss.
/// </summary>
public class RenkoTrendReversalStrategy : Strategy
{
private readonly StrategyParam<int> _stdLength;
private readonly StrategyParam<decimal> _brickMultiplier;
private readonly StrategyParam<DataType> _candleType;
private decimal _brickHigh;
private decimal _brickLow;
private bool _isUpTrend;
private bool _hasBrick;
private decimal _entryPrice;
public int StdLength { get => _stdLength.Value; set => _stdLength.Value = value; }
public decimal BrickMultiplier { get => _brickMultiplier.Value; set => _brickMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public RenkoTrendReversalStrategy()
{
_stdLength = Param(nameof(StdLength), 14)
.SetGreaterThanZero()
.SetDisplay("StdDev Length", "StdDev period for brick size", "General");
_brickMultiplier = Param(nameof(BrickMultiplier), 0.5m)
.SetDisplay("Brick Multiplier", "Multiplier for brick size", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle Type", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_hasBrick = false;
_entryPrice = 0;
_brickHigh = 0;
_brickLow = 0;
_isUpTrend = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var stdDev = new StandardDeviation { Length = StdLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(stdDev, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, stdDev);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal stdValue)
{
if (candle.State != CandleStates.Finished)
return;
if (stdValue <= 0)
return;
var brickSize = stdValue * BrickMultiplier;
if (!_hasBrick)
{
_brickHigh = candle.ClosePrice + brickSize;
_brickLow = candle.ClosePrice - brickSize;
_isUpTrend = candle.ClosePrice > candle.OpenPrice;
_hasBrick = true;
return;
}
if (candle.ClosePrice >= _brickHigh)
{
// Bullish brick
if (!_isUpTrend && Position <= 0)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
}
_isUpTrend = true;
_brickHigh = candle.ClosePrice + brickSize;
_brickLow = candle.ClosePrice - brickSize;
}
else if (candle.ClosePrice <= _brickLow)
{
// Bearish brick
if (_isUpTrend && Position >= 0)
{
SellMarket();
_entryPrice = candle.ClosePrice;
}
_isUpTrend = false;
_brickHigh = candle.ClosePrice + brickSize;
_brickLow = candle.ClosePrice - brickSize;
}
// Stop loss check
if (Position > 0 && _entryPrice > 0 && candle.ClosePrice < _entryPrice * 0.97m)
SellMarket();
else if (Position < 0 && _entryPrice > 0 && candle.ClosePrice > _entryPrice * 1.03m)
BuyMarket();
}
}
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 renko_trend_reversal_strategy(Strategy):
def __init__(self):
super(renko_trend_reversal_strategy, self).__init__()
self._std_length = self.Param("StdLength", 14) \
.SetDisplay("StdDev Length", "StdDev period for brick size", "General")
self._brick_multiplier = self.Param("BrickMultiplier", 0.5) \
.SetDisplay("Brick Multiplier", "Multiplier for brick size", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle Type", "General")
self._brick_high = 0.0
self._brick_low = 0.0
self._is_up_trend = False
self._has_brick = False
self._entry_price = 0.0
@property
def std_length(self):
return self._std_length.Value
@property
def brick_multiplier(self):
return self._brick_multiplier.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(renko_trend_reversal_strategy, self).OnReseted()
self._brick_high = 0.0
self._brick_low = 0.0
self._is_up_trend = False
self._has_brick = False
self._entry_price = 0.0
def OnStarted2(self, time):
super(renko_trend_reversal_strategy, self).OnStarted2(time)
std_dev = StandardDeviation()
std_dev.Length = self.std_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(std_dev, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, std_dev)
self.DrawOwnTrades(area)
def on_process(self, candle, std_value):
if candle.State != CandleStates.Finished:
return
if std_value <= 0:
return
brick_size = std_value * self.brick_multiplier
if not self._has_brick:
self._brick_high = candle.ClosePrice + brick_size
self._brick_low = candle.ClosePrice - brick_size
self._is_up_trend = candle.ClosePrice > candle.OpenPrice
self._has_brick = True
return
if candle.ClosePrice >= self._brick_high:
# Bullish brick
if not self._is_up_trend and self.Position <= 0:
self.BuyMarket()
self._entry_price = candle.ClosePrice
self._is_up_trend = True
self._brick_high = candle.ClosePrice + brick_size
self._brick_low = candle.ClosePrice - brick_size
elif candle.ClosePrice <= self._brick_low:
# Bearish brick
if self._is_up_trend and self.Position >= 0:
self.SellMarket()
self._entry_price = candle.ClosePrice
self._is_up_trend = False
self._brick_high = candle.ClosePrice + brick_size
self._brick_low = candle.ClosePrice - brick_size
# Stop loss check
if self.Position > 0 and self._entry_price > 0 and candle.ClosePrice < self._entry_price * 0.97:
self.SellMarket()
elif self.Position < 0 and self._entry_price > 0 and candle.ClosePrice > self._entry_price * 1.03:
self.BuyMarket()
def CreateClone(self):
return renko_trend_reversal_strategy()