algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
config.hpp
1#pragma once
2
3#include "../../network/oauth.hpp"
4#include "../../network/token_store.hpp"
5
6#include "../../core/types.hpp"
7
8#include <boost/json.hpp>
9
10#include <chrono>
11#include <cstdlib>
12#include <ctime>
13#include <fstream>
14#include <iterator>
15#include <stdexcept>
16#include <string>
17#include <string_view>
18
19namespace algotradelib {
20namespace kiwoom {
21
22// https://openapi.kiwoom.com/guide/apiguide
23// Token issue: au10001 POST https://api.kiwoom.com/oauth2/token
24// Token revoke: au10002 POST https://api.kiwoom.com/oauth2/revoke
25struct KiwoomConfig;
26struct KiwoomRest;
27
34enum class MarketTape {
36 CONSOLIDATED,
38 KRX,
40 NXT,
41};
42
48inline constexpr const char* tape_suffix(MarketTape tape) noexcept {
49 switch (tape) {
50 case MarketTape::KRX:
51 return "";
52 case MarketTape::NXT:
53 return "_NX";
55 return "_AL";
56 }
57 return "_AL";
58}
59
66inline std::chrono::system_clock::time_point parse_compact_expiry(std::string_view text) {
67 if (text.size() != 14) {
68 return {};
69 }
70 for (const char digit : text) {
71 if (digit < '0' || digit > '9') {
72 return {};
73 }
74 }
75 const auto number = [text](std::size_t offset, std::size_t length) {
76 int value = 0;
77 for (std::size_t index = offset; index < offset + length; ++index) {
78 value = value * 10 + (text[index] - '0');
79 }
80 return value;
81 };
82 std::tm parts{};
83 parts.tm_year = number(0, 4) - 1900;
84 parts.tm_mon = number(4, 2) - 1;
85 parts.tm_mday = number(6, 2);
86 parts.tm_hour = number(8, 2);
87 parts.tm_min = number(10, 2);
88 parts.tm_sec = number(12, 2);
89 parts.tm_isdst = 0;
90#ifdef _WIN32
91 const std::time_t utc = _mkgmtime(&parts) - 9 * 3600;
92#else
93 const std::time_t utc = timegm(&parts) - 9 * 3600;
94#endif
95 return std::chrono::system_clock::from_time_t(utc);
96}
97
115
125inline constexpr bool kiwoom_position_scope_asserted(KiwoomPositionScope scope) noexcept {
126 switch (scope) {
128 return false;
130 return true;
131 }
132 return false;
133}
134
145
155struct KiwoomConfig : public network::ClientCredentials<KiwoomConfig> {
163 bool is_demo_ = true;
164
172
183 Venue holdings_venue_ = Venue::UNSPECIFIED;
184
195
204
211 const char* key = std::getenv("KIWOOM_APP_KEY");
212 const char* secret = std::getenv("KIWOOM_SECRET_KEY");
213 if (!key || !secret) {
214 throw std::runtime_error("Add KIWOOM_APP_KEY and KIWOOM_SECRET_KEY environment variables.");
215 }
216 // Read before anything is assigned, so a refused load leaves this config as it was.
217 const bool demo = demo_from_env();
218 key_ = key;
219 secret_ = secret;
220 is_demo_ = demo;
221 }
222
234 void from_json_impl(const std::string& filename) {
235 std::ifstream ifs(filename);
236 if (!ifs.is_open()) {
237 throw std::runtime_error("Cannot open Kiwoom credential file: " + filename);
238 }
239 const std::string content(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>{});
240 from_json_text_impl(content, "file " + filename);
241 }
242
251 void from_json_text_impl(std::string_view text, const std::string& origin) {
252 boost::system::error_code ec;
253 const auto jv = json::parse(text, ec);
254 if (ec || !jv.is_object()) {
255 throw std::runtime_error(
256 "Failed to parse Kiwoom credentials " + origin +
257 (ec ? " — " + ec.message() : std::string(" — not a JSON object"))
258 );
259 }
260 const auto& doc = jv.as_object();
261 const json::value* key = doc.if_contains("appkey");
262 const json::value* secret = doc.if_contains("secretkey");
263 if (!key || !secret || !key->is_string() || !secret->is_string()) {
264 throw std::runtime_error("Kiwoom credential " + origin + " should contain appkey and secretkey as strings");
265 }
266 // Everything is read and checked before anything is assigned, so a refused document leaves this
267 // config -- and the endpoint it already selected -- exactly as it was.
268 const bool demo = demo_from_json(doc, origin);
269 key_ = key->get_string().c_str();
270 secret_ = secret->get_string().c_str();
271 is_demo_ = demo;
272 }
273
279 static bool demo_from_env() {
280 const char* demo = std::getenv("KIWOOM_DEMO");
281 if (!demo || std::string_view(demo) == "1") {
282 return true;
283 }
284 if (std::string_view(demo) == "0") {
285 return false;
286 }
287 throw std::runtime_error(
288 std::string("KIWOOM_DEMO is \"") + demo +
289 "\"; set it to 1 for the demo endpoints or 0 to trade "
290 "live, or leave it unset for demo."
291 );
292 }
293
301 static bool demo_from_json(const json::object& doc, const std::string& origin) {
302 const json::value* demo = doc.if_contains("demo");
303 if (!demo) {
304 return true;
305 }
306 if (!demo->is_bool()) {
307 throw std::runtime_error(
308 "Kiwoom credential " + origin +
309 " has a \"demo\" that is not true or false; write "
310 "true for the demo endpoints or false to trade live, or leave it out for demo."
311 );
312 }
313 return demo->get_bool();
314 }
315
320 static constexpr std::string_view key_field() noexcept {
321 return "appkey";
322 }
323
328 static constexpr std::string_view secret_field() noexcept {
329 return "secretkey";
330 }
331
336 std::string token_identity() const {
337 return network::token_identity("kiwoom", is_demo_ ? "demo" : "real", key_);
338 }
339
344 const char* rest_host() const noexcept {
345 return is_demo_ ? "mockapi.kiwoom.com" : "api.kiwoom.com";
346 }
347
352 const char* rest_port() const noexcept {
353 return "443";
354 }
355
360 const char* ws_host() const noexcept {
361 return is_demo_ ? "mockapi.kiwoom.com" : "api.kiwoom.com";
362 }
363
368 const char* ws_port() const noexcept {
369 return "10000";
370 }
371
377 std::string tape_symbol(std::string_view symbol) const {
378 return std::string(symbol) + tape_suffix(market_tape_);
379 }
380};
381
383struct KiwoomRest : public network::AuthBody<KiwoomRest> {
385 std::string token_type_;
386
391 static constexpr std::string_view token_field() noexcept {
392 return "token";
393 }
394
400 void from_json_impl(const json::object& doc) {
401 if (const auto expiry = doc.if_contains("expires_dt"); expiry && expiry->is_string()) {
402 expires_at_ = parse_compact_expiry(std::string_view(expiry->as_string()));
403 }
404 if (const auto type = doc.if_contains("token_type"); type && type->is_string()) {
405 token_type_ = type->as_string().c_str();
406 }
407 }
408};
409
410} // namespace kiwoom
411} // namespace algotradelib
OAuth client credentials (an app key and secret), the base of each broker's credentials class.
Definition oauth.hpp:37
const std::string & key() const noexcept
Definition oauth.hpp:78
const std::string & secret() const noexcept
Definition oauth.hpp:86
The Kiwoom Securities REST API client.
Definition auth.hpp:12
constexpr const char * tape_suffix(MarketTape tape) noexcept
Returns the symbol suffix for a tape.
Definition config.hpp:48
MarketTape
Which venue's prices Kiwoom market-data requests read (see KiwoomConfig::market_tape_).
Definition config.hpp:34
@ CONSOLIDATED
KRX and NXT combined, the SOR book (_AL).
Definition config.hpp:36
@ KRX
KRX alone (no suffix).
Definition config.hpp:38
KiwoomSellableScope
What a Kiwoom holdings row's tradable quantity (trde_able_qty) covers; undocumented,...
Definition config.hpp:139
@ UNSPECIFIED
Not stated: the sellable basis is unestablished, and a sell checked against it is refused.
Definition config.hpp:141
@ WHOLE_HOLDING
Asserted: it covers every share held of the instrument, on any venue.
Definition config.hpp:143
std::chrono::system_clock::time_point parse_compact_expiry(std::string_view text)
Reads Kiwoom's token expiry, yyyyMMddHHmmss in Korean time.
Definition config.hpp:66
constexpr bool kiwoom_position_scope_asserted(KiwoomPositionScope scope) noexcept
Tests whether a holdings scope states what Kiwoom's holdings figure covers, so holdings may be read a...
Definition config.hpp:125
KiwoomPositionScope
What the venue named on a Kiwoom holdings request (kt00018's dmst_stex_tp) means for the positions it...
Definition config.hpp:103
@ UNSPECIFIED
Not stated: every new order and amendment is refused (cancellations are not), and the session's holdi...
Definition config.hpp:108
@ VALUATION_ONLY
Asserted: the venue only selects which venue's price values each position, and every position is list...
Definition config.hpp:113
std::string token_identity(std::string_view broker, std::string_view environment, std::string_view key)
Names what a token may not outlive: the broker, the environment and the app key.
The library: broker-neutral types (core), and the modules below.
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
Kiwoom credentials (app key and secret key), demo or real account, the market-data tape,...
Definition config.hpp:155
void from_json_impl(const std::string &filename)
Reads the credentials from a JSON file; called by from_json(filename). Nothing changes if it throws.
Definition config.hpp:234
static bool demo_from_json(const json::object &doc, const std::string &origin)
Reads a credential document's "demo".
Definition config.hpp:301
static constexpr std::string_view secret_field() noexcept
The JSON field Kiwoom expects the application secret under.
Definition config.hpp:328
const char * rest_port() const noexcept
The REST port, which is the same for both environments.
Definition config.hpp:352
const char * ws_host() const noexcept
The WebSocket host for the selected environment.
Definition config.hpp:360
KiwoomPositionScope holdings_position_scope_
Your assertion of what holdings_venue_ means for the positions listed. No default: until it is set,...
Definition config.hpp:194
bool is_demo_
Whether to use Kiwoom's demo (모의투자) endpoints; true unless stated otherwise.
Definition config.hpp:163
static constexpr std::string_view key_field() noexcept
The JSON field Kiwoom expects the application key under.
Definition config.hpp:320
MarketTape market_tape_
Which venue's prices every Kiwoom market-data request reads (quotes, depth, trades,...
Definition config.hpp:171
std::string tape_symbol(std::string_view symbol) const
Returns a symbol with this configuration's tape suffix, for a market-data request.
Definition config.hpp:377
KiwoomSellableScope holdings_sellable_scope_
Your assertion of what a holdings row's tradable quantity covers; separate from the position scope,...
Definition config.hpp:203
const char * ws_port() const noexcept
The WebSocket port, which is the same for both environments.
Definition config.hpp:368
std::string token_identity() const
Names what a token of these credentials may not outlive, for a network::TokenStore.
Definition config.hpp:336
void from_env_impl()
Reads the credentials from KIWOOM_APP_KEY and KIWOOM_SECRET_KEY, and the environment from KIWOOM_DEMO...
Definition config.hpp:210
void from_json_text_impl(std::string_view text, const std::string &origin)
Reads the credentials from JSON text in the file's format; called by from_json_text....
Definition config.hpp:251
static bool demo_from_env()
Reads KIWOOM_DEMO.
Definition config.hpp:279
const char * rest_host() const noexcept
The REST host for the selected environment.
Definition config.hpp:344
Venue holdings_venue_
The venue holdings requests (kt00018) name: Venue::KRX or Venue::NXT. No default: holdings requests a...
Definition config.hpp:183
A Kiwoom REST access token (au10001's token) and its expiry (expires_dt).
Definition config.hpp:383
std::string token_type_
Kiwoom's token_type (bearer in its example).
Definition config.hpp:385
static constexpr std::string_view token_field() noexcept
The field Kiwoom returns the bearer token under.
Definition config.hpp:391
void from_json_impl(const json::object &doc)
Reads the expiry (expires_dt, the only one Kiwoom states) and token_type; called by from_json....
Definition config.hpp:400
An OAuth access token and its expiry, the base of each broker's token-response class.
Definition oauth.hpp:150
std::chrono::system_clock::time_point expires_at_
Definition oauth.hpp:154