Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
md_event_writer.hpp
Go to the documentation of this file.
1#pragma once
2
13#include <slick/logger.hpp>
14#include <slick/queue.hpp>
15#include <slick/stream_buffer_multiplexer.hpp>
16#include <nlohmann/json.hpp>
17#include <algorithm>
18#include <cstdint>
19#include <cstring>
20#include <memory>
21#include <span>
22#include <string>
23#include <string_view>
24
25namespace slick::trader {
26
27// A broker's producer ids in the event multiplexer: odd for its market data, even for
28// its order events.
29constexpr uint32_t md_producer_id(BrokerId broker) noexcept { return static_cast<uint32_t>(broker) * 2 - 1; }
30constexpr uint32_t order_producer_id(BrokerId broker) noexcept { return static_cast<uint32_t>(broker) * 2; }
31
32// Copies `name` into a register event's fixed shm_name field.
33template <typename E>
34void set_shm_name(E& event, const std::string& name) {
35 const size_t n = std::min(name.size(), sizeof(event.shm_name) - 1);
36 std::memcpy(event.shm_name, name.data(), n);
37 event.shm_name[n] = '\0';
38}
39
40// Calls `f(offset, n)` for `count` items in runs of at most `max`, and once with none
41// when there are none. An empty snapshot is still published: it is what clears a
42// subscriber's book.
43template <typename F>
44void for_each_part(size_t count, size_t max, F&& f) {
45 size_t offset = 0;
46 do {
47 const size_t n = std::min(count - offset, max);
48 f(offset, n);
49 offset += n;
50 } while (offset < count);
51}
52
53// One instrument as a market data connector describes it.
55 std::string_view symbol;
57 double multiplier = 1.0;
61 std::string_view currency;
62};
63
64// Publishes `d` into `buffer` as `broker`'s InstrumentDefinitionEvent. From the buffer's one writer.
65inline bool publish_definition(slick::stream_buffer_multiplexer::producer_buffer& buffer, BrokerId broker,
66 const MdDefinition& d) {
68 ev.broker_id = broker;
71 ev.tick_size = d.tick_size;
77 });
78}
79
80// A market data connector's output: its producer buffer in the event multiplexer, and
81// the events written into it. Single-threaded: the connector's worker is the one writer.
83public:
84 // A Level2UpdateEvent carries a uint16 level count; a book is published in events of
85 // at most this many levels.
86 static constexpr size_t MAX_LEVELS_PER_EVENT = 1024;
87 // And an MboUpdateEvent this many orders, which makes the two records about the same size.
88 static constexpr size_t MAX_ORDERS_PER_EVENT = 640;
89
90 explicit MdEventWriter(BrokerId broker) noexcept : broker_(broker) {}
91
92 // Adds the producer, sized by `queue_size` / `control_size` and named by `shm_name`
93 // in `config` when it sets them.
94 void open(slick::stream_buffer_multiplexer& mux, const nlohmann::json& config) {
95 shm_name_ = config.value("shm_name", std::string());
96 buffer_ = mux.add_producer(md_producer_id(broker_), config.value("queue_size", 1u << 26),
97 config.value("control_size", 1u << 24),
98 shm_name_.empty() ? nullptr : shm_name_.c_str());
99 }
100 [[nodiscard]] bool is_open() const noexcept { return buffer_ != nullptr; }
101
102 void register_connector(slick::queue<uint8_t>& control_queue) const {
103 EventSerializer::publish<RegisterEvent>(control_queue, [this](RegisterEvent& event) {
104 event.broker_id = broker_;
105 event.component_type = ComponentType::MARKET_DATA;
106 event.producer_id = md_producer_id(broker_);
107 set_shm_name(event, shm_name_);
108 });
109 }
110
111 void trade(std::string_view symbol, price_t price, qty_t qty, Side aggressor, uint64_t event_time_ns,
112 uint64_t trade_id = 0) {
114 ev.broker_id = broker_;
116 ev.event_time_ns = event_time_ns;
117 ev.set_instrument(symbol);
118 ev.price = price;
119 ev.quantity = qty;
120 ev.side = aggressor;
121 // A sell aggressor hit a resting buyer: the buyer was the maker.
122 ev.is_buyer_maker = aggressor == Side::SELL;
123 ev.trade_id = trade_id;
124 });
125 }
126
127 // Changed levels (quantity 0 = the level emptied), or with `is_snapshot` every level.
128 void levels(std::string_view symbol, std::span<const PriceLevel> levels, bool is_snapshot,
129 uint64_t event_time_ns, uint64_t sequence) {
130 for_each_part(levels.size(), MAX_LEVELS_PER_EVENT, [&](size_t offset, size_t n) {
131 const auto event_size = static_cast<uint32_t>(sizeof(Level2UpdateEvent) + n * sizeof(PriceLevel));
132 EventSerializer::publish<Level2UpdateEvent>(*buffer_, event_size, [&](Level2UpdateEvent& ev) {
133 ev.broker_id = broker_;
134 ev.timestamp_ns = get_timestamp_ns();
135 ev.event_time_ns = event_time_ns;
136 ev.set_instrument(symbol);
137 // Only the first part of a snapshot clears the book.
138 ev.is_snapshot = is_snapshot && offset == 0;
139 ev.sequence_num = sequence;
140 ev.num_levels = static_cast<uint16_t>(n);
141 if (n > 0) {
142 std::memcpy(ev.levels, levels.data() + offset, n * sizeof(PriceLevel));
143 }
144 });
145 });
146 }
147
148 // One exchange event's order changes, or with `is_snapshot` every resting order.
149 void orders(std::string_view symbol, std::span<const MboOrder> orders, bool is_snapshot,
150 uint64_t event_time_ns, uint64_t sequence) {
151 for_each_part(orders.size(), MAX_ORDERS_PER_EVENT, [&](size_t offset, size_t n) {
152 EventSerializer::publish<MboUpdateEvent>(*buffer_, MboUpdateEvent::size_for(n), [&](MboUpdateEvent& ev) {
153 ev.broker_id = broker_;
154 ev.timestamp_ns = get_timestamp_ns();
155 ev.event_time_ns = event_time_ns;
156 ev.set_instrument(symbol);
157 // Only the first part of a snapshot clears the book, and only after the
158 // last is the book whole.
159 ev.is_snapshot = is_snapshot && offset == 0;
160 ev.is_last = offset + n == orders.size();
161 ev.sequence_num = sequence;
162 ev.num_orders = static_cast<uint16_t>(n);
163 if (n > 0) {
164 std::memcpy(ev.orders, orders.data() + offset, n * sizeof(MboOrder));
165 }
166 });
167 });
168 }
169
170 void status(std::string_view symbol, TradingStatus status, bool cancel_allowed, std::string_view reason,
171 uint64_t event_time_ns) {
173 ev.broker_id = broker_;
175 ev.event_time_ns = event_time_ns;
176 ev.set_instrument(symbol);
177 ev.status = status;
178 ev.cancel_allowed = cancel_allowed;
179 ev.set_reason(reason);
180 });
181 }
182
184
185 void definition(const Definition& d) { publish_definition(*buffer_, broker_, d); }
186
187 [[nodiscard]] BrokerId broker() const noexcept { return broker_; }
188
189private:
190 BrokerId broker_;
191 std::string shm_name_;
192 std::shared_ptr<slick::stream_buffer_multiplexer::producer_buffer> buffer_;
193};
194
195// Reads one request off `broker`'s market data request queue (MdRequestQueues) and hands a
196// subscribe to `on_subscribe(const MDSubscription&)` and an unsubscribe to `on_unsubscribe`.
197// Returns whether a request was read.
198//
199// The handlers get the request where it lies in the queue, valid until they return: keep what
200// outlives the call. It is reported read to BrokerStatusRegistry after they return, and
201// StrategyManager writes nothing over what this connector has not reported read. A connector
202// reading the queue without this helper reports the same way, or its requests wait on it.
203template <typename Subscribe, typename Unsubscribe>
204bool process_md_request(slick::queue<uint8_t>& queue, uint64_t& cursor, BrokerId broker, Subscribe&& on_subscribe,
205 Unsubscribe&& on_unsubscribe) {
206 auto [data, size] = queue.read(cursor);
207 if (!data) {
208 return false;
209 }
210 const auto& request = *reinterpret_cast<const MDSubscription*>(data);
211 // Only a connector that is not waited on, with market data off, can be lapped: what it read
212 // then is dropped, not read past its end.
213 if (size >= sizeof(MDSubscription) && request.broker_id == broker &&
214 size == sizeof(MDSubscription) + uint64_t{request.num_instruments} * sizeof(request.instruments[0])) {
215 switch (request.type) {
217 on_subscribe(request);
218 break;
220 on_unsubscribe(request);
221 break;
222 default:
223 LOG_ERROR("{} market data request dropped: unknown type {}", to_string(broker),
224 static_cast<int>(request.type));
225 break;
226 }
227 } else {
228 LOG_WARN("{} market data request dropped: {} bytes that read as no request of its own, as when "
229 "lapped while not waited on",
230 to_string(broker), size);
231 }
232 BrokerStatusRegistry::instance().set_md_request_cursor(broker, cursor);
233 return true;
234}
235
236} // namespace slick::trader
static BrokerStatusRegistry & instance()
static bool publish(slick::SlickQueue< uint8_t > &queue, uint32_t size, populate_event_fn &&populate_event_func)
void trade(std::string_view symbol, price_t price, qty_t qty, Side aggressor, uint64_t event_time_ns, uint64_t trade_id=0)
void status(std::string_view symbol, TradingStatus status, bool cancel_allowed, std::string_view reason, uint64_t event_time_ns)
void open(slick::stream_buffer_multiplexer &mux, const nlohmann::json &config)
static constexpr size_t MAX_ORDERS_PER_EVENT
MdEventWriter(BrokerId broker) noexcept
void definition(const Definition &d)
void orders(std::string_view symbol, std::span< const MboOrder > orders, bool is_snapshot, uint64_t event_time_ns, uint64_t sequence)
bool is_open() const noexcept
void levels(std::string_view symbol, std::span< const PriceLevel > levels, bool is_snapshot, uint64_t event_time_ns, uint64_t sequence)
void register_connector(slick::queue< uint8_t > &control_queue) const
static constexpr size_t MAX_LEVELS_PER_EVENT
BrokerId broker() const noexcept
uint64_t get_timestamp_ns()
Definition time.hpp:7
const char * to_string(BrokerId bid)
Definition event.hpp:78
constexpr uint32_t order_producer_id(BrokerId broker) noexcept
void set_shm_name(E &event, const std::string &name)
constexpr uint32_t md_producer_id(BrokerId broker) noexcept
void for_each_part(size_t count, size_t max, F &&f)
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
bool process_md_request(slick::queue< uint8_t > &queue, uint64_t &cursor, BrokerId broker, Subscribe &&on_subscribe, Unsubscribe &&on_unsubscribe)
bool publish_definition(slick::stream_buffer_multiplexer::producer_buffer &buffer, BrokerId broker, const MdDefinition &d)
uint64_t event_time_ns
Definition event.hpp:59
uint64_t timestamp_ns
Definition event.hpp:58
void set_instrument(std::string_view instr)
Definition event.hpp:70
BrokerId broker_id
Definition event.hpp:60