algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
config.hpp
1#pragma once
2
3#include <boost/json.hpp>
4#include <chrono>
5#include <cstdlib>
6#include <ctime>
7#include <fstream>
8#include <iterator>
9#include <stdexcept>
10#include <string>
11#include <string_view>
12#include "../../network/oauth.hpp"
13#include "../../network/token_store.hpp"
14
15namespace algotradelib {
16namespace kis {
17
18// https://apiportal.koreainvestment.com/apiservice-apiservice?/oauth2/tokenP
19// Real-time(websocket):
20// https://apiportal.koreainvestment.com/apiservice-apiservice?/oauth2/Approval
21// https://github.com/koreainvestment/open-trading-api/blob/main/examples_user/auth/auth_examples.py
22// https://github.com/koreainvestment/open-trading-api/blob/main/examples_user/auth/auth_functions.py
23struct KisConfig;
24
34
40inline constexpr const char* market_division_code(MarketTape tape) noexcept {
41 switch (tape) {
42 case MarketTape::KRX:
43 return "J";
44 case MarketTape::NXT:
45 return "NX";
47 return "UN";
48 }
49 return "UN";
50}
51struct KisRest;
52struct KisWebsocket;
53
59static inline std::chrono::system_clock::time_point parse_expiry(const char* s) {
60 std::tm tm{};
61 if (
62 std::sscanf(s, "%d-%d-%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6
63 ) {
64 return {};
65 }
66 tm.tm_year -= 1900;
67 tm.tm_mon -= 1;
68 tm.tm_isdst = 0;
69#ifdef _WIN32
70 const std::time_t utc = _mkgmtime(&tm) - 9 * 3600;
71#else
72 const std::time_t utc = timegm(&tm) - 9 * 3600;
73#endif
74 return std::chrono::system_clock::from_time_t(utc);
75}
76
83struct KisConfig : public network::ClientCredentials<KisConfig> {
84 // std::string grant_type = "client_credentials"; // length = 18
85 // std::string app_key_; // length = 36
86 // std::string app_secret_; // length = 180
94 bool is_demo_ = true;
95
103
110 const char* key = std::getenv("KIS_APP_KEY");
111 const char* secret = std::getenv("KIS_APP_SECRET");
112 if (!key || !secret) {
113 throw std::runtime_error("Add KIS_APP_KEY and KIS_APP_SECRET environment variables.");
114 }
115 // Read before anything is assigned, so a refused load leaves this config as it was.
116 const bool demo = demo_from_env();
117 key_ = key;
118 secret_ = secret;
119 is_demo_ = demo;
120 }
121
133 void from_json_impl(const std::string& filename) {
134 std::ifstream ifs(filename);
135 if (!ifs.is_open()) {
136 throw std::runtime_error("Cannot open KIS credential file: " + filename);
137 }
138 const std::string content(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>{});
139 from_json_text_impl(content, "file " + filename);
140 }
141
150 void from_json_text_impl(std::string_view text, const std::string& origin) {
151 boost::system::error_code ec;
152 const auto jv = json::parse(text, ec);
153 if (ec) {
154 throw std::runtime_error("Failed to parse KIS credentials " + origin + " — " + ec.message());
155 }
156 if (!jv.is_object()) {
157 throw std::runtime_error("Failed to parse KIS credentials " + origin + " — not a JSON object");
158 }
159 const auto& doc = jv.as_object();
160 const json::value* key = doc.if_contains("app_key");
161 const json::value* secret = doc.if_contains("app_secret");
162 if (!key || !secret || !key->is_string() || !secret->is_string()) {
163 throw std::runtime_error("KIS credential " + origin + " should contain app_key and app_secret as strings");
164 }
165 // Everything is read and checked before anything is assigned, so a refused document leaves this
166 // config -- and the endpoint it already selected -- exactly as it was.
167 const bool demo = demo_from_json(doc, origin);
168 key_ = key->get_string().c_str();
169 secret_ = secret->get_string().c_str();
170 is_demo_ = demo;
171 }
172
178 static bool demo_from_env() {
179 const char* demo = std::getenv("KIS_DEMO");
180 if (!demo || std::string_view(demo) == "1") {
181 return true;
182 }
183 if (std::string_view(demo) == "0") {
184 return false;
185 }
186 throw std::runtime_error(
187 std::string("KIS_DEMO is \"") + demo +
188 "\"; set it to 1 for the demo endpoints or 0 to trade "
189 "live, or leave it unset for demo."
190 );
191 }
192
200 static bool demo_from_json(const json::object& doc, const std::string& origin) {
201 const json::value* demo = doc.if_contains("demo");
202 if (!demo) {
203 return true;
204 }
205 if (!demo->is_bool()) {
206 throw std::runtime_error(
207 "KIS credential " + origin +
208 " has a \"demo\" that is not true or false; write "
209 "true for the demo endpoints or false to trade live, or leave it out for demo."
210 );
211 }
212 return demo->get_bool();
213 }
214
219 static constexpr std::string_view key_field() noexcept {
220 return "appkey";
221 }
222
227 static constexpr std::string_view secret_field() noexcept {
228 return "appsecret";
229 }
230
235 std::string token_identity() const {
236 return network::token_identity("kis", is_demo_ ? "demo" : "real", key_);
237 }
238
243 const char* rest_host() const noexcept {
244 return is_demo_ ? "openapivts.koreainvestment.com" : "openapi.koreainvestment.com";
245 }
246
251 const char* rest_port() const noexcept {
252 return is_demo_ ? "29443" : "9443";
253 }
254
259 const char* ws_host() const noexcept {
260 return "ops.koreainvestment.com";
261 }
262
267 const char* ws_port() const noexcept {
268 return is_demo_ ? "31000" : "21000";
269 }
270
275 std::string ws_to_jsonbody() const {
276 return R"({"grant_type":"client_credentials","appkey":")" + key_ + R"(","secretkey":")" + secret_ + R"("})";
277 }
278};
279
281struct KisRest : public network::AuthBody<KisRest> {
282 // std::string access_token_; // length = 350
283 // // std::string token_type; // length = 20, Bearer
284 // int64_t expires_in_; // 10-digits
286 std::chrono::system_clock::time_point access_token_expired_; // length = 50, format: "2022-08-30 08:10:10"
287
290
295 static constexpr std::string_view token_field() noexcept {
296 return "access_token";
297 }
298
303 void from_json_impl(const json::object& doc) {
304 // if (!doc.contains("access_token")) {
305 // throw std::runtime_error("Token authentication failed");
306 // }
307 // access_token_ = doc.at("access_token").as_string().c_str();
308 // expires_in_ = doc.contains("expires_in")
309 // ? doc.at("expires_in").as_int64()
310 // : 86400;
311 access_token_expired_ = doc.contains("access_token_token_expired") ?
312 parse_expiry(doc.at("access_token_token_expired").as_string().c_str()) :
314 if (access_token_expired_ != std::chrono::system_clock::time_point{}) {
316 }
317 }
318
323 bool valid() const noexcept {
325 }
326};
327
331 std::string approval_key_; // length = 286
333 std::chrono::system_clock::time_point last_auth_time_;
334
337
343 void from_json(const json::object& doc) {
344 if (!doc.contains("approval_key")) {
345 throw std::runtime_error("WS approval key authentication failed");
346 }
347 approval_key_ = doc.at("approval_key").as_string().c_str();
348 last_auth_time_ = std::chrono::system_clock::now();
349 }
350
355 bool valid() const noexcept {
356 // https://github.com/koreainvestment/open-trading-api/blob/33e0e1e65cd1c8c8b639531483ec0b327087bab1/examples_user/kis_auth.py#L507
357 const auto now = std::chrono::system_clock::now();
358 const bool never_authed = last_auth_time_ == std::chrono::system_clock::time_point{};
359 const auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - last_auth_time_).count();
360 return !approval_key_.empty() && !never_authed && elapsed < 86400;
361 }
362};
363
364} // namespace kis
365} // 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 Korea Investment & Securities (KIS) Open API client.
Definition auth.hpp:9
constexpr const char * market_division_code(MarketTape tape) noexcept
Returns KIS's FID_COND_MRKT_DIV_CODE for a tape.
Definition config.hpp:40
MarketTape
Which venue's prices KIS market-data requests read (see KisConfig::market_tape_).
Definition config.hpp:26
@ CONSOLIDATED
KRX and NXT combined (UN).
Definition config.hpp:28
static std::chrono::system_clock::time_point parse_expiry(const char *s)
Reads KIS's token expiry, YYYY-MM-DD HH:MM:SS in Korean time.
Definition config.hpp:59
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.
KIS credentials (app key and secret), demo or real account, and the market-data tape.
Definition config.hpp:83
MarketTape market_tape_
Which venue's prices every KIS market-data request reads (quotes, bars, depth, price bands,...
Definition config.hpp:102
std::string token_identity() const
Names what a token of these credentials may not outlive, for a network::TokenStore.
Definition config.hpp:235
bool is_demo_
Whether to use KIS's demo (모의투자) endpoints; true unless stated otherwise.
Definition config.hpp:94
const char * ws_port() const noexcept
Returns the WebSocket port for the environment.
Definition config.hpp:267
static bool demo_from_json(const json::object &doc, const std::string &origin)
Reads a credential document's "demo".
Definition config.hpp:200
static constexpr std::string_view key_field() noexcept
Returns the token request's field for the app key.
Definition config.hpp:219
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:150
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:133
void from_env_impl()
Reads the credentials from KIS_APP_KEY and KIS_APP_SECRET, and the environment from KIS_DEMO (see dem...
Definition config.hpp:109
static bool demo_from_env()
Reads KIS_DEMO.
Definition config.hpp:178
static constexpr std::string_view secret_field() noexcept
Returns the token request's field for the app secret.
Definition config.hpp:227
std::string ws_to_jsonbody() const
Builds the WebSocket approval-key request body (the secret under secretkey).
Definition config.hpp:275
const char * rest_port() const noexcept
Returns the REST port for the environment.
Definition config.hpp:251
const char * rest_host() const noexcept
Returns the REST host for the environment.
Definition config.hpp:243
const char * ws_host() const noexcept
Returns the WebSocket host (the same for both environments).
Definition config.hpp:259
void from_json_impl(const json::object &doc)
Reads KIS's stated expiry from a token response; called by from_json.
Definition config.hpp:303
std::chrono::system_clock::time_point access_token_expired_
KIS's stated expiry (access_token_token_expired), which takes precedence over expires_in.
Definition config.hpp:286
static constexpr std::string_view token_field() noexcept
Returns the token response's field for the token.
Definition config.hpp:295
KisRest()
Constructs an empty token.
Definition config.hpp:289
bool valid() const noexcept
Tests whether the token is set and stays valid for at least five more minutes.
Definition config.hpp:323
KisWebsocket()
Constructs an empty key.
Definition config.hpp:336
void from_json(const json::object &doc)
Reads an approval-key response.
Definition config.hpp:343
bool valid() const noexcept
Tests whether the key is set and was received less than a day ago.
Definition config.hpp:355
std::chrono::system_clock::time_point last_auth_time_
When it was received.
Definition config.hpp:333
std::string approval_key_
The approval key.
Definition config.hpp:331
An OAuth access token and its expiry, the base of each broker's token-response class.
Definition oauth.hpp:150
bool valid(std::chrono::seconds margin=std::chrono::minutes(5)) const noexcept
Tests whether the token is set and stays valid for at least a margin.
Definition oauth.hpp:201
std::chrono::system_clock::time_point expires_at_
Definition oauth.hpp:154