Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
pending_responses.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <common/messages.hpp>
4#include <cstdint>
5#include <functional>
6#include <utility>
7#include <vector>
8
10
24public:
25 using Id = uint64_t;
28 using Completion = std::function<void(const OrderResponse*)>;
29 using Predicate = std::function<bool(const OrderResponse&)>;
30
31 static constexpr Id kNoId = 0;
32
33 Id add(Predicate matches, Completion complete) {
34 const Id id = ++next_id_;
35 waiters_.push_back({id, std::move(matches), std::move(complete)});
36 return id;
37 }
38
43 bool dispatch(const OrderResponse &response) {
44 for (auto it = waiters_.begin(); it != waiters_.end(); ++it) {
45 if (!it->matches(response)) {
46 continue;
47 }
48 // Lifted out and erased before running: a completion may register a new
49 // waiter, which would reallocate the vector under us.
50 Completion complete = std::move(it->complete);
51 waiters_.erase(it);
52 complete(&response);
53 return true;
54 }
55 return false;
56 }
57
60 void expire(Id id) {
61 auto it = find(id);
62 if (it == waiters_.end()) {
63 return;
64 }
65 Completion complete = std::move(it->complete);
66 waiters_.erase(it);
67 complete(nullptr);
68 }
69
72 void abandon(Id id) {
73 auto it = find(id);
74 if (it != waiters_.end()) {
75 waiters_.erase(it);
76 }
77 }
78
79 bool waiting(Id id) const {
80 for (const auto &waiter : waiters_) {
81 if (waiter.id == id) {
82 return true;
83 }
84 }
85 return false;
86 }
87
88 size_t size() const noexcept { return waiters_.size(); }
89
90private:
91 struct Waiter {
92 Id id;
93 Predicate matches;
94 Completion complete;
95 };
96
97 std::vector<Waiter>::iterator find(Id id) {
98 for (auto it = waiters_.begin(); it != waiters_.end(); ++it) {
99 if (it->id == id) {
100 return it;
101 }
102 }
103 return waiters_.end();
104 }
105
106 std::vector<Waiter> waiters_;
107 Id next_id_ = kNoId;
108};
109
110} // end namespace slick::sim::order_gateway
Correlates an in-flight HTTP request with its execution report.
std::function< void(const OrderResponse *)> Completion
Invoked with the matching report, or with nullptr when the wait timed out.
void expire(Id id)
Completes a waiter as timed out.
bool dispatch(const OrderResponse &response)
Offers a report to the waiters, completing at most one of them.
std::function< bool(const OrderResponse &)> Predicate
void abandon(Id id)
Drops a waiter without completing it, for a client that went away.
Id add(Predicate matches, Completion complete)