Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
order_entry.hpp
Go to the documentation of this file.
1#pragma once
2
7#include <nlohmann/json.hpp>
8#include <atomic>
9#include <cstdint>
10#include <format>
11#include <functional>
12#include <initializer_list>
13#include <limits>
14#include <stdexcept>
15#include <string>
16#include <string_view>
17#include <unordered_map>
18
19// Order-entry rules that do not depend on any exchange's protocol: what a post-only
20// order becomes where the exchange has no such instruction, whole-lot quantities, a
21// request rate limit, per-contract fees, and the local reject of a new order.
22namespace slick::trader {
23
24// What becomes of an order the strategy marked post-only.
25enum class PostOnlyPolicy : uint8_t {
26 // Checked against the book before it is sent, and rejected locally if it would
27 // trade, or if the book is not known well enough to tell. The check is against the
28 // book as market data last showed it: an order can still trade against a price that
29 // arrived in between.
31 ACCEPT, // sent as an ordinary order, which can take liquidity
32 REJECT, // rejected locally
33 NATIVE, // sent with the exchange's own instruction, where it has one
34};
35
36// Reads a `post_only_policy` config value. `native` is the exchange's own word for
37// NATIVE ("passive", say), or empty when it has none. Throws for anything else.
38inline PostOnlyPolicy parse_post_only_policy(const std::string& value, std::string_view native,
39 std::string_view who) {
40 if (value == "reject_if_crossing") {
42 }
43 if (value == "accept") {
45 }
46 if (value == "reject") {
48 }
49 if (!native.empty() && value == native) {
51 }
52 throw std::runtime_error(std::format(
53 "{}: post_only_policy must be \"reject_if_crossing\", \"accept\" or \"reject\"{}, not \"{}\"", who,
54 native.empty() ? std::string() : std::format(" or \"{}\"", native), value));
55}
56
57// Only an order that is to rest can be post-only. A market order, a stop waiting for its
58// trigger and an order that is killed unless it fills are takers by nature.
59inline bool rests(OrderType type, TimeInForce tif) noexcept {
60 return type == OrderType::LIMIT && tif != TimeInForce::IOC && tif != TimeInForce::FOK;
61}
62
63// Whole lots, or 0 when `qty` is not a positive whole number of them.
64inline uint32_t whole_lots(qty_t qty) noexcept {
65 if (qty <= 0 || qty % QTY_SCALE != 0 || qty / QTY_SCALE > std::numeric_limits<uint32_t>::max()) {
66 return 0;
67 }
68 return static_cast<uint32_t>(qty / QTY_SCALE);
69}
70
71inline qty_t lots_to_qty(int64_t lots) noexcept {
72 return static_cast<qty_t>(lots) * QTY_SCALE;
73}
74
75// Why a post-only order at `price` cannot be sent under `policy`, or null when it can.
76// `top` is the instrument's book as market data keeps it, null when there is none.
77// `warned` makes ACCEPT's warning a one-off; `who` names the session in it.
78const char* post_only_problem(PostOnlyPolicy policy, const SharedTopOfBook* top, Side side, OrderType type,
79 TimeInForce tif, price_t price, bool& warned, std::string_view who);
80
81// Requests allowed per one-second window; 0 for no limit. One over is refused, not
82// queued: a request held back would reach the exchange later than its sender thinks.
84public:
85 explicit RateLimiter(uint32_t per_sec = 0) noexcept : per_sec_(per_sec) {}
86
87 // False when this request would go over the limit.
88 [[nodiscard]] bool allow(uint64_t now_ns) noexcept {
89 if (per_sec_ == 0) {
90 return true;
91 }
92 const uint64_t window = now_ns / 1'000'000'000ULL;
93 if (window != window_) {
94 window_ = window;
95 count_ = 0;
96 }
97 return ++count_ <= per_sec_;
98 }
99
100 [[nodiscard]] uint32_t per_sec() const noexcept { return per_sec_; }
101
102private:
103 uint32_t per_sec_;
104 uint64_t window_ = 0;
105 uint32_t count_ = 0;
106};
107
108// Exchange and clearing fees per contract, by whatever names an instrument goes by
109// (symbol, product), with a default for the rest. Looked up without building a string.
110class FeeTable {
111public:
112 // `{ "default": 1.18, "ES": 1.18, "MES": 0.35 }`; empty or absent is no fees.
113 static FeeTable from_json(const nlohmann::json& config) {
114 FeeTable table;
115 if (!config.is_object()) {
116 return table;
117 }
118 for (const auto& [key, value] : config.items()) {
119 if (key == "default") {
120 table.default_fee_ = value.get<double>();
121 } else {
122 table.fees_[key] = value.get<double>();
123 }
124 }
125 return table;
126 }
127
128 // The first of `names` the table lists, else the default.
129 [[nodiscard]] double per_contract(std::initializer_list<std::string_view> names) const {
130 for (const auto name : names) {
131 auto it = fees_.find(name);
132 if (it != fees_.end()) {
133 return it->second;
134 }
135 }
136 return default_fee_;
137 }
138
139 [[nodiscard]] double default_fee() const noexcept { return default_fee_; }
140 void set(std::string_view name, double fee) { fees_.insert_or_assign(std::string(name), fee); }
141 void set_default(double fee) noexcept { default_fee_ = fee; }
142
143private:
144 std::unordered_map<std::string, double, StringHash, std::equal_to<>> fees_;
145 double default_fee_ = 0.0;
146};
147
148// The reject a new order gets when it is refused before it reaches the exchange.
149inline OrderRejectEvent reject_of(const NewOrderEvent& request, BrokerId broker, std::string_view reason) {
150 OrderRejectEvent event;
151 event.broker_id = broker;
152 event.set_instrument(request.instrument);
153 event.set_client_order_id(request.client_order_id);
154 event.side = request.side;
155 event.price = request.price;
156 event.stop_price = request.stop_price;
157 event.quantity = request.quantity;
158 event.set_reason(reason);
159 return event;
160}
161
162} // namespace slick::trader
double per_contract(std::initializer_list< std::string_view > names) const
double default_fee() const noexcept
void set_default(double fee) noexcept
void set(std::string_view name, double fee)
static FeeTable from_json(const nlohmann::json &config)
bool allow(uint64_t now_ns) noexcept
uint32_t per_sec() const noexcept
RateLimiter(uint32_t per_sec=0) noexcept
PostOnlyPolicy parse_post_only_policy(const std::string &value, std::string_view native, std::string_view who)
uint32_t whole_lots(qty_t qty) noexcept
qty_t lots_to_qty(int64_t lots) noexcept
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
OrderRejectEvent reject_of(const NewOrderEvent &request, BrokerId broker, std::string_view reason)
const char * post_only_problem(PostOnlyPolicy policy, const SharedTopOfBook *top, Side side, OrderType type, TimeInForce tif, price_t price, bool &warned, std::string_view who)
bool rests(OrderType type, TimeInForce tif) noexcept
constexpr int64_t QTY_SCALE
Definition types.hpp:21
char instrument[MAX_INSTRUMENT_LENGTH]
Definition event.hpp:61
BrokerId broker_id
Definition event.hpp:60