algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
auth.hpp
1#pragma once
2
3#include "./config.hpp"
4#include "./network.hpp"
5
6#include <mutex>
7
8namespace algotradelib {
9namespace kis {
10
11class KisAuth;
12
19class KisAuth {
20public:
27 KisAuth(net::io_context& ioc, ssl::context& ctx, const KisConfig& config) : ioc_(ioc), ctx_(ctx), req_(config) {}
28
30 virtual ~KisAuth() = default;
31
39 std::string accessToken() {
40 std::lock_guard<std::mutex> lock(mtx_);
41 if (!rest_resp_.valid()) {
42 refresh();
43 }
44 return rest_resp_.access_token_;
45 }
46
53 std::string accessWebsocket() {
54 std::lock_guard<std::mutex> lock(mtx_);
55 if (!ws_resp_.valid()) {
56 refreshWebsocket();
57 }
58 return ws_resp_.approval_key_;
59 }
60
61private:
62 net::io_context& ioc_;
63 ssl::context& ctx_;
64 KisConfig req_;
65 KisRest rest_resp_;
66 KisWebsocket ws_resp_;
67 std::mutex mtx_;
68
69 void refresh() {
70 const std::string jsonbody = req_.to_jsonbody();
71 KisHttpClient rest(ioc_, ctx_, req_.rest_host(), req_.rest_port());
72 auto response = rest.post("/oauth2/tokenP", jsonbody, {{"content-type", "application/json"}});
73 if (response.result_int() < 200 || response.result_int() >= 300) {
74 throw std::runtime_error("Token authentication failed with HTTP status " + std::to_string(response.result_int()));
75 }
76 const std::string resp = std::move(response.body());
77 boost::system::error_code ec;
78 const auto jv = json::parse(resp, ec);
79 // const auto* doc = (!ec && jv.is_object()) ? &jv.as_object() : nullptr;
80 // if (!doc || !doc->contains("access_token")) {
81 // throw std::runtime_error("Token authentication failed: " + resp);
82 // }
83 // rest_resp_.access_token_ = doc->at("access_token").as_string().c_str();
84 // rest_resp_.expires_in_ = doc->contains("expires_in") ? doc->at("expires_in").as_int64() :
85 // 86400; rest_resp_.access_token_expired_ = doc->contains("access_token_token_expired") ?
86 // parse_expiry(doc->at("access_token_token_expired").as_string().c_str()) :
87 // std::chrono::system_clock::now() + std::chrono::seconds(86400);
88 if (ec || !jv.is_object()) {
89 // Not the body: a token reply that did not parse may still hold the token.
90 throw std::runtime_error(
91 "Token authentication failed: the reply is not a JSON object (" + std::to_string(resp.size()) + " bytes)"
92 );
93 }
94 rest_resp_.from_json(jv.as_object());
95 }
96
97 void refreshWebsocket() {
98 const std::string jsonbody = req_.ws_to_jsonbody();
99 KisHttpClient rest(ioc_, ctx_, req_.rest_host(), req_.rest_port());
100 // _base_headers_ws = {
101 // "content-type": "utf-8",
102 // }
103 auto response = rest.post("/oauth2/Approval", jsonbody, {{"content-type", "utf-8"}});
104 if (response.result_int() < 200 || response.result_int() >= 300) {
105 throw std::runtime_error(
106 "WebSocket authentication failed with HTTP status " + std::to_string(response.result_int())
107 );
108 }
109 const std::string resp = std::move(response.body());
110 boost::system::error_code ec;
111 const auto jv = json::parse(resp, ec);
112 // const auto* doc = (!ec && jv.is_object()) ? &jv.as_object() : nullptr;
113 // if (!doc || !doc->contains("approval_key")) {
114 // throw std::runtime_error("WS approval key authentication failed: " + resp);
115 // }
116 // ws_resp_.approval_key = doc->at("approval_key").as_string().c_str();
117 // ws_resp_.last_auth_time = std::chrono::system_clock::now();
118 if (ec || !jv.is_object()) {
119 // Not the body: an approval reply that did not parse may still hold the key.
120 throw std::runtime_error(
121 "WebSocket authentication failed: the reply is not a JSON object (" + std::to_string(resp.size()) + " bytes)"
122 );
123 }
124 ws_resp_.from_json(jv.as_object());
125 }
126};
127
128} // namespace kis
129} // namespace algotradelib
Obtains and caches KIS access tokens and WebSocket approval keys with blocking requests; thread-safe.
Definition auth.hpp:19
virtual ~KisAuth()=default
Destroys the wrapper.
std::string accessWebsocket()
Returns a WebSocket approval key, requesting a new one if none is held or it is a day old.
Definition auth.hpp:53
KisAuth(net::io_context &ioc, ssl::context &ctx, const KisConfig &config)
Constructs the wrapper.
Definition auth.hpp:27
std::string accessToken()
Returns a REST access token, requesting a new one if none is held or it expires within five minutes.
Definition auth.hpp:39
std::string to_jsonbody() const
Builds a JSON token-request body (grant type, key and secret under the broker's field names).
Definition oauth.hpp:95
The Korea Investment & Securities (KIS) Open API client.
Definition auth.hpp:9
network::HttpClient KisHttpClient
The blocking HTTP client KisAuth uses.
Definition network.hpp:9
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
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
A KIS REST access token and its expiry.
Definition config.hpp:281
A KIS WebSocket approval key and when it was issued.
Definition config.hpp:329