Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
manual_strategy.hpp
Go to the documentation of this file.
1#pragma once
2
6#include <algorithm>
7#include <array>
8#include <atomic>
9#include <cstring>
10#include <memory>
11#include <string>
12#include <string_view>
13#include <type_traits>
14#include <unordered_set>
15#include <utility>
16#include <vector>
17
18namespace slick::trader {
19
20// Lightweight strategy that owns all orders placed manually through the Web UI.
21// Always registered at startup. It lists the instruments brokers define for the Web UI's
22// ladders to pick from, and subscribes an instrument's level 2 book and trades only while a
23// ladder shows it: the WebServer holds and releases them over the bus. In MANUAL.config.json (any
24// <name>.config.json naming it), parameter "instruments" narrows the list: symbols, or prefixes
25// ending in '*' ("ZN*"). With no such parameter it lists everything defined, with [] nothing.
27public:
28 static constexpr const char* ID = "MANUAL";
29 static constexpr uint32_t CHUNK_SIZE = 256;
30 static constexpr uint32_t MAX_INSTRUMENTS = CHUNK_SIZE * 256;
31 // What it subscribes of each instrument a ladder holds, SUBSCRIPTIONS[i] for LadderFeed bit i:
32 // the book, and the trades for its LTQ.
33 static constexpr std::array<SubscriptionType, 2> SUBSCRIPTIONS{SubscriptionType::LEVEL2, SubscriptionType::TRADE};
34 static_assert(LADDER_BOOK == 1 << 0 && LADDER_TRADES == 1 << 1, "LadderFeed bits follow SUBSCRIPTIONS");
35
37
38 // The feeds ladders hold, one request per broker and type. Each is subscribed as it is held,
39 // not at start(). Read where the StrategyManager thread is not running: by add_strategy(),
40 // when nothing is held, and by stop() after the worker has joined, which unsubscribes them
41 // and has release_all() let go of them.
42 std::vector<SubscriptionRequest> get_subscriptions() const override {
43 std::vector<SubscriptionRequest> subs;
44 for (size_t b = 0; b < held_.size(); ++b) {
45 for (size_t i = 0; i < SUBSCRIPTIONS.size(); ++i) {
46 std::vector<std::string> instruments;
47 for (const auto& [instrument, feeds] : held_[b]) {
48 if (feeds & (1u << i)) {
49 instruments.push_back(instrument);
50 }
51 }
52 if (!instruments.empty()) {
53 subs.emplace_back(static_cast<BrokerId>(b), SUBSCRIPTIONS[i], std::move(instruments));
54 }
55 }
56 }
57 return subs;
58 }
59
60 // Calls `f(broker, instrument, tick_size, min_qty)` (or without min_qty, for an `f` that takes
61 // three) for each instrument listed from the `from`th on, in
62 // the order listed, and returns how many are listed: passed back as `from`, it hands over only
63 // what is new. Safe from any thread: the WebServer reads it while the StrategyManager lists.
64 template <typename F>
65 uint32_t for_each_listed(uint32_t from, F&& f) const {
66 const uint32_t count = count_.load(std::memory_order_acquire);
67 for (uint32_t i = from; i < count; ++i) {
68 const Slot& slot = chunks_[i / CHUNK_SIZE][i % CHUNK_SIZE];
69 if constexpr (std::is_invocable_v<F&, BrokerId, std::string_view, price_t, qty_t>) {
70 f(slot.broker, std::string_view(slot.instrument), slot.tick_size, slot.min_qty);
71 } else {
72 f(slot.broker, std::string_view(slot.instrument), slot.tick_size);
73 }
74 }
75 return count;
76 }
77
78 uint32_t listed_count() const noexcept { return count_.load(std::memory_order_acquire); }
79
80 // Lists an instrument a broker defined. False when the config does not take it, when listed
81 // already, when full, or when no broker is named: one of UNKNOWN takes no order and has no
82 // request queue. StrategyManager thread only: it is the one writer.
83 bool add_listing(BrokerId broker, std::string_view instrument, price_t tick_size = 0, qty_t min_qty = 0) {
84 const auto b = static_cast<size_t>(broker);
85 // Listed already is the common case, as a venue replays its definitions: found with no
86 // string built.
87 if (broker == BrokerId::UNKNOWN || b >= listed_.size() || !lists(instrument) ||
88 listed_[b].contains(instrument)) {
89 return false;
90 }
91 const uint32_t n = count_.load(std::memory_order_relaxed);
92 if (n == MAX_INSTRUMENTS) [[unlikely]] {
93 // Once: it stays full, and a venue's worth past it would each log a line.
94 if (!full_) {
95 full_ = true;
96 LOG_WARN("Strategy {}: listing the maximum of {} instruments, so {} and any it is offered after "
97 "are not listed",
98 ID, MAX_INSTRUMENTS, instrument);
99 }
100 return false;
101 }
102 listed_[b].emplace(instrument);
103 auto& chunk = chunks_[n / CHUNK_SIZE];
104 if (!chunk) {
105 chunk = std::make_unique<Slot[]>(CHUNK_SIZE);
106 }
107 Slot& slot = chunk[n % CHUNK_SIZE];
108 slot.broker = broker;
109 slot.tick_size = tick_size;
110 slot.min_qty = min_qty;
111 const size_t len = std::min(instrument.size(), sizeof(slot.instrument) - 1);
112 std::memcpy(slot.instrument, instrument.data(), len);
113 slot.instrument[len] = '\0';
114 count_.store(n + 1, std::memory_order_release);
115 return true;
116 }
117
118 // Whether the config takes `instrument`: by its symbol or a prefix, or all with no list.
119 bool lists(std::string_view instrument) const {
120 return all_ || symbols_.contains(instrument) ||
121 std::ranges::any_of(prefixes_, [&](const std::string& prefix) { return instrument.starts_with(prefix); });
122 }
123
124 // A ladder shows `instrument`: true when that makes its `feeds` (LadderFeed bits) held. Only
125 // one listed at `broker` can be, or one `subscribed` there by a strategy, which ladders list
126 // too. release() lets go, and returns the feeds it held, 0 for none. StrategyManager thread only.
127 bool hold(BrokerId broker, std::string_view instrument, bool subscribed = false, uint8_t feeds = LADDER_ALL) {
128 const auto b = static_cast<size_t>(broker);
129 return feeds != 0 && b < held_.size() && (subscribed || listed_[b].contains(instrument)) &&
130 held_[b].try_emplace(std::string(instrument), feeds).second;
131 }
132 uint8_t release(BrokerId broker, std::string_view instrument) {
133 const auto b = static_cast<size_t>(broker);
134 if (b >= held_.size()) {
135 return 0;
136 }
137 const auto it = held_[b].find(instrument);
138 if (it == held_[b].end()) {
139 return 0;
140 }
141 const uint8_t feeds = it->second;
142 held_[b].erase(it);
143 return feeds;
144 }
145 void release_all() {
146 for (auto& held : held_) {
147 held.clear();
148 }
149 }
150
151protected:
152 bool on_initialize() override { return true; }
153
154 // At load, and on a parameter update from the Web UI, on the StrategyManager thread, which
155 // then lists the instruments brokers defined already that the new list takes. An update
156 // replaces the list, as it does every parameter, here and in the file it is saved to: one
157 // without "instruments" takes everything. What is listed stays listed.
158 void on_config(const nlohmann::json& params) override {
159 symbols_.clear();
160 prefixes_.clear();
161 const auto it = params.find("instruments");
162 all_ = it == params.end() || !it->is_array();
163 if (all_) {
164 LOG_INFO("Strategy {}: lists every instrument brokers define", ID);
165 return;
166 }
167 for (const auto& entry : *it) {
168 if (!entry.is_string()) {
169 continue;
170 }
171 auto symbol = entry.get<std::string>();
172 if (symbol.ends_with('*')) {
173 symbol.pop_back();
174 prefixes_.push_back(std::move(symbol));
175 } else {
176 symbols_.insert(std::move(symbol));
177 }
178 }
179 LOG_INFO("Strategy {}: lists {} symbol(s) and {} prefix(es) as brokers define them", ID, symbols_.size(),
180 prefixes_.size());
181 }
182
183private:
184 struct Slot {
185 BrokerId broker;
186 price_t tick_size; // 0 when its broker did not say
187 qty_t min_qty; // 0 when its broker did not say
188 char instrument[MAX_INSTRUMENT_LENGTH];
189 };
190
191 static constexpr size_t BROKER_COUNT = static_cast<size_t>(BrokerId::_BROKER_ID_COUNT_);
192
193 // Append-only, so readers take no lock: a slot is written before the count that covers
194 // it is released, and never changes after. Chunks grow memory only with what is listed.
195 std::array<std::unique_ptr<Slot[]>, MAX_INSTRUMENTS / CHUNK_SIZE> chunks_;
196 std::atomic<uint32_t> count_{0};
197 // Writer only: what it lists and holds, by broker, and what the config takes.
198 std::array<StringSet, BROKER_COUNT> listed_;
199 std::array<StringMap<uint8_t>, BROKER_COUNT> held_; // instrument -> the LadderFeed bits held
200 StringSet symbols_;
201 std::vector<std::string> prefixes_;
202 bool all_ = true; // no "instruments" list: everything
203 bool full_ = false; // MAX_INSTRUMENTS listed, and said so
204};
205
206} // namespace slick::trader
void on_config(const nlohmann::json &params) override
static constexpr const char * ID
bool hold(BrokerId broker, std::string_view instrument, bool subscribed=false, uint8_t feeds=LADDER_ALL)
static constexpr std::array< SubscriptionType, 2 > SUBSCRIPTIONS
uint32_t listed_count() const noexcept
std::vector< SubscriptionRequest > get_subscriptions() const override
bool lists(std::string_view instrument) const
bool add_listing(BrokerId broker, std::string_view instrument, price_t tick_size=0, qty_t min_qty=0)
uint8_t release(BrokerId broker, std::string_view instrument)
uint32_t for_each_listed(uint32_t from, F &&f) const
static constexpr uint32_t CHUNK_SIZE
static constexpr uint32_t MAX_INSTRUMENTS
StrategyBase(const std::string &name, const std::string &version)
std::unordered_set< std::string, StringHash, std::equal_to<> > StringSet
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
constexpr size_t MAX_INSTRUMENT_LENGTH
Definition event.hpp:13