Three-Bar Reversal Up Strategy
This pattern catches quick bullish turns after a short decline. It requires two consecutive down candles followed by a strong up candle that closes above the prior bar's high. The logic optionally checks that price was trending lower beforehand.
Testing indicates an average annual return of about 85%. It performs best in the crypto market.
The strategy keeps the last three candles in memory. Once the sequence matches the criteria and any downtrend filter is satisfied, a long position is opened. A volatility stop below the pattern low caps risk on the trade.
After entry the system waits for either a stop hit or the appearance of another setup in the opposite direction. This simple approach suits markets prone to sharp bounces from oversold conditions.
Details
- Entry Criteria: Two bearish candles with lower lows then a bullish candle closing above the middle bar's high.
- Long/Short: Long only.
- Exit Criteria: Stop-loss or next pattern.
- Stops: Yes, below pattern low.
- Default Values:
CandleType= 15 minuteStopLossPercent= 1RequireDowntrend= trueDowntrendLength= 5
- Filters:
- Category: Pattern
- Direction: Long
- Indicators: Candlestick
- Stops: Yes
- Complexity: Intermediate
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
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>
/// Three-Bar Reversal Up strategy.
/// Pattern: 1st bar bearish, 2nd bar bearish with lower low, 3rd bar bullish closing above 2nd high.
/// Uses SMA for exit.
/// </summary>
public class ThreeBarReversalUpStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private ICandleMessage _bar1;
private ICandleMessage _bar2;
private int _cooldown;
/// <summary>
/// MA Period.
/// </summary>
public int MAPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Cooldown bars.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public ThreeBarReversalUpStrategy()
{
_maPeriod = Param(nameof(MAPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Period for SMA", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_cooldownBars = Param(nameof(CooldownBars), 500)
.SetRange(1, 1000)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_bar1 = null;
_bar2 = null;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_bar1 = null;
_bar2 = null;
_cooldown = 0;
var sma = new SimpleMovingAverage { Length = MAPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldown > 0)
{
_cooldown--;
_bar1 = _bar2;
_bar2 = candle;
return;
}
if (_bar1 != null && _bar2 != null)
{
// Three-bar reversal up: bar1 bearish, bar2 bearish with lower low, bar3 (current) bullish closing above bar2 high
var bar1Bearish = _bar1.ClosePrice < _bar1.OpenPrice;
var bar2Bearish = _bar2.ClosePrice < _bar2.OpenPrice;
var bar2LowerLow = _bar2.LowPrice < _bar1.LowPrice;
var bar3Bullish = candle.ClosePrice > candle.OpenPrice;
var bar3AboveBar2High = candle.ClosePrice > _bar2.HighPrice;
var threeBarReversalUp = bar1Bearish && bar2Bearish && bar2LowerLow && bar3Bullish && bar3AboveBar2High;
// Three-bar reversal down: bar1 bullish, bar2 bullish with higher high, bar3 bearish closing below bar2 low
var bar1Bullish = _bar1.ClosePrice > _bar1.OpenPrice;
var bar2Bullish = _bar2.ClosePrice > _bar2.OpenPrice;
var bar2HigherHigh = _bar2.HighPrice > _bar1.HighPrice;
var bar3Bearish = candle.ClosePrice < candle.OpenPrice;
var bar3BelowBar2Low = candle.ClosePrice < _bar2.LowPrice;
var threeBarReversalDown = bar1Bullish && bar2Bullish && bar2HigherHigh && bar3Bearish && bar3BelowBar2Low;
if (Position == 0 && threeBarReversalUp)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (Position == 0 && threeBarReversalDown)
{
SellMarket();
_cooldown = CooldownBars;
}
else if (Position > 0 && candle.ClosePrice < smaValue)
{
SellMarket();
_cooldown = CooldownBars;
}
else if (Position < 0 && candle.ClosePrice > smaValue)
{
BuyMarket();
_cooldown = CooldownBars;
}
}
_bar1 = _bar2;
_bar2 = candle;
}
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class three_bar_reversal_up_strategy(Strategy):
"""
Three-Bar Reversal Up strategy.
Pattern: 1st bar bearish, 2nd bar bearish with lower low, 3rd bar bullish closing above 2nd high.
Uses SMA for exit.
"""
def __init__(self):
super(three_bar_reversal_up_strategy, self).__init__()
self._ma_period = self.Param("MAPeriod", 20).SetDisplay("MA Period", "Period for SMA", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown_bars = self.Param("CooldownBars", 500).SetDisplay("Cooldown Bars", "Bars to wait between trades", "General")
self._bar1 = None
self._bar2 = None
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(three_bar_reversal_up_strategy, self).OnReseted()
self._bar1 = None
self._bar2 = None
self._cooldown = 0
def OnStarted2(self, time):
super(three_bar_reversal_up_strategy, self).OnStarted2(time)
self._bar1 = None
self._bar2 = None
self._cooldown = 0
sma = SimpleMovingAverage()
sma.Length = self._ma_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def _process_candle(self, candle, sma_val):
if candle.State != CandleStates.Finished:
return
if self._cooldown > 0:
self._cooldown -= 1
self._bar1 = self._bar2
self._bar2 = candle
return
if self._bar1 is not None and self._bar2 is not None:
# Three-bar reversal up: bar1 bearish, bar2 bearish with lower low, bar3 bullish closing above bar2 high
bar1_bearish = self._bar1.ClosePrice < self._bar1.OpenPrice
bar2_bearish = self._bar2.ClosePrice < self._bar2.OpenPrice
bar2_lower_low = self._bar2.LowPrice < self._bar1.LowPrice
bar3_bullish = candle.ClosePrice > candle.OpenPrice
bar3_above_bar2_high = candle.ClosePrice > self._bar2.HighPrice
three_bar_up = bar1_bearish and bar2_bearish and bar2_lower_low and bar3_bullish and bar3_above_bar2_high
# Three-bar reversal down: bar1 bullish, bar2 bullish with higher high, bar3 bearish closing below bar2 low
bar1_bullish = self._bar1.ClosePrice > self._bar1.OpenPrice
bar2_bullish = self._bar2.ClosePrice > self._bar2.OpenPrice
bar2_higher_high = self._bar2.HighPrice > self._bar1.HighPrice
bar3_bearish = candle.ClosePrice < candle.OpenPrice
bar3_below_bar2_low = candle.ClosePrice < self._bar2.LowPrice
three_bar_down = bar1_bullish and bar2_bullish and bar2_higher_high and bar3_bearish and bar3_below_bar2_low
sv = float(sma_val)
close = float(candle.ClosePrice)
cd = self._cooldown_bars.Value
if self.Position == 0 and three_bar_up:
self.BuyMarket()
self._cooldown = cd
elif self.Position == 0 and three_bar_down:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0 and close < sv:
self.SellMarket()
self._cooldown = cd
elif self.Position < 0 and close > sv:
self.BuyMarket()
self._cooldown = cd
self._bar1 = self._bar2
self._bar2 = candle
def CreateClone(self):
return three_bar_reversal_up_strategy()