Estratégia de Velas Baixistas Consecutivas
Entra comprado após uma sequência de velas baixistas e sai quando o preço rompe acima da máxima anterior.
Esta abordagem de reversão à média compra após pressão de baixa excessiva, buscando uma recuperação quando os vendedores se esgotam.
Detalhes
- Critérios de entrada:
Nvelas baixistas consecutivas dentro da janela de tempo. - Comprado/Vendido: Somente comprado.
- Critérios de saída: Fechamento acima da máxima anterior.
- Stops: Não.
- Valores padrão:
Lookback= 3CandleType= TimeSpan.FromDays(1)StartTime= 2014-01-01EndTime= 2099-01-01
- Filtros:
- Categoria: Reversão à média
- Direção: Comprado
- Indicadores: Price Action
- Stops: Não
- Complexidade: Básico
- Período: Diário
- Sazonalidade: Não
- Redes neurais: Não
- Divergência: Não
- Nível de risco: Médio
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Consecutive Bearish Candle strategy.
/// A candle is bearish when it closes below the previous close. After Lookback bearish candles in a row inside the
/// StartTime-EndTime window the strategy buys, and it closes the long when a candle closes above the previous candle's high.
/// </summary>
public class ConsecutiveBearishCandleStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<DateTimeOffset> _startTime;
private readonly StrategyParam<DateTimeOffset> _endTime;
private decimal? _prevClose;
private decimal? _prevHigh;
private int _bearishCount;
/// <summary>
/// Number of consecutive bearish candles.
/// </summary>
public int Lookback
{
get => _lookback.Value;
set => _lookback.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Start of the trading window.
/// </summary>
public DateTimeOffset StartTime
{
get => _startTime.Value;
set => _startTime.Value = value;
}
/// <summary>
/// End of the trading window.
/// </summary>
public DateTimeOffset EndTime
{
get => _endTime.Value;
set => _endTime.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public ConsecutiveBearishCandleStrategy()
{
_lookback = Param(nameof(Lookback), 3)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Number of consecutive bearish candles", "Signals");
_candleType = Param(nameof(CandleType), TimeSpan.FromDays(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_startTime = Param(nameof(StartTime), new DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero))
.SetDisplay("Start Time", "Start of the trading window", "Time");
_endTime = Param(nameof(EndTime), new DateTimeOffset(2099, 1, 1, 0, 0, 0, TimeSpan.Zero))
.SetDisplay("End Time", "End of the trading window", "Time");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetState();
}
private void ResetState()
{
_prevClose = null;
_prevHigh = null;
_bearishCount = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var prevClose = _prevClose;
var prevHigh = _prevHigh;
_prevClose = candle.ClosePrice;
_prevHigh = candle.HighPrice;
if (prevClose is not decimal lastClose || prevHigh is not decimal lastHigh)
return;
_bearishCount = candle.ClosePrice < lastClose ? _bearishCount + 1 : 0;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (Position > 0 && candle.ClosePrice > lastHigh)
{
SellMarket(Position);
return;
}
var inWindow = candle.OpenTime >= StartTime.UtcDateTime && candle.OpenTime <= EndTime.UtcDateTime;
if (inWindow && _bearishCount >= Lookback && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, DateTimeOffset
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
class consecutive_bearish_candle_strategy(Strategy):
"""
Consecutive Bearish Candle strategy.
A candle is bearish when it closes below the previous close. After Lookback bearish candles in a row inside the
StartTime-EndTime window the strategy buys, and it closes the long when a candle closes above the previous candle's high.
"""
def __init__(self):
super(consecutive_bearish_candle_strategy, self).__init__()
self._lookback = self.Param("Lookback", 3).SetGreaterThanZero().SetDisplay("Lookback", "Number of consecutive bearish candles", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromDays(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._start_time = self.Param("StartTime", DateTimeOffset(2014, 1, 1, 0, 0, 0, TimeSpan.Zero)).SetDisplay("Start Time", "Start of the trading window", "Time")
self._end_time = self.Param("EndTime", DateTimeOffset(2099, 1, 1, 0, 0, 0, TimeSpan.Zero)).SetDisplay("End Time", "End of the trading window", "Time")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_close = None
self._prev_high = None
self._bearish_count = 0
def OnReseted(self):
super(consecutive_bearish_candle_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(consecutive_bearish_candle_strategy, self).OnStarted2(time)
self._reset_state()
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
last_close = self._prev_close
last_high = self._prev_high
self._prev_close = candle.ClosePrice
self._prev_high = candle.HighPrice
if last_close is None or last_high is None:
return
self._bearish_count = self._bearish_count + 1 if candle.ClosePrice < last_close else 0
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self.Position > 0 and candle.ClosePrice > last_high:
self.SellMarket(self.Position)
return
in_window = self._start_time.Value.UtcDateTime <= candle.OpenTime <= self._end_time.Value.UtcDateTime
if in_window and self._bearish_count >= self._lookback.Value and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return consecutive_bearish_candle_strategy()