Run this benchmark

If you can, run this benchmark indicator and paste console output along with NT version (CPU/SSD if available) in this thread. It would be interesting to see if numbers vary, and by how much, from system to system and NT version.

[TickScanBenchmarkV1] Ready. Ticks loaded so far: 12,315,904
[TickScanBenchmarkV1] Click chart, press Ctrl+Shift+B to run.
[TickScanBenchmarkV1] NinjaTrader: 8.1.7.2

[TickScanBenchmarkV1] MES  tick=0.25  calc=OnBarClose
[TickScanBenchmarkV1] secondary series ticks loaded=12,315,966
[TickScanBenchmarkV1] --- raw read only ---
[TickScanBenchmarkV1] raw read   N=      1,000
[TickScanBenchmarkV1]   elapsed=     0.09ms  rate=  10,822,511/s
[TickScanBenchmarkV1]   60fps budget=   180,375/frame
[TickScanBenchmarkV1] raw read   N=      5,000
[TickScanBenchmarkV1]   elapsed=     0.47ms  rate=  10,622,477/s
[TickScanBenchmarkV1]   60fps budget=   177,041/frame
[TickScanBenchmarkV1] raw read   N=     20,000
[TickScanBenchmarkV1]   elapsed=     1.88ms  rate=  10,642,260/s
[TickScanBenchmarkV1]   60fps budget=   177,371/frame
[TickScanBenchmarkV1] raw read   N=    100,000
[TickScanBenchmarkV1]   elapsed=     9.61ms  rate=  10,401,173/s
[TickScanBenchmarkV1]   60fps budget=   173,353/frame
[TickScanBenchmarkV1] raw read   N=    500,000
[TickScanBenchmarkV1]   elapsed=    49.19ms  rate=  10,164,895/s
[TickScanBenchmarkV1]   60fps budget=   169,415/frame
[TickScanBenchmarkV1] raw read   N=  1,000,000
[TickScanBenchmarkV1]   elapsed=    98.86ms  rate=  10,115,570/s
[TickScanBenchmarkV1]   60fps budget=   168,593/frame
[TickScanBenchmarkV1] --- with accumulation (dict insert) ---
[TickScanBenchmarkV1] with accum N=      1,000
[TickScanBenchmarkV1]   elapsed=     0.11ms  rate=   8,936,550/s
[TickScanBenchmarkV1]   60fps budget=   148,943/frame  levels=   21
[TickScanBenchmarkV1] with accum N=      5,000
[TickScanBenchmarkV1]   elapsed=     0.55ms  rate=   9,028,530/s
[TickScanBenchmarkV1]   60fps budget=   150,476/frame  levels=   40
[TickScanBenchmarkV1] with accum N=     20,000
[TickScanBenchmarkV1]   elapsed=     2.22ms  rate=   9,006,575/s
[TickScanBenchmarkV1]   60fps budget=   150,110/frame  levels=  100
[TickScanBenchmarkV1] with accum N=    100,000
[TickScanBenchmarkV1]   elapsed=    11.16ms  rate=   8,957,523/s
[TickScanBenchmarkV1]   60fps budget=   149,292/frame  levels=  216
[TickScanBenchmarkV1] with accum N=    500,000
[TickScanBenchmarkV1]   elapsed=    55.67ms  rate=   8,981,385/s
[TickScanBenchmarkV1]   60fps budget=   149,690/frame  levels=  237
[TickScanBenchmarkV1] with accum N=  1,000,000
[TickScanBenchmarkV1]   elapsed=   111.52ms  rate=   8,966,969/s
[TickScanBenchmarkV1]   60fps budget=   149,449/frame  levels=  237
[TickScanBenchmarkV1] --- full available range ---
[TickScanBenchmarkV1] with accum N= 12,315,966
[TickScanBenchmarkV1]   elapsed=  1409.03ms  rate=   8,740,730/s
[TickScanBenchmarkV1]   60fps budget=   145,679/frame  levels=2,056
[TickScanBenchmarkV1] Done. Press Ctrl+Shift+B again to re-run.

Benchmark code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;

using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.DrawingTools;

namespace NinjaTrader.NinjaScript.Indicators
{
    /// <summary>
    /// TickScanBenchmarkV1 — standalone diagnostic. NOT a real feature; throwaway tool to measure
    /// how many ticks/sec can realistically be scanned out of the secondary tick series
    /// (BarsArray[1] on demand —
    /// which is exactly the operation a live mouse-driven trade-size threshold would need to
    /// perform on every rebuild.
    ///
    /// HOW TO USE:
    ///   1. Add to a chart with enough loaded history to be representative (a full session, or
    ///      however much you'd expect a Region Profile to span).
    ///   2. Wait for "[TickScanBenchmarkV1] Ready." to print in the Output window — this confirms
    ///      historical load finished and the indicator reached State.Realtime. If you never see
    ///      this line, the historical tick load itself hasn't completed yet; that's useful
    ///      information on its own (a session-wide Infinite-lookback tick load can take a while).
    ///   3. Click on the chart to give it focus, then press Ctrl+Shift+B to run the benchmark.
    ///      Runs synchronously against whatever history is already loaded — no reconfigure, no
    ///      reload, so it's safe to press repeatedly to re-test (e.g. after more history loads).
    ///   4. Results print to the NinjaScript Output window (Output tab / New > NinjaScript Output).
    ///
    /// Deliberately keyboard-triggered rather than a [NinjaScriptProperty] toggle: changing a
    /// NinjaScriptProperty on a live chart forces a full historical reprocess before anything runs
    /// again, which (a) is slow to iterate on and (b) can look exactly like "no output" while it's
    /// silently reloading. A keypress runs immediately against already-loaded data instead.
    ///
    /// WHAT IT MEASURES, per sample size N (the most recent N ticks in the loaded secondary
    /// series):
    ///   - "raw read"   pass: just the four NT accessor calls (GetClose/GetVolume/GetAsk/GetBid)
    ///                  plus the same buy/sell classification arithmetic OnBarUpdate already does.
    ///                  No accumulation — isolates NT's own per-tick accessor cost.
    ///   - "with accum" pass: the same reads PLUS a Dictionary&lt;long,PriceLevel&gt; insert per
    ///                  tick — i.e. the full cost a live BuildFromSecondarySeries rebuild would
    ///                  actually pay. This is the number that matters for the debounce/quantization
    ///                  design; "raw read" is only there to show how much of the cost is NT's
    ///                  accessors vs. our own accumulation.
    ///
    /// A short untimed warmup pass runs first (over a small slice) to get past JIT warmup before
    /// any timed measurement, so the printed numbers reflect steady-state cost, not first-call cost.
    /// </summary>
    public class TickScanBenchmarkV1 : Indicator
    {
        private struct PriceLevel
        {
            public long Buy;
            public long Sell;
        }

        // Sample sizes to test, in ticks. Filtered down to whatever's actually available at run
        // time — e.g. on a thin instrument or short session you may only see the smaller ones.
        private static readonly int[] SampleSizes = { 1_000, 5_000, 20_000, 100_000, 500_000, 1_000_000 };

        private double cachedTickSize;
        private bool   readyPrinted;

        // UI/render-thread-only hotkey subscription — same subscribe-once-in-OnRender pattern
        // SwingVPreplyV4 uses for its scrub-to-cursor mouse handlers. No locking needed: WPF key
        // events and OnRender both run on the UI/render thread.
        private ChartControl hotkeyChartControl;
        private bool         hotkeySubscribed;

        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
				MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
                Name             = "TickScanBenchmarkV1";
                Description      = "Diagnostic only: press Ctrl+Shift+B on the chart (after 'Ready' " +
                                   "prints) to measure secondary-tick-series scan throughput. Not a " +
                                   "trading tool. See class doc comment for usage.";
                IsChartOnly      = true;
                IsOverlay        = true;
                DisplayInDataBox = false;
            }
            else if (State == State.Configure)
            {
                AddDataSeries(BarsPeriodType.Tick, 1);

                cachedTickSize = 0;
                readyPrinted   = false;
            }
            else if (State == State.DataLoaded)
            {
                if (Instrument != null) cachedTickSize = Instrument.MasterInstrument.TickSize;
            }
            else if (State == State.Realtime)
            {
                // Fires exactly once, right after historical processing finishes — independent of
                // whether any new bar/tick has arrived yet. This is the reliable "we're ready"
                // signal; if you never see this print, historical load hasn't completed.
                int available = BarsArray[1]?.Count ?? 0;
                Print($"[TickScanBenchmarkV1] Ready. Ticks loaded so far: {available:N0}");
                Print("[TickScanBenchmarkV1] Click chart, press Ctrl+Shift+B to run.");
				Print("[TickScanBenchmarkV1] NinjaTrader: " + NinjaTrader.Core.Globals.ProductVersion);
                readyPrinted = true;
            }
            else if (State == State.Terminated)
            {
                if (hotkeySubscribed && hotkeyChartControl != null)
                    hotkeyChartControl.KeyDown -= OnHotkeyDown;
                hotkeySubscribed   = false;
                hotkeyChartControl = null;
            }
        }

        protected override void OnBarUpdate()
        {
            // No per-bar work needed — the benchmark is entirely hotkey-driven (see OnHotkeyDown)
            // so it runs on demand against whatever's already loaded, rather than waiting on the
            // next primary-series OnBarUpdate call.
        }

        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
        {
            if (!hotkeySubscribed && chartControl != null)
            {
                chartControl.KeyDown += OnHotkeyDown;
                hotkeyChartControl    = chartControl;
                hotkeySubscribed      = true;
            }

            // No drawing — this indicator is purely a diagnostic; OnRender exists only to obtain
            // the ChartControl reference above, the same way SwingVPreplyV4's scrub-to-cursor does.
        }

        private void OnHotkeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            bool ctrlShiftB = e.Key == System.Windows.Input.Key.B
                              && System.Windows.Input.Keyboard.Modifiers.HasFlag(System.Windows.Input.ModifierKeys.Control)
                              && System.Windows.Input.Keyboard.Modifiers.HasFlag(System.Windows.Input.ModifierKeys.Shift);
            if (!ctrlShiftB) return;

            if (!readyPrinted)
            {
                Print("[TickScanBenchmarkV1] Not ready — waiting for 'Ready' message.");
                return;
            }
            if (cachedTickSize <= 0)
            {
                Print("[TickScanBenchmarkV1] TickSize not ready — try again shortly.");
                return;
            }

            RunBenchmark();
        }

        private void RunBenchmark()
        {
            var secondary = BarsArray[1];
            int total = secondary?.Count ?? 0;

            Print("============================================================");
            Print($"[TickScanBenchmarkV1] {Instrument?.MasterInstrument?.Name}  tick={cachedTickSize}  calc={Calculate}");
            Print($"[TickScanBenchmarkV1] secondary series ticks loaded={total:N0}");

            if (total < 100)
            {
                Print("[TickScanBenchmarkV1] Not enough history loaded yet (need 100+ ticks).");
                return;
            }

            // Untimed warmup: run the full read+accum loop once over a small slice so JIT/tiering
            // costs land here, not in the first timed measurement below.
            RunPass(secondary, Math.Max(0, total - 2000), Math.Min(2000, total), withAccum: true, warmup: true);

            Print("[TickScanBenchmarkV1] --- raw read only ---");
            foreach (int n in SampleSizes)
            {
                if (n > total) continue;
                RunPass(secondary, total - n, n, withAccum: false, warmup: false);
            }

            Print("[TickScanBenchmarkV1] --- with accumulation (dict insert) ---");
            foreach (int n in SampleSizes)
            {
                if (n > total) continue;
                RunPass(secondary, total - n, n, withAccum: true, warmup: false);
            }

            // Always include one pass over everything actually available, even if it doesn't match
            // one of the fixed SampleSizes — this is the realistic "whole session" worst case.
            if (Array.IndexOf(SampleSizes, total) < 0)
            {
                Print("[TickScanBenchmarkV1] --- full available range ---");
                RunPass(secondary, 0, total, withAccum: true, warmup: false);
            }

            Print("[TickScanBenchmarkV1] Done. Press Ctrl+Shift+B again to re-run.");
            Print("============================================================");
        }

        /// <summary>Scans ticks [startIdx, startIdx+count) from the secondary series, optionally
        /// accumulating into a Dictionary the same way SwingVPreplyV4's BarLevels/OpenZoneAccumulator
        /// would. Prints elapsed time and derived ticks/sec unless this is the untimed warmup pass.</summary>
        private void RunPass(Bars secondary, int startIdx, int count, bool withAccum, bool warmup)
        {
            if (count <= 0) return;

            var dict = withAccum ? new Dictionary<long, PriceLevel>() : null;

            var sw = warmup ? null : Stopwatch.StartNew();

            int endIdxExclusive = startIdx + count;
            for (int i = startIdx; i < endIdxExclusive; i++)
            {
                double price  = secondary.GetClose(i);
                long   volume = (long)secondary.GetVolume(i);
                if (volume <= 0) continue;

                double ask = secondary.GetAsk(i);
                double bid = secondary.GetBid(i);

                long buyVol, sellVol;
                if (ask > 0 && bid > 0 && bid < ask)
                {
                    buyVol  = price >= ask ? volume : 0;
                    sellVol = price <= bid ? volume : 0;
                }
                else
                {
                    buyVol  = volume / 2;
                    sellVol = volume - buyVol;
                }

                if (dict != null)
                {
                    long tickIndex = (long)Math.Round(price / cachedTickSize);
                    dict.TryGetValue(tickIndex, out var lvl);
                    dict[tickIndex] = new PriceLevel { Buy = lvl.Buy + buyVol, Sell = lvl.Sell + sellVol };
                }
            }

            if (warmup) return;

            sw.Stop();
            double ms          = sw.Elapsed.TotalMilliseconds;
            double ticksPerSec = ms > 0 ? count / (ms / 1000.0) : double.PositiveInfinity;
            double budgetTicks = ms > 0 ? (1000.0 / 60.0) / ms * count : double.PositiveInfinity;
            string label       = withAccum ? "with accum" : "raw read  ";

            // Kept short and split across a few lines rather than one long line: the NT Output
            // window wraps/truncates well before 100 chars, so a single combined-fields line reads
            // badly. Each line here stays comfortably under ~70 chars even at worst-case (7-8
            // digit) values.
            Print($"[TickScanBenchmarkV1] {label} N={count,11:N0}");
            Print($"[TickScanBenchmarkV1]   elapsed={ms,9:F2}ms  rate={ticksPerSec,12:N0}/s");
            string levelsSuffix = dict != null ? $"  levels={dict.Count,5:N0}" : "";
            Print($"[TickScanBenchmarkV1]   60fps budget={budgetTicks,10:N0}/frame{levelsSuffix}");
        }
    }
}

NIce ,are you trying to see how far you can go without crashing or freezing?

This particular benchmark helps to determine how many ticks can be processed in OnRender w/o visible UI freezing/stutter. Knowing the the budget, ticks can be processed in blocks to keep rendering smooth.

2 Likes