Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
sim_control.cpp
Go to the documentation of this file.
2#include <slick/logger.hpp> // before slick-socket's headers, which log through the LOG_ macros they find
3#include <slick/socket/polled_tcp_client.h>
4#include <algorithm>
5#include <array>
6#include <charconv>
7#include <chrono>
8#include <cstring>
9#include <format>
10
11namespace slick::trader {
12
13namespace {
14
15constexpr std::string_view TARGET = "pcap";
16constexpr std::string_view FEED_PREFIX = "pcap/";
17constexpr std::string_view LIVE_PREFIX = "live ";
18constexpr std::string_view PCAP_PREFIX = "pcap ";
19// How slick-sim refuses a command it doesn't have.
20constexpr std::string_view NO_COMMAND = "unknown command";
21
22struct StateName {
23 std::string_view name;
24 SimFeedState state;
25};
26constexpr std::array STATES{
27 StateName{"IDLE", SimFeedState::IDLE},
28 StateName{"LOADING", SimFeedState::LOADING},
29 StateName{"SYNCING", SimFeedState::SYNCING},
30 StateName{"READY", SimFeedState::READY},
31 StateName{"REPLAYING", SimFeedState::REPLAYING},
32 StateName{"FINISHED", SimFeedState::FINISHED},
33 StateName{"ERROR", SimFeedState::FAILED},
34};
35
36// Takes what is before `delimiter` off `text`, and the delimiter: all of it when there is none.
37std::string_view take(std::string_view& text, std::string_view delimiter) {
38 const size_t at = text.find(delimiter);
39 const std::string_view taken = text.substr(0, at);
40 text.remove_prefix(at == std::string_view::npos ? text.size() : at + delimiter.size());
41 return taken;
42}
43
44// The state `answer` starts with, UNKNOWN when none.
45SimFeedState leading_state(std::string_view answer) {
46 const auto it = std::ranges::find(STATES, answer.substr(0, answer.find(' ')), &StateName::name);
47 return it == STATES.end() ? SimFeedState::UNKNOWN : it->state;
48}
49
50// "12.3%" in permille.
51uint32_t to_permille(std::string_view percent) {
52 uint32_t whole = 0;
53 uint32_t tenth = 0;
54 const char* const end = percent.data() + percent.size();
55 const auto [next, error] = std::from_chars(percent.data(), end, whole);
56 if (error == std::errc() && next != end && *next == '.') {
57 std::from_chars(next + 1, end, tenth);
58 }
59 return std::min(whole, 100u) * 10 + std::min(tenth, 9u);
60}
61
62// "<STATE> <pct>%, capture <t>, window <t>..<t>, speed <n>[ - <message>]" into `feed`.
63void parse_answer(std::string_view answer, SimFeed& feed) {
64 feed.state = leading_state(answer);
65 if (feed.state == SimFeedState::UNKNOWN) {
66 feed.message = answer;
67 return;
68 }
69 take(answer, " ");
70 feed.permille = to_permille(take(answer, ", capture "));
71 feed.capture = take(answer, ", window ");
72 feed.begin = take(answer, "..");
73 feed.end = take(answer, ", speed ");
74 feed.speed = take(answer, " - ");
75 feed.message = answer;
76}
77
78// The length of the feed's name at the front of "<name>: <answer>". A name may hold a ": " of its
79// own, so the one before a state wins. npos when there is none.
80size_t name_length(std::string_view line) {
81 const size_t first = line.find(": ");
82 for (size_t at = first; at != std::string_view::npos; at = line.find(": ", at + 1)) {
83 if (leading_state(line.substr(at + 2)) != SimFeedState::UNKNOWN) {
84 return at;
85 }
86 }
87 return first;
88}
89
90bool loaded(const SimFeed& feed) {
91 return feed.state == SimFeedState::READY || feed.state == SimFeedState::REPLAYING ||
92 feed.state == SimFeedState::FINISHED;
93}
94
95bool has_state(const std::vector<SimFeed>& feeds, SimFeedState state) {
96 return std::ranges::find(feeds, state, &SimFeed::state) != feeds.end();
97}
98
99} // namespace
100
101std::string_view to_string(SimFeedState state) noexcept {
102 const auto it = std::ranges::find(STATES, state, &StateName::state);
103 return it == STATES.end() ? "UNKNOWN" : it->name;
104}
105
106std::vector<SimFeed> parse_sim_feeds(std::string_view text) {
107 std::vector<SimFeed> feeds;
108 while (!text.empty()) {
109 std::string_view line = take(text, "\n");
110 if (!line.starts_with(FEED_PREFIX)) {
111 continue;
112 }
113 line.remove_prefix(FEED_PREFIX.size());
114 const size_t length = name_length(line);
115 if (length == std::string_view::npos) {
116 continue;
117 }
118 const std::string_view name = line.substr(0, length);
119 const std::string_view answer = line.substr(length + 2);
120 // A line break in what a feed said: slick-sim names the feed again on the next line.
121 if (!feeds.empty() && feeds.back().name == name && leading_state(answer) == SimFeedState::UNKNOWN) {
122 feeds.back().message += ' ';
123 feeds.back().message += answer;
124 continue;
125 }
126 SimFeed& feed = feeds.emplace_back();
127 feed.name = name;
128 parse_answer(answer, feed);
129 }
130 return feeds;
131}
132
133SimFeedList parse_sim_feed_list(std::string_view text) {
134 SimFeedList list;
135 while (!text.empty()) {
136 std::string_view line = take(text, "\n");
137 if (line.starts_with(PCAP_PREFIX)) {
138 list.pcap = true;
139 } else if (line.starts_with(LIVE_PREFIX)) {
140 line.remove_prefix(LIVE_PREFIX.size());
141 if (std::ranges::find(list.live, line) == list.live.end()) { // an instance may have several
142 list.live.emplace_back(line);
143 }
144 }
145 }
146 return list;
147}
148
149SimControl::Pending SimControl::send(uint8_t command, uint64_t now_ns) {
150 if (++last_request_id_ == 0) {
151 ++last_request_id_; // 0 says none is pending
152 }
153 sim_cli::Request request{};
154 request.header = {static_cast<uint16_t>(sizeof(request)), sim_cli::REQUEST};
155 request.request_id = last_request_id_;
156 request.command = command;
157 if (command != sim_cli::LIST_FEEDS && command != sim_cli::GET_VERSION) { // these have no target
158 std::memcpy(request.target, TARGET.data(), TARGET.size());
159 }
160 transport_.send(reinterpret_cast<const uint8_t*>(&request), sizeof(request));
161 return {last_request_id_, now_ns};
162}
163
164void SimControl::send_poll(uint64_t now_ns) {
165 poll_command_ = !(listed_ && list_.pcap) ? sim_cli::LIST_FEEDS
166 : can_watch_ ? sim_cli::WATCH_STATUS
167 : sim_cli::PCAP_STATUS;
168 poll_ = send(poll_command_, now_ns);
169 next_poll_ns_ = now_ns + POLL_NS;
170}
171
172void SimControl::on_connected(uint64_t now_ns) {
173 held_ = false;
174 version_request_ = send(sim_cli::GET_VERSION, now_ns); // first, to be known once connected
175 send_poll(now_ns);
176}
177
178size_t SimControl::on_data(const uint8_t* data, size_t size, uint64_t now_ns) {
179 size_t used = 0;
180 while (size - used >= sizeof(sim_cli::Reply)) {
181 sim_cli::Reply reply;
182 std::memcpy(&reply, data + used, sizeof(reply));
183 const size_t length = reply.header.length;
184 if (reply.header.type != sim_cli::REPLY || length < sizeof(reply)) {
185 LOG_WARN("SimControl: malformed reply from slick-sim, reconnecting");
186 transport_.close();
187 return size;
188 }
189 if (size - used < length) {
190 break;
191 }
192 const std::string_view text(reinterpret_cast<const char*>(data) + used + sizeof(reply),
193 length - sizeof(reply));
194 const bool ok = reply.status == sim_cli::STATUS_OK;
195 if (poll_.is(reply.request_id)) {
196 poll_ = {};
197 if (poll_command_ == sim_cli::WATCH_STATUS && ok) {
198 watch_id_ = reply.request_id; // each change comes under it
199 }
200 on_poll(poll_command_, ok, text, now_ns);
201 } else if (watch_id_ != 0 && reply.request_id == watch_id_) {
202 on_poll(sim_cli::WATCH_STATUS, ok, text, now_ns);
203 } else if (replay_.is(reply.request_id)) {
204 replay_ = {};
205 on_replay(ok, text, now_ns);
206 } else if (version_request_.is(reply.request_id)) {
207 version_request_ = {};
208 if (const auto version = ok ? text : std::string_view(); version != version_) {
209 version_ = version;
210 changed_ = true;
211 }
212 }
213 used += length;
214 }
215 return used;
216}
217
218void SimControl::on_timer(uint64_t now_ns) {
219 if (poll_.expired(now_ns) || replay_.expired(now_ns)) {
220 LOG_WARN("SimControl: no reply from slick-sim, reconnecting");
221 transport_.close();
222 return;
223 }
224 if (poll_.request_id == 0 && now_ns >= next_poll_ns_ && !settled()) {
225 send_poll(now_ns);
226 }
227 if (starting_ && replay_.request_id == 0 && now_ns - started_ns_ >= STARTING_NS) {
228 starting_ = false;
229 changed_ = true;
230 }
231}
232
234 held_ = settled() && poll_.request_id == 0;
235 if (replay_.request_id != 0) {
236 replay_answer_ = ReplayAnswer{false, "the link to slick-sim dropped before it answered"};
237 }
238 poll_ = {};
239 replay_ = {};
240 version_request_ = {};
241 watch_id_ = 0;
242 can_watch_ = true;
243 starting_ = false;
244 listed_ = false;
245 last_command_ = 0;
246 last_text_.clear();
247 if (!held_) {
248 on_lost();
249 }
250}
251
253 if (connected_ || !version_.empty()) {
254 changed_ = true;
255 }
256 held_ = false;
257 connected_ = false;
258 error_.clear();
259 version_.clear();
260 feeds_.clear();
261}
262
263void SimControl::on_poll(uint8_t command, bool ok, std::string_view text, uint64_t now_ns) {
264 if (command == sim_cli::WATCH_STATUS && !ok && text.starts_with(NO_COMMAND)) {
265 can_watch_ = false; // too old to: asked each second instead
266 send_poll(now_ns);
267 return;
268 }
269 if (connected_ && command == last_command_ && ok == last_ok_ && text == last_text_) {
270 return;
271 }
272 changed_ = true;
273 last_command_ = command;
274 last_ok_ = ok;
275 last_text_ = text;
276 error_.clear();
277 if (command == sim_cli::LIST_FEEDS) {
278 on_list(ok, text, now_ns);
279 } else {
280 on_status(text);
281 }
282}
283
284void SimControl::on_list(bool ok, std::string_view text, uint64_t now_ns) {
285 // A failed list: this one's feeds aren't known, whatever the one before it had.
286 list_ = ok ? parse_sim_feed_list(text) : SimFeedList{};
287 if (!list_.pcap) {
288 feeds_.clear(); // kept through a held link, which another slick-sim may have taken
289 }
290 if (!ok) {
291 connected_ = true;
292 listed_ = text.starts_with(NO_COMMAND);
293 error_ = listed_ ? std::string_view("too old to list its feeds, update it") : text;
294 return;
295 }
296 listed_ = true;
297 if (list_.pcap) {
298 send_poll(now_ns); // connected with their status, rather than shown without it
299 } else {
300 connected_ = true;
301 }
302}
303
304void SimControl::on_status(std::string_view text) {
305 connected_ = true;
306 if (auto feeds = parse_sim_feeds(text); !feeds.empty()) {
307 feeds_ = std::move(feeds);
308 if (!has_state(feeds_, SimFeedState::READY)) {
309 starting_ = false; // every feed took the start
310 }
311 } else {
312 // Busy, say, which tells nothing of the feeds.
313 error_ = text.empty() ? std::string_view("slick-sim gave no status") : text;
314 }
315}
316
317void SimControl::on_replay(bool ok, std::string_view text, uint64_t now_ns) {
318 starting_ = ok && has_state(feeds_, SimFeedState::READY); // none: a status has shown it already
319 started_ns_ = now_ns;
320 changed_ = true;
321 next_poll_ns_ = now_ns; // what it did shows at once
322 replay_answer_ = ReplayAnswer{ok, std::string(text)};
323 std::string line(text);
324 std::ranges::replace(line, '\n', ';');
325 if (ok) {
326 LOG_INFO("SimControl: replay started: {}", line);
327 } else {
328 LOG_ERROR("SimControl: slick-sim refused the replay: {}", line);
329 }
330}
331
332std::string SimControl::start_blocked() const {
333 if (!connected_) {
334 return "Not connected to slick-sim";
335 }
336 if (!error_.empty()) {
337 return error_;
338 }
339 if (feeds_.empty()) {
340 return list_.pcap ? "Waiting for the feeds' status" : "slick-sim has no pcap feed";
341 }
342 if (!status_fresh()) {
343 // Held, or made again and not yet given the feeds' status, which may have changed meanwhile.
344 return "Reconnecting to slick-sim";
345 }
346 if (starting_) {
347 return "Starting";
348 }
349 if (const auto failed = std::ranges::find(feeds_, SimFeedState::FAILED, &SimFeed::state); failed != feeds_.end()) {
350 return failed->name + " is in ERROR";
351 }
352 if (const auto count = std::ranges::count_if(feeds_, loaded); static_cast<size_t>(count) != feeds_.size()) {
353 return std::format("{} of {} feeds ready", count, feeds_.size());
354 }
355 if (!has_state(feeds_, SimFeedState::READY)) {
356 return has_state(feeds_, SimFeedState::REPLAYING) ? "Replaying" : "Finished";
357 }
358 return {};
359}
360
361bool SimControl::start_replay(uint64_t now_ns) {
362 if (!start_blocked().empty()) {
363 return false;
364 }
365 replay_ = send(sim_cli::START_REPLAY, now_ns);
366 starting_ = true;
367 changed_ = true;
368 return true;
369}
370
371nlohmann::json SimControl::to_json() const {
372 auto feeds = nlohmann::json::array();
373 for (const auto& feed : feeds_) {
374 feeds.push_back({
375 {"name", feed.name},
376 {"state", to_string(feed.state)},
377 {"progress", feed.permille / 10.0},
378 {"capture", feed.capture},
379 {"begin", feed.begin},
380 {"end", feed.end},
381 {"speed", feed.speed},
382 {"message", feed.message}
383 });
384 }
385 const std::string blocked = start_blocked();
386 return {
387 {"connected", connected_},
388 {"version", version_},
389 {"live_feeds", list_.live},
390 {"pcap", list_.pcap},
391 {"can_start", blocked.empty()},
392 {"start_blocked", blocked},
393 {"starting", starting_},
394 {"error", error_},
395 {"feeds", std::move(feeds)}
396 };
397}
398
400 using Client = slick::socket::PolledTCPClient;
401
402 static constexpr uint64_t RECONNECT_NS = 5'000'000'000;
403
404 static std::unique_ptr<Client> make_client(const SimControlConfig& config) {
405 slick::socket::PolledTCPClientConfig tcp;
406 tcp.server_address = config.addr;
407 tcp.server_port = config.port;
408 tcp.connection_timeout = std::chrono::milliseconds(3000);
409 tcp.send_timeout = std::chrono::milliseconds(100); // a wait here holds up the event loop
410 return std::make_unique<Client>("SimControl", tcp);
411 }
412
413 explicit Impl(const SimControlConfig& config) : link(make_client(config), RECONNECT_NS) {}
414
417 std::array<uint8_t, 16384> buffer;
418};
419
421 : impl_(std::make_unique<Impl>(config))
422 , address_(std::format("{}:{}", config.addr, config.port))
423{}
424
426
427void SimControlLink::service(uint64_t now_ns) {
428 next_service_ns_ = now_ns + SERVICE_NS;
429 auto& [link, control, buffer] = *impl_;
430 const bool was_connected = link.connected();
431 link.service(control, now_ns, buffer);
432 if (control.held()) [[unlikely]] {
433 if (was_connected) {
434 link.connect_now();
435 } else if (link.client().state() == Impl::Client::State::Disconnected) {
436 control.on_lost(); // tried, and failed
437 }
438 }
439}
440
442 impl_->link.disconnect();
443 impl_->control.on_disconnected();
444 impl_->control.on_lost();
445}
446
447SimControl& SimControlLink::control() noexcept { return impl_->control; }
448const SimControl& SimControlLink::control() const noexcept { return impl_->control; }
449
450} // namespace slick::trader
void on_connected(uint64_t now_ns)
nlohmann::json to_json() const
bool start_replay(uint64_t now_ns)
static constexpr uint64_t POLL_NS
size_t on_data(const uint8_t *data, size_t size, uint64_t now_ns)
static constexpr uint64_t STARTING_NS
std::string start_blocked() const
const std::vector< SimFeed > & feeds() const noexcept
const std::string & version() const noexcept
void on_timer(uint64_t now_ns)
constexpr uint8_t REPLY
constexpr uint8_t REQUEST
constexpr uint8_t PCAP_STATUS
constexpr uint8_t LIST_FEEDS
constexpr uint8_t GET_VERSION
constexpr uint8_t WATCH_STATUS
constexpr uint8_t STATUS_OK
constexpr uint8_t START_REPLAY
SimFeedList parse_sim_feed_list(std::string_view text)
const char * to_string(BrokerId bid)
Definition event.hpp:78
std::vector< SimFeed > parse_sim_feeds(std::string_view text)
std::vector< std::string > live