Order Block Finder Strategy
This strategy identifies bullish and bearish order blocks based on a specified number of consecutive candles and a minimum percent move. When a bullish order block is detected, the strategy buys; when a bearish block is found, it sells.
Parameters
- Relevant Periods – number of subsequent candles to confirm an order block
- Min Percent Move – minimal percent change between the block and the last confirming candle
- Use Whole Range – use High/Low range instead of Open-based boundaries
- Candle Type – candle type used for calculations
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Order block finder strategy.
/// Buys on detected bullish order blocks and sells on bearish ones.
/// </summary>
public class OrderBlockFinderStrategy : Strategy
{
private readonly StrategyParam<int> _periods;
private readonly StrategyParam<decimal> _threshold;
private readonly StrategyParam<DataType> _candleType;
public int Periods { get => _periods.Value; set => _periods.Value = value; }
public decimal Threshold { get => _threshold.Value; set => _threshold.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public OrderBlockFinderStrategy()
{
_periods = Param(nameof(Periods), 5).SetGreaterThanZero();
_threshold = Param(nameof(Threshold), 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = 20 };
var buffer = new Queue<ICandleMessage>();
var lastSignal = DateTimeOffset.MinValue;
var cooldown = TimeSpan.FromMinutes(360);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, (candle, smaVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!sma.IsFormed)
return;
buffer.Enqueue(candle);
var need = Periods + 1;
while (buffer.Count > need)
buffer.Dequeue();
if (buffer.Count < need)
return;
if (candle.OpenTime - lastSignal < cooldown)
return;
var arr = buffer.ToArray();
var ob = arr[0];
var last = arr[^1];
var move = ob.ClosePrice != 0 ? Math.Abs((last.ClosePrice - ob.ClosePrice) / ob.ClosePrice) * 100m : 0m;
if (move < Threshold)
return;
var up = 0;
var down = 0;
for (var i = 1; i < arr.Length; i++)
{
if (arr[i].ClosePrice > arr[i].OpenPrice) up++;
if (arr[i].ClosePrice < arr[i].OpenPrice) down++;
}
if (ob.ClosePrice < ob.OpenPrice && up == Periods && Position <= 0)
{
BuyMarket();
lastSignal = candle.OpenTime;
}
else if (ob.ClosePrice > ob.OpenPrice && down == Periods && Position >= 0)
{
SellMarket();
lastSignal = candle.OpenTime;
}
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
}
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 order_block_finder_strategy(Strategy):
def __init__(self):
super(order_block_finder_strategy, self).__init__()
self._periods = self.Param("Periods", 5) \
.SetGreaterThanZero()
self._threshold = self.Param("Threshold", 0.5)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._buffer = []
self._last_signal_ticks = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(order_block_finder_strategy, self).OnReseted()
self._buffer = []
self._last_signal_ticks = 0
def OnStarted2(self, time):
super(order_block_finder_strategy, self).OnStarted2(time)
self._buffer = []
self._last_signal_ticks = 0
self._sma = SimpleMovingAverage()
self._sma.Length = 20
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._sma, self.OnProcess).Start()
def OnProcess(self, candle, sma_val):
if candle.State != CandleStates.Finished:
return
if not self._sma.IsFormed:
return
close = float(candle.ClosePrice)
opn = float(candle.OpenPrice)
need = self._periods.Value + 1
self._buffer.append((opn, close))
while len(self._buffer) > need:
self._buffer.pop(0)
if len(self._buffer) < need:
return
cooldown_ticks = TimeSpan.FromMinutes(360).Ticks
current_ticks = candle.OpenTime.Ticks
if current_ticks - self._last_signal_ticks < cooldown_ticks:
return
ob_open, ob_close = self._buffer[0]
last_open, last_close = self._buffer[-1]
move = abs((last_close - ob_close) / ob_close) * 100.0 if ob_close != 0 else 0.0
thresh = float(self._threshold.Value)
if move < thresh:
return
up = 0
down = 0
periods = self._periods.Value
for i in range(1, len(self._buffer)):
o, c = self._buffer[i]
if c > o:
up += 1
if c < o:
down += 1
if ob_close < ob_open and up == periods and self.Position <= 0:
self.BuyMarket()
self._last_signal_ticks = current_ticks
elif ob_close > ob_open and down == periods and self.Position >= 0:
self.SellMarket()
self._last_signal_ticks = current_ticks
def CreateClone(self):
return order_block_finder_strategy()