Symr New Bar Strategy
The Symr New Bar Strategy demonstrates how to detect the beginning of new candles across multiple timeframes using a single subscription. The strategy monitors a base timeframe and calculates when larger intervals such as 5m, 15m, 30m, 1h, 4h, 1d, 20m and 55m begin. Each detected bar is logged.
Details
- Entry Criteria: None. The strategy does not place trades.
- Exit Criteria: None.
- Long/Short: Not applicable.
- Stops: No stops are used.
Parameters
| Name | Default | Description |
|---|---|---|
CandleType |
TimeSpan.FromMinutes(1).TimeFrame() |
Base timeframe for new bar detection. |
Notes
- Stores the last open time for each predefined period.
- When the base period advances, larger periods are evaluated and logged if they roll over.
- Useful as a template for multi-timeframe event handling.
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 detects new bar openings and trades breakouts.
/// Enters when price breaks the high/low of the previous bar with EMA confirmation.
/// </summary>
public class SymrNewBarStrategy : Strategy
{
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevHigh;
private decimal _prevLow;
private bool _hasPrev;
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public SymrNewBarStrategy()
{
_emaLength = Param(nameof(EmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period for trend filter", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevHigh = 0;
_prevLow = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaVal)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
if (!_hasPrev)
{
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
_hasPrev = true;
return;
}
// Breakout above previous high with EMA confirmation
if (close > _prevHigh && close > emaVal && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Breakout below previous low with EMA confirmation
else if (close < _prevLow && close < emaVal && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_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
from StockSharp.Algo.Strategies import Strategy
class symr_new_bar_strategy(Strategy):
def __init__(self):
super(symr_new_bar_strategy, self).__init__()
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Length", "EMA period for trend filter", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
@property
def ema_length(self):
return self._ema_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(symr_new_bar_strategy, self).OnReseted()
self._prev_high = 0.0
self._prev_low = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(symr_new_bar_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
close = candle.ClosePrice
if not self._has_prev:
self._prev_high = candle.HighPrice
self._prev_low = candle.LowPrice
self._has_prev = True
return
# Breakout above previous high with EMA confirmation
if close > self._prev_high and close > ema_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Breakout below previous low with EMA confirmation
elif close < self._prev_low and close < ema_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_high = candle.HighPrice
self._prev_low = candle.LowPrice
def CreateClone(self):
return symr_new_bar_strategy()