algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
calendar_cache.hpp
1#pragma once
2
3#include "../core/calendar.hpp"
4
5#include <optional>
6#include <string>
7#include <string_view>
8
9namespace algotradelib {
10namespace network {
11
24public:
25 virtual ~CalendarCache() = default;
26
32 virtual Result<std::optional<TradingCalendar>> load(const std::string& name) = 0;
33
40 virtual std::optional<BrokerError> publish(const std::string& name, const TradingCalendar& calendar) = 0;
41};
42
48inline BrokerError calendar_cache_error(std::string_view reason) {
49 BrokerError error;
51 error.reached_broker_ = false;
52 error.broker_code_ = "calendar_cache";
53 error.message_ = std::string(reason);
54 return error;
55}
56
57} // namespace network
58} // namespace algotradelib
59
60#if !defined(_WIN32)
61
62#include <boost/json.hpp>
63
64#include <algorithm>
65#include <atomic>
66#include <cerrno>
67#include <chrono>
68#include <cstdint>
69#include <utility>
70
71#include <fcntl.h>
72#include <sys/stat.h>
73#include <unistd.h>
74
75namespace algotradelib {
76namespace network {
77
97public:
102 explicit FileCalendarCache(std::string folder) : folder_(std::move(folder)) {}
103
109 Result<std::optional<TradingCalendar>> load(const std::string& name) override {
110 Descriptor folder;
111 if (auto error = open_folder(name, folder)) {
112 return *error;
113 }
114 Descriptor file;
115 if (auto error = open_file(folder, name, file)) {
116 return *error;
117 }
118 if (file.get() < 0) {
119 return std::optional<TradingCalendar>();
120 }
121 std::string text;
122 char buffer[4096];
123 while (text.size() <= MAXIMUM_FILE) {
124 const auto count = ::read(file.get(), buffer, sizeof(buffer));
125 if (count == 0) {
126 return parse(text);
127 }
128 if (count < 0 && errno != EINTR) {
129 return calendar_cache_error("calendar cache: the file could not be read");
130 }
131 if (count > 0) {
132 text.append(buffer, static_cast<std::size_t>(count));
133 }
134 }
135 return std::optional<TradingCalendar>();
136 }
137
144 std::optional<BrokerError> publish(const std::string& name, const TradingCalendar& calendar) override {
145 const auto latest = std::chrono::duration_cast<std::chrono::system_clock::duration>(LATEST_RECEIPT);
146 const auto received = calendar.received_at_.time_since_epoch();
147 if (received < -latest || latest < received) {
148 return calendar_cache_error("calendar cache: the receipt time is outside the range the file holds");
149 }
150 Descriptor folder;
151 if (auto error = open_folder(name, folder)) {
152 return error;
153 }
154 Descriptor existing;
155 if (auto error = open_file(folder, name, existing)) {
156 return error;
157 }
158 auto temporary = write_temporary(folder, name, serialize(calendar));
159 if (!temporary) {
160 return std::move(temporary.error());
161 }
162 return rename_temporary(folder, name, temporary.value());
163 }
164
165private:
166 friend struct FileCalendarCacheTestAccess;
167
168 // Opened without following a link, closed on exec, and never blocking on a special file.
169 static constexpr int FILE_FLAGS = O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK;
170 // Larger calendar files are not well formed.
171 static constexpr std::size_t MAXIMUM_FILE = 256 * 1024;
172 // The receipt times the file holds, either side of the epoch: a day of margin keeps their date in Seoul within the clock's range.
173 static constexpr auto LATEST_RECEIPT = std::chrono::nanoseconds::max() - std::chrono::hours(24);
174
175 // Owns a descriptor; negative for none.
176 class Descriptor {
177 public:
178 explicit Descriptor(int descriptor = -1) noexcept : descriptor_(descriptor) {}
179
180 ~Descriptor() {
181 if (descriptor_ >= 0) {
182 ::close(descriptor_);
183 }
184 }
185
186 Descriptor(const Descriptor&) = delete;
187 Descriptor& operator=(const Descriptor&) = delete;
188
189 int get() const noexcept {
190 return descriptor_;
191 }
192
193 void reset(int descriptor) noexcept {
194 if (descriptor_ >= 0) {
195 ::close(descriptor_);
196 }
197 descriptor_ = descriptor;
198 }
199
200 private:
201 int descriptor_;
202 };
203
204 // Tests what the cache requires of everything it opens: the type, the user's own, nothing for group or others.
205 static bool owned_privately(int descriptor, mode_t type) noexcept {
206 struct stat status{};
207 return ::fstat(descriptor, &status) == 0 && (status.st_mode & S_IFMT) == type && status.st_uid == ::geteuid() &&
208 (status.st_mode & 077) == 0;
209 }
210
211 // Checks the name can name a file (letters, digits, `-` and `_`, at most 200), then creates the folder if it does not exist and opens it, checked.
212 std::optional<BrokerError> open_folder(const std::string& name, Descriptor& folder) const {
213 bool safe = !name.empty() && name.size() <= 200;
214 for (const char ch : name) {
215 safe = safe &&
216 ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_');
217 }
218 if (!safe) {
219 return calendar_cache_error("calendar cache: the name cannot name a file");
220 }
221 if (::mkdir(folder_.c_str(), 0700) != 0 && errno != EEXIST) {
222 return calendar_cache_error("calendar cache: the folder could not be created");
223 }
224 folder.reset(::open(folder_.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
225 if (folder.get() < 0) {
226 struct stat status{};
227 const bool link = ::lstat(folder_.c_str(), &status) == 0 && S_ISLNK(status.st_mode);
229 link ? "calendar cache: the folder is a symbolic link" : "calendar cache: the folder could not be opened"
230 );
231 }
232 if (!owned_privately(folder.get(), S_IFDIR)) {
233 return calendar_cache_error("calendar cache: the folder is not private (owner or permissions)");
234 }
235 return std::nullopt;
236 }
237
238 // Opens the name's calendar file, checked; leaves `file` closed when there is none.
239 static std::optional<BrokerError> open_file(const Descriptor& folder, const std::string& name, Descriptor& file) {
240 file.reset(::openat(folder.get(), (name + ".calendar").c_str(), FILE_FLAGS | O_RDONLY));
241 if (file.get() < 0 && errno == ENOENT) {
242 return std::nullopt;
243 }
244 if (file.get() < 0) {
246 errno == ELOOP ? "calendar cache: the file is a symbolic link" : "calendar cache: the file could not be opened"
247 );
248 }
249 if (!owned_privately(file.get(), S_IFREG)) {
250 return calendar_cache_error("calendar cache: the file is not private (owner, permissions or type)");
251 }
252 return std::nullopt;
253 }
254
255 // Returns a country's ISO 3166 code, as the file stores it.
256 static const char* country_code(Country country) noexcept {
257 switch (country) {
258 case Country::KR:
259 return "KR";
260 case Country::US:
261 return "US";
262 }
263 return "";
264 }
265
266 // Writes the calendar's file text.
267 static std::string serialize(const TradingCalendar& calendar) {
268 boost::json::array days;
269 days.reserve(calendar.days_.size());
270 for (const auto& day : calendar.days_) {
271 const std::int64_t date =
272 std::int64_t{day.date_.year_} * 10000 + std::int64_t{day.date_.month_} * 100 + std::int64_t{day.date_.day_};
273 days.push_back(boost::json::array{date, day.open_});
274 }
275 boost::json::object document;
276 document["format"] = 1;
277 document["country"] = country_code(calendar.country_);
278 document["received_at_ns"] =
279 std::chrono::duration_cast<std::chrono::nanoseconds>(calendar.received_at_.time_since_epoch()).count();
280 document["unreadable_days"] = calendar.unreadable_days_;
281 document["days"] = std::move(days);
282 return boost::json::serialize(document);
283 }
284
285 // Reads a calendar file's text; nothing unless every field is present, of its type and in its range.
286 static std::optional<TradingCalendar> parse(const std::string& text) {
287 boost::system::error_code ec;
288 const auto document = boost::json::parse(text, ec);
289 if (ec || !document.is_object()) {
290 return std::nullopt;
291 }
292 const auto& object = document.as_object();
293 const auto* format = object.if_contains("format");
294 const auto* country = object.if_contains("country");
295 const auto* received = object.if_contains("received_at_ns");
296 const auto* unreadable = object.if_contains("unreadable_days");
297 const auto* days = object.if_contains("days");
298 if (
299 !format || !format->is_int64() || format->as_int64() != 1 || !country || !country->is_string() || !received ||
300 !received->is_int64() || !unreadable || !unreadable->is_int64() || !days || !days->is_array()
301 ) {
302 return std::nullopt;
303 }
304 TradingCalendar calendar;
305 const auto named = std::find_if(all_countries.begin(), all_countries.end(), [country](Country candidate) {
306 return country->as_string() == country_code(candidate);
307 });
308 if (named == all_countries.end()) {
309 return std::nullopt;
310 }
311 calendar.country_ = *named;
312 const auto since_epoch = std::chrono::nanoseconds(received->as_int64());
313 if (since_epoch < -LATEST_RECEIPT || LATEST_RECEIPT < since_epoch) {
314 return std::nullopt;
315 }
316 calendar.received_at_ = std::chrono::system_clock::time_point(
317 std::chrono::duration_cast<std::chrono::system_clock::duration>(since_epoch)
318 );
319 if (unreadable->as_int64() < 0 || static_cast<std::uint64_t>(unreadable->as_int64()) > SIZE_MAX) {
320 return std::nullopt;
321 }
322 calendar.unreadable_days_ = static_cast<std::size_t>(unreadable->as_int64());
323 calendar.days_.reserve(days->as_array().size());
324 for (const auto& row : days->as_array()) {
325 if (
326 !row.is_array() || row.as_array().size() != 2 || !row.as_array()[0].is_int64() || !row.as_array()[1].is_bool()
327 ) {
328 return std::nullopt;
329 }
330 const auto number = row.as_array()[0].as_int64();
331 if (number < 10101 || number > 99991231) {
332 return std::nullopt;
333 }
334 const Date date{
335 static_cast<int>(number / 10000),
336 static_cast<unsigned>(number / 100 % 100),
337 static_cast<unsigned>(number % 100),
338 };
339 if (!is_valid_date(date)) {
340 return std::nullopt;
341 }
342 calendar.days_.push_back(TradingDay{date, row.as_array()[1].as_bool()});
343 }
344 return calendar;
345 }
346
347 // Creates a temporary file of the caller's own (a name taken by another is not opened), writes `text` to it and flushes it; returns its name.
348 static Result<std::string> write_temporary(
349 const Descriptor& folder, const std::string& name, const std::string& text
350 ) {
351 static std::atomic<unsigned long> counter{0};
352 std::string temporary;
353 Descriptor file;
354 for (int attempt = 0; attempt < 100 && file.get() < 0; ++attempt) {
355 temporary = name + ".calendar." + std::to_string(::getpid()) + '-' + std::to_string(counter++) + ".tmp";
356 file.reset(::openat(folder.get(), temporary.c_str(), FILE_FLAGS | O_WRONLY | O_CREAT | O_EXCL, 0600));
357 if (file.get() < 0 && errno != EEXIST) {
358 break;
359 }
360 }
361 if (file.get() < 0) {
362 return calendar_cache_error("calendar cache: a temporary file could not be created");
363 }
364 bool written = true;
365 for (std::size_t offset = 0; written && offset < text.size();) {
366 const auto count = ::write(file.get(), text.data() + offset, text.size() - offset);
367 if (count > 0) {
368 offset += static_cast<std::size_t>(count);
369 } else if (count == 0 || errno != EINTR) {
370 written = false;
371 }
372 }
373 if (!written || ::fsync(file.get()) != 0) {
374 ::unlinkat(folder.get(), temporary.c_str(), 0);
375 return calendar_cache_error("calendar cache: the calendar file could not be written");
376 }
377 return temporary;
378 }
379
380 // Renames the caller's own temporary file over the calendar file; removes it if the rename fails.
381 static std::optional<BrokerError> rename_temporary(
382 const Descriptor& folder, const std::string& name, const std::string& temporary
383 ) {
384 if (::renameat(folder.get(), temporary.c_str(), folder.get(), (name + ".calendar").c_str()) != 0) {
385 ::unlinkat(folder.get(), temporary.c_str(), 0);
386 return calendar_cache_error("calendar cache: the calendar file could not be written");
387 }
388 return std::nullopt;
389 }
390
391 std::string folder_;
392};
393
394} // namespace network
395} // namespace algotradelib
396
397#endif
Either a value or a BrokerError.
Definition types.hpp:1058
Where blocking broker clients share a market's trading calendar, across threads and processes.
virtual std::optional< BrokerError > publish(const std::string &name, const TradingCalendar &calendar)=0
Stores a calendar under a name, replacing what was stored.
virtual Result< std::optional< TradingCalendar > > load(const std::string &name)=0
Reads the calendar stored under a name.
FileCalendarCache(std::string folder)
Constructs a cache; nothing is created or opened until the first call.
Result< std::optional< TradingCalendar > > load(const std::string &name) override
Reads the name's calendar file.
std::optional< BrokerError > publish(const std::string &name, const TradingCalendar &calendar) override
Replaces the name's calendar file.
HTTP and WebSocket transport, OAuth tokens, and request pacing.
BrokerError calendar_cache_error(std::string_view reason)
Returns a calendar cache's error: TRANSPORT, not sent to the broker, code calendar_cache.
The library: broker-neutral types (core), and the modules below.
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
Country
A country (market) the library supports.
Definition types.hpp:32
bool is_valid_date(const Date &date)
Tests whether a date exists in the Gregorian calendar, in years 1 to 9999.
Definition types.hpp:1480
constexpr std::array< Country, 2 > all_countries
Every Country, in declaration order.
Definition types.hpp:38
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
std::chrono::system_clock::time_point received_at_
When the calendar was received, on this machine's clock.
Definition calendar.hpp:78