Add Per-Request Latency & Cycle Time Metrics to a Trading Bot
In this article
Adding per-request latency and cycle time metrics to a trading bot gives you a precise view of how fast your bot reacts to market data and how long each full trading cycle takes. This helps you spot slow exchanges, network issues, or bottlenecks in your own code before they cost you money. You'll need a trading bot that already sends requests (REST or WebSocket) and a place to store or log numeric values—a simple in-memory list, a database, or a monitoring service like Prometheus will work.
What You'll Need
- A trading bot with identifiable request and response points (e.g., an order placement function, a price fetch function).
- Access to the bot's codebase (Python, JavaScript, C++, etc.).
- A way to record timestamps with millisecond or microsecond precision (most languages have a built-in high-resolution timer).
- Optional: a metrics library (e.g., Prometheus client, StatsD) or a simple log file.
Step-by-Step
- Define what you're measuring. Per-request latency is the time from when your bot sends a request (e.g., an HTTP POST to place an order) to when it receives the response. Cycle time is the total time for one complete bot loop: reading market data, making a decision, executing a trade, and updating state. Decide whether you want to measure both separately or just one.
- Pick a time source. Use a monotonic clock that isn't affected by system time changes. In Python, that's
time.perf_counter(); in Node.js,process.hrtime.bigint(); in C++,std::chrono::steady_clock. Avoid wall-clock time for duration measurements. - Instrument the request path. Wrap each outgoing request (REST call or WebSocket message) with a start timestamp before sending and an end timestamp after receiving the response. Compute the difference and store it as the latency for that request.
- Instrument the cycle loop. At the start of your bot's main loop (e.g., before fetching new market data), record a cycle start time. At the end of the loop (after all processing and any sleeps), record the cycle end time. The difference is your cycle time.
- Store the metrics. For each measurement, push it into a rolling buffer (e.g., a deque with a max length of 1000) or send it to a metrics system. If you're using Prometheus, create a Histogram or Summary metric. For a simple log, print or write the values with a timestamp.
- Aggregate and expose. Compute running averages, percentiles (p50, p95, p99), and max values. If you're logging, you can calculate these after the fact. If you're using a monitoring system, it will handle aggregation for you.
- Add a health check or alert. Set thresholds—for example, alert if p95 latency exceeds 500ms or if cycle time exceeds 2 seconds. This turns raw metrics into actionable signals.
- Test with live data. Run your bot in a sandbox or paper trading mode first. Verify that the metrics are being recorded correctly and that the overhead of measuring doesn't itself slow down the bot (measurement overhead is usually negligible, but check).
Common Mistakes
- Using wall-clock time instead of a monotonic clock. System time can jump forward or backward (NTP sync, manual changes), giving you negative or wildly inflated durations.
- Measuring only the network call, not the full request. If your request includes serialization, signing, or retries, include those in your latency measurement—otherwise you're missing real delays.
- Not accounting for asynchronous code. In async frameworks, a simple start/end around an
awaitmay not capture the actual wait time if you're not careful. Use the library's built-in timing or wrap the entire coroutine. - Ignoring clock precision. Some languages' timers have millisecond resolution, which is too coarse for sub-millisecond latencies. Use a high-resolution timer.
- Recording every request without sampling. If your bot makes thousands of requests per second, storing every single one can bloat memory. Use a fixed-size buffer or sample.
Tips
- Start with the two most important metrics: average latency and p99 latency. Average hides outliers; p99 shows the worst case.
- Log the timestamp of each measurement so you can correlate latency spikes with market events or code deployments.
- Use a histogram in your metrics system to avoid storing raw data points indefinitely.
- Measure both the time to receive a response and the time to process it (e.g., parsing, validation). This separates network issues from CPU issues.
- If you're using WebSockets, measure the time between sending a message and receiving a matching response—this is true round-trip latency.
Troubleshooting
- Metrics are all zero or negative. Check that you're using a monotonic clock and that you're computing the difference correctly (end - start). If using
perf_counter(), it returns seconds as a float—make sure you're not mixing units. - Latency seems too high. You might be including retries or queue wait time. Verify that your start timestamp is placed right before the actual send, not earlier in the function. Also check if your logging or metrics collection is adding overhead.
- Cycle time is inconsistent. This can be normal if your bot has variable sleep times or if market data arrives irregularly. Look at the distribution, not just the average.
- Metrics aren't being recorded at all. Ensure the code path is actually being executed. Add a debug print to verify. Also check that your buffer or logging is thread-safe if you're using multiple threads.
- Memory grows unbounded. If you're storing raw measurements, cap the buffer size or switch to a streaming aggregation like a histogram.
Frequently Asked Questions
What's the difference between latency and cycle time?
Latency measures the time for a single request-response pair (e.g., placing an order). Cycle time measures the entire loop of your bot—from fetching data to executing actions—which includes multiple requests and processing time.
Do I need a monitoring service like Prometheus?
No. For a small bot, logging to a file and analyzing with a script is enough. For production bots with many instances, a monitoring service helps aggregate and alert.
How often should I sample latency?
Every request is ideal, but if that's too much, sample at least 1% or every Nth request. For cycle time, measure every cycle—it's usually low frequency.
Can I measure latency for WebSocket messages the same way?
Yes, but you need to match a sent message to its response. Use a unique ID in the message and track the timestamp when the response with that ID arrives.
What's a good latency threshold for a trading bot?
It depends on your strategy. High-frequency strategies may need sub-10ms; others can tolerate 100ms+. Start by measuring your current baseline, then set alerts at 2x your typical p95.
Will adding metrics slow down my bot?
Minimally. Reading a high-resolution timer and computing a difference is nanoseconds. Storing or sending metrics can add overhead, so batch or sample if needed.