algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
adapter.hpp
1#pragma once
2
8#define ATL_BROKER_ADAPTER_PRESENT 1
9
10#include <algotradelib/network>
11
12#include <boost/json.hpp>
13
14#include <charconv>
15#include <cstddef>
16#include <cstdint>
17#include <limits>
18#include <optional>
19#include <string>
20#include <string_view>
21#include <utility>
22
23namespace algotradelib::broker_detail {
24
25// Reads a whole-number header, or nothing when it is absent or malformed. Which headers carry meaning
26// is a broker's own contract, so each adapter reads the ones its documentation promises; only the
27// parsing lives here.
28inline std::optional<std::int64_t> integer_header(const network::HttpResponse& response, std::string_view name) {
29 const auto value = response.base().find(name);
30 if (value == response.base().end()) {
31 return std::nullopt;
32 }
33 const auto text = value->value();
34 std::int64_t number{0};
35 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), number);
36 if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || number < 0) {
37 return std::nullopt;
38 }
39 return number;
40}
41
42// The most of a reply body an error message carries. The error envelopes seen so far (a code, a
43// message, a request id) fit; whatever else arrives is not copied whole into logs and journals. It is
44// an excerpt, not redaction.
45inline constexpr std::size_t reply_excerpt_limit = 512;
46
47// Returns `body` whole if it fits in `limit` bytes; otherwise its first `limit` bytes, cut back so no
48// UTF-8 character is split (KIS and Kiwoom write Korean), then how many bytes were left out. A UTF-8
49// character is at most four bytes, so the cut moves back at most three: a body that is not UTF-8
50// keeps its prefix rather than losing it to a run of continuation bytes.
51inline std::string reply_excerpt(std::string_view body, std::size_t limit = reply_excerpt_limit) {
52 if (body.size() <= limit) {
53 return std::string(body);
54 }
55 std::size_t cut = limit;
56 while (cut > 0 && limit - cut < 3 && (static_cast<unsigned char>(body[cut]) & 0xC0U) == 0x80U) {
57 --cut;
58 }
59 return std::string(body.substr(0, cut)) + "... (" + std::to_string(body.size() - cut) + " more bytes)";
60}
61
62inline BrokerError http_error(const network::HttpResponse& response) {
63 BrokerError error;
64 error.http_status_ = response.result_int();
65 error.category_ =
66 response.result() == http::status::too_many_requests ? ErrorCategory::RATE_LIMIT : ErrorCategory::HTTP;
67 error.message_ = reply_excerpt(response.body());
68 return error;
69}
70
71// Reads a response's body as a JSON object. A body that is not one is `PROTOCOL` `invalid_json`, with the
72// response's HTTP status kept and the parser's message, never the body.
73inline std::optional<json::object> parse_object(const network::HttpResponse& response, BrokerError& error) {
74 boost::system::error_code ec;
75 auto value = json::parse(response.body(), ec);
76 if (ec || !value.is_object()) {
77 error.category_ = ErrorCategory::PROTOCOL;
78 error.http_status_ = response.result_int();
79 error.broker_code_ = "invalid_json";
80 error.message_ = ec ? ec.message() : "JSON response is not an object";
81 return std::nullopt;
82 }
83 return std::move(value.as_object());
84}
85
86inline std::string json_string(const json::object& object, std::string_view key) {
87 const auto value = object.if_contains(key);
88 if (!value || !value->is_string()) {
89 throw std::runtime_error("missing string field: " + std::string(key));
90 }
91 return std::string(value->as_string());
92}
93
94inline std::int64_t json_int64(const json::object& object, std::string_view key) {
95 const auto value = object.if_contains(key);
96 if (!value) {
97 throw std::runtime_error("missing integer field: " + std::string(key));
98 }
99 if (value->is_int64()) {
100 return value->as_int64();
101 }
102 if (
103 value->is_uint64() && value->as_uint64() <= static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())
104 ) {
105 return static_cast<std::int64_t>(value->as_uint64());
106 }
107 throw std::runtime_error("invalid integer field: " + std::string(key));
108}
109
110inline bool valid_symbol(std::string_view symbol) {
111 if (symbol.empty()) {
112 return false;
113 }
114 for (const char ch : symbol) {
115 const bool valid =
116 (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '.' || ch == '-';
117 if (!valid) {
118 return false;
119 }
120 }
121 return true;
122}
123
124inline std::string query_encode(std::string_view value) {
125 static constexpr char hex[] = "0123456789ABCDEF";
126 std::string result;
127 result.reserve(value.size());
128 for (const unsigned char ch : value) {
129 const bool unreserved = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') ||
130 ch == '-' || ch == '.' || ch == '_' || ch == '~';
131 if (unreserved) {
132 result.push_back(static_cast<char>(ch));
133 } else {
134 result.push_back('%');
135 result.push_back(hex[ch >> 4]);
136 result.push_back(hex[ch & 0x0F]);
137 }
138 }
139 return result;
140}
141
142inline bool decimal_digits(std::string_view value, std::size_t length) {
143 if (value.size() != length) {
144 return false;
145 }
146 for (const char ch : value) {
147 if (ch < '0' || ch > '9') {
148 return false;
149 }
150 }
151 return true;
152}
153
154// Reads `YYYYMMDD` as a calendar date, or nothing when it is not one. Every character is checked as
155// a digit before any arithmetic, and the result must be a real date: `std::stoi` per component would
156// read `"2026092x"` as 2026-09-02, and unchecked digit arithmetic would read `"2026090:"` as
157// 2026-09-10, since `':'` follows `'9'`.
158inline std::optional<Date> compact_date(std::string_view text) {
159 if (!decimal_digits(text, 8)) {
160 return std::nullopt;
161 }
162 const auto number = [text](std::size_t offset, std::size_t length) {
163 int value = 0;
164 for (std::size_t index = offset; index < offset + length; ++index) {
165 value = value * 10 + (text[index] - '0');
166 }
167 return value;
168 };
169 Date date{number(0, 4), static_cast<unsigned>(number(4, 2)), static_cast<unsigned>(number(6, 2))};
170 return is_valid_date(date) ? std::optional<Date>(date) : std::nullopt;
171}
172
173inline Decimal64 percent_to_ratio(std::string_view value) {
174 const auto percent = Decimal64::parse(value);
175 if (percent.scale() > std::numeric_limits<std::uint8_t>::max() - 2) {
176 throw std::out_of_range("percentage scale exceeds Decimal64 range");
177 }
178
179 auto coefficient = percent.coefficient();
180 auto scale = static_cast<std::uint8_t>(percent.scale() + 2);
181 while (scale > 0 && coefficient % 10 == 0) {
182 coefficient /= 10;
183 --scale;
184 }
185 return Decimal64(coefficient, scale);
186}
187
188} // namespace algotradelib::broker_detail
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
http::response< http::string_body > HttpResponse
The HTTP response type the transport clients return.
@ RATE_LIMIT
The broker refused the request for its rate limit.
Definition types.hpp:958
@ HTTP
The broker answered with an HTTP error status (http_status_).
Definition types.hpp:954
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
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