Constructing Renko Bars from MQL5 Tick Streams in Real Time
Introduction
A Renko chart shows where the market actually moved by a meaningful amount, not merely where time passed. A candlestick tells you open, high, low, and close for a fixed interval. A Renko chart discards the interval entirely and prints a new brick only when price has traveled a fixed distance. Every brick shares the same height, and that fixed height is the whole point. It filters out the small, directionless chop that a time-based candle records as if it mattered.
MetaTrader 5 has no native way to build this kind of chart. There is no PERIOD_RENKO constant, and no built-in chart mode that switches a symbol's bars from time-based to distance-based. Anyone who wants a genuine Renko chart has to build the aggregation logic themselves. Some Renko implementations reconstruct bricks from M1 OHLC data rather than from the raw tick stream. They use the open, high, low, and close of each one-minute bar to estimate which brick boundaries were crossed, without knowing the exact sequence of crossings.
That guess is where accuracy breaks down. An OHLC bar tells you the highest and lowest price reached during the minute. It does not tell you the order price visited those levels. When a single minute crosses three or four brick boundaries, several crossing sequences are consistent with the exact same OHLC numbers, and only one of them actually happened.
This article builds the alternative. A state machine reads quotes from OnTick() in the order the terminal received them from the broker's trade server, which removes the ambiguity inherent in inferring a bar's internal crossing order from OHLC data alone. It does not guarantee that OnTick() was invoked for every server tick. Under heavy load, calls can be coalesced. Every completed brick is written to a MetaTrader custom symbol via CustomRatesUpdate(). The symbol stores MqlRates records, so the Renko chart opens as a normal chart and built-in indicators run without modification. Whether those indicator readings mean the same as on time-based charts is addressed under Limitations. We ran the pipeline live on demo accounts across three symbols, XAUUSD, EURUSD, and ETHUSD, and the Live Test Results section lists the conditions and counters. The runs covered continuation bricks, reversals, bursts of bricks from a single quote (including one that reversed direction), and one restart. They did not include a controlled test of connection loss.
RenkoBuilderEA — Architecture

Legend:
- Navy — the driver EA, RenkoBuilderEA, which orchestrates every other class.
- Coral — one-time setup infrastructure, CCustomSymbolManager, which prepares the custom symbol before any tick is processed.
- Gray — external data boundaries: the raw tick stream coming in, and the finished custom symbol chart going out.
- Teal — the two classes that do the actual per-tick transformation work, CRenkoEngine and CBrickWriter.
Figure 1: Architecture of the Renko builder pipeline. The numbered badges give the call order within each stage. In OnInit(), which runs once, RenkoBuilderEA has CCustomSymbolManager create and register the custom symbol, and then initializes CRenkoEngine with the Bid price snapped to the brick grid. In OnTick(), each quote goes to CRenkoEngine, which produces zero, one, or several bricks. CBrickWriter writes each brick as one M1 bar on the custom symbol, continuing after the last stored bar, and the loop arrow (↻) marks the return to the next quote. In OnDeinit(), the EA prints the session counters.
Why OHLC Approximation Fails
Consider one M1 bar: open 1.10005, high 1.10035, low 1.09985, close 1.10015. With a brick size of 10 points, boundaries sit at 1.09990, 1.10000, 1.10010, 1.10020, and 1.10030. This bar's 50-point range crosses five of them. Nothing in the four OHLC numbers tells a reconstruction the order those crossings happened in.
One plausible reading sends price up first, climbing to the high before reversing down through every boundary to the low, then recovering to the close. A second, equally plausible reading sends price down first instead, reaching the low before the high. Both readings share identical OHLC values. They produce different brick counts and different reversal points, and neither can be proven correct from the four summary numbers alone.
The tick stream removes this ambiguity. Each tick carries its own price and timestamp, delivered to OnTick() in the order the price server actually received it. A state machine that consumes that sequence evaluates every rule against the real path price took, not a plausible guess. That is why this article builds from OnTick() rather than CopyRates() on M1.
ENUM_BRICK_DIRECTION and SRenkoBrick
The engine needs a way to name which direction the current run of bricks is moving, and a way to hand a completed brick outward. ENUM_BRICK_DIRECTION covers the first need with three members. BRICK_DIRECTION_NONE applies only before the first brick of a session completes. BRICK_DIRECTION_UP and BRICK_DIRECTION_DOWN describe every brick after that.
//+------------------------------------------------------------------+ //| BrickDirection.mqh | //+------------------------------------------------------------------+ #ifndef BRICKDIRECTION_MQH #define BRICKDIRECTION_MQH //+------------------------------------------------------------------+ //| ENUM_BRICK_DIRECTION | //| Direction of the current run of Renko bricks. BRICK_DIRECTION_ | //| NONE applies only before the first brick of a session completes. | //+------------------------------------------------------------------+ enum ENUM_BRICK_DIRECTION { BRICK_DIRECTION_NONE = 0, // no brick has completed yet BRICK_DIRECTION_UP = 1, // current run of bricks is upward BRICK_DIRECTION_DOWN = 2 // current run of bricks is downward }; #endif // BRICKDIRECTION_MQH //+------------------------------------------------------------------+
SRenkoBrick covers the second need, handed outward as a value type rather than exposed by reference into the engine's internal state. This matters because a single fast quote can complete three bricks at once, and the engine only ever has one "current" state at a time. Returning an array of struct values instead means each completed brick arrives as its own independent record the rest of the pipeline can simply loop over.
//+------------------------------------------------------------------+ //| RenkoBrick.mqh | //+------------------------------------------------------------------+ #ifndef RENKOBRICK_MQH #define RENKOBRICK_MQH #include "BrickDirection.mqh" //+------------------------------------------------------------------+ //| SRenkoBrick | //| One completed Renko brick handed outward by CRenkoEngine. Fields | //| describe the brick's boundaries, direction, timing, and the tick | //| count since the previous emission. | //+------------------------------------------------------------------+ struct SRenkoBrick { double brick_open; // boundary price where the brick opened double brick_close; // boundary price where the brick closed ENUM_BRICK_DIRECTION direction; // BRICK_DIRECTION_UP or BRICK_DIRECTION_DOWN datetime open_time; // time at which the brick opened datetime close_time; // timestamp of the tick that closed the brick long tick_count; // ticks received since the previous emission SRenkoBrick(void); }; //+------------------------------------------------------------------+ //| SRenkoBrick default constructor | //| Zero-initializes every field so an unfilled struct never carries | //| stale values from a previous use of the same variable. | //+------------------------------------------------------------------+ SRenkoBrick::SRenkoBrick(void) { brick_open = 0.0; brick_close = 0.0; direction = BRICK_DIRECTION_NONE; open_time = 0; close_time = 0; tick_count = 0; } #endif // RENKOBRICK_MQH
brick_open and brick_close are the two boundary prices, always one brick size apart, and direction tells the reader which is earlier and which is later. close_time is the time of the tick that completed the brick. open_time is the time of the first tick received after the previous emission, but only for the first brick that a tick emits. When one fast tick completes several bricks, each later brick opens at the moment the previous one closes, so its open_time equals that tick's time. tick_count records how many ticks have arrived since the previous emission. Every brick from the same tick carries the same count, so it measures ticks since the last emission and is not a precise per-brick activity figure.
CRenkoEngine — the State Machine
The engine carries a small amount of internal state: the grid anchor, the fixed brick size, the symbol's point value, the current direction, a running tick counter for the brick in progress, its open timestamp, and a session brick total. Every calculation is anchored off m_grid_anchor, the boundary price of the most recently completed brick or, before the first brick, the starting price snapped to the grid. The upper and lower boundaries are always the anchor plus or minus one brick size. Before the first brick, either boundary opens the session. Afterward, only the boundary in the direction of the current run completes a continuation brick, and reversal is a separate, larger threshold at two brick sizes, described below.
//+------------------------------------------------------------------+ //| RenkoEngine.mqh | //+------------------------------------------------------------------+ #ifndef RENKOENGINE_MQH #define RENKOENGINE_MQH #include "RenkoBrick.mqh" //+------------------------------------------------------------------+ //| CRenkoEngine | //| State machine that tracks the current Renko direction and brick | //| boundaries on a fixed grid, converting raw quotes into completed | //| Renko bricks. | //+------------------------------------------------------------------+ class CRenkoEngine { private: double m_grid_anchor; // boundary price of the last completed brick double m_brick_height; // fixed brick size expressed in price units double m_symbol_point; // point value of the underlying symbol ENUM_BRICK_DIRECTION m_direction; // current direction of the brick run long m_ticks_in_brick; // ticks counted toward the brick in progress datetime m_brick_open_time; // timestamp of the first tick in progress long m_bricks_total; // running total of bricks emitted this session void AppendBrick(SRenkoBrick &emitted[], const double open_price, const double close_price, const ENUM_BRICK_DIRECTION brick_direction, const datetime tick_time); public: CRenkoEngine(void); ~CRenkoEngine(void); bool Initialize(const double anchor_price, const double brick_points, const double symbol_point); int ProcessTick(const double bid_price, const datetime tick_time, SRenkoBrick &emitted[]); ENUM_BRICK_DIRECTION CurrentDirection(void) const; double UpperBoundary(void) const; double LowerBoundary(void) const; long BricksTotal(void) const; };
The constructor zeroes every member. The destructor is empty, since the engine owns no dynamic resources and there is nothing to release.
//+------------------------------------------------------------------+ //| CRenkoEngine constructor | //+------------------------------------------------------------------+ CRenkoEngine::CRenkoEngine(void) { m_grid_anchor = 0.0; m_brick_height = 0.0; m_symbol_point = 0.0; m_direction = BRICK_DIRECTION_NONE; m_ticks_in_brick = 0; m_brick_open_time = 0; m_bricks_total = 0; } //+------------------------------------------------------------------+ //| CRenkoEngine destructor | //+------------------------------------------------------------------+ CRenkoEngine::~CRenkoEngine(void) { }
Initialize() accepts an anchor price fresh from the market, typically the current Bid, and rounds it to the nearest multiple of the brick size, whether that multiple sits above or below the price. The rounding puts every boundary on a clean, predictable grid, but it also means the first brick is a grid snap and not a full brick-size move from the launch price. With a 10-point brick on EURUSD and a Bid of 1.10004, the anchor snaps to 1.10000. The first up brick then closes at 1.10010 after a 6-point move, and the first down brick closes at 1.09990 after a 14-point move. Every brick after the first measures a full brick size. Initialize() also rejects a non-positive brick size, point value, or anchor price up front, before any grid math runs, since a bad input would otherwise silently corrupt every boundary afterward.
//+------------------------------------------------------------------+ //| Initialize | //+------------------------------------------------------------------+ bool CRenkoEngine::Initialize(const double anchor_price, const double brick_points, const double symbol_point) { //--- reject nonsensical brick sizes before any grid math is attempted if(brick_points <= 0.0 || symbol_point <= 0.0 || anchor_price <= 0.0) { ::Print("CRenkoEngine::Initialize failed: invalid brick_points, symbol_point, or anchor_price"); return(false); } //--- store the brick size in price units and snap the anchor to the fixed grid double grid_step = brick_points * symbol_point; double grid_ratio = anchor_price / grid_step; long grid_index = (long)::MathRound(grid_ratio); double snapped_anchor = grid_index * grid_step; m_symbol_point = symbol_point; m_brick_height = grid_step; m_grid_anchor = snapped_anchor; m_direction = BRICK_DIRECTION_NONE; m_ticks_in_brick = 0; m_brick_open_time = 0; m_bricks_total = 0; return(true); }
ProcessTick() and its helper AppendBrick() belong together. ProcessTick() runs once per quote and is written as a loop, since a fast quote can complete several bricks at once. It keeps re-testing the crossing conditions against the updated anchor until nothing further crosses. Each pass tests the cases in this order: the first brick of the session when no direction exists yet, then continuation in the established direction, and then reversal against it.
The continuation rule fires once price reaches one brick size past the anchor. The reversal rule is deliberately not symmetric with this: it requires two full brick sizes of travel before it fires. That asymmetry exists because a market that has already committed to a direction should need a genuinely larger move before the chart agrees it flipped, rather than just retraced. Anything smaller than two brick sizes is a retracement and changes nothing.
AppendBrick() is the small private helper that every branch calls, which avoids repeating the same struct fill six times. It resizes the output array by one slot and fills it from the boundary pair and direction it is handed, together with the engine's running tick count and open time. Only the first brick of a call takes the stored open time, a detail covered with SRenkoBrick above.
//+------------------------------------------------------------------+ //| ProcessTick | //| Feeds one quote into the state machine. Returns the number of | //| bricks completed by this quote and fills them in crossing order. | //+------------------------------------------------------------------+ int CRenkoEngine::ProcessTick(const double bid_price, const datetime tick_time, SRenkoBrick &emitted[]) { int emitted_count = 0; double upper_boundary = 0.0; double lower_boundary = 0.0; ::ArrayResize(emitted, 0); //--- track this quote toward whichever brick is currently forming m_ticks_in_brick++; if(m_brick_open_time == 0) m_brick_open_time = tick_time; while(true) { upper_boundary = m_grid_anchor + m_brick_height; lower_boundary = m_grid_anchor - m_brick_height; //--- no direction established yet: the first crossing in either direction opens the session if(m_direction == BRICK_DIRECTION_NONE) { if(bid_price >= upper_boundary) { AppendBrick(emitted, m_grid_anchor, upper_boundary, BRICK_DIRECTION_UP, tick_time); m_direction = BRICK_DIRECTION_UP; m_grid_anchor = upper_boundary; emitted_count++; continue; } if(bid_price <= lower_boundary) { AppendBrick(emitted, m_grid_anchor, lower_boundary, BRICK_DIRECTION_DOWN, tick_time); m_direction = BRICK_DIRECTION_DOWN; m_grid_anchor = lower_boundary; emitted_count++; continue; } break; } //--- established uptrend: continuation needs one brick size, reversal needs two if(m_direction == BRICK_DIRECTION_UP) { if(bid_price >= upper_boundary) { AppendBrick(emitted, m_grid_anchor, upper_boundary, BRICK_DIRECTION_UP, tick_time); m_grid_anchor = upper_boundary; emitted_count++; continue; } double reversal_trigger = m_grid_anchor - 2.0 * m_brick_height; if(bid_price <= reversal_trigger) { double reversal_open = m_grid_anchor - m_brick_height; double reversal_close = m_grid_anchor - 2.0 * m_brick_height; AppendBrick(emitted, reversal_open, reversal_close, BRICK_DIRECTION_DOWN, tick_time); m_direction = BRICK_DIRECTION_DOWN; m_grid_anchor = reversal_close; emitted_count++; continue; } break; } //--- established downtrend: mirror image of the uptrend branch above if(m_direction == BRICK_DIRECTION_DOWN) { if(bid_price <= lower_boundary) { AppendBrick(emitted, m_grid_anchor, lower_boundary, BRICK_DIRECTION_DOWN, tick_time); m_grid_anchor = lower_boundary; emitted_count++; continue; } double reversal_trigger = m_grid_anchor + 2.0 * m_brick_height; if(bid_price >= reversal_trigger) { double reversal_open = m_grid_anchor + m_brick_height; double reversal_close = m_grid_anchor + 2.0 * m_brick_height; AppendBrick(emitted, reversal_open, reversal_close, BRICK_DIRECTION_UP, tick_time); m_direction = BRICK_DIRECTION_UP; m_grid_anchor = reversal_close; emitted_count++; continue; } break; } break; } //--- a completed brick resets the in-progress tick counter and open time for the next brick if(emitted_count > 0) { m_ticks_in_brick = 0; m_brick_open_time = 0; m_bricks_total += emitted_count; } return(emitted_count); } //+------------------------------------------------------------------+ //| AppendBrick | //| Appends one completed brick to the output array. The first brick | //| of a call opens at the first quote since the previous emission; | //| any later brick from the same quote opens at that quote's time, | //| because it opens the moment the previous brick closes. | //+------------------------------------------------------------------+ void CRenkoEngine::AppendBrick(SRenkoBrick &emitted[], const double open_price, const double close_price, const ENUM_BRICK_DIRECTION brick_direction, const datetime tick_time) { int new_index = ::ArraySize(emitted); ::ArrayResize(emitted, new_index + 1); emitted[new_index].brick_open = open_price; emitted[new_index].brick_close = close_price; emitted[new_index].direction = brick_direction; emitted[new_index].open_time = (new_index == 0 && m_brick_open_time != 0) ? m_brick_open_time : tick_time; emitted[new_index].close_time = tick_time; emitted[new_index].tick_count = m_ticks_in_brick; }
The four accessors are one-line reads with no side effects, worth grouping together. CurrentDirection() returns the last completed run's direction. UpperBoundary() and LowerBoundary() return the anchor plus and minus one brick size. BricksTotal() returns a running session count, available for logging or test assertions.
//+------------------------------------------------------------------+ //| CurrentDirection | //| Returns the direction of the most recently completed brick run. | //+------------------------------------------------------------------+ ENUM_BRICK_DIRECTION CRenkoEngine::CurrentDirection(void) const { return(m_direction); } //+------------------------------------------------------------------+ //| UpperBoundary | //| Returns the anchor plus one brick size: the level that completes | //| the next continuation brick while direction is up. This is not | //| the reversal trigger; a reversal against an established downtrend| //| fires separately, at two brick sizes above the anchor, inside | //| ProcessTick(). | //+------------------------------------------------------------------+ double CRenkoEngine::UpperBoundary(void) const { return(m_grid_anchor + m_brick_height); } //+------------------------------------------------------------------+ //| LowerBoundary | //| Returns the anchor minus one brick size: the level that completes| //| the next continuation brick while direction is down. This is not | //| the reversal trigger; a reversal against an established uptrend | //| fires separately, at two brick sizes below the anchor, inside | //| ProcessTick(). | //+------------------------------------------------------------------+ double CRenkoEngine::LowerBoundary(void) const { return(m_grid_anchor - m_brick_height); } //+------------------------------------------------------------------+ //| BricksTotal | //| Returns the running count of bricks emitted since Initialize was | //| last called. | //+------------------------------------------------------------------+ long CRenkoEngine::BricksTotal(void) const { return(m_bricks_total); } #endif // RENKOENGINE_MQH
CCustomSymbolManager — Preparing the Custom Symbol
CustomSymbolCreate() builds the custom symbol and can clone a base symbol's properties in the process. A Renko clone of XAUUSD should keep XAUUSD's digit count and point value, changing only the fact that its bars are now distance-based bricks.
Create() first checks whether a symbol of the requested name already exists, using SymbolInfoInteger() against a property that only succeeds on a symbol genuinely backed by the terminal. This matters because an EA restarts far more often than it starts fresh, and treating an existing symbol as success rather than failure makes the pipeline idempotent across restarts. On the first run, CustomSymbolCreate() clones the base symbol. Digits and point are then set explicitly; otherwise boundaries may display incorrectly. AddToMarketWatch() wraps SymbolSelect() and is the step that makes the symbol visible enough for a chart window to open on it.
//+------------------------------------------------------------------+ //| CustomSymbolManager.mqh | //+------------------------------------------------------------------+ #ifndef CUSTOMSYMBOLMANAGER_MQH #define CUSTOMSYMBOLMANAGER_MQH //+------------------------------------------------------------------+ //| CCustomSymbolManager | //| Creates and prepares the custom symbol that will receive the | //| aggregated Renko bricks, and registers it in Market Watch. | //+------------------------------------------------------------------+ class CCustomSymbolManager { private: string m_custom_name; // name of the custom symbol this instance manages bool SymbolAlreadyExists(const string custom_name); public: CCustomSymbolManager(void); ~CCustomSymbolManager(void); bool Create(const string base_symbol, const string custom_name); bool AddToMarketWatch(void); string CustomName(void) const; }; //+------------------------------------------------------------------+ //| CCustomSymbolManager constructor | //| Leaves the managed symbol name empty until Create is called. | //+------------------------------------------------------------------+ CCustomSymbolManager::CCustomSymbolManager(void) { m_custom_name = ""; } //+------------------------------------------------------------------+ //| CCustomSymbolManager destructor | //| The manager does not delete the custom symbol on destruction, so | //| its bar history survives across EA restarts. The engine's | //| anchor and direction are not part of that history and are not | //| restored on restart. The writer re-seeds its sequencer from the | //| last stored bar. | //+------------------------------------------------------------------+ CCustomSymbolManager::~CCustomSymbolManager(void) { } //+------------------------------------------------------------------+ //| SymbolAlreadyExists | //| Tests whether a custom symbol of this name is already backed by | //| the terminal, using a property query that only succeeds for a | //| symbol that genuinely exists. | //+------------------------------------------------------------------+ bool CCustomSymbolManager::SymbolAlreadyExists(const string custom_name) { long digits_probe = 0; bool query_result = ::SymbolInfoInteger(custom_name, SYMBOL_DIGITS, digits_probe); return(query_result); } //+------------------------------------------------------------------+ //| Create | //| Creates the custom symbol by cloning a base symbol's properties, | //| then explicitly sets digits and point. Succeeds without error if | //| the custom symbol already exists from a previous run. | //+------------------------------------------------------------------+ bool CCustomSymbolManager::Create(const string base_symbol, const string custom_name) { m_custom_name = custom_name; //--- an existing custom symbol from a previous session is treated as success, not failure if(SymbolAlreadyExists(custom_name)) { ::Print("CCustomSymbolManager::Create: custom symbol ", custom_name, " already exists, reusing it"); return(true); } //--- clone the base symbol's properties into a brand new custom symbol bool created = ::CustomSymbolCreate(custom_name, "Renko\\Custom", base_symbol); if(!created) { ::Print("CCustomSymbolManager::Create failed: CustomSymbolCreate returned error ", ::GetLastError()); return(false); } //--- digits and point drive every price the pipeline computes, so set them explicitly long base_digits = (long)::SymbolInfoInteger(base_symbol, SYMBOL_DIGITS); double base_point = ::SymbolInfoDouble(base_symbol, SYMBOL_POINT); bool digits_set = ::CustomSymbolSetInteger(custom_name, SYMBOL_DIGITS, base_digits); bool point_set = ::CustomSymbolSetDouble(custom_name, SYMBOL_POINT, base_point); if(!digits_set || !point_set) { ::Print("CCustomSymbolManager::Create warning: could not set digits or point on ", custom_name); } return(true); } //+------------------------------------------------------------------+ //| AddToMarketWatch | //| Registers the custom symbol in Market Watch so a chart window | //| can be opened on it, wrapping SymbolSelect. | //+------------------------------------------------------------------+ bool CCustomSymbolManager::AddToMarketWatch(void) { if(m_custom_name == "") { ::Print("CCustomSymbolManager::AddToMarketWatch failed: no custom symbol has been created yet"); return(false); } bool selected = ::SymbolSelect(m_custom_name, true); if(!selected) { ::Print("CCustomSymbolManager::AddToMarketWatch failed: SymbolSelect returned error ", ::GetLastError()); return(false); } return(true); } //+------------------------------------------------------------------+ //| CustomName | //| Returns the name of the custom symbol this instance manages. | //+------------------------------------------------------------------+ string CCustomSymbolManager::CustomName(void) const { return(m_custom_name); } #endif // CUSTOMSYMBOLMANAGER_MQH
CBrickWriter — from Bricks to Custom Symbol Bars
A completed brick and an MqlRates record describe the same event from two angles. Since a Renko brick has no intra-brick wick by construction, high and low are simply the higher and lower boundary, regardless of direction. Open and close come straight from the brick's own fields: brick_open always maps to the bar's open, brick_close always maps to the bar's close. CRenkoEngine has already resolved which boundary is which before the brick reaches the writer, so no direction check is needed here.
The harder problem is time. CustomRatesUpdate() stores each bar under its own time value, and a bar written with a time that already exists replaces the stored bar. Bricks, however, complete whenever price moves the right distance, not on a predictable clock. A single fast tick can legitimately complete several bricks at the same instant, and records with identical timestamps would overwrite one another. WriteBrick() solves this with its own bar-time sequencer, advanced by one minute after every write, regardless of how close together the ticks actually arrived. On its first write, the sequencer starts at the first brick's open time rounded down to a whole minute. If the custom symbol already holds a bar at or after that time, it starts one minute after that bar instead, so a restarted EA never overwrites or interleaves with existing bricks.
//+------------------------------------------------------------------+ //| BrickWriter.mqh | //+------------------------------------------------------------------+ #ifndef BRICKWRITER_MQH #define BRICKWRITER_MQH #include "RenkoBrick.mqh" //+------------------------------------------------------------------+ //| CBrickWriter | //| Converts completed Renko bricks into custom symbol bars and | //| writes them via CustomRatesUpdate, maintaining a strictly | //| increasing bar-time sequencer independent of wall-clock time. | //+------------------------------------------------------------------+ class CBrickWriter { private: datetime m_next_bar_time; // time key to assign to the next custom symbol bar bool m_sequencer_ready; // true once the sequencer has been seeded from a first brick public: CBrickWriter(void); ~CBrickWriter(void); bool WriteBrick(const string custom_name, const SRenkoBrick &brick); }; //+------------------------------------------------------------------+ //| CBrickWriter constructor | //| The sequencer is not seeded until the first brick is written, so | //| it can start after the last bar already stored on the symbol. | //+------------------------------------------------------------------+ CBrickWriter::CBrickWriter(void) { m_next_bar_time = 0; m_sequencer_ready = false; } //+------------------------------------------------------------------+ //| CBrickWriter destructor | //| No dynamic resources are owned by the writer. | //+------------------------------------------------------------------+ CBrickWriter::~CBrickWriter(void) { }
WriteBrick() seeds the sequencer on its first call, fills a single-element MqlRates array from the brick's fields, then calls CustomRatesUpdate(). tick_volume on the resulting bar carries tick_count, giving anyone inspecting the chart a rough sense of market activity since the last emission — not a precise per-brick figure when a single tick completes multiple bricks, as noted earlier for SRenkoBrick.
//+------------------------------------------------------------------+ //| WriteBrick | //| Maps one completed brick onto an MqlRates record and writes it | //| to the custom symbol via CustomRatesUpdate. The sequencer is | //| seeded on the first call and continues after any bar already | //| stored on the symbol, so a restart never overwrites or | //| interleaves with existing bricks. | //+------------------------------------------------------------------+ bool CBrickWriter::WriteBrick(const string custom_name, const SRenkoBrick &brick) { MqlRates bar_record[1]; //--- seed the sequencer on the first call; never start at or before a bar that already exists if(!m_sequencer_ready) { long seed_time = ((long)brick.open_time / 60) * 60; long last_bar_time = (long)::SeriesInfoInteger(custom_name, PERIOD_M1, SERIES_LASTBAR_DATE); if(last_bar_time > 0 && seed_time <= last_bar_time) { seed_time = last_bar_time + 60; ::Print("CBrickWriter: ", custom_name, " already holds bars, continuing after ", ::TimeToString((datetime)last_bar_time, TIME_DATE | TIME_SECONDS)); } m_next_bar_time = (datetime)seed_time; m_sequencer_ready = true; } //--- open and close come straight from the engine, which has already resolved direction double record_open = brick.brick_open; double record_close = brick.brick_close; //--- high and low are simply the higher and lower boundary, independent of direction double record_high = ::MathMax(brick.brick_open, brick.brick_close); double record_low = ::MathMin(brick.brick_open, brick.brick_close); bar_record[0].time = m_next_bar_time; bar_record[0].open = record_open; bar_record[0].high = record_high; bar_record[0].low = record_low; bar_record[0].close = record_close; bar_record[0].tick_volume = brick.tick_count; bar_record[0].real_volume = 0; bar_record[0].spread = 0; int written = ::CustomRatesUpdate(custom_name, bar_record); if(written <= 0) { ::Print("CBrickWriter::WriteBrick failed: CustomRatesUpdate returned error ", ::GetLastError()); return(false); } //--- advance the sequencer by one minute so the next brick, however soon it completes, gets a unique time key m_next_bar_time += 60; return(true); } #endif // BRICKWRITER_MQH
RenkoBuilderEA.mq5 — the Driver EA
Every class built so far solves one narrow problem in isolation. None of them, on their own, produces a chart a trader can actually look at. RenkoBuilderEA is where that changes: it is the thin layer of glue that turns three independent classes into a single running pipeline, and it is the only file in this project that ever touches OnTick() directly.
The EA's job splits cleanly into two halves, and the split maps directly onto MetaTrader's own event lifecycle. OnInit() handles everything that only needs to happen once: creating the custom symbol, reading a starting price, and seeding the engine. OnTick() handles everything that repeats for as long as the chart stays open: pulling the current quote, feeding it to the engine, and pushing out whatever bricks come back. Keeping that boundary clean matters more than it might first appear, since any setup logic that leaked into OnTick() would run again on every single quote for no reason.
//+------------------------------------------------------------------+ //| RenkoBuilderEA.mq5 | //+------------------------------------------------------------------+ #include <RenkoBuilder/RenkoEngine.mqh> #include <RenkoBuilder/CustomSymbolManager.mqh> #include <RenkoBuilder/BrickWriter.mqh> input int InpBrickPoints = 100; // brick size, in points (100 is a demonstration default) input string InpCustomSuffix = ".RENKO"; // suffix appended to build the custom symbol name input bool InpLogOnlyReversals = false; // true: log only reversal bricks, false: log every brick CRenkoEngine g_engine; CCustomSymbolManager g_symbol_manager; CBrickWriter g_writer; string g_custom_symbol_name; long g_ticks_processed = 0; long g_bricks_written = 0; long g_write_errors = 0; //+------------------------------------------------------------------+ //| OnInit | //| Creates the custom symbol, initializes the state machine from the| //| current Bid snapped to the brick grid, and logs the configuration| //| the session is starting with. | //+------------------------------------------------------------------+ int OnInit(void) { g_custom_symbol_name = ::Symbol() + InpCustomSuffix; //--- prepare the custom symbol that will receive the aggregated bricks if(!g_symbol_manager.Create(::Symbol(), g_custom_symbol_name)) { ::Print("RenkoBuilderEA::OnInit failed: could not create custom symbol ", g_custom_symbol_name); return(INIT_FAILED); } if(!g_symbol_manager.AddToMarketWatch()) { ::Print("RenkoBuilderEA::OnInit failed: could not add ", g_custom_symbol_name, " to Market Watch"); return(INIT_FAILED); } //--- seed the engine from the current Bid, snapped to the fixed brick grid double symbol_point = ::SymbolInfoDouble(::Symbol(), SYMBOL_POINT); double current_bid = ::SymbolInfoDouble(::Symbol(), SYMBOL_BID); if(!g_engine.Initialize(current_bid, (double)InpBrickPoints, symbol_point)) { ::Print("RenkoBuilderEA::OnInit failed: engine initialization rejected the supplied parameters"); return(INIT_FAILED); } int symbol_digits_init = (int)::SymbolInfoInteger(::Symbol(), SYMBOL_DIGITS); ::Print("RenkoBuilderEA initialized: custom symbol=", g_custom_symbol_name, ", brick_points=", InpBrickPoints, ", digits=", symbol_digits_init, ", point=", ::DoubleToString(symbol_point, symbol_digits_init), ", lower_boundary=", ::DoubleToString(g_engine.LowerBoundary(), symbol_digits_init), ", upper_boundary=", ::DoubleToString(g_engine.UpperBoundary(), symbol_digits_init), ", server=", ::AccountInfoString(ACCOUNT_SERVER), ", build=", ::TerminalInfoInteger(TERMINAL_BUILD)); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| OnTick | //| Reads the current quote, feeds it into the state machine, writes | //| every emitted brick through the writer, and logs each completed | //| brick according to the configured logging policy. | //+------------------------------------------------------------------+ void OnTick(void) { MqlTick current_tick; if(!::SymbolInfoTick(::Symbol(), current_tick)) { ::Print("RenkoBuilderEA::OnTick warning: SymbolInfoTick failed with error ", ::GetLastError()); return; } g_ticks_processed++; //--- capture the direction as it stood before this tick, since ProcessTick below will update it ENUM_BRICK_DIRECTION direction_before_tick = g_engine.CurrentDirection(); SRenkoBrick emitted[]; int emitted_count = g_engine.ProcessTick(current_tick.bid, current_tick.time, emitted); if(emitted_count <= 0) return; int symbol_digits = (int)::SymbolInfoInteger(::Symbol(), SYMBOL_DIGITS); for(int i = 0; i < emitted_count; i++) { //--- write every emitted brick regardless of the logging policy if(!g_writer.WriteBrick(g_custom_symbol_name, emitted[i])) { g_write_errors++; ::Print("RenkoBuilderEA::OnTick warning: failed to write brick to ", g_custom_symbol_name); continue; } g_bricks_written++; //--- only the first brick from this tick can be a reversal; later bricks in the same gap //--- continue in the new direction. The comparison uses the direction recorded before //--- ProcessTick ran, since g_engine.CurrentDirection() is already updated by this point. bool is_reversal = (i == 0) && (direction_before_tick != BRICK_DIRECTION_NONE) && (emitted[i].direction != direction_before_tick); if(InpLogOnlyReversals && !is_reversal) continue; string direction_text = (emitted[i].direction == BRICK_DIRECTION_UP) ? "UP" : "DOWN"; string kind_text = is_reversal ? "reversal" : ((i > 0) ? "same-tick" : "continuation"); ::Print("Brick completed: kind=", kind_text, ", direction=", direction_text, ", open=", ::DoubleToString(emitted[i].brick_open, symbol_digits), ", close=", ::DoubleToString(emitted[i].brick_close, symbol_digits), ", tick_count=", emitted[i].tick_count); } } //+------------------------------------------------------------------+ //| OnDeinit | //| Prints the session counters so a run can be summarized from the | //| Experts log alone. | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { ::Print("RenkoBuilderEA stopped: reason=", reason, ", ticks_processed=", g_ticks_processed, ", bricks_written=", g_bricks_written, ", write_errors=", g_write_errors); }
OnDeinit() prints one summary line when the EA is removed or the terminal closes: the stop reason, the number of ticks processed, the bricks written, and the write errors. The tick counter counts OnTick() calls that returned a valid quote, so it can be lower than the number of server ticks. Each brick line also carries a kind tag. The value continuation marks the first brick from a quote that extends the current run, reversal marks the first brick that flips it, and same-tick marks any second or later brick from the same quote. The very first brick of a session is logged as continuation, because no direction exists yet.
Choosing the Brick Size
InpBrickPoints = 100 is a demonstration default, not a recommendation. The brick height in price terms is InpBrickPoints multiplied by SYMBOL_POINT, so the same input means different things on different symbols. On a five-digit EURUSD quote, 100 points is 10 pips (0.00100). On a two-digit XAUUSD quote, it is 1.00. Check the digits and point in the symbol specification before reusing a value.
To choose a value for a symbol, follow this rule:
- Decide how large a price move one brick should represent. A common starting point is one quarter to one half of the average true range on the timeframe you normally trade.
- Divide that price move by SYMBOL_POINT to get InpBrickPoints. For example, if the H1 average true range on EURUSD is 0.0030, one quarter of it is 0.00075, which is 75 points. The numbers here are illustrative.
- Keep the brick several times larger than the typical spread. The engine reads the Bid only, but a brick close to the spread size turns quote noise into bricks.
- Run a demo session and count the bricks per hour. If bricks complete much faster than one per minute for long periods, the bar-time sequencer runs ahead of the clock (see Limitations), so choose a larger brick. If almost none complete, choose a smaller one.
Our live runs give a sense of scale (see Live Test Results). A 100-point brick on XAUUSD (1.00) produced about 48 bricks per hour, a 10-point brick on EURUSD (one pip) about 17 per hour, and a 250-point brick on ETHUSD (2.50) about 7 per hour. Volatility changes during the day, and the brick size is fixed once the engine initializes, so revisit the value when the market changes.
Installing RenkoBuilderEA and Viewing the Output
The Renko output does not appear on the chart where the EA runs, so follow these steps in order.
Step 1: Copy the files. Copy the five .mqh files into MQL5\Include\RenkoBuilder, keeping that subfolder name, for example MQL5\Include\RenkoBuilder\RenkoEngine.mqh. Copy RenkoBuilderEA.mq5 into MQL5\Experts. The #include directives expect the RenkoBuilder subfolder, so any other location causes a "cannot open source file" error in Step 2.
Step 2: Refresh and compile. In the Navigator, right-click Include and Experts and choose Refresh. Open RenkoBuilderEA.mq5 and compile it. A clean compile shows no errors in the Toolbox.
Step 3: Attach the EA to the base symbol. Open an ordinary chart of the base symbol, for example XAUUSD, on any timeframe, and drag RenkoBuilderEA onto it. Do not attach it to the custom symbol's chart. A custom symbol has no live Bid, so initialization fails with the invalid brick size, point, or anchor price message.
Step 4: Confirm initialization. Enable Algo Trading and check that the smiley icon in the chart's top-right corner is not red. On the Experts tab, look for a line similar to this:
RenkoBuilderEA initialized: custom symbol=XAUUSD.RENKO, brick_points=100, digits=2, point=0.01, lower_boundary=4042.00, upper_boundary=4044.00, server=MetaQuotes-Demo, build=6291
The boundaries, server, and build depend on your terminal. The line confirms that OnInit() succeeded and the custom symbol exists. The value 100 is a demonstration default (see Choosing the Brick Size).
Step 5: Find the custom symbol. The chart with the EA keeps showing ordinary candles of the base symbol, because it only supplies the ticks. The bricks go to a separate symbol named after the base symbol plus InpCustomSuffix, for example XAUUSD.RENKO. The EA adds it to Market Watch at startup. If it is missing, right-click in Market Watch and choose Show All, or search for the name.
Step 6: Open a chart on it. Drag XAUUSD.RENKO onto an empty chart window, or right-click it and choose Chart Window.
Step 7: Use M1 and scroll to the data. Set the timeframe to M1. The writer spaces bricks one minute apart, so a coarser timeframe packs many bricks into a few tall bars. Press Home or scroll fully left to reach the newly written bars.
Step 8: Confirm the result. The chart should show uniform-height bricks with reversals wherever price moved two brick sizes against the run. An EMA or RSI that plots without error confirms the symbol is readable by standard indicators. It does not confirm that their values mean what they mean on time-based charts (see Limitations).

Figure 2: The XAUUSD.RENKO custom symbol charted on M1 in MetaTrader, produced by RenkoBuilderEA running live against a demo account. Each brick holds a uniform height, and green and red bricks follow MetaTrader's ordinary open/close bar coloring. The staircase pattern is the expected visual result of the tick-driven construction described in the CRenkoEngine section; the screenshot illustrates that output rather than independently proving it.
Verification — TestRenkoEngine.mq5
A state machine with continuation, reversal, and gap handling has enough branches that watching a live chart is not a reliable way to catch a regression. This script drives CRenkoEngine directly with synthetic ticks and checks the emitted bricks against exact boundaries, using a small local ASSERT macro.
The script runs four scenarios. TestContinuation() covers a steady climb worth exactly two brick sizes, which should emit two continuation bricks with a third left incomplete. It checks the open, close, direction, and tick count of the first and second bricks explicitly, and confirms that the second brick opens where the first one closed. TestRetracementVersusReversal() confirms a retracement smaller than two brick sizes emits nothing, while a further move past that threshold emits exactly one reversal brick. TestGapHandling() confirms a single fast quote jumping three brick sizes in the established direction emits three continuation bricks in correct ascending order, each opening when the previous one closes. TestReversalGapHandling() confirms a single fast quote jumping more than two brick sizes against the established direction emits a reversal brick followed by continuation bricks in the new direction, all from that one tick.
To run the tests, copy TestRenkoEngine.mq5 into MQL5\Scripts\RenkoBuilder, compile it, and drag it onto any chart. The results appear on the Experts tab. On the code in this article, the script prints 40 ASSERT PASSED lines and ends with ALL TESTS PASSED.
//+------------------------------------------------------------------+ //| TestRenkoEngine.mq5 | //+------------------------------------------------------------------+ #property script_show_inputs #include <RenkoBuilder/RenkoEngine.mqh> #define ASSERT(condition, message) \ if(!(condition)) \ { \ ::Print("ASSERT FAILED: ", message); \ g_failures++; \ } \ else \ { \ ::Print("ASSERT PASSED: ", message); \ } int g_failures = 0; //+------------------------------------------------------------------+ //| TestContinuation | //| Drives a steady climb worth exactly two brick sizes and confirms | //| two continuation bricks emit with exact boundaries, leaving the | //| third brick incomplete. Checks open, close, direction, and tick | //| count of the first and second bricks, and that the second brick | //| opens where the first one closed. | //+------------------------------------------------------------------+ void TestContinuation(void) { CRenkoEngine engine; SRenkoBrick emitted[]; int bricks_seen = 0; double previous_close = 0.0; double brick_size = 10.0 * 0.00001; engine.Initialize(1.10000, 10.0, 0.00001); double climb_quotes[] = {1.10003, 1.10008, 1.10010, 1.10015, 1.10020, 1.10022, 1.10025}; int quote_count = ::ArraySize(climb_quotes); for(int i = 0; i < quote_count; i++) { int count_here = engine.ProcessTick(climb_quotes[i], ::TimeCurrent() + i, emitted); for(int j = 0; j < count_here; j++) { bricks_seen++; if(bricks_seen == 1) { ASSERT(::MathAbs(emitted[j].brick_open - 1.10000) < 0.0000001, "first brick opens at 1.10000"); ASSERT(::MathAbs(emitted[j].brick_close - 1.10010) < 0.0000001, "first brick closes at 1.10010"); ASSERT(emitted[j].direction == BRICK_DIRECTION_UP, "first brick direction is up"); ASSERT(emitted[j].tick_count == 3, "first brick counts the three quotes received before it closed"); } if(bricks_seen == 2) { ASSERT(::MathAbs(emitted[j].brick_open - 1.10010) < 0.0000001, "second brick opens at 1.10010"); ASSERT(::MathAbs(emitted[j].brick_close - 1.10020) < 0.0000001, "second brick closes at 1.10020"); ASSERT(::MathAbs(emitted[j].brick_open - previous_close) < 0.0000001, "second brick opens where the first one closed"); ASSERT(emitted[j].direction == BRICK_DIRECTION_UP, "second brick direction is up"); ASSERT(emitted[j].tick_count == 2, "second brick counts the two quotes received before it closed"); } ASSERT(::MathAbs(emitted[j].brick_close - emitted[j].brick_open - brick_size) < 0.0000001, "every continuation brick closes exactly one brick size above its open"); previous_close = emitted[j].brick_close; } } ASSERT(bricks_seen == 2, "exactly two continuation bricks emitted from the climb"); ASSERT(engine.CurrentDirection() == BRICK_DIRECTION_UP, "direction is up after the climb"); ASSERT(::MathAbs(engine.LowerBoundary() - 1.10010) < 0.0000001, "lower boundary sits at 1.10010 with the third brick incomplete"); ASSERT(::MathAbs(engine.UpperBoundary() - 1.10030) < 0.0000001, "upper boundary sits at 1.10030 with the third brick incomplete"); } //+------------------------------------------------------------------+ //| TestRetracementVersusReversal | //| Confirms a retracement smaller than the reversal threshold emits | //| nothing, and a further move past the threshold emits exactly one | //| reversal brick with exact boundaries. | //+------------------------------------------------------------------+ void TestRetracementVersusReversal(void) { CRenkoEngine engine; SRenkoBrick emitted[]; engine.Initialize(1.10000, 10.0, 0.00001); engine.ProcessTick(1.10010, ::TimeCurrent(), emitted); engine.ProcessTick(1.10020, ::TimeCurrent() + 1, emitted); ASSERT(engine.CurrentDirection() == BRICK_DIRECTION_UP, "direction is up after two continuation bricks"); int retracement_count = engine.ProcessTick(1.10005, ::TimeCurrent() + 2, emitted); ASSERT(retracement_count == 0, "a 15 point retracement smaller than two brick sizes emits nothing"); ASSERT(engine.CurrentDirection() == BRICK_DIRECTION_UP, "direction is unchanged after the retracement"); int reversal_count = engine.ProcessTick(1.10000, ::TimeCurrent() + 3, emitted); ASSERT(reversal_count == 1, "a full 20 point move from the boundary emits exactly one reversal brick"); ASSERT(::MathAbs(emitted[0].brick_open - 1.10010) < 0.0000001, "reversal brick opens at 1.10010"); ASSERT(::MathAbs(emitted[0].brick_close - 1.10000) < 0.0000001, "reversal brick closes at 1.10000"); ASSERT(emitted[0].direction == BRICK_DIRECTION_DOWN, "reversal brick direction is down"); ASSERT(engine.CurrentDirection() == BRICK_DIRECTION_DOWN, "direction flips to down after the reversal brick"); } //+------------------------------------------------------------------+ //| TestGapHandling | //| Confirms a single quote that jumps three brick sizes in the | //| established direction emits three continuation bricks in correct | //| ascending order with contiguous boundaries. | //+------------------------------------------------------------------+ void TestGapHandling(void) { CRenkoEngine engine; SRenkoBrick emitted[]; engine.Initialize(1.10000, 10.0, 0.00001); engine.ProcessTick(1.10010, ::TimeCurrent(), emitted); engine.ProcessTick(1.10020, ::TimeCurrent() + 1, emitted); engine.ProcessTick(1.10030, ::TimeCurrent() + 2, emitted); int gap_count = engine.ProcessTick(1.10062, ::TimeCurrent() + 3, emitted); ASSERT(gap_count == 3, "a single gap quote emits exactly three continuation bricks"); ASSERT(::MathAbs(emitted[0].brick_open - 1.10030) < 0.0000001, "first gap brick opens at 1.10030"); ASSERT(::MathAbs(emitted[0].brick_close - 1.10040) < 0.0000001, "first gap brick closes at 1.10040"); ASSERT(::MathAbs(emitted[1].brick_open - 1.10040) < 0.0000001, "second gap brick opens at 1.10040"); ASSERT(::MathAbs(emitted[1].brick_close - 1.10050) < 0.0000001, "second gap brick closes at 1.10050"); ASSERT(::MathAbs(emitted[2].brick_open - 1.10050) < 0.0000001, "third gap brick opens at 1.10050"); ASSERT(::MathAbs(emitted[2].brick_close - 1.10060) < 0.0000001, "third gap brick closes at 1.10060"); ASSERT(emitted[1].open_time == emitted[0].close_time, "second gap brick opens when the first one closes"); ASSERT(emitted[2].open_time == emitted[1].close_time, "third gap brick opens when the second one closes"); for(int i = 0; i < gap_count; i++) ASSERT(emitted[i].direction == BRICK_DIRECTION_UP, "every gap brick is a continuation brick in the up direction"); } //+------------------------------------------------------------------+ //| TestReversalGapHandling | //| Confirms a single quote that jumps more than two brick sizes | //| against the established direction emits one reversal brick, | //| followed by continuation bricks in the new direction, all from | //| that one tick. | //+------------------------------------------------------------------+ void TestReversalGapHandling(void) { CRenkoEngine engine; SRenkoBrick emitted[]; engine.Initialize(1.10000, 10.0, 0.00001); engine.ProcessTick(1.10010, ::TimeCurrent(), emitted); // establish an UP direction int gap_count = engine.ProcessTick(1.09975, ::TimeCurrent() + 1, emitted); // jump down 3.5 brick sizes in one tick ASSERT(gap_count >= 2, "a reversal gap against an established UP direction emits more than one brick"); ASSERT(emitted[0].direction == BRICK_DIRECTION_DOWN, "first emitted brick is the reversal brick, direction down"); ASSERT(::MathAbs(emitted[0].brick_open - 1.10000) < 0.0000001, "reversal brick opens at 1.10000"); ASSERT(::MathAbs(emitted[0].brick_close - 1.09990) < 0.0000001, "reversal brick closes at 1.09990"); for(int i = 1; i < gap_count; i++) ASSERT(emitted[i].direction == BRICK_DIRECTION_DOWN, "every brick after the reversal continues down"); } //+------------------------------------------------------------------+ //| OnStart | //| Runs all four verification scenarios in sequence and reports a | //| final pass or fail summary based on the accumulated failure count| //+------------------------------------------------------------------+ void OnStart(void) { ::Print("--- TestRenkoEngine: starting verification ---"); TestContinuation(); TestRetracementVersusReversal(); TestGapHandling(); TestReversalGapHandling(); if(g_failures == 0) ::Print("--- TestRenkoEngine: ALL TESTS PASSED ---"); else ::Print("--- TestRenkoEngine: ", g_failures, " ASSERTION(S) FAILED ---"); }
Live Test Results
We ran the pipeline live on demo accounts to check that continuation, reversal, and multi-brick bursts behave as the synthetic tests predict. The conditions are listed first, followed by the run totals: ticks processed, bricks written, and write errors are taken from the EA's shutdown message, while continuation, reversal, and same-tick counts are tallied from individual brick entries in the Experts log.
| Item | Value |
|---|---|
| Accounts | Demo accounts on two servers: MetaQuotes-Demo (terminal build 6291) for runs 1, 2, and 2b on XAUUSD, and a second demo server (terminal build 6230) for runs 3 and 4 on EURUSD and ETHUSD. |
| Terminal host | Windows 11 build 26200, Intel Core i7-13650HX laptop with 64 GB of RAM |
| Dates | November 10, 2026 (XAUUSD) and November 11, 2026 (EURUSD, ETHUSD) |
| Symbols | XAUUSD and ETHUSD (2 digits, point 0.01), EURUSD (5 digits, point 0.00001) |
| Base chart timeframe | M1 for XAUUSD and ETHUSD, H1 for EURUSD (the timeframe does not affect the bricks) |
| Inputs | InpLogOnlyReversals = false; the brick size and suffix for each run are in the next table |
| Data source | The Experts log of each terminal, plus the counters in the stop line |
Clock times in the log lines are the terminal host's clock (UTC+1). Bar labels on the custom symbols, such as 20:57:00, use server time.
| Run | Symbol | Brick points | Brick height | Duration | Ticks processed | Bricks written | Write errors | Continuation | Reversal | Same-tick |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | XAUUSD | 100 | 1.00 | 1 h 59 min | 25,480 | 95 | 0 | 65 | 27 | 3 |
| 2 | XAUUSD (.RENKO30) | 30 | 0.30 | 14 min | 3,147 | 60 | 0 | 40 | 20 | 0 |
| 2b | Same, after a restart | 30 | 0.30 | 6 min | 887 | 17 | 0 | 14 | 3 | 0 |
| 3 | EURUSD (.RENKO10) | 10 | 0.00010 | 79 min | 2,847 | 22 | 0 | 17 | 5 | 0 |
| 4 | ETHUSD (.RENKO250) | 250 | 2.50 | 78 min | 11,005 | 9 | 0 | 4 | 5 | 0 |
The first brick of every run is logged as a continuation brick, because no direction exists yet. The counts of ticks processed are the number of OnTick() calls that returned a valid quote, and they can be lower than the number of server ticks, as described under Limitations.
Representative lines from run 1 show each kind:
Brick completed: kind=continuation, direction=DOWN, open=4043.00, close=4042.00, tick_count=34 Brick completed: kind=reversal, direction=UP, open=4043.00, close=4044.00, tick_count=102 Brick completed: kind=reversal, direction=UP, open=4038.00, close=4039.00, tick_count=203 Brick completed: kind=same-tick, direction=UP, open=4039.00, close=4040.00, tick_count=203
The last two lines come from one quote. It first completed a reversal brick, then a continuation brick in the new direction, so this run includes a gap through a reversal. A second burst in the same run, at 18:53:01, produced a reversal brick followed by two same-tick bricks.
Run 2 ended with the EA removed from the chart. It was attached again 47 seconds later. The writer found the existing bars and printed CBrickWriter: XAUUSD.RENKO30 already holds bars, continuing after 2026.11.10 20:57:00. The custom symbol's last bar was then roughly 43 minutes ahead of the server clock, because the sequencer had written 60 bricks in 14 minutes. New bricks continued from 20:58, so none replaced or interleaved with earlier ones. The last brick before the restart closed at 4017.30, and the first brick after it opened at 4018.20, because the new grid anchor snapped to the Bid at that moment.
Extending the Builder
The pipeline only sees ticks that arrive while the terminal runs, but ProcessTick() works identically against historical ticks pulled through CopyTicksRange(). Feeding historical ticks through the engine before switching to live quotes backfills the custom symbol with bricks otherwise missing from the chart's left edge. Run the backfill on an empty custom symbol, before any live bricks exist. Because the writer continues after the last stored bar, historical bricks written later would land after the live ones and not before them.
Asymmetric brick sizes for up and down moves are a fairly common variant. Supporting them means replacing m_brick_height with two separate fields, one for each direction, with the reversal rule adjusted to use whichever size corresponds to the direction being entered.
Wick tracking would let traders see how far price traveled beyond a boundary before the next brick completed, information the engine currently discards since high and low are always exactly the two boundary prices. Publishing custom ticks with CustomTicksAdd() on every incoming quote would let the chart show live movement inside the brick currently forming, rather than staying flat between completions.
Limitations
The engine sees only the ticks the terminal actually received. Any period when the terminal was closed, disconnected, or asleep leaves a gap in brick history unless it is backfilled with historical ticks, as described in the previous section. The first quote after such a gap appears as a burst of same-tick bricks. In one session, the first quote after a hibernation produced six bricks at once, because the price had moved 30 pips while the terminal slept. Those bricks describe the gap, not the path inside it. OnTick() also does not guarantee that every server tick is processed individually, because MetaTrader can merge several quotes into one call under load.
The one-minute bar-time sequencer is an ordering device, not a record of when bricks completed. Once bricks complete faster than one per minute, the bar times drift away from the wall clock. SRenkoBrick.close_time holds the real completion time, but the writer does not store it on the chart, so log it if you need it. For the same reason, indicators read the bricks as ordinary M1 bars with a different meaning. A 20-period EMA averages 20 bricks, not 20 minutes, session filters see the synthetic times, and volume indicators read tick_volume, which repeats on every brick that one quote completes. They plot without error, but read them as brick data.
Brick size is fixed once Initialize() runs, so the builder cannot adapt to changing volatility mid-session. CCustomSymbolManager::Create() reuses any existing symbol of the requested name without checking that this EA created it or that its digits, base symbol, and brick size match the current run. Reattaching the EA with a different InpBrickPoints leaves the old bricks on the chart next to the new ones. In testing, changing the brick size on ETHUSD and EURUSD left bricks of both sizes on the same custom symbol.
An EA restart reinitializes CRenkoEngine from the current Bid, not from the last stored bar, so the anchor and direction start fresh while the bar history does not. On its first write, CBrickWriter therefore reads the time of the last stored bar and continues one minute after it whenever that bar is at or after the new brick's start minute. Without this step, the sequencer would be seeded from the clock. Since it can run ahead of the clock, new bars could land on occupied times, replacing old bricks, or between them. With it, the bar order stays intact, as the restart test in Live Test Results shows. The first brick after a restart may still not start where the last one ended, because the new anchor can differ.
The first brick after every start is a grid snap. It can close after a move of less than one brick size from the starting price, or after up to one and a half in the other direction. Treat it as a calibration step, not a full brick of movement.
Custom symbols are stored per terminal installation and do not travel with the EA's source files, so a different machine or terminal means recreating the symbol and its history from scratch. The engine is driven by the Bid alone. For instruments where Ask or Last is the economically relevant price, the chart may not track the series actually traded.
Conclusion
This article builds a small, three-class pipeline that turns a raw MQL5 tick stream into Renko bricks whose boundaries follow the order price crossed each level as delivered to OnTick(), rather than an order inferred after the fact from OHLC summaries. Live runs on demo accounts with XAUUSD, EURUSD, and ETHUSD processed 43,366 quotes and wrote 203 bricks with no write errors, covering continuation, reversal, and same-tick bursts, plus one restart. They did not include a controlled test of connection loss, which is discussed under Limitations.
True tick aggregation guarantees that the brick sequence matches the order in which OnTick() delivered quotes, nothing reordered. It does not guarantee the terminal's price server delivered every tick to OnTick() without coalescing any under load, it does not guarantee brick size was chosen well, and it does not recover history the terminal never received.
Brick size is fixed at Initialize() and does not adapt mid-session to changing volatility. Custom symbols are also stored per terminal installation and do not travel with the EA's source files, so moving this builder elsewhere means recreating the symbol from scratch.
Programs used in the article:
| # | Name | Type | Description |
|---|---|---|---|
| 1 | BrickDirection.mqh | Include File | Defines ENUM_BRICK_DIRECTION, the three-state direction enum used throughout the pipeline |
| 2 | RenkoBrick.mqh | Include File | Defines SRenkoBrick, the struct describing one completed Renko brick |
| 3 | RenkoEngine.mqh | Include File | Defines CRenkoEngine, the tick-driven state machine handling continuation, reversal, and gap crossings |
| 4 | CustomSymbolManager.mqh | Include File | Defines CCustomSymbolManager, which creates and registers the custom symbol receiving the bricks |
| 5 | BrickWriter.mqh | Include File | Defines CBrickWriter, which maps completed bricks onto MqlRates records and writes them via CustomRatesUpdate() |
| 6 | RenkoBuilderEA.mq5 | Expert Advisor | The driver EA that wires the pipeline together and feeds it from the live tick stream |
| 7 | TestRenkoEngine.mq5 | Script | Verification script driving the state machine with synthetic quotes and asserting exact expected boundaries |
| 8 | RenkoBuilder.zip | Zip Archive | Zip archive containing all the attached files and their paths relative to the terminal's root folder. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.