All mode: smaller and faster when Last and Volume are constant
If Last and Volume stay equal to the block's first tick (typical for forex), the block is written with short records: time, flags, Bid and Ask only. Records are 5 bytes instead of 8, or 7 instead of 11 for wide price moves. Last and Volume come from the block's first tick.
If either one changes inside a block, that block is written in the v4.30 layout automatically.
Result on 5 forex symbols: All-mode files are 37.5% smaller, decode is about 70–90% faster, and compression is about 20% faster.
Faster wide-record decoding (5+ digit symbols)
Blocks with wide price moves now use the faster accumulator step on 5+ digit symbols, measured +31–36% in C++ tests. 2–4-digit symbols such as BTC and XAU keep the old step, which is faster for them. The choice is made at compile time.
What v4.31 changed in All mode (FastAccum, best pure-RAM decode speed):
Symbol
All-mode file size, v4.30 → v4.31
Decode Mt/s: v4.30 (lab) → v4.31 (benchmark)
EURUSD
35.59 → 22.25 MB
242 → 460 (+90%)
GBPUSD
50.32 → 31.45 MB
240 → 454 (+89%)
USDJPY
46.96 → 29.35 MB
278 → 490 (+76%)
AUDCAD
55.70 → 34.82 MB
274 → 494 (+80%)
AUDUSD
38.81 → 24.26 MB
272 → 466 (+71%)
Size: All-mode files are 37.5% smaller on every symbol (13.34% → 8.34% of raw MqlTick size). Last and Volume are constant in all of these blocks.
Speed: All mode is now almost as fast as BidAsk (473 vs 499 Mt/s on average for FastAccum), where before it was about half
Benchmark change — the tick handler now uses each tick
Problem: the benchmark's Strategy() was empty. Because MQL5 inlines OnTickDecompressed , the compiler could skip computing prices nobody read.
Evidence: OFF and ExactDiv reached about 1100 Mt/s with an empty handler but about 530–600 Mt/s with one that reads the tick. With an identical handler, each mode slowed by a different amount, which points to skipped work rather than handler cost.
Fix: Strategy() now reads every field the decoder writes (bid, ask, last, volume_real, volume, time, time_msc, flags) into a checksum, so no decode work can be dropped.
Effect: all speeds drop to roughly half of the old figures. Those are the real ones.
The ranking changes: the gaps between modes shrink (FastAccum trails OFF by 8%, not 12–15%), so older rankings overstated how far OFF was ahead.
FastAccum's real cost: it trails OFF by 8%, not the 12–15% the empty-handler benchmark showed. In All mode it is within 2% of OFF.
ULP now matches FastAccum on BidAsk decode.It still compresses at about half the speed.
Standard and Cache are slow only on symbols that use FastAccum, not ExactDiv (EURUSD, GBPUSD: about 200 and 290 Mt/s). That's the cost of calling NormalizeDouble or the cache on every tick. On ExactDiv symbols all exact modes perform the same.
Как видно мой вариант с только ULP ADJUST на 1.3% медленнее вашей аккумуляторной (которая по прежнему в 2+ раза медленнее на старом сервере).
Отключение режима All для форекс символов у меня тоже было, но потом перенес его в MathTicker, чтобы код компрессора был короче и проще. Отключаю там просто по режиму торговли, есть инпут на автопереключение или выбор вручную любого варианта.
ИИ нашел замену /1000 для времени в секундах - даст ускорение всем методам.
Вот сравнение замеров:
Aleksei, the idea is worth testing, but the constant is wrong. (x * 4294968) >> 32 stops matching x / 1000 at x = 6,100,999 ms, about 1.7 hours after the block's first tick. Checking every x below 2³², 35% of the values come out wrong. A 50,000-tick EURUSD block covers roughly a day, so many ticks get a time that is off by one second. Verification didn't catch it because neither VerifyBlock nor the benchmark compares the time field. It's worth adding that check: with it, this constant fails immediately.
An exact version costs the same: (x * 274877907) >> 38 gives 0 wrong values across all 2³² inputs, and the product stays below 2⁶⁰. If the offset reaches 2³² ms or goes negative, that tick falls back to the normal division and starts a new base, so the result always equals l_tp / 1000 .
I benchmarked this exact version on 5 symbols (29.8 M ticks), with a Strategy() that reads every tick field so the compiler can't drop the decode work. It brought no gain:
FastAccum: −8% BidAsk, −11% All; on EURUSD and GBPUSD −16…−20%.
OFF and ULP: −3…−5%.
Only Standard gained (+8% BidAsk).
The MQL5 compiler most likely already turns /1000 into a multiply. The extra base variables and branch then add register pressure to loops that already carry a lot of state. Your +4–9% was probably measured with an empty Strategy() , where the compiler can skip some of the work. I'm keeping the plain l_tp / 1000 .
amrali #: Aleksei, the idea is worth testing, but the constant is wrong. (x * 4294968) >> 32 stops matching x / 1000 at x = 6,100,999 ms, about 1.7 hours after
AI has found a replacement for /1000 for time in seconds - it will give a speed boost to all methods.
// Mode for calculating seconds l_tick.time from l_tp (choose ONE or comment out all for standard l_tp / 1000): //#define TimeSecFastMul // 1) Fast multiplication with shift from block start (no idiv and no if, ~3 clock cycles on any CPU) #define TimeSecInc // 2) Incremental millisecond counter l_ms += dt_u with check >= 1000 // 3) If both are commented out -> standard 64-bit division l_tp / 1000 #ifdef TimeSecFastMul
#define TIME_SEC_INIT long base_sec = this .tp / 1000 , base_tp = base_sec * 1000 ;
#define TIME_SEC_STEP(DT)
#define TIME_SEC_SYNC if (( ulong )(l_tp - base_tp) >= 4294967295 UL){ base_sec = l_tp / 1000 ; base_tp = base_sec * 1000 ; }
#define TIME_SEC_GET ( datetime )(base_sec + ( long )((( ulong )(l_tp - base_tp) * 4294968 UL) >> 32 ))
An exact version costs the same: (x * 274877907) >> 38 gives 0 wrong values across all 2³² inputs, and the product stays below 2⁶⁰. If the offset reaches 2³² ms or goes negative, that tick falls back to the normal division and starts a new base, so the result always equals l_tp / 1000 .
This script compresses a symbol's tick history with TickCompressor and reads the stat[] counters (records grouped by size in bytes). For each record type it prints the count, the share of ticks and bytes, and how often it occurs ("1 per N ticks"). It then shows the total size against MqlTick[] , bytes per tick and the compression ratio. It also checks that stat[] adds up to the bytes that Compress() returned. A ZIP option adds the ZIP size and ratio.
TCO_BlockKinds
This script compresses a symbol's tick history with TickCompressor and reads each block's header byte. It shows the share of blocks and ticks that are:
Exact: restored by a plain division;
ULP: restored with a ±1 ULP code;
Plain: everything else.
It also counts the prices that aren't exactly points / 10^digits , since one such price makes its whole block non-exact. In All mode it adds the share of blocks with constant Last and Volume, and the volume flags.
Both work well with TickCompressor v4.31.
Demo:
=======================================================================================
TickCompressor v4.31 BLOCK KINDS | BidAsk mode | Normalization: Exact+ULP (0 ULP)
EURUSD | digits 5 | period 3M (2026.09.05 - 2026.12.03) | blocks of 50,000 ticks
4,664,634 ticks in 94 blocks (avg 49,623 ticks/block)
---------------------------------------------------------------------------------------
Block kind Blocks % blocks Ticks % ticks
Exact (prices) 00.00% 00.00%
ULP (+/-1 ULP code) 94100.00% 4,664,634100.00%
Plain 00.00% 00.00%
---------------------------------------------------------------------------------------
Non-exact 94 blocks (100.00%), 4,664,634 ticks (100.00%)
Prices 387,717 of 9,329,268 inexact (4.16%), in 305,441 ticks (6.55%)
Records 94 blocks (100.00%) use char deltas (4B/8B/5B), the rest short
Size 18,668,650 bytes (17.80 MB) vs MqlTick[] 279,878,040 bytes (266.91 MB)
Per tick 4.002 bytes (MqlTick = 60) -> ratio 14.99 : 1 (6.67%)
=======================================================================================
Сделал переработку архитектуры, для увеличения скорости.
Сначала о результатах
OnTick пустышка показал рост *2 с 605 до 1000+. Но он не актуален.
OnTick с сложением (файлы замеров приложил). Их Анализ от ИИ:
Сводная таблица сравнения v4.58 vs v5.10 (при одинаковом полном расчёте всех 8 полей тика в Strategy ):
1. На Intel Pentium Gold G7400T ( , 8 символов, 148.82 млн тиков):
Режим и метрика
v4.58 (было)
v5.10 (стало)
Прирост v5.10
ULP ADJUST (0 ULP) — Combined Max
223.1 Мт/с
244.6 Мт/с
+9.6%
ULP ADJUST (0 ULP) — BidAsk Max (ср.)
293.8 ( 288.8 )
324.9 ( 320.3 )
+10.6%
ULP ADJUST (0 ULP) — All Max (ср.)
152.4 ( 147.1 )
164.4 ( 161.9 )
+7.9%
EURUSD BidAsk ( 0 ULP , RAM макс)
277.5 Мт/с
314.2 Мт/с
+13.2%
BTCUSD BidAsk ( 0 ULP , RAM макс)
232.7 Мт/с
330.1 Мт/с
+41.9%
OFF (LP*point) — Combined Max
—
258.5 Мт/с
—
EURUSD / GBPUSD BidAsk ( OFF , RAM макс)
286.3 Мт/с
379.8 Мт/с
+32.7%
EURUSD / GBPUSD All ( OFF , RAM макс)
147.0 Мт/с
202.5 Мт/с
+37.8%
2. На 2× Intel Xeon E5-2699 v3 ( , 7 символов, 147.29 млн тиков):
Режим и метрика
v4.58 (было)
v5.10 (стало)
Прирост v5.10
ULP ADJUST (0 ULP) — Combined Max
114.0 Мт/с
134.6 Мт/с
+18.1%
ULP ADJUST (0 ULP) — BidAsk Max (ср.)
135.4 ( 128.9 )
162.4 ( 144.9 )
+19.9%
ULP ADJUST (0 ULP) — All Max (ср.)
92.7 ( 78.1 )
106.8 ( 99.4 )
+15.2%
EURUSD / GBPUSD BidAsk ( 0 ULP , RAM макс)
205.7 Мт/с
250.8 Мт/с
+21.9%
OFF (LP*point) — Combined Max
107.2 Мт/с
144.5 Мт/с
+34.8%
EURUSD / GBPUSD BidAsk ( OFF , RAM макс)
211.0 Мт/с
295.3 Мт/с
+40.0%
EURUSD / GBPUSD All ( OFF , RAM макс)
117.1 Мт/с
154.2 Мт/с
+31.7%
Три главных вывода по этим замерам:
Победа v5.10 по всем без исключения позициям на обоих CPU:
Даже при полной нагрузке в Strategy() (где подсчёт всех 8 полей тика съедает основную долю тактов CPU) v5.10 даёт +10% .. +20% ускорения в режиме 0 ULP и +33% .. +40% в режиме OFF , а на крипте ( BTCUSD ) за счёт выровненного 64-битного слова ulong прирост составляет +41.9% .
Цена точности 0 ULP практически бесплатна:
На Gold G7400T режим ULP ADJUST (0 ULP) сохраняет 94.6% скорости турбо-режима без нормализации ( 244.6 против 258.5 Мт/с ), а на Xeon E5-2699 v3 — 93.1% ( 134.6 против 144.5 Мт/с ), обеспечивая при этом 100% побитовое совпадение котировок с MetaTrader 5 .
Ниже приведено структурированное описание всех ключевых архитектурных и алгоритмических изменений в TickCompressor.mqh при переходе с версии 4.28 к 5.10 .
1. Смена базового формата хранения и буфера ( uchar[] → ulong[] )
Прямой 64-битный буфер ( ulong &m[] ) вместо побайтового ( uchar &m[] ):
Полностью убраны побайтовое чтение, ручная сборка целых чисел из байтов ( ArrToInt2 ) и промежуточное копирование данных.
Дисковые операции ( FileWriteArray / FileReadArray ) и потоковая распаковка работают напрямую с 64-битными словами ulong (8 байт за одну операцию CPU).
Выровненные 16-байтные заголовки ( 2 × ulong ):
И внешний заголовок блока, и внутренний заголовок каждого подблока строго кратны 8 байтам ( m[q] хранит размер полезной нагрузки и количество тиков, m[q+1] — временные метки first_time и last_time ).
2. Архитектура горячих циклов распаковки ( 0 ветвлений if и 0 проверок границ)
Разрыв подблоков при сжатии ( Compress ) вместо исключений 0xFFFF при чтении:
В версии 4.28 при паузах времени dt >= 65535 мс или резких скачках цены/объёма внутрь потока вставлялся маркер 0xFFFF , из-за чего в цикле чтения стояла проверка if(dt_u == 65535) с переменным шагом чтения.
В версии 5.10 компрессор сам закрывает текущий подблок перед любой паузой > 65535 мс, выбросом цены/объёма или достижением лимита L2-кэша ( MaxSubBlockTicks ).
Канонические циклы for для JIT-компилятора MQL5:
За счёт отсутствия исключений внутри подблока цикл while заменён на жёсткий канонический цикл for(int q = body_q; q < end_q; q++) без единого if и без проверок выхода за границы массива.
В режиме BidAsk ( subMode = 1 , 4 байта/тик) за одну итерацию извлекаются сразу 2 тика из одного 64-битного слова ulong qw = m[q] (плюс 1 хвостовой тик после цикла при нечётном количестве).
Все 8 вариантов декодирования (ExactDiv / ULP Adjust × BidAsk / All × узкий / широкий формат) вынесены в изолированные методы класса Dec* , чтобы минимизировать давление на регистры x86-64 и кэш инструкций L1i.
3. Упрощение и ускорение точности восстановления цен ( 0 ULP )
Отказ от медленных и громоздких режимов ( FastAccum , PipsCache , Std ):
Оставлены только 2 оптимальных режима: #define NormalizePricesUlpAdjust (побитовая корректировка ULP Adjust с точностью 0 ULP на 100% инструментов) и турбо-режим LP * point (при закомментированном макросе).
Специализация по Digits ( SW_DIG_1 / SW_DIG_4 ):
Для символов с кратными десятичными ценами ( ExactDiv ) компилятор подставляет константу P10D ( 1.0 .. 1e8 ) во время компиляции, заменяя вызов NormalizeDouble() на одно аппаратное деление.
Исправлена пограничная проверка сегмента при смене точности:
Исключена ситуация, когда внутри одного подблока менялся режим exactP (из-за чего дельта +32 пипса могла выйти за 6-битный диапазон ULP-кода).
4. Двухуровневая иерархия блоков для L2-кэша и диска
Разделение внешнего блока (диск) и внутреннего подблока (CPU L2):
В Start() добавлен параметр maxSubBlockTicks ( MaxSubBlockTicks , по умолчанию 50 000 ).
Внешний вызов Compress() может принимать целый торговый день ( 100 000 – 1 000 000+ тиков) для записи за одну дисковую операцию, а внутри автоматически нарезает его на L2-подблоки оптимального размера, не вытесняющие кэш процессора.
Для авторизации и пользования сайтом MQL5.com необходимо разрешить использование файлов Сookie.
Пожалуйста, включите в вашем браузере данную настройку, иначе вы не сможете авторизоваться.
Вы вошли в аккаунт. Двухфакторная аутентификация отключена. Настройте её заново и отсканируйте новый QR-код или продолжите с отключённой двухфакторной аутентификацией.
Feature - TickCompressor v4.31
All mode: smaller and faster when Last and Volume are constant
Faster wide-record decoding (5+ digit symbols)
What v4.31 changed in All mode (FastAccum, best pure-RAM decode speed):
Benchmark change — the tick handler now uses each tick
Problem: the benchmark's Strategy() was empty. Because MQL5 inlines OnTickDecompressed , the compiler could skip computing prices nobody read.
Fix: Strategy() now reads every field the decoder writes (bid, ask, last, volume_real, volume, time, time_msc, flags) into a checksum, so no decode work can be dropped.
The ranking with a handler that uses each tick:
Feature - TickCompressor v4.31
Сравнил на своем современном компьютере 12 поколения.
Моя текущая версия с только ULP ADJUST (код приложен выше)
Ваша новая версия:
Как видно мой вариант с только ULP ADJUST на 1.3% медленнее вашей аккумуляторной (которая по прежнему в 2+ раза медленнее на старом сервере).
Отключение режима All для форекс символов у меня тоже было, но потом перенес его в MathTicker, чтобы код компрессора был короче и проще. Отключаю там просто по режиму торговли, есть инпут на автопереключение или выбор вручную любого варианта.
ИИ нашел замену /1000 для времени в секундах - даст ускорение всем методам.
Вот сравнение замеров:
Aleksei, the idea is worth testing, but the constant is wrong. (x * 4294968) >> 32 stops matching x / 1000 at x = 6,100,999 ms, about 1.7 hours after
Видимо ИИ сократил для описания.
Замерил в режиме без нормализации. С этой формулой было
Вернул /1000 и стало:
Разница 0.5 - 1%. Пожалуй тоже оставлю надежное и понятное /1000
Forum on trading, automated trading systems, and trading strategy testing
Libraries: TickCompressor - with compression of 1 tick to 2-3 bytes on average
Aleksei Kuznetsov , 2026.12.04 14:07
AI has found a replacement for /1000 for time in seconds - it will give a speed boost to all methods.
An exact version costs the same: (x * 274877907) >> 38 gives 0 wrong values across all 2³² inputs, and the product stays below 2⁶⁰. If the offset reaches 2³² ms or goes negative, that tick falls back to the normal division and starts a new base, so the result always equals l_tp / 1000 .
A. Modify verify() to detect the error:
TCO_RecordStats
This script compresses a symbol's tick history with TickCompressor and reads the stat[] counters (records grouped by size in bytes). For each record type it prints the count, the share of ticks and bytes, and how often it occurs ("1 per N ticks"). It then shows the total size against MqlTick[] , bytes per tick and the compression ratio. It also checks that stat[] adds up to the bytes that Compress() returned. A ZIP option adds the ZIP size and ratio.
TCO_BlockKinds
This script compresses a symbol's tick history with TickCompressor and reads each block's header byte. It shows the share of blocks and ticks that are:
It also counts the prices that aren't exactly points / 10^digits , since one such price makes its whole block non-exact. In All mode it adds the share of blocks with constant Last and Volume, and the volume flags.
Both work well with TickCompressor v4.31.
Demo:
B. Also, use with a Strategy() that reads every tick field so the compiler can't drop the decode work.
Сделал переработку архитектуры, для увеличения скорости.
Сначала о результатах
OnTick пустышка показал рост *2 с 605 до 1000+. Но он не актуален.
OnTick с сложением (файлы замеров приложил).
Их Анализ от ИИ:
И описание.