Consecutive Bars Above MA Strategy
Short-only strategy that counts consecutive closes above a moving average and shorts on breakouts above the previous high. Exits when price falls below the prior low. Optional 200 EMA filter enforces downtrend.
Details
- Entry Criteria: threshold of consecutive closes above MA and close > previous high
- Long/Short: Short
- Exit Criteria: close below previous low
- Stops: No
- Default Values:
Threshold= 3MaType= SMAMaLength= 5EmaPeriod= 200
- Filters:
- Category: Pattern
- Direction: Short
- Indicators: MA, EMA
- Stops: No
- Complexity: Basic
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
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>
/// Short strategy entering after consecutive closes above moving average.
/// </summary>
public class ConsecutiveBarsAboveMaStrategy : Strategy
{
private readonly StrategyParam<int> _threshold;
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<DataType> _candleType;
private int _bullCount;
private decimal _prevHigh;
private decimal _prevLow;
private bool _isReady;
public int Threshold { get => _threshold.Value; set => _threshold.Value = value; }
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ConsecutiveBarsAboveMaStrategy()
{
_threshold = Param(nameof(Threshold), 3)
.SetGreaterThanZero()
.SetDisplay("Signal Threshold", "Number of bars above MA", "Parameters");
_maLength = Param(nameof(MaLength), 10)
.SetGreaterThanZero()
.SetDisplay("MA Length", "Moving average length", "Parameters");
_emaPeriod = Param(nameof(EmaPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA length for trend filter", "Filters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_bullCount = 0;
_prevHigh = 0;
_prevLow = 0;
_isReady = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = MaLength };
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, ema, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal maValue, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_isReady)
{
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
_isReady = true;
return;
}
if (candle.ClosePrice > maValue)
_bullCount++;
else
_bullCount = 0;
// Short: consecutive bars above MA, below EMA trend filter (mean reversion)
var shortCondition = _bullCount >= Threshold &&
candle.ClosePrice < emaValue;
if (shortCondition && Position >= 0)
SellMarket();
else if (Position < 0 && candle.ClosePrice < _prevLow)
BuyMarket();
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
}
}
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 ExponentialMovingAverage, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class consecutive_bars_above_ma_strategy(Strategy):
def __init__(self):
super(consecutive_bars_above_ma_strategy, self).__init__()
self._threshold = self.Param("Threshold", 3) \
.SetDisplay("Signal Threshold", "Number of bars above MA", "Parameters")
self._ma_length = self.Param("MaLength", 10) \
.SetDisplay("MA Length", "Moving average length", "Parameters")
self._ema_period = self.Param("EmaPeriod", 50) \
.SetDisplay("EMA Period", "EMA length for trend filter", "Filters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._bull_count = 0
self._prev_high = 0.0
self._prev_low = 0.0
self._is_ready = False
@property
def threshold(self):
return self._threshold.Value
@property
def ma_length(self):
return self._ma_length.Value
@property
def ema_period(self):
return self._ema_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(consecutive_bars_above_ma_strategy, self).OnReseted()
self._bull_count = 0
self._prev_high = 0.0
self._prev_low = 0.0
self._is_ready = False
def OnStarted2(self, time):
super(consecutive_bars_above_ma_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.ma_length
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def on_process(self, candle, ma_value, ema_value):
if candle.State != CandleStates.Finished:
return
if not self._is_ready:
self._prev_high = candle.HighPrice
self._prev_low = candle.LowPrice
self._is_ready = True
return
if candle.ClosePrice > ma_value:
self._bull_count += 1
else:
self._bull_count = 0
# Short: consecutive bars above MA, below EMA trend filter (mean reversion)
short_condition = (self._bull_count >= self.threshold and
candle.ClosePrice < ema_value)
if short_condition and self.Position >= 0:
self.SellMarket()
elif self.Position < 0 and candle.ClosePrice < self._prev_low:
self.BuyMarket()
self._prev_high = candle.HighPrice
self._prev_low = candle.LowPrice
def CreateClone(self):
return consecutive_bars_above_ma_strategy()