algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
rate_limit.hpp
1#pragma once
2
8#define ATL_TRANSPORT_LAYER_PRESENT 1
9
11
12#include <array>
13#include <chrono>
14#include <cstddef>
15#include <cstdint>
16#include <stdexcept>
17#include <string_view>
18
19namespace algotradelib {
20namespace network {
21
41
50
60inline constexpr int rate_limit_priority(RateLimitGroup group) noexcept {
61 switch (group) {
63 return 50;
65 return 40;
67 return 30;
69 return 20;
71 return 10;
72 }
73 return 0;
74}
75
81inline constexpr std::string_view rate_limit_group_name(RateLimitGroup group) noexcept {
82 switch (group) {
84 return "auth";
86 return "trading";
88 return "account";
90 return "market_data";
92 return "reference";
93 }
94 return "";
95}
96
97static_assert(
100 [](RateLimitGroup group) {
101 return !rate_limit_group_name(group).empty();
102 }
103 ),
104 "all_rate_limit_groups must list every RateLimitGroup"
105);
106
108inline constexpr std::size_t rate_limit_group_count = all_rate_limit_groups.size();
109
115inline constexpr std::size_t rate_limit_group_index(RateLimitGroup group) noexcept {
116 return static_cast<std::size_t>(group);
117}
118
129 int burst_{8};
138};
139
146inline constexpr int usable_burst(const RateLimitBudget& budget, RateLimitGroup group) noexcept {
147 switch (group) {
148 // An order, and the token it needs, may use the reserve.
151 return budget.burst_;
155 break;
156 }
157 const int reserved = budget.burst_ - budget.trading_reserve_;
158 return reserved > 0 ? reserved : 1;
159}
160
171template <typename Clock = std::chrono::steady_clock>
173public:
175 using ClockType = Clock;
176
178 using TimePoint = typename Clock::time_point;
179
181 using Duration = std::chrono::nanoseconds;
182
192
198 explicit BasicRateLimitBucket(const RateLimitBudget& budget)
199 : BasicRateLimitBucket(budget.burst_, budget.per_second_) {}
200
207 void resize(int burst, int per_second) {
208 if (burst < 1) {
209 throw std::invalid_argument("rate limit burst must be at least one request");
210 }
211 if (per_second < 1) {
212 throw std::invalid_argument("rate limit rate must be at least one request per second");
213 }
214 burst_ = burst;
215 per_second_ = per_second;
216 interval_ = Duration(std::chrono::nanoseconds(std::chrono::seconds(1)).count() / per_second);
217 }
218
225 Duration delay_until(TimePoint now, int allowance) const {
226 if (!started_) {
227 return Duration::zero();
228 }
229 const auto earliest = schedule_ - tolerance(allowance);
230 if (now >= earliest) {
231 return Duration::zero();
232 }
233 return std::chrono::duration_cast<Duration>(earliest - now);
234 }
235
242 bool ready(TimePoint now, int allowance) const {
243 return delay_until(now, allowance) == Duration::zero();
244 }
245
253 bool try_acquire(TimePoint now, int allowance) {
254 if (!ready(now, allowance)) {
255 return false;
256 }
257 if (!started_) {
258 schedule_ = now + interval_;
259 started_ = true;
260 return true;
261 }
262 schedule_ = (schedule_ > now ? schedule_ : now) + interval_;
263 return true;
264 }
265
275 void cool_down(TimePoint now, Duration duration) {
276 if (duration < Duration::zero()) {
277 duration = Duration::zero();
278 }
279 const auto held = now + duration + tolerance(burst_);
280 if (!started_ || held > schedule_) {
281 schedule_ = held;
282 started_ = true;
283 }
284 }
285
294 void observe_limit(TimePoint now, int burst, int per_second, Duration refill) {
296 cool_down(now, refill > Duration::zero() ? refill : interval_);
297 }
298
305 int available(TimePoint now, int allowance) const {
306 if (!started_) {
307 return allowance;
308 }
309 const auto earliest = schedule_ - tolerance(allowance);
310 if (now < earliest) {
311 return 0;
312 }
313 const auto spare = std::chrono::duration_cast<Duration>(now - earliest);
314 const auto slots = spare / interval_ + 1;
315 return slots > allowance ? allowance : static_cast<int>(slots);
316 }
317
322 int burst() const noexcept {
323 return burst_;
324 }
325
330 int per_second() const noexcept {
331 return per_second_;
332 }
333
338 Duration interval() const noexcept {
339 return interval_;
340 }
341
342private:
343 // Returns how far ahead of now the schedule may run for `allowance`.
344 Duration tolerance(int allowance) const noexcept {
345 const int slots = allowance < 1 ? 1 : (allowance > burst_ ? burst_ : allowance);
346 return interval_ * (slots - 1);
347 }
348
349 int burst_{1};
350 int per_second_{1};
351 Duration interval_{std::chrono::seconds(1)};
352 TimePoint schedule_{};
353 bool started_{false};
354};
355
358
362 std::uint64_t admitted_{0};
364 std::uint64_t delayed_{0};
366 std::uint64_t shed_{0};
368 std::chrono::nanoseconds waited_{0};
369};
370
405
414public:
417
423 explicit RateLimitController(RateLimitBudget budget = {}) : budget_(budget), bucket_(budget) {
424 stats_.burst_ = budget.burst_;
426 }
427
434 return bucket_.delay_until(RateLimitBucket::ClockType::now(), usable_burst(budget_, group));
435 }
436
443 const auto now = RateLimitBucket::ClockType::now();
444 if (!bucket_.try_acquire(now, usable_burst(budget_, group))) {
445 return false;
446 }
447 ++stats_.group(group).admitted_;
448 stats_.available_ = bucket_.available(now, usable_burst(budget_, group));
449 return true;
450 }
451
458 auto& counters = stats_.group(group);
459 ++counters.delayed_;
460 counters.waited_ += waited;
461 }
462
468 ++stats_.group(group).shed_;
469 }
470
479 void hold(Duration duration) {
480 ++stats_.broker_rejections_;
481 bucket_.cool_down(RateLimitBucket::ClockType::now(), duration);
482 }
483
494 void shrink(int burst, int per_second, Duration retry) {
495 // The bucket validates first, so a refused figure leaves the reported budget the one in force.
496 bucket_.observe_limit(RateLimitBucket::ClockType::now(), burst, per_second, retry);
497 ++stats_.broker_rejections_;
498 apply_budget(burst, per_second);
499 }
500
505 const RateLimitBudget& budget() const noexcept {
506 return budget_;
507 }
508
513 const RateLimitStats& stats() const noexcept {
514 return stats_;
515 }
516
517private:
518 // Records a new allowance, keeping the reserve smaller than the burst.
519 void apply_budget(int burst, int per_second) {
520 budget_.burst_ = burst;
521 budget_.per_second_ = per_second;
522 if (budget_.trading_reserve_ >= burst) {
523 budget_.trading_reserve_ = burst > 1 ? burst - 1 : 0;
524 }
525 stats_.burst_ = burst;
526 stats_.per_second_ = per_second;
527 }
528
529 RateLimitBudget budget_;
530 RateLimitBucket bucket_;
531 RateLimitStats stats_{};
532};
533
534} // namespace network
535} // namespace algotradelib
A rate limiter (the generic cell rate algorithm) that computes when a request may go; it neither wait...
void observe_limit(TimePoint now, int burst, int per_second, Duration refill)
Adopts a burst and rate the broker reported, then holds requests until it refills.
int available(TimePoint now, int allowance) const
Returns how many requests could go back to back now.
Duration interval() const noexcept
Returns the spacing of the sustained rate.
std::chrono::nanoseconds Duration
The duration type of all results.
void cool_down(TimePoint now, Duration duration)
Holds every request for at least a duration (for a broker refusal that is not this client's pacing fa...
typename Clock::time_point TimePoint
The clock's instant type.
int burst() const noexcept
Returns the burst.
BasicRateLimitBucket(const RateLimitBudget &budget)
Constructs a bucket from a budget's burst and rate.
BasicRateLimitBucket(int burst, int per_second)
Constructs a bucket.
Duration delay_until(TimePoint now, int allowance) const
Returns how long a request must wait.
void resize(int burst, int per_second)
Changes the burst and rate, keeping the current schedule.
bool try_acquire(TimePoint now, int allowance)
Admits one request if it may go now.
int per_second() const noexcept
Returns the sustained rate.
bool ready(TimePoint now, int allowance) const
Tests whether a request may go now.
Duration delay_until(RateLimitGroup group) const
Returns how long a request of a class must wait.
const RateLimitBudget & budget() const noexcept
Returns the budget in force.
bool acquire(RateLimitGroup group)
Admits one request of a class if it may go now, and counts it.
void shrink(int burst, int per_second, Duration retry)
Counts a broker refusal, adopts the burst and rate the broker reported, and holds.
RateLimitController(RateLimitBudget budget={})
Constructs a controller.
RateLimitBucket::Duration Duration
The duration type.
const RateLimitStats & stats() const noexcept
Returns the counters.
void record_shed(RateLimitGroup group)
Records that a request was refused unsent.
void record_delay(RateLimitGroup group, Duration waited)
Records that a request waited before admission.
void hold(Duration duration)
Counts a broker refusal and holds every request for a duration, keeping the budget.
A compile-time check that a list names every value of an enum, and a parser over the list.
HTTP and WebSocket transport, OAuth tokens, and request pacing.
RateLimitGroup
The traffic class of a request, for rate limiting and queue priority. The broker adapter that builds ...
@ MARKET_DATA
Quotes, bars, order book and trades.
@ ACCOUNT
Holdings, working orders, order history and buying power.
@ TRADING
Order placement, amendment and cancellation. HttpClientOptions::fresh_connection_for_orders_ applies ...
@ REFERENCE
Instrument reference data and trading calendars.
@ AUTH
Access-token issue and refresh.
constexpr int rate_limit_priority(RateLimitGroup group) noexcept
Returns a traffic class's queue priority.
constexpr int usable_burst(const RateLimitBudget &budget, RateLimitGroup group) noexcept
Returns how much of the burst a traffic class may use.
constexpr std::array< RateLimitGroup, 5 > all_rate_limit_groups
Every RateLimitGroup, in declaration order.
constexpr std::size_t rate_limit_group_index(RateLimitGroup group) noexcept
Returns a traffic class's index, for per-class arrays.
constexpr std::size_t rate_limit_group_count
The number of traffic classes.
BasicRateLimitBucket<> RateLimitBucket
A rate-limit bucket on the steady clock.
constexpr std::string_view rate_limit_group_name(RateLimitGroup group) noexcept
Returns a lowercase name for a traffic class, such as "market_data", for logs.
The library: broker-neutral types (core), and the modules below.
constexpr bool lists_every_value(const std::array< Enum, N > &values, IsEnumerator is_enumerator) noexcept
Tests whether a list holds every value of an enum exactly once, in any order.
The request rate a connection may use.
int trading_reserve_
The part of burst_ only AUTH and TRADING requests may use, so polling cannot use up the capacity an o...
int per_second_
The sustained rate, in requests per second; at least 1.
int burst_
How many requests may be sent back to back after an idle period; at least 1.
A rate limiter's counters for one traffic class.
std::uint64_t delayed_
Admitted requests that had to wait first (on a polling class, often the trading reserve at work).
std::chrono::nanoseconds waited_
Total time admitted requests waited.
std::uint64_t admitted_
Requests admitted.
std::uint64_t shed_
Requests refused locally: the queue was full, or the wait would have exceeded the timeout.
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...
std::uint64_t broker_rejections_
How many rate-limit refusals the broker sent; if it keeps rising, lower the budget.
RateLimitGroupStats groups_[rate_limit_group_count]
The counters per traffic class; read them with group().
int per_second_
The sustained rate in force.
const RateLimitGroupStats & group(RateLimitGroup value) const
Returns the counters for one traffic class.
int available_
How much of the burst was unspent just after the last admitted request (for that request's class); no...
RateLimitGroupStats & group(RateLimitGroup value)
Returns the counters for one traffic class.