Renko 图表来自 Ticks 策略
直接从 ticks 生成 Renko 砖,并在砖方向反转时交易。展示如何使用 StockSharp 高级 API 构建无时间限制的蜡烛。
细节
- 入场条件:
- 当新完成的砖块改变方向时,按新方向入场。
- 多/空:同时支持。
- 出场条件:出现反向砖块时反转仓位。
- 止损:无。
- 默认值:
BrickSize= 10Volume= 1
- 过滤器:
- 类别:Renko
- 方向:双向
- 指标:无
- 止损:无
- 复杂度:初级
- 时间框架:基于 tick
- 季节性:否
- 神经网络:否
- 背离:否
- 风险等级:中
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>
/// Strategy that trades on candle direction changes, inspired by Renko-style logic.
/// Buys when candle direction flips from down to up, sells when it flips from up to down.
/// Uses ATR-based filter to only trade on significant candles.
/// </summary>
public class RenkoChartFromTicksStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _bodyAtrFactor;
private readonly StrategyParam<int> _cooldownCandles;
private bool? _prevUp;
private int _barsSinceSignal;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int AtrPeriod
{
get => _atrPeriod.Value;
set => _atrPeriod.Value = value;
}
public decimal BodyAtrFactor
{
get => _bodyAtrFactor.Value;
set => _bodyAtrFactor.Value = value;
}
public int CooldownCandles
{
get => _cooldownCandles.Value;
set => _cooldownCandles.Value = value;
}
public RenkoChartFromTicksStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "ATR period for significance filter", "General");
_bodyAtrFactor = Param(nameof(BodyAtrFactor), 0.7m)
.SetGreaterThanZero()
.SetDisplay("Body ATR Factor", "Minimum body size as ATR fraction", "General");
_cooldownCandles = Param(nameof(CooldownCandles), 2)
.SetGreaterThanZero()
.SetDisplay("Cooldown Candles", "Minimum candles between signals", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevUp = null;
_barsSinceSignal = CooldownCandles;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevUp = null;
_barsSinceSignal = CooldownCandles;
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, atr);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal atrValue)
{
if (candle.State != CandleStates.Finished)
return;
_barsSinceSignal++;
if (atrValue <= 0)
return;
var body = Math.Abs(candle.ClosePrice - candle.OpenPrice);
if (body < atrValue * BodyAtrFactor)
return;
var isUp = candle.ClosePrice > candle.OpenPrice;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevUp = isUp;
return;
}
if (_prevUp.HasValue && _prevUp.Value != isUp && _barsSinceSignal >= CooldownCandles)
{
if (isUp && Position <= 0)
{
BuyMarket();
_barsSinceSignal = 0;
}
else if (!isUp && Position >= 0)
{
SellMarket();
_barsSinceSignal = 0;
}
}
_prevUp = isUp;
}
}
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 AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class renko_chart_from_ticks_strategy(Strategy):
def __init__(self):
super(renko_chart_from_ticks_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._atr_period = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "ATR period for significance filter", "General")
self._body_atr_factor = self.Param("BodyAtrFactor", 0.7) \
.SetDisplay("Body ATR Factor", "Minimum body size as ATR fraction", "General")
self._cooldown_candles = self.Param("CooldownCandles", 2) \
.SetDisplay("Cooldown Candles", "Minimum candles between signals", "General")
self._prev_up = None
self._bars_since_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
@property
def atr_period(self):
return self._atr_period.Value
@property
def body_atr_factor(self):
return self._body_atr_factor.Value
@property
def cooldown_candles(self):
return self._cooldown_candles.Value
def OnReseted(self):
super(renko_chart_from_ticks_strategy, self).OnReseted()
self._prev_up = None
self._bars_since_signal = int(self.cooldown_candles)
def OnStarted2(self, time):
super(renko_chart_from_ticks_strategy, self).OnStarted2(time)
self._prev_up = None
self._bars_since_signal = int(self.cooldown_candles)
atr = AverageTrueRange()
atr.Length = int(self.atr_period)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(atr, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, atr)
self.DrawOwnTrades(area)
def process_candle(self, candle, atr_value):
if candle.State != CandleStates.Finished:
return
atr_value = float(atr_value)
self._bars_since_signal += 1
if atr_value <= 0:
return
close = float(candle.ClosePrice)
open_p = float(candle.OpenPrice)
body = abs(close - open_p)
baf = float(self.body_atr_factor)
if body < atr_value * baf:
return
is_up = close > open_p
cd = int(self.cooldown_candles)
if self._prev_up is not None and self._prev_up != is_up and self._bars_since_signal >= cd:
if is_up and self.Position <= 0:
self.BuyMarket()
self._bars_since_signal = 0
elif not is_up and self.Position >= 0:
self.SellMarket()
self._bars_since_signal = 0
self._prev_up = is_up
def CreateClone(self):
return renko_chart_from_ticks_strategy()