Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#ifdef _WIN32
2#define WIN32_LEAN_AND_MEAN
3#include <winsock2.h>
4#include <ws2tcpip.h>
5#endif
6
7#include <slick/logger.hpp>
8// #include <slick/socket/tcp_server.h>
9// #include <order_gateway/order_gateway.hpp>
10// #include <order_gateway/message_parser.hpp>
11#include <exchange/exchange.hpp>
14#include <common/messages.hpp>
15#include <cli/cli_endpoint.hpp>
16#ifdef SLICK_SIM_HAS_CLI
17#include <cli/cli_server.hpp>
18#endif
19// #include <market_data_publisher/market_data_publisher.hpp>
20#ifdef SLICK_SIM_HAS_SLICK_NET
21// slick::net belongs to the venue adapters that speak HTTP/WebSocket, not to the
22// simulator: it arrives only because such an adapter declared it, so the log bridge
23// below is compiled in only then. A core-only build has no networking to bridge,
24// and neither would a venue on a different stack - a CME or ICE adapter over
25// slick::socket. main.cpp still names no venue: the flag is set from the link list.
26#include <slick/net/logging.hpp>
27#endif
28#include <exception>
29#include <format>
30#include <iostream>
31#include <thread>
32#include <chrono>
33#include <string>
34#include <filesystem>
35#include <csignal>
36#include <fstream>
37
38using namespace slick::sim;
39using namespace slick::sim::order_gateway;
40using namespace slick::sim::md_publisher;
41using json = nlohmann::json;
43
44namespace
45{
46 std::atomic_bool run{true};
47
48 extern "C" void _signal_handler(int /* signum */)
49 {
50 run.store(false, std::memory_order_release);
51 // exit(signum); // Terminate the program
52 }
53
56 bool serve_sim_command(const cli::Command &command, std::string &out)
57 {
58 auto &logger = slick::logger::Logger::instance();
59 switch (command.command)
60 {
62 if (!command.arg_view().empty())
63 {
64 try
65 {
66 logger.set_level(slick::logger::to_log_level(command.arg_view()));
67 }
68 catch (const std::invalid_argument &)
69 {
70 out = std::format("unknown log level '{}'", command.arg_view());
71 return false;
72 }
73 }
74 out = std::format("log level {}", slick::logger::to_string(logger.get_level()));
75 return true;
77 run.store(false, std::memory_order_release);
78 out = "stopping";
79 return true;
80 default:
81 return cli::refuse_unserved(command, out);
82 }
83 }
84}
85
86int main(int argc, char *argv[])
87{
88
89 std::signal(SIGINT, _signal_handler);
90
91 auto &logger = slick::logger::Logger::instance();
92 logger.clear_sinks();
93#ifdef DEBUG
94 logger.add_console_sink(true, true);
95#endif
96 logger.add_file_sink("logs/slick-sim.log");
97 logger.init(65535, 16777216);
98
99#ifdef SLICK_SIM_HAS_SLICK_NET
100 slick::net::set_log_handler(
101 [&logger](slick::net::LogLevel level, const char *format_text, std::format_args args)
102 {
103 logger.log(static_cast<slick::logger::LogLevel>(level), format_text, std::move(args));
104 },
105 [&logger]() -> slick::net::LogLevel
106 {
107 return static_cast<slick::net::LogLevel>(logger.get_level());
108 });
109#endif
110
111 std::string config_file = "slick-sim.json";
112 if (argc > 1)
113 {
114 config_file = argv[1];
115 }
116
117 if (!std::filesystem::exists(config_file))
118 {
119 std::cout << "Missing configuration JSON file. Usange\n"
120 << " slick-sim [config_file]\n"
121 << " options:\n"
122 << " config_file: config JSON file. Default to slick-sim.json";
123 LOG_ERROR("Missing configuration JSON file. Usage\n slick-sim [config_file]\n options:\n config_file: config JSON file. Default to slick-sim.json");
124 return EXIT_FAILURE;
125 }
126
127 std::fstream f(config_file);
128 json config;
129 try
130 {
131 config = json::parse(f);
132 }
133 catch (const json::parse_error &ex)
134 {
135 std::cerr << "Parsing failed: \n"
136 << ex.byte;
137 LOG_ERROR("Parsing failed: \n{}", ex.byte);
138 return EXIT_FAILURE;
139 }
140
141 if (!config.contains("exchanges"))
142 {
143 std::cerr << "Missing exchanges config";
144 LOG_ERROR("Missing exchanges config");
145 return EXIT_FAILURE;
146 }
147
148 logger.set_level(slick::logger::to_log_level(config.value("log_level", "info")));
149
151
152 // A venue that was compiled out otherwise looks exactly like a typo in the
153 // config, so say up front which adapters this binary actually carries.
154 std::string built_in;
155 for (const auto &key : registry.keys())
156 {
157 if (!built_in.empty())
158 {
159 built_in += ", ";
160 }
161 built_in += key;
162 }
163 LOG_INFO("Venue adapters built in: {}", built_in.empty() ? "(none)" : built_in);
164
165 auto &exch_coinfig = config["exchanges"];
166 std::vector<std::unique_ptr<Exchange>> exchanges;
167 // The CLI endpoints of each venue config key's exchanges, which that key addresses.
168 std::vector<std::pair<std::string, std::vector<cli::CliEndpoint *>>> cli_groups;
169 // The feeds' endpoints (`pcap/<venue>/<feed>`), addressed only by their names.
170 std::vector<cli::CliEndpoint *> feed_endpoints;
171 std::vector<exch::FeedInfo> feeds;
172 for (auto it = exch_coinfig.begin(); it != exch_coinfig.end(); ++it)
173 {
174 // Checked BEFORE the registry lookup, deliberately: the committed sample
175 // config carries a "cme" block with "enabled": false, and a disabled venue
176 // must not require an adapter to exist.
177 if (!it.value().value("enabled", true))
178 {
179 LOG_INFO("Exchange {} is disabled, skipping", it.key());
180 continue;
181 }
182
183 auto factory = registry.find(it.key());
184 if (!factory)
185 {
186 // This used to fall through to a bare Exchange, which bound no ports and
187 // processed at most one request before going quiet. Failing loudly is
188 // also what turns a venue whose registration the linker dropped into an
189 // obvious error rather than a mystery.
190 std::cerr << "No venue adapter for exchanges.\"" << it.key() << "\"\n";
191 LOG_ERROR("No venue adapter for exchanges.\"{}\". This build has: {}. "
192 "Check the spelling, or configure with -DSLICK_SIM_ENABLE_<VENUE>=ON.",
193 it.key(), built_in.empty() ? "(none)" : built_in);
194 return EXIT_FAILURE;
195 }
196
197 // A venue split into instances (an exchange's market segments) yields several.
198 // A venue rejects a config it cannot run by throwing - say why, rather
199 // than terminating on an uncaught exception.
200 std::vector<std::unique_ptr<Exchange>> created;
201 try
202 {
203 created = factory(it.value());
204 for (const auto &exchange : created)
205 {
206 auto enabled = exchange->enabledFeeds(); // before start(), see there
207 feeds.insert(feeds.end(), enabled.begin(), enabled.end());
208 }
210 }
211 catch (const std::exception &ex)
212 {
213 std::cerr << "exchanges.\"" << it.key() << "\": " << ex.what() << "\n";
214 LOG_ERROR("exchanges.\"{}\": {}", it.key(), ex.what());
215 return EXIT_FAILURE;
216 }
217 auto &group = cli_groups.emplace_back(it.key(), std::vector<cli::CliEndpoint *>{}).second;
218 for (auto &exchange : created)
219 {
220 exchanges.emplace_back(std::move(exchange));
221 auto endpoints_of_feeds = exchanges.back()->feedCliEndpoints(); // before start(), see there
222 feed_endpoints.insert(feed_endpoints.end(), endpoints_of_feeds.begin(), endpoints_of_feeds.end());
223 auto endpoints = exchanges.back()->cliEndpoints();
224 group.insert(group.end(), endpoints.begin(), endpoints.end());
225 }
226 }
227
228 // Only once every venue is built and its feeds accepted, so a config error leaves none running.
229 for (auto &exch : exchanges)
230 {
231 exch->start();
232 }
233 auto stop_exchanges = [&exchanges]
234 {
235 for (auto &exch : exchanges)
236 {
237 exch->stop();
238 }
239 };
240
241 // Declared after `exchanges`, so destroyed first: the server reads the endpoints
242 // the exchanges' gateways own.
243 cli::CliEndpoint sim_cli("sim");
244 bool cli_running = false;
245#ifdef SLICK_SIM_HAS_CLI
246 std::unique_ptr<cli::CliServer> cli_server;
247#endif
248 if (config.contains("cli") && config["cli"].value("enabled", true))
249 {
250#ifdef SLICK_SIM_HAS_CLI
251 const auto &cli_config = config["cli"];
252 slick::socket::TCPServerConfig tcp;
253 tcp.port = cli_config.value("port", cli::CliServer::DEFAULT_PORT);
254 tcp.max_connections = cli_config.value("max_connections", 4);
255 tcp.idle_timeout = std::chrono::seconds(
256 cli_config.value("idle_timeout", cli::CliServer::DEFAULT_IDLE_TIMEOUT.count()));
257 cli_server = std::make_unique<cli::CliServer>(tcp);
258 cli_server->add_endpoints("sim", {&sim_cli});
259 for (const auto &[key, endpoints] : cli_groups)
260 {
261 cli_server->add_endpoints(key, endpoints);
262 }
263 // No group: `pcap`, `pcap/cme` and so on come from the names, and `cme` stays the gateways'.
264 cli_server->add_endpoints({}, feed_endpoints);
265 cli_server->set_feeds(exch::list_feeds(feeds));
266 cli_server->set_version(SLICK_SIM_VERSION);
267 if (!cli_server->start())
268 {
269 std::cerr << "CLI failed to start on port " << tcp.port << "\n";
270 // Not left to ~Exchange(), which joins a thread that has lost its venue's members.
271 stop_exchanges();
272 return EXIT_FAILURE;
273 }
274 cli_running = true;
275#else
276 LOG_WARN("\"cli\" is configured, but this build has no CLI: it needs SLICK_SIM_ENABLE_TCP_GATEWAY");
277#endif
278 }
279
280 // Wait for user input to stop
281 LOG_INFO("Press Ctrl+C to stop the server...");
282 while (run.load(std::memory_order_relaxed))
283 {
284 sim_cli.serve(serve_sim_command);
285 std::this_thread::sleep_for(cli_running ? std::chrono::milliseconds(10) : std::chrono::milliseconds(1000));
286 }
287
288#ifdef SLICK_SIM_HAS_CLI
289 if (cli_server)
290 {
291 // Lets the answer to a SHUTDOWN go out, then stops the server before the
292 // exchanges, whose gateways own its endpoints.
293 cli_server->flush(std::chrono::milliseconds(500));
294 cli_server->stop();
295 }
296#endif
297
298 stop_exchanges();
299
300 LOG_INFO("ExchangeSimulator stopped");
301 return EXIT_SUCCESS;
302}
Where the CLI server's commands reach a thread that owns some state (the main thread,...
void serve(Handler &&handler)
Owner thread.
static constexpr uint16_t DEFAULT_PORT
static constexpr std::chrono::seconds DEFAULT_IDLE_TIMEOUT
For TCPServerConfig::idle_timeout, so dead connections can't hold every slot.
static ExchangeRegistry & instance()
nlohmann::json json
Definition order.hpp:16
int main(int argc, char *argv[])
Definition main.cpp:86
slick::sim::exch::Exchange Exchange
Definition main.cpp:42
bool refuse_unserved(const Command &command, std::string &out)
A handler's answer to a command it doesn't serve: says so in out, false.
Helpers for a venue whose one config entry describes several independent exchange instances,...
Definition exchange.hpp:30
void reject_mixed_feeds(const std::vector< FeedInfo > &feeds)
Throws when one venue has both live and pcap feeds, in whichever of its instances: a venue's market i...
Definition feed_info.hpp:22
std::string list_feeds(const std::vector< FeedInfo > &feeds)
<live|pcap> <name> per feed, one per line: the CLI's answer to feeds.
Definition feed_info.hpp:36
@ SET_LOG_LEVEL
sim. arg is the level; empty reports the current one.
@ SHUTDOWN
sim. Stops the simulator.
One command, as the CLI server hands it to the thread that runs it.
std::string_view arg_view() const noexcept