28#include "fastmm/core/spin_mutex.hpp"
48 std::uint32_t
limit = 0;
59 std::uint32_t
bulk = 0;
62 [[nodiscard]] std::int64_t
aligned_start(std::int64_t now)
const noexcept {
66 void roll(std::int64_t now)
noexcept {
75 void realign(std::int64_t off, std::int64_t now)
noexcept {
84 [[nodiscard]]
bool would_exceed(std::uint32_t add,
double threshold)
const noexcept {
85 if (
limit == 0)
return false;
86 return static_cast<double>(
used + add) >
static_cast<double>(
limit) * threshold;
89 [[nodiscard]]
bool bulk_would_exceed(std::uint32_t add,
double threshold)
const noexcept {
90 if (
limit == 0)
return false;
91 return static_cast<double>(
bulk + add) >
static_cast<double>(
limit) * threshold;
99 std::int64_t lag)
noexcept {
102 used = std::clamp(
used, count, count + recent);
109 static constexpr std::size_t
kSlots = 32;
110 static constexpr std::int64_t
kSlotNs = 125'000'000;
111 void add(std::uint32_t n, std::int64_t now)
noexcept {
113 Slot& s = slots_[
static_cast<std::size_t
>(t) %
kSlots];
114 if (s.t != t) s = Slot{t, 0};
118 [[nodiscard]] std::uint32_t
since(std::int64_t now, std::int64_t lag)
const noexcept {
119 const std::int64_t from = (now - lag) /
kSlotNs - 1;
120 std::uint32_t sum = 0;
121 for (
const Slot& s : slots_) {
122 if (s.t >= from && s.t <= now /
kSlotNs) sum += s.n;
132 std::array<Slot, kSlots> slots_{};
164 static constexpr std::int64_t
kHeaderLagNs = 2'000'000'000;
170 void share_ip(std::shared_ptr<SharedRate> ip)
noexcept;
174 if (ip_)
return ip_add_weight_bucket(limit, window_ns);
175 return add(weight_, limit, window_ns, offset_);
177 bool add_order_bucket(std::uint32_t limit, std::int64_t window_ns)
noexcept {
178 return add(orders_, limit, window_ns, offset_);
183 bool set_order_limit(std::uint32_t limit, std::int64_t window_ns)
noexcept {
185 if (!b.active || b.window_ns != window_ns)
continue;
186 if (b.limit == limit)
return false;
190 return add(orders_, limit, window_ns, offset_);
194 void set_clock_offset(std::int64_t venue_minus_local_ns, std::int64_t now)
noexcept;
195 void set_threshold(
double t)
noexcept { threshold_ = std::clamp(t, 0.0, 1.0); }
198 void set_order_threshold(
double t)
noexcept { order_threshold_ = std::clamp(t, 0.0, 1.0); }
199 [[nodiscard]]
double order_threshold() const noexcept {
return order_threshold_; }
201 [[nodiscard]]
double threshold() const noexcept {
return threshold_; }
204 [[nodiscard]] std::int64_t
cap_of(std::uint32_t limit)
const noexcept {
205 return static_cast<std::int64_t
>(std::floor(
static_cast<double>(limit) * threshold_));
208 [[nodiscard]] std::int64_t
order_cap_of(std::uint32_t limit)
const noexcept {
209 return static_cast<std::int64_t
>(std::floor(
static_cast<double>(limit) * order_threshold_));
215 [[nodiscard]]
bool can_send(std::uint32_t weight,
217 bool is_order =
false,
218 double share = 1.0) noexcept {
219 return check(weight, now, is_order, share).
ok();
224 bool is_order =
false,
225 double share = 1.0) noexcept {
226 const RateRefusal w = ip_ ? ip_weight_fits(weight, now, share)
227 : weight_fits(weight, now, threshold_ * share, share < 1.0);
231 if (!b.active)
continue;
240 void on_sent(std::uint32_t weight, std::int64_t now,
bool is_order =
false) noexcept {
241 sent(weight, now, is_order,
false);
245 void on_bulk_sent(std::uint32_t weight, std::int64_t now)
noexcept {
246 sent(weight, now,
false,
true);
252 std::int64_t order_count,
256 if (used_weight >= 0 && ip_) {
258 }
else if (used_weight >= 0 &&
weight_bucket < weight_.size() &&
260 weight_[
weight_bucket].calibrate(
static_cast<std::uint32_t
>(used_weight),
266 orders_[
order_bucket].calibrate(
static_cast<std::uint32_t
>(order_count),
274 void on_order_count(std::int64_t count, std::int64_t window_ns, std::int64_t now)
noexcept {
275 if (count < 0)
return;
277 if (!b.active || b.window_ns != window_ns)
continue;
278 b.calibrate(
static_cast<std::uint32_t
>(count),
286 void on_remaining(std::int64_t limit, std::int64_t remaining, std::int64_t now)
noexcept {
287 if (limit < 0 || remaining < 0 || weight_.empty() || !weight_[0].active)
return;
290 b.limit =
static_cast<std::uint32_t
>(limit);
291 b.used =
static_cast<std::uint32_t
>(std::max<std::int64_t>(0, limit - remaining));
297 void cooldown(std::int64_t retry_after_ns, std::int64_t now)
noexcept {
300 return ip_cooldown(retry_after_ns, now);
302 if (now >= cooldown_until_) {
303 streak_ = cooldowns_ > 0 && now - cooldown_until_ <=
kStreakWindowNs ? streak_ + 1 : 0;
305 const std::int64_t backoff =
307 cooldown_until_ = std::max(cooldown_until_, now + std::max(retry_after_ns, backoff));
312 [[nodiscard]] std::uint32_t
streak() const noexcept;
320 [[nodiscard]] std::uint64_t
cooldowns() const noexcept {
return cooldowns_; }
323 [[nodiscard]] std::optional<RateBucket>
weight_bucket(std::size_t i)
const noexcept;
324 [[nodiscard]] std::optional<RateBucket>
order_bucket(std::size_t i)
const noexcept {
325 if (i < orders_.size() && orders_[i].active)
return orders_[i];
330 static bool add(std::array<RateBucket, kMaxBuckets>& arr,
332 std::int64_t window_ns,
333 std::int64_t offset)
noexcept {
335 if (b.active)
continue;
336 b =
RateBucket{limit, window_ns, 0, 0,
true, offset, 0};
342 void sent(std::uint32_t weight, std::int64_t now,
bool is_order,
bool bulk)
noexcept {
344 ip_on_sent(weight, now, bulk);
346 spend(weight_, weight, now, bulk);
347 recent_weight_.
add(weight, now);
350 spend(orders_, 1, now,
false);
351 recent_orders_.
add(1, now);
354 static void spend(std::array<RateBucket, kMaxBuckets>& arr,
357 bool bulk)
noexcept {
358 for (RateBucket& b : arr) {
359 if (!b.active)
continue;
362 if (bulk) b.bulk += n;
372 bool paced)
noexcept {
374 for (RateBucket& b : weight_) {
375 if (!b.active)
continue;
378 if (paced && b.window_ns > 0) {
380 static_cast<double>(now - b.window_start) /
static_cast<double>(b.window_ns);
389 bool add_weight_bucket_once(std::uint32_t limit, std::int64_t window_ns)
noexcept {
390 for (
const RateBucket& b : weight_) {
391 if (b.active && b.limit == limit && b.window_ns == window_ns)
return true;
393 return add(weight_, limit, window_ns, offset_);
397 RateRefusal ip_weight_fits(std::uint32_t weight, std::int64_t now,
double share)
noexcept;
398 void ip_on_sent(std::uint32_t weight, std::int64_t now,
bool bulk)
noexcept;
399 void ip_on_headers(std::int64_t used, std::int64_t now, std::size_t bucket)
noexcept;
400 bool ip_add_weight_bucket(std::uint32_t limit, std::int64_t window_ns)
noexcept;
401 void ip_cooldown(std::int64_t retry_after_ns, std::int64_t now)
noexcept;
404 double order_threshold_;
405 std::shared_ptr<SharedRate> ip_;
406 std::array<RateBucket, kMaxBuckets> weight_{};
407 std::array<RateBucket, kMaxBuckets> orders_{};
408 RecentSpend recent_weight_;
409 RecentSpend recent_orders_;
410 std::int64_t offset_ = 0;
411 std::int64_t cooldown_until_ = 0;
412 std::uint64_t cooldowns_ = 0;
413 std::uint32_t streak_ = 0;
414 bool hard_stopped_ =
false;
429[[nodiscard]]
inline std::string
ip_weight_key(std::string_view kind,
430 std::string_view rest_url,
431 std::string_view source) {
432 std::string key(kind);
435 if (!source.empty()) {
443inline std::shared_ptr<SharedRate>
shared_rate(std::string_view key) {
445 static std::map<std::string, std::shared_ptr<SharedRate>, std::less<>> by_key;
446 const std::lock_guard<std::mutex> lock(m);
447 auto it = by_key.find(key);
448 if (it == by_key.end())
449 it = by_key.emplace(std::string(key), std::make_shared<SharedRate>()).first;
455 const std::lock_guard<SpinMutex> lock(ip->m);
457 if (b.active)
static_cast<void>(ip->r.add_weight_bucket_once(b.limit, b.window_ns));
462inline RateRefusal RateLimiter::ip_weight_fits(std::uint32_t weight,
464 double share)
noexcept {
465 const std::lock_guard<SpinMutex> lock(ip_->m);
466 return ip_->r.weight_fits(weight, now, threshold_ * share, share < 1.0);
468inline void RateLimiter::ip_on_sent(std::uint32_t weight, std::int64_t now,
bool bulk)
noexcept {
469 const std::lock_guard<SpinMutex> lock(ip_->m);
470 spend(ip_->r.weight_, weight, now, bulk);
471 ip_->r.recent_weight_.add(weight, now);
473inline void RateLimiter::ip_on_headers(std::int64_t used,
475 std::size_t bucket)
noexcept {
479 const std::lock_guard<SpinMutex> lock(ip_->m);
480 auto& w = ip_->r.weight_;
481 if (bucket >= w.size() || !w[bucket].active)
return;
482 w[bucket].calibrate(
static_cast<std::uint32_t
>(used),
483 ip_->r.recent_weight_.since(now, kHeaderLagNs),
488 std::int64_t now)
noexcept {
489 offset_ = venue_minus_local_ns;
491 if (b.active) b.realign(offset_, now);
495 if (b.active) b.realign(offset_, now);
499 const std::lock_guard<SpinMutex> lock(ip_->m);
500 ip_->r.offset_ = offset_;
501 for (RateBucket& b : ip_->r.weight_) {
502 if (b.active) b.realign(offset_, now);
505inline bool RateLimiter::ip_add_weight_bucket(std::uint32_t limit,
506 std::int64_t window_ns)
noexcept {
507 const std::lock_guard<SpinMutex> lock(ip_->m);
508 return ip_->r.add_weight_bucket_once(limit, window_ns);
510inline void RateLimiter::ip_cooldown(std::int64_t retry_after_ns, std::int64_t now)
noexcept {
511 const std::lock_guard<SpinMutex> lock(ip_->m);
512 ip_->r.cooldown(retry_after_ns, now);
515 if (!ip_)
return cooldown_until_;
516 const std::lock_guard<SpinMutex> lock(ip_->m);
517 return ip_->r.cooldown_until_;
521 hard_stopped_ =
true;
524 const std::lock_guard<SpinMutex> lock(ip_->m);
525 ip_->r.hard_stopped_ =
true;
529 hard_stopped_ =
false;
532 const std::lock_guard<SpinMutex> lock(ip_->m);
533 ip_->r.hard_stopped_ =
false;
537 if (i < weight_.size() && weight_[i].active)
return weight_[i];
540 const std::lock_guard<SpinMutex> lock(ip_->m);
541 return ip_->r.weight_bucket(i);
544 if (!ip_)
return streak_;
545 const std::lock_guard<SpinMutex> lock(ip_->m);
546 return ip_->r.streak_;
549 if (!ip_)
return hard_stopped_;
550 const std::lock_guard<SpinMutex> lock(ip_->m);
551 return ip_->r.hard_stopped_;
557template <
class Sleep>
559 std::uint32_t weight,
561 std::int64_t max_wait_ns,
562 Sleep&& sleep_ns)
noexcept {
563 const std::int64_t until = now_ns + max_wait_ns;
564 std::int64_t now = now_ns;
566 constexpr std::int64_t kStep = 100'000'000;
Definition rate_limiter.hpp:146
static constexpr std::size_t kMaxBuckets
Definition rate_limiter.hpp:148
void hard_stop() noexcept
418: the IP is banned; stop REST entirely until an operator clears it.
Definition rate_limiter.hpp:521
bool add_weight_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept
Buckets are added at startup from exchangeInfo.rateLimits / the Bybit rate limit table.
Definition rate_limiter.hpp:175
bool set_order_limit(std::uint32_t limit, std::int64_t window_ns) noexcept
The account's own limit on the order-count window of window_ns (Binance raises it per account,...
Definition rate_limiter.hpp:185
static constexpr std::int64_t kStreakWindowNs
A pause asked (429) within this long after the last one ended is the same incident going on: each suc...
Definition rate_limiter.hpp:156
static constexpr double kBulkShare
The part of each weight window a bulk request may fill (can_send's share): with 170 symbols' snapshot...
Definition rate_limiter.hpp:152
bool can_send(std::uint32_t weight, std::int64_t now, bool is_order=false, double share=1.0) noexcept
True if a request of weight (and one order if is_order) fits under threshold * limit in every bucket ...
Definition rate_limiter.hpp:217
bool add_order_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept
Definition rate_limiter.hpp:179
bool in_cooldown(std::int64_t now) const noexcept
Definition rate_limiter.hpp:315
void clear_hard_stop() noexcept
Definition rate_limiter.hpp:529
std::uint64_t cooldowns() const noexcept
Definition rate_limiter.hpp:322
void set_threshold(double t) noexcept
Definition rate_limiter.hpp:197
void on_sent(std::uint32_t weight, std::int64_t now, bool is_order=false) noexcept
Local accounting after a send.
Definition rate_limiter.hpp:242
static constexpr double kBulkPaceFloor
The part of kBulkShare this limiter's own bulk weight in a window may fill before a bulk request grow...
Definition rate_limiter.hpp:163
void on_remaining(std::int64_t limit, std::int64_t remaining, std::int64_t now) noexcept
Bybit style: remaining requests for this endpoint (X-Bapi-Limit-Status) and the limit.
Definition rate_limiter.hpp:288
double threshold() const noexcept
The share of each limit can_send fills before it refuses.
Definition rate_limiter.hpp:203
std::int64_t cap_of(std::uint32_t limit) const noexcept
The count a bucket of limit admits under that share: can_send refuses the order or request that would...
Definition rate_limiter.hpp:206
std::optional< RateBucket > order_bucket(std::size_t i) const noexcept
Definition rate_limiter.hpp:326
void set_clock_offset(std::int64_t venue_minus_local_ns, std::int64_t now) noexcept
The venue's clock minus the local (now) clock, ns: every window, the IP's included,...
Definition rate_limiter.hpp:489
bool hard_stopped() const noexcept
Definition rate_limiter.hpp:550
void cooldown(std::int64_t retry_after_ns, std::int64_t now) noexcept
429 / -1003 / 10006: block sends until now + retry_after, or longer when the last pause ended less th...
Definition rate_limiter.hpp:299
std::uint32_t streak() const noexcept
Pauses in the current streak after the first.
Definition rate_limiter.hpp:545
void on_order_count(std::int64_t count, std::int64_t window_ns, std::int64_t now) noexcept
The venue's order count on the window of window_ns (WS API rateLimits[], which name each window),...
Definition rate_limiter.hpp:276
void on_bulk_sent(std::uint32_t weight, std::int64_t now) noexcept
on_sent for a bulk request (one can_send checked against kBulkShare): its weight counts in the bulk p...
Definition rate_limiter.hpp:247
RateCheck check(std::uint32_t weight, std::int64_t now, bool is_order=false, double share=1.0) noexcept
can_send, saying which limit refused.
Definition rate_limiter.hpp:224
static constexpr std::int64_t kBackoffBaseNs
Definition rate_limiter.hpp:157
static constexpr std::int64_t kBackoffMaxNs
Definition rate_limiter.hpp:158
std::optional< RateBucket > weight_bucket(std::size_t i) const noexcept
Copies of the i-th bucket (insertion order), empty past the last; a shared IP's is copied under its l...
Definition rate_limiter.hpp:537
static constexpr std::int64_t kHeaderLagNs
How late a venue's count (on_headers) may be: what was sent in this long before it arrived may be mis...
Definition rate_limiter.hpp:166
void on_headers(std::int64_t used_weight, std::int64_t order_count, std::int64_t now, std::size_t weight_bucket=0, std::size_t order_bucket=0) noexcept
The venue's counts from a response (RateBucket::calibrate).
Definition rate_limiter.hpp:253
void set_order_threshold(double t) noexcept
The share of each order-count limit (ORDERS buckets) can_send fills; the weight keeps threshold().
Definition rate_limiter.hpp:200
std::int64_t cooldown_until() const noexcept
Definition rate_limiter.hpp:516
double order_threshold() const noexcept
Definition rate_limiter.hpp:201
std::int64_t order_cap_of(std::uint32_t limit) const noexcept
cap_of for an order-count bucket.
Definition rate_limiter.hpp:210
void share_ip(std::shared_ptr< SharedRate > ip) noexcept
The IP's weight, cooldown and hard stop live in ip from now on (null: this limiter's own).
Definition rate_limiter.hpp:455
static constexpr std::int64_t kSlotNs
Definition rate_limiter.hpp:112
static constexpr std::size_t kSlots
Definition rate_limiter.hpp:111
std::uint32_t since(std::int64_t now, std::int64_t lag) const noexcept
Sent from now - lag on (whole slots: a little more, never less).
Definition rate_limiter.hpp:120
void add(std::uint32_t n, std::int64_t now) noexcept
Definition rate_limiter.hpp:113
std::string ip_weight_key(std::string_view kind, std::string_view rest_url, std::string_view source)
The key of one IP's weight at one venue: the connector kind, its REST host and the address its connec...
Definition rate_limiter.hpp:431
void wait_for_weight(RateLimiter &r, std::uint32_t weight, std::int64_t now_ns, std::int64_t max_wait_ns, Sleep &&sleep_ns) noexcept
A blocking start-up request (reference data, account settings, one per symbol) waits for its weight t...
Definition rate_limiter.hpp:560
RateRefusal
Why can_send refused (RateLimiter::check): the IP or account is paused (429 cooldown,...
Definition rate_limiter.hpp:139
@ None
not a multicast venue
std::shared_ptr< SharedRate > shared_rate(std::string_view key)
The SharedRate of key (ip_weight_key), made on first use; process-wide.
Definition rate_limiter.hpp:445
Definition rate_limiter.hpp:49
void calibrate(std::uint32_t count, std::uint32_t recent, std::int64_t now, std::int64_t lag) noexcept
The venue's count count for this window, recent sent in the last kHeaderLagNs: raised to the count,...
Definition rate_limiter.hpp:98
void roll(std::int64_t now) noexcept
Definition rate_limiter.hpp:68
bool would_exceed(std::uint32_t add, double threshold) const noexcept
Definition rate_limiter.hpp:86
std::int64_t offset
The venue's clock minus the local one (RateLimiter::set_clock_offset): windows start where now + offs...
Definition rate_limiter.hpp:57
bool active
Definition rate_limiter.hpp:54
std::int64_t window_start
ns; the window rolls when now - window_start >= window_ns
Definition rate_limiter.hpp:53
void realign(std::int64_t off, std::int64_t now) noexcept
A new clock offset: the window holding now starts where the venue's does.
Definition rate_limiter.hpp:77
std::uint32_t bulk
What this limiter sent in the current window as bulk requests (RateLimiter::on_bulk_sent),...
Definition rate_limiter.hpp:61
std::uint32_t used
consumed in the current window
Definition rate_limiter.hpp:52
std::int64_t aligned_start(std::int64_t now) const noexcept
The start of the venue's window that holds now.
Definition rate_limiter.hpp:64
bool bulk_would_exceed(std::uint32_t add, double threshold) const noexcept
The same for this limiter's own bulk weight in the window.
Definition rate_limiter.hpp:91
std::int64_t window_ns
fixed window length
Definition rate_limiter.hpp:51
std::uint32_t limit
0 = unlimited
Definition rate_limiter.hpp:50
Definition rate_limiter.hpp:140
bool ok() const noexcept
Definition rate_limiter.hpp:143
RateRefusal refusal
Definition rate_limiter.hpp:141
std::int64_t window_ns
Orders: the window at its threshold.
Definition rate_limiter.hpp:142
SpinMutex m
Every order of every account on the IP takes it twice (ip_weight_fits, ip_on_sent),...
Definition rate_limiter.hpp:424
RateLimiter r
its weight buckets, cooldown and hard stop; never shared itself
Definition rate_limiter.hpp:425