Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
kill_switch.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <slick/logger.hpp>
5#include <cstddef>
6#include <cstdint>
7#include <string_view>
8#include <thread>
9
10namespace slick::trader {
11
12// Working orders a kill switch is still waiting on.
14 size_t waiting = 0; // on sessions that can still be told
15 size_t unreachable = 0; // on sessions that are down
16};
17
18// The last thing an order worker does: pulls every working order before its sessions
19// end, waiting up to `timeout_ns` for the exchange to confirm. No new requests are read
20// from here on, only the exchange's answers.
21//
22// `service(now) -> bool` reads the sockets (true when anything was read); `step(now) ->
23// KillSwitchCount` asks each session to cancel what it still has and counts what is
24// left. `fallback` says what takes the orders left over (an exchange's cancel on
25// disconnect, say).
26template <typename Service, typename Step>
27KillSwitchCount run_kill_switch(std::string_view who, size_t working, uint64_t timeout_ns, Service&& service,
28 Step&& step, std::string_view fallback) {
29 KillSwitchCount left;
30 if (working == 0) {
31 return left;
32 }
33 if (timeout_ns == 0) {
34 LOG_WARN("{}: stopping with {} order(s) working (cancel_on_stop_ms is 0)", who, working);
35 left.waiting = working;
36 return left;
37 }
38 LOG_INFO("{}: stopping, cancelling {} working order(s)", who, working);
39 const uint64_t deadline_ns = get_timestamp_ns() + timeout_ns;
40 for (;;) {
41 const uint64_t now_ns = get_timestamp_ns();
42 const bool worked = service(now_ns);
43 left = step(now_ns);
44 if (left.waiting == 0 || now_ns >= deadline_ns) {
45 break;
46 }
47 if (!worked) {
48 std::this_thread::yield();
49 }
50 }
51 if (left.waiting + left.unreachable == 0) {
52 LOG_INFO("{}: every working order is cancelled or filled", who);
53 } else {
54 LOG_ERROR("{}: {} order(s) may still be working ({} unconfirmed, {} on a session that is down) - {}", who,
55 left.waiting + left.unreachable, left.waiting, left.unreachable, fallback);
56 }
57 return left;
58}
59
60} // namespace slick::trader
KillSwitchCount run_kill_switch(std::string_view who, size_t working, uint64_t timeout_ns, Service &&service, Step &&step, std::string_view fallback)
uint64_t get_timestamp_ns()
Definition time.hpp:7