algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
client.hpp
1#pragma once
2
3#include "./config.hpp"
4#include "./errors.hpp"
5
6#include "../../core/instrument.hpp"
7#include "../../core/market_data.hpp"
8#include "../../core/types.hpp"
9#include "../common/adapter.hpp"
10#include "../common/krx.hpp"
11
12#include <boost/asio/any_completion_handler.hpp>
13#include <boost/asio/any_io_executor.hpp>
14#include <boost/asio/async_result.hpp>
15#include <boost/asio/post.hpp>
16#include <boost/asio/strand.hpp>
17
18#include <array>
19#include <chrono>
20#include <cstdlib>
21#include <ctime>
22#include <deque>
23#include <memory>
24#include <optional>
25#include <string>
26#include <string_view>
27#include <utility>
28#include <vector>
29
30namespace algotradelib::kiwoom {
31
42 friend bool operator==(const KiwoomAccount&, const KiwoomAccount&) {
43 return true;
44 }
45};
46
50 std::string account_number_;
51};
52
61 std::string order_number_;
63 std::string symbol_;
64};
65
80 Venue venue_{Venue::UNSPECIFIED};
87 std::optional<Decimal64> price_;
92 std::optional<Decimal64> condition_price_;
93};
94
114
133
137 std::vector<KiwoomOpenOrder> orders_;
139 std::chrono::system_clock::time_point received_at_;
140};
141
150 std::string symbol_;
151};
152
158 const auto seoul = std::chrono::system_clock::now() + std::chrono::hours(9);
159 const std::time_t raw =
160 std::chrono::system_clock::to_time_t(std::chrono::time_point_cast<std::chrono::seconds>(seoul));
161 std::tm parts{};
162#ifdef _WIN32
163 gmtime_s(&parts, &raw);
164#else
165 gmtime_r(&raw, &parts);
166#endif
167 Date date;
168 date.year_ = parts.tm_year + 1900;
169 date.month_ = parts.tm_mon + 1;
170 date.day_ = parts.tm_mday;
171 return date;
172}
173
185inline std::optional<BrokerError> unestablished_holdings_scope() {
186 BrokerError error;
188 error.reached_broker_ = false;
189 error.broker_code_ = "holdings_scope_unestablished";
190 // **Names the way out, not only the gap.** A refusal that reports a fact about a vendor and no
191 // action leaves a caller with nothing to do about it, and this one has a remedy: state what the
192 // parameter means. Saying which setting that is turns a dead end into a decision.
193 error.message_ =
194 "this library cannot establish what a Kiwoom account holds -- kt00018 names one venue "
195 "(dmst_stex_tp: KRX or NXT) and publishes no all-venue value, and whether that filters the "
196 "positions or only values them is not stated -- so it will not place a new order, or reprice a "
197 "resting one into a fillable price, against a position it cannot read. Cancelling is "
198 "unaffected, including cancel_quantity(). To proceed, assert what the parameter means by "
199 "setting KiwoomConfig::holdings_position_scope_ to KiwoomPositionScope::VALUATION_ONLY, having "
200 "read its documentation -- an assertion that is wrong undercounts the account";
201 return error;
202}
203
210inline std::optional<BrokerError> unsupported_client_order_id(const OrderRequest& order) {
211 if (!order.client_order_id_) {
212 return std::nullopt;
213 }
214 BrokerError error;
216 error.reached_broker_ = false;
217 error.broker_code_ = "client_order_id_unsupported";
218 error.message_ =
219 "Kiwoom publishes no caller-supplied order identifier; its order endpoints accept no such "
220 "field and it would be silently dropped";
221 return error;
222}
223
229inline bool valid_trigger_value(const Decimal64& trigger) {
230 return trigger.coefficient() > 0 && trigger.scale() == 0;
231}
232
243inline std::optional<BrokerError> invalid_trigger(OrderType type, const std::optional<Decimal64>& trigger) {
244 BrokerError error;
246 error.reached_broker_ = false;
247 error.broker_code_ = "invalid_trigger_price";
248 if (carries_trigger_price(type)) {
249 if (!trigger) {
250 error.message_ = "a Kiwoom stop-limit order (28) requires a trigger price in cond_uv";
251 return error;
252 }
253 if (!valid_trigger_value(*trigger)) {
254 error.message_ = "a Kiwoom trigger price must be a positive whole number of won";
255 return error;
256 }
257 return std::nullopt;
258 }
259 if (trigger) {
260 error.message_ =
261 "Kiwoom takes a trigger price only on a stop-limit order (28); on this basis it would be "
262 "dropped";
263 return error;
264 }
265 return std::nullopt;
266}
267
269namespace detail {
270
271// Reads one of Kiwoom's signed magnitude strings as a price or a quantity.
272//
273// **Kiwoom prefixes a market-data number with a change *direction*, not a sign.** `"+181400"` and
274// `"-91200"` are prices of 181,400 and 91,200 won; the specification says so field by field
275// ("단위: 원, 부호가 포함된 숫자"). Parsing `-91200` as a negative price produces a number that is
276// wrong by a factor of minus one, is a perfectly valid `Decimal64`, and passes every type check
277// downstream — so every price and quantity this adapter reads from a market-data response goes
278// through here, and the direction is read separately from `pred_pre_sig` where it is wanted.
279//
280// Account responses pad to a fixed width with leading zeros (`"000000017598258"`), which
281// `Decimal64::parse` handles, and may carry a genuine minus on a profit-and-loss figure — so
282// `signed_value` is the entry point for those, and this one is for the market-data fields whose
283// sign is a direction.
284//
285// Returns nothing for an empty or unparsable field, which is how Kiwoom spells "no value".
286inline std::optional<Decimal64> magnitude(const json::object& row, std::string_view key) {
287 const auto value = row.if_contains(key);
288 if (!value || !value->is_string()) {
289 return std::nullopt;
290 }
291 std::string_view text(value->as_string());
292 if (!text.empty() && (text.front() == '+' || text.front() == '-')) {
293 text.remove_prefix(1);
294 }
295 if (text.empty()) {
296 return std::nullopt;
297 }
298 for (const char digit : text) {
299 if ((digit < '0' || digit > '9') && digit != '.') {
300 return std::nullopt;
301 }
302 }
303 return Decimal64::parse(text);
304}
305
306// Reads a magnitude, or zero where Kiwoom reported nothing.
307inline Decimal64 magnitude_or_zero(const json::object& row, std::string_view key) {
308 const auto value = magnitude(row, key);
309 return value ? *value : Decimal64();
310}
311
312// Reads a field whose minus sign is arithmetic rather than a direction.
313//
314// **Use this only where the value can genuinely be negative**: holdings' profit and loss and return
315// ratios, and the `kt00001` / `kt00010` deposit figures, which go negative when the account is in
316// 미수. Everything that is a price, a quantity or a holdings money total goes through `magnitude`,
317// because none of those can be negative and Kiwoom documents
318// *both* kinds with the same phrase: `kt00018`'s 현재가 is "단위: 원, 좌측 0-padding 처리된 부호 포함
319// 12자리 숫자", the identical wording it uses for 평가손익 on the row beside it.
320//
321// So the field description cannot tell them apart, and only the *meaning* can: a 현재가 of minus
322// 59,000 won is not a price, so a sign there is a direction — while a 평가손익 of minus 196,888 won
323// is exactly what it says. Reading a mark price as negative would put it straight into
324// `HoldingPosition::last_price_` and from there into every valuation that reads a holding.
325//
326// Values are zero-padded to a fixed width, sometimes with the sign inside the padding, and
327// `Decimal64::parse` reads both the sign and the leading zeros.
328inline std::optional<Decimal64> signed_value(const json::object& row, std::string_view key) {
329 const auto value = row.if_contains(key);
330 if (!value || !value->is_string()) {
331 return std::nullopt;
332 }
333 const std::string_view text(value->as_string());
334 if (text.empty()) {
335 return std::nullopt;
336 }
337 std::size_t index = (text.front() == '+' || text.front() == '-') ? 1 : 0;
338 if (index == text.size()) {
339 return std::nullopt;
340 }
341 for (; index < text.size(); ++index) {
342 if ((text[index] < '0' || text[index] > '9') && text[index] != '.') {
343 return std::nullopt;
344 }
345 }
346 // `Decimal64::parse` reads the sign itself, and the leading zeros Kiwoom pads with are digits
347 // like any other, so the padded and signed forms both go through unchanged.
348 return Decimal64::parse(text);
349}
350
351// Reads a magnitude that must be there, and throws when it is not.
352//
353// **`magnitude_or_zero` cannot be used for a figure a risk check consumes.** It turns a missing,
354// blank *or malformed* field into zero, and zero is a statement: a holdings row whose `rmnd_qty`
355// came back garbled would be a successful listing saying the account holds none of that
356// instrument, and `Portfolio::net_quantity_of` would undercount the exposure a position ceiling is
357// measured against. A working order whose `ord_qty` was unreadable would understate
358// `Portfolio::working_quantity`, which is what the sellable guard deducts a resting sell with.
359//
360// A *reported* zero is still zero and still fine. It is the unreadable one that must fail the row,
361// because the two are indistinguishable afterwards.
362//
363// **The line is drawn at what a risk check consumes, and no wider**, because the failure mode of
364// this guard is the opposite one: a field made required that Kiwoom may legitimately omit fails a
365// valid listing, and a listing that fails is a poll that fails. So it covers `rmnd_qty`
366// (`Portfolio::net_quantity_of`), and `ord_qty` and `cntr_qty` (`Portfolio::working_quantity`),
367// plus a bar's `trde_qty`, which a strategy reads directly. The reporting figures beside them --
368// cost basis, market value, profit and loss, the account totals, the deposit detail -- stay
369// tolerant: a missing one there is wrong in a report, not in an order, and an account with no
370// positions is the kind of edge case that should not fail a poll.
371inline Decimal64 required_magnitude(const json::object& row, std::string_view key) {
372 const auto value = magnitude(row, key);
373 if (!value) {
374 throw std::runtime_error("missing or unreadable numeric field: " + std::string(key));
375 }
376 return *value;
377}
378
379// Reads a genuinely signed figure that must be there, and throws when it is not.
380inline Decimal64 required_signed(const json::object& row, std::string_view key) {
381 const auto value = signed_value(row, key);
382 if (!value) {
383 throw std::runtime_error("missing or unreadable numeric field: " + std::string(key));
384 }
385 return *value;
386}
387
388// Reads a signed field, or zero where Kiwoom reported nothing.
389inline Decimal64 signed_or_zero(const json::object& row, std::string_view key) {
390 const auto value = signed_value(row, key);
391 return value ? *value : Decimal64();
392}
393
394// Reads a string field, or an empty string where Kiwoom reported none.
395inline std::string text_field(const json::object& row, std::string_view key) {
396 const auto value = row.if_contains(key);
397 if (!value || !value->is_string()) {
398 return {};
399 }
400 return std::string(value->as_string());
401}
402
403// Returns a symbol as Kiwoom's order endpoints spell it.
404//
405// **Kiwoom's account listings prefix a symbol with `A`** — `kt00018` reports `"A005930"` and
406// `kt00007` reports `"A069500"` — while `ka10075` and every market-data endpoint report the bare
407// six digits. An instrument identity built from the prefixed form would not compare equal to one
408// built from the bare form, so a holding and its own working order would stop matching. The prefix
409// is stripped once, here.
410//
411// The tape suffix is stripped for the same reason: `005930_AL` is the same instrument as `005930`,
412// read off a different book.
413inline std::string bare_symbol(std::string_view reported) {
414 std::string_view symbol = reported;
415 if (symbol.size() > 1 && symbol.front() == 'A') {
416 symbol.remove_prefix(1);
417 }
418 if (const auto underscore = symbol.find('_'); underscore != std::string_view::npos) {
419 symbol = symbol.substr(0, underscore);
420 }
421 return std::string(symbol);
422}
423
424// Reads Kiwoom's `HHmmss` or `HH:mm:ss` clock time as an instant on `date` in Seoul.
425inline std::optional<std::chrono::system_clock::time_point> seoul_timestamp(const Date& date, std::string_view clock) {
426 std::string digits;
427 for (const char character : clock) {
428 if (character >= '0' && character <= '9') {
429 digits.push_back(character);
430 } else if (character != ':') {
431 return std::nullopt;
432 }
433 }
434 if (digits.size() != 6) {
435 return std::nullopt;
436 }
437 if (!is_valid_date(date)) {
438 return std::nullopt;
439 }
440 std::tm parts{};
441 parts.tm_year = date.year_ - 1900;
442 parts.tm_mon = date.month_ - 1;
443 parts.tm_mday = date.day_;
444 parts.tm_hour = (digits[0] - '0') * 10 + (digits[1] - '0');
445 parts.tm_min = (digits[2] - '0') * 10 + (digits[3] - '0');
446 parts.tm_sec = (digits[4] - '0') * 10 + (digits[5] - '0');
447 parts.tm_isdst = 0;
448#ifdef _WIN32
449 const std::time_t utc = _mkgmtime(&parts) - 9 * 3600;
450#else
451 const std::time_t utc = timegm(&parts) - 9 * 3600;
452#endif
453 return std::chrono::system_clock::from_time_t(utc);
454}
455
456// Reads Kiwoom's `YYYYMMDD` as a calendar date, or nothing when it is not one.
457inline std::optional<Date> compact_date(std::string_view text) {
458 return broker_detail::compact_date(text);
459}
460
461// Reads a `YYYYMMDD` field that states a date or leaves it blank, as one of three answers.
462//
463// Reads the raw value rather than `text_field`, which maps every non-string to `""` and would so
464// report a number as a date not stated. Not stated: absent, `null` or `""`. Stated: eight digits
465// forming a real date. Unreadable: anything else -- **including `"00000000"`**, since nothing in
466// Kiwoom's specification uses a zero date as a blank, and KIS's use of one says nothing about Kiwoom.
467inline StatedDate stated_compact_date(const json::object& row, std::string_view key) {
468 const auto value = row.if_contains(key);
469 if (!value || value->is_null()) {
470 return StatedDate{};
471 }
472 if (!value->is_string()) {
473 return StatedDate::unreadable();
474 }
475 const std::string_view text(value->as_string());
476 if (text.empty()) {
477 return StatedDate{};
478 }
479 const auto date = compact_date(text);
480 return date ? StatedDate::stated(*date) : StatedDate::unreadable();
481}
482
483// Renders a calendar date as Kiwoom's `YYYYMMDD`.
484inline std::string compact_text(const Date& date) {
485 std::string text(8, '0');
486 int year = date.year_;
487 for (int index = 3; index >= 0; --index) {
488 text[static_cast<std::size_t>(index)] = static_cast<char>('0' + year % 10);
489 year /= 10;
490 }
491 text[4] = static_cast<char>('0' + date.month_ / 10);
492 text[5] = static_cast<char>('0' + date.month_ % 10);
493 text[6] = static_cast<char>('0' + date.day_ / 10);
494 text[7] = static_cast<char>('0' + date.day_ % 10);
495 return text;
496}
497
498} // namespace detail
500
525
533inline constexpr std::array<KiwoomOrderShapeRow, 21> kOrderShapes{{
534 // Each row: code, name, alternate name, type, condition, session, requestable.
535 {"0", "보통", "지정가", OrderType::LIMIT, TimeInForce::DAY, OrderSession::REGULAR, true},
536 {"3", "시장가", nullptr, OrderType::MARKET, TimeInForce::DAY, OrderSession::REGULAR, true},
537 {"5", "조건부지정가", nullptr, OrderType::CONDITIONAL_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, true},
538 {"6", "최유리지정가", nullptr, OrderType::BEST_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, true},
539 {"7", "최우선지정가", nullptr, OrderType::PRIMARY_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, true},
540 {"10", "보통(IOC)", "지정가(IOC)", OrderType::LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, true},
541 {"13", "시장가(IOC)", nullptr, OrderType::MARKET, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, true},
542 {"16", "최유리(IOC)", nullptr, OrderType::BEST_LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, true},
543 {"20", "보통(FOK)", "지정가(FOK)", OrderType::LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, true},
544 {"23", "시장가(FOK)", nullptr, OrderType::MARKET, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, true},
545 {"26", "최유리(FOK)", nullptr, OrderType::BEST_LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, true},
546 {"29", "중간가", nullptr, OrderType::MID_PRICE, TimeInForce::DAY, OrderSession::REGULAR, true},
547 {"30", "중간가(IOC)", nullptr, OrderType::MID_PRICE, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, true},
548 {"31", "중간가(FOK)", nullptr, OrderType::MID_PRICE, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, true},
549 {"61", "장시작전시간외", nullptr, OrderType::CLOSING_PRICE, TimeInForce::DAY, OrderSession::PRE_MARKET, true},
550 {"81", "장마감후시간외", nullptr, OrderType::CLOSING_PRICE, TimeInForce::DAY, OrderSession::AFTER_HOURS, true},
551 {"40", "보통(GTP)", nullptr, OrderType::LIMIT, TimeInForce::DAY, OrderSession::GTP, true},
552 {"46", "최유리(GTP)", nullptr, OrderType::BEST_LIMIT, TimeInForce::DAY, OrderSession::GTP, true},
553 {"47", "최우선(GTP)", nullptr, OrderType::PRIMARY_LIMIT, TimeInForce::DAY, OrderSession::GTP, true},
554 {"28", "스톱지정가", nullptr, OrderType::STOP_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, true},
555 {nullptr, "시간외단일가", nullptr, OrderType::LIMIT, TimeInForce::DAY, OrderSession::AFTER_HOURS_AUCTION, false},
556}};
557
567inline std::optional<BrokerError> order_division(
568 OrderType type, TimeInForce time_in_force, OrderSession session, std::string& division
569) {
570 const KiwoomOrderShapeRow* matched = nullptr;
571 for (const auto& row : kOrderShapes) {
572 if (row.type_ == type && row.time_in_force_ == time_in_force && row.session_ == session) {
573 matched = &row;
574 break;
575 }
576 }
577 BrokerError error;
579 error.reached_broker_ = false;
580 error.broker_code_ = "unsupported_order";
581 if (matched == nullptr) {
582 error.message_ =
583 "Kiwoom publishes no order code for this combination of price basis, validity condition and "
584 "session";
585 return error;
586 }
587 if (!matched->requestable_ || matched->code_ == nullptr) {
588 const auto why = matched->code_ == nullptr ?
589 ": it publishes no order code for that shape at all" :
590 ": the code is read on a response and not sent on a request";
591 error.message_ =
592 std::string("Kiwoom reports ") + matched->name_ + " on an inquiry but this library cannot place one" + why;
593 return error;
594 }
595 division = matched->code_;
596 return std::nullopt;
597}
598
604inline const KiwoomOrderShapeRow* shape_by_name(std::string_view name) noexcept {
605 for (const auto& row : kOrderShapes) {
606 if (name == row.name_) {
607 return &row;
608 }
609 if (row.alternate_name_ != nullptr && name == row.alternate_name_) {
610 return &row;
611 }
612 }
613 return nullptr;
614}
615
621inline const KiwoomOrderShapeRow* shape_by_code(std::string_view code) noexcept {
622 for (const auto& row : kOrderShapes) {
623 if (row.code_ != nullptr && code == row.code_) {
624 return &row;
625 }
626 }
627 return nullptr;
628}
629
635inline const char* exchange_code(Venue venue) noexcept {
636 switch (venue) {
637 case Venue::KRX:
638 return "KRX";
639 case Venue::NXT:
640 return "NXT";
641 // Kiwoom calls the consolidated book SOR, which is what routes across both venues.
642 case Venue::COMBINED:
643 return "SOR";
644 case Venue::UNSPECIFIED:
645 return "";
646 }
647 return "";
648}
649
656inline constexpr Venue kiwoom_effective_route(Venue asked) noexcept {
657 return asked;
658}
659
665inline Venue normalized_venue(std::string_view code) noexcept {
666 if (code == "KRX" || code == "1") {
667 return Venue::KRX;
668 }
669 if (code == "NXT" || code == "2") {
670 return Venue::NXT;
671 }
672 if (code == "SOR" || code == "0") {
673 return Venue::COMBINED;
674 }
675 return Venue::UNSPECIFIED;
676}
677
688inline Venue listed_venue(std::string_view stex_tp, std::string_view sor_yn) noexcept {
689 if (sor_yn == "Y") {
690 return Venue::COMBINED;
691 }
692 return normalized_venue(stex_tp);
693}
694
702inline std::optional<OrderSide> normalized_order_side(std::string_view text) noexcept {
703 if (text.find("매수") != std::string_view::npos) {
704 return OrderSide::BUY;
705 }
706 if (text.find("매도") != std::string_view::npos) {
707 return OrderSide::SELL;
708 }
709 return std::nullopt;
710}
711
718inline OrderStatus normalized_order_status(std::string_view text) noexcept {
719 if (text == "접수") {
720 return OrderStatus::PENDING;
721 }
722 if (text == "확인") {
723 return OrderStatus::PENDING;
724 }
725 if (text == "체결") {
726 return OrderStatus::FILLED;
727 }
728 if (text == "취소") {
729 return OrderStatus::CANCELED;
730 }
731 return OrderStatus::UNKNOWN;
732}
733
740inline constexpr const char* chart_api_id(BarInterval interval) noexcept {
741 switch (interval) {
742 case BarInterval::ONE_MINUTE:
743 return "ka10080";
744 case BarInterval::ONE_DAY:
745 return "ka10081";
746 case BarInterval::ONE_WEEK:
747 return "ka10082";
748 case BarInterval::ONE_MONTH:
749 return "ka10083";
750 case BarInterval::ONE_YEAR:
751 return "ka10094";
756 return nullptr;
757 }
758 return nullptr;
759}
760
766inline constexpr const char* chart_rows_field(BarInterval interval) noexcept {
767 switch (interval) {
768 case BarInterval::ONE_MINUTE:
769 return "stk_min_pole_chart_qry";
770 case BarInterval::ONE_DAY:
771 return "stk_dt_pole_chart_qry";
772 case BarInterval::ONE_WEEK:
773 return "stk_stk_pole_chart_qry";
774 case BarInterval::ONE_MONTH:
775 return "stk_mth_pole_chart_qry";
776 case BarInterval::ONE_YEAR:
777 return "stk_yr_pole_chart_qry";
782 return nullptr;
783 }
784 return nullptr;
785}
786
792inline std::optional<BrokerError> unsupported_bar_interval(BarInterval interval) {
793 if (chart_api_id(interval) != nullptr && chart_rows_field(interval) != nullptr) {
794 return std::nullopt;
795 }
796 BrokerError error;
798 error.reached_broker_ = false;
799 error.broker_code_ = "unsupported_interval";
800 error.message_ = std::string("this Kiwoom client does not request ") + std::string(bar_interval_name(interval)) +
801 " bars yet (Kiwoom serves them through ka10080's tic_scope, which this adapter has not observed)";
802 return error;
803}
804
830
836 bool reduced_{false};
838 std::optional<Decimal64> amount_;
840 std::optional<Decimal64> quantity_;
841};
842
869
871
882class KiwoomClient : public std::enable_shared_from_this<KiwoomClient> {
883public:
885 using QuoteHandler = net::any_completion_handler<void(Result<QuoteSnapshot>)>;
887 using BarsHandler = net::any_completion_handler<void(Result<BarSeries>)>;
889 using DepthHandler = net::any_completion_handler<void(Result<DepthSnapshot>)>;
891 using PriceLimitsHandler = net::any_completion_handler<void(Result<PriceLimits>)>;
893 using TradesHandler = net::any_completion_handler<void(Result<std::vector<TradePrint>>)>;
895 using InstrumentHandler = net::any_completion_handler<void(Result<Instrument>)>;
897 using HoldingsHandler = net::any_completion_handler<void(Result<HoldingsSnapshot>)>;
899 using BuyingPowerHandler = net::any_completion_handler<void(Result<BuyingPower>)>;
901 using DepositHandler = net::any_completion_handler<void(Result<KiwoomDeposit>)>;
903 using OrderableHandler = net::any_completion_handler<void(Result<KiwoomOrderableAmount>)>;
905 using AccountsHandler = net::any_completion_handler<void(Result<std::vector<KiwoomAccountInfo>>)>;
907 using OrderAckHandler = net::any_completion_handler<void(Result<KiwoomOrderAck>)>;
909 using OpenOrderHandler = net::any_completion_handler<void(Result<KiwoomOpenOrderPage>)>;
911 using OrderPageHandler = net::any_completion_handler<void(Result<OrderPage>)>;
913 using TokenHandler = net::any_completion_handler<void(std::optional<BrokerError>)>;
914
916 using TokenResultHandler = net::any_completion_handler<void(Result<KiwoomRest>)>;
917
926 net::any_io_executor executor, ssl::context& context, KiwoomConfig config, network::HttpClientOptions options = {}
927 )
928 : strand_(net::make_strand(std::move(executor))),
929 config_(std::move(config)),
930 http_(
931 std::make_shared<network::AsyncHttpClient>(strand_, context, config_.rest_host(), config_.rest_port(), options)
932 ) {}
933
941 template <typename CompletionToken>
942 auto async_quote(InstrumentId instrument, CompletionToken&& token) {
943 return net::async_initiate<CompletionToken, void(Result<QuoteSnapshot>)>(
944 [self = shared_from_this()](auto handler, InstrumentId subject) mutable {
945 net::post(self->strand_, [self, subject = std::move(subject), handler = std::move(handler)]() mutable {
946 self->start_market_read<QuoteSnapshot>(
947 std::move(subject), "ka10007", "/api/dostk/mrkcond", QuoteHandler(std::move(handler)),
948 &KiwoomClient::parse_quote
949 );
950 });
951 },
952 token, std::move(instrument)
953 );
954 }
955
963 template <typename CompletionToken>
964 auto async_price_limits(InstrumentId instrument, CompletionToken&& token) {
965 return net::async_initiate<CompletionToken, void(Result<PriceLimits>)>(
966 [self = shared_from_this()](auto handler, InstrumentId subject) mutable {
967 net::post(self->strand_, [self, subject = std::move(subject), handler = std::move(handler)]() mutable {
968 self->start_market_read<PriceLimits>(
969 std::move(subject), "ka10007", "/api/dostk/mrkcond", PriceLimitsHandler(std::move(handler)),
970 &KiwoomClient::parse_price_limits
971 );
972 });
973 },
974 token, std::move(instrument)
975 );
976 }
977
985 template <typename CompletionToken>
986 auto async_depth(InstrumentId instrument, CompletionToken&& token) {
987 return net::async_initiate<CompletionToken, void(Result<DepthSnapshot>)>(
988 [self = shared_from_this()](auto handler, InstrumentId subject) mutable {
989 net::post(self->strand_, [self, subject = std::move(subject), handler = std::move(handler)]() mutable {
990 self->start_market_read<DepthSnapshot>(
991 std::move(subject), "ka10004", "/api/dostk/mrkcond", DepthHandler(std::move(handler)),
992 &KiwoomClient::parse_depth
993 );
994 });
995 },
996 token, std::move(instrument)
997 );
998 }
999
1008 template <typename CompletionToken>
1009 auto async_trades(InstrumentId instrument, int count, CompletionToken&& token) {
1010 return net::async_initiate<CompletionToken, void(Result<std::vector<TradePrint>>)>(
1011 [self = shared_from_this()](auto handler, InstrumentId subject, int wanted) mutable {
1012 net::post(self->strand_, [self, subject = std::move(subject), wanted, handler = std::move(handler)]() mutable {
1013 self->start_trades(std::move(subject), wanted, TradesHandler(std::move(handler)));
1014 });
1015 },
1016 token, std::move(instrument), count
1017 );
1018 }
1019
1027 template <typename CompletionToken>
1028 auto async_instrument(InstrumentId instrument, CompletionToken&& token) {
1029 return net::async_initiate<CompletionToken, void(Result<Instrument>)>(
1030 [self = shared_from_this()](auto handler, InstrumentId subject) mutable {
1031 net::post(self->strand_, [self, subject = std::move(subject), handler = std::move(handler)]() mutable {
1032 self->start_instrument(std::move(subject), InstrumentHandler(std::move(handler)));
1033 });
1034 },
1035 token, std::move(instrument)
1036 );
1037 }
1038
1054 template <typename CompletionToken>
1055 auto async_bars(BarQuery query, CompletionToken&& token) {
1056 return net::async_initiate<CompletionToken, void(Result<BarSeries>)>(
1057 [self = shared_from_this()](auto handler, BarQuery wanted) mutable {
1058 net::post(self->strand_, [self, wanted = std::move(wanted), handler = std::move(handler)]() mutable {
1059 self->start_bars(std::move(wanted), BarsHandler(std::move(handler)));
1060 });
1061 },
1062 token, std::move(query)
1063 );
1064 }
1065
1070 const KiwoomConfig& config() const noexcept {
1071 return config_;
1072 }
1073
1078 net::strand<net::any_io_executor> get_executor() const noexcept {
1079 return strand_;
1080 }
1081
1095 template <typename CompletionToken>
1096 auto async_holdings(KiwoomAccount account, CompletionToken&& token) {
1097 return net::async_initiate<CompletionToken, void(Result<HoldingsSnapshot>)>(
1098 [self = shared_from_this()](auto handler, KiwoomAccount) mutable {
1099 net::post(self->strand_, [self, handler = std::move(handler)]() mutable {
1100 self->start_holdings(HoldingsHandler(std::move(handler)));
1101 });
1102 },
1103 token, account
1104 );
1105 }
1106
1115 template <typename CompletionToken>
1116 auto async_buying_power(Currency currency, KiwoomAccount account, CompletionToken&& token) {
1117 return net::async_initiate<CompletionToken, void(Result<BuyingPower>)>(
1118 [self = shared_from_this()](auto handler, Currency wanted, KiwoomAccount) mutable {
1119 net::post(self->strand_, [self, wanted, handler = std::move(handler)]() mutable {
1120 self->start_buying_power(wanted, BuyingPowerHandler(std::move(handler)));
1121 });
1122 },
1123 token, currency, account
1124 );
1125 }
1126
1133 template <typename CompletionToken>
1134 auto async_deposit(CompletionToken&& token) {
1135 return net::async_initiate<CompletionToken, void(Result<KiwoomDeposit>)>(
1136 [self = shared_from_this()](auto handler) mutable {
1137 net::post(self->strand_, [self, handler = std::move(handler)]() mutable {
1138 self->start_deposit(DepositHandler(std::move(handler)));
1139 });
1140 },
1141 token
1142 );
1143 }
1144
1154 template <typename CompletionToken>
1156 InstrumentId instrument, OrderSide side, std::optional<Decimal64> price, CompletionToken&& token
1157 ) {
1158 return net::async_initiate<CompletionToken, void(Result<KiwoomOrderableAmount>)>(
1159 [self = shared_from_this()](
1160 auto handler, InstrumentId subject, OrderSide direction, std::optional<Decimal64> limit
1161 ) mutable {
1162 net::post(
1163 self->strand_,
1164 [self, subject = std::move(subject), direction, limit = std::move(limit),
1165 handler = std::move(handler)]() mutable {
1166 self->start_orderable_amount(
1167 std::move(subject), direction, std::move(limit), OrderableHandler(std::move(handler))
1168 );
1169 }
1170 );
1171 },
1172 token, std::move(instrument), side, std::move(price)
1173 );
1174 }
1175
1182 template <typename CompletionToken>
1183 auto async_accounts(CompletionToken&& token) {
1184 return net::async_initiate<CompletionToken, void(Result<std::vector<KiwoomAccountInfo>>)>(
1185 [self = shared_from_this()](auto handler) mutable {
1186 net::post(self->strand_, [self, handler = std::move(handler)]() mutable {
1187 self->start_accounts(AccountsHandler(std::move(handler)));
1188 });
1189 },
1190 token
1191 );
1192 }
1193
1225 template <typename CompletionToken>
1226 auto async_place_order(KiwoomAccount account, OrderRequest order, CompletionToken&& token) {
1227 return net::async_initiate<CompletionToken, void(Result<KiwoomOrderAck>)>(
1228 [self = shared_from_this()](auto handler, KiwoomAccount, OrderRequest placed) mutable {
1229 net::post(self->strand_, [self, placed = std::move(placed), handler = std::move(handler)]() mutable {
1230 self->start_place_order(std::move(placed), OrderAckHandler(std::move(handler)));
1231 });
1232 },
1233 token, account, std::move(order)
1234 );
1235 }
1236
1251 template <typename CompletionToken>
1252 auto async_replace_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken&& token) {
1253 return net::async_initiate<CompletionToken, void(Result<KiwoomOrderAck>)>(
1254 [self = shared_from_this()](auto handler, KiwoomAccount, KiwoomAmendment change) mutable {
1255 net::post(self->strand_, [self, change = std::move(change), handler = std::move(handler)]() mutable {
1256 self->start_amend_order(std::move(change), false, OrderAckHandler(std::move(handler)));
1257 });
1258 },
1259 token, account, std::move(amendment)
1260 );
1261 }
1262
1282 template <typename CompletionToken>
1283 auto async_cancel_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken&& token) {
1284 return net::async_initiate<CompletionToken, void(Result<KiwoomOrderAck>)>(
1285 [self = shared_from_this()](auto handler, KiwoomAccount, KiwoomAmendment change) mutable {
1286 net::post(self->strand_, [self, change = std::move(change), handler = std::move(handler)]() mutable {
1287 self->start_amend_order(std::move(change), true, OrderAckHandler(std::move(handler)));
1288 });
1289 },
1290 token, account, std::move(amendment)
1291 );
1292 }
1293
1301 template <typename CompletionToken>
1302 auto async_open_orders(KiwoomAccount account, CompletionToken&& token) {
1303 return net::async_initiate<CompletionToken, void(Result<KiwoomOpenOrderPage>)>(
1304 [self = shared_from_this()](auto handler, KiwoomAccount) mutable {
1305 net::post(self->strand_, [self, handler = std::move(handler)]() mutable {
1306 self->start_open_orders(OpenOrderHandler(std::move(handler)));
1307 });
1308 },
1309 token, account
1310 );
1311 }
1312
1321 template <typename CompletionToken>
1322 auto async_order_history(KiwoomAccount account, KiwoomHistoryQuery query, CompletionToken&& token) {
1323 return net::async_initiate<CompletionToken, void(Result<OrderPage>)>(
1324 [self = shared_from_this()](auto handler, KiwoomAccount, KiwoomHistoryQuery wanted) mutable {
1325 net::post(self->strand_, [self, wanted = std::move(wanted), handler = std::move(handler)]() mutable {
1326 self->start_order_history(std::move(wanted), OrderPageHandler(std::move(handler)));
1327 });
1328 },
1329 token, account, std::move(query)
1330 );
1331 }
1332
1342 const auto* limiter = http_->rate_limits();
1343 return limiter ? &limiter->stats() : nullptr;
1344 }
1345
1357 return token_;
1358 }
1359
1377 if (!token.valid()) {
1378 return false;
1379 }
1380 token_ = std::move(token);
1381 return true;
1382 }
1383
1391 template <typename CompletionToken>
1392 auto async_ensure_token(CompletionToken&& token) {
1393 return net::async_initiate<CompletionToken, void(Result<KiwoomRest>)>(
1394 [self = shared_from_this()](auto&& handler) mutable {
1395 auto completion = TokenResultHandler(std::forward<decltype(handler)>(handler));
1396 net::post(self->strand_, [self, completion = std::move(completion)]() mutable {
1397 self->request_token(
1398 TokenHandler([self, completion = std::move(completion)](std::optional<BrokerError> error) mutable {
1399 self->deliver(
1400 std::move(completion), error ? Result<KiwoomRest>(std::move(*error)) : Result<KiwoomRest>(self->token_)
1401 );
1402 })
1403 );
1404 });
1405 },
1406 token
1407 );
1408 }
1409
1416 token_ = KiwoomRest{};
1417 }
1418
1424 void close() {
1425 http_->close();
1426 }
1427
1428private:
1429 friend struct KiwoomClientTestAccess;
1430 friend class KiwoomBlockingClient;
1431
1432 net::strand<net::any_io_executor> strand_;
1433 KiwoomConfig config_;
1434 std::shared_ptr<network::AsyncHttpClient> http_;
1435 KiwoomRest token_;
1436 bool refreshing_{false};
1437 std::deque<TokenHandler> token_waiters_;
1438 // Set by a blocking client with a token store, which prepares every token under the store's lock.
1439 bool store_managed_{false};
1440
1441 // Most pages one paged inquiry may consume, for the reason every paging path is bounded.
1442 static constexpr int page_budget_ = 50;
1443
1444 // Builds one Kiwoom request: the group path, the operation header, and the token.
1445 //
1446 // **Every Kiwoom endpoint has this shape**, which is why it is built once. The operation is the
1447 // `api-id` header rather than the path — `/api/dostk/acnt` alone serves the balance, the deposit,
1448 // the unfilled listing and the execution detail — so a request with the right path and the wrong
1449 // header is a valid request for the wrong thing, and there is exactly one place that pairs them.
1450 network::HttpRequest make_request(
1451 std::string_view api_id, std::string_view path, std::string body, network::RateLimitGroup group,
1452 std::string_view next_key = {}
1453 ) const {
1454 network::HttpRequest request;
1455 request.group_ = group;
1456 // Every Kiwoom read is a POST, including the market-data ones. A POST is never replayed after
1457 // a reconnect, which is the transport's own rule and the conservative one here.
1458 request.method_ = http::verb::post;
1459 request.target_ = std::string(path);
1460 request.body_ = std::move(body);
1461 request.headers_ = {
1462 {"authorization", "Bearer " + token_.access_token_},
1463 {"api-id", std::string(api_id)},
1464 {"content-type", "application/json;charset=UTF-8"},
1465 };
1466 if (!next_key.empty()) {
1467 request.headers_.emplace_back("cont-yn", "Y");
1468 request.headers_.emplace_back("next-key", std::string(next_key));
1469 }
1470 return request;
1471 }
1472
1473 // Returns the continuation a response carries: nothing when it reports no further page.
1474 //
1475 // **An absent value and an empty one are different answers**, which is why this is an optional
1476 // rather than a string. `cont-yn: Y` means Kiwoom has another page; `next-key` is how to ask for
1477 // it. A `Y` with a missing or blank key is therefore *another page this walk cannot fetch* — and
1478 // collapsing that into "no further page", which returning a bare empty string did, turned a
1479 // listing the adapter could not finish into one it reported as complete.
1480 //
1481 // - `std::nullopt` — Kiwoom offered no further page. The listing is complete.
1482 // - a non-empty string — another page, and the key to ask for it.
1483 // - an empty string — another page, and no usable key. Incomplete.
1484 static std::optional<std::string> continuation_key(const network::HttpResponse& response) {
1485 const auto flag = response.base().find("cont-yn");
1486 if (flag == response.base().end() || flag->value() != "Y") {
1487 return std::nullopt;
1488 }
1489 const auto key = response.base().find("next-key");
1490 if (key == response.base().end()) {
1491 return std::string();
1492 }
1493 return std::string(key->value());
1494 }
1495
1496 // Lets a request through with a valid token, and otherwise requests one, unless a store manages the
1497 // token: one requested here, mid-call, would bypass the store's lock, so the call fails locally instead.
1498 // With a store, the token's validity is read once and nothing past this branch reads it again.
1499 void ensure_token(TokenHandler handler) {
1500 if (store_managed_) {
1501 if (token_.valid()) {
1502 std::move(handler)(std::nullopt);
1503 } else {
1504 std::move(handler)(network::token_unusable_error());
1505 }
1506 return;
1507 }
1508 request_token(std::move(handler));
1509 }
1510
1511 // Fetches a token when the held one has expired, coalescing concurrent waiters.
1512 //
1513 // Identical in shape to the KIS and Toss clients: at most one refresh is ever in flight, and
1514 // every other request waits behind it.
1515 void request_token(TokenHandler handler) {
1516 if (token_.valid()) {
1517 std::move(handler)(std::nullopt);
1518 return;
1519 }
1520 token_waiters_.push_back(std::move(handler));
1521 if (refreshing_) {
1522 return;
1523 }
1524 refreshing_ = true;
1525
1526 network::HttpRequest request;
1527 request.group_ = network::RateLimitGroup::AUTH;
1528 request.method_ = http::verb::post;
1529 request.target_ = "/oauth2/token";
1530 request.body_ = config_.to_jsonbody();
1531 request.headers_.emplace_back("content-type", "application/json;charset=UTF-8");
1532 http_->async_request(std::move(request), [self = shared_from_this()](Result<network::HttpResponse> result) mutable {
1533 net::post(self->strand_, [self, result = std::move(result)]() mutable {
1534 self->finish_token(std::move(result));
1535 });
1536 });
1537 }
1538
1539 // Parses a token response and releases every waiter, with the failure if there was one.
1540 void finish_token(Result<network::HttpResponse> result) {
1541 refreshing_ = false;
1542 std::optional<BrokerError> failure;
1543 if (!result) {
1544 failure = std::move(result.error());
1545 } else if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
1546 failure = kiwoom_http_error(result.value());
1547 failure->category_ = ErrorCategory::AUTHENTICATION;
1548 } else {
1549 BrokerError parse_error;
1550 auto document = broker_detail::parse_object(result.value(), parse_error);
1551 if (!document) {
1552 failure = std::move(parse_error);
1553 } else if (auto declared = kiwoom_declared_error(*document)) {
1554 // Kiwoom answers a refused token with HTTP 200 and a non-zero return_code, so the status
1555 // says nothing. `8020`, `8011` and `8012` all land here.
1556 failure = std::move(declared);
1557 } else {
1558 try {
1559 token_.from_json(*document);
1560 } catch (const std::exception& exception) {
1561 BrokerError error;
1562 error.category_ = ErrorCategory::AUTHENTICATION;
1563 error.broker_code_ = "invalid_token_response";
1564 error.message_ = exception.what();
1565 failure = std::move(error);
1566 }
1567 }
1568 }
1569
1570 if (failure) {
1571 // The waiters asked for something else, and none of their requests was sent. Same marking as
1572 // the KIS and Toss clients: an unmarked authentication failure reads to a runner as the
1573 // broker refusing an order it never received, spending rate-limit budget on nothing.
1574 failure->reached_broker_ = false;
1575 }
1576 auto waiters = std::move(token_waiters_);
1577 token_waiters_.clear();
1578 for (auto& waiter : waiters) {
1579 if (failure) {
1580 std::move(waiter)(*failure);
1581 } else {
1582 std::move(waiter)(std::nullopt);
1583 }
1584 }
1585 }
1586
1587 // Returns the error for a non-2xx reply: `broker_detail::http_error`, with Kiwoom's `return_code` read
1588 // from the whole body into `broker_code_` when the body is an object that carries one (the message
1589 // keeps only the body's start, so a code past it would otherwise be lost). The category stays what
1590 // the HTTP status says, unlike a 2xx reply's (`kiwoom_declared_error`): on an order, a rate-limit
1591 // category would turn an unknown 5xx outcome into a refusal (`kis_http_error` keeps orders out of its
1592 // mapping for that reason), and no Kiwoom non-2xx reply has been observed.
1593 static BrokerError kiwoom_http_error(const network::HttpResponse& response) {
1594 auto error = broker_detail::http_error(response);
1595 boost::system::error_code ec;
1596 const auto document = json::parse(response.body(), ec);
1597 if (ec || !document.is_object()) {
1598 return error;
1599 }
1600 if (const auto* code = document.as_object().if_contains("return_code")) {
1601 if (code->is_int64()) {
1602 error.broker_code_ = std::to_string(code->as_int64());
1603 } else if (code->is_uint64()) {
1604 error.broker_code_ = std::to_string(code->as_uint64());
1605 } else if (code->is_string()) {
1606 error.broker_code_ = std::string(code->as_string());
1607 }
1608 }
1609 return error;
1610 }
1611
1612 // Sends a request that carries the access token, and forgets that token if Kiwoom refuses it.
1613 //
1614 // Kiwoom refuses a token with `return_code` `8005` ("Token이 유효하지 않습니다"), and one issued to
1615 // another address with `8010` ("Token을 발급받은 IP와 서비스를 요청한 IP가 동일하지 않습니다", as after the
1616 // machine changes network), read here whatever the HTTP status, as `kiwoom_declared_error` and
1617 // `kiwoom_http_error` both read the code. Kept, the token would be sent until its stated expiry and every
1618 // request would fail; forgotten, the next request asks for a new one. The refused request is not sent
1619 // again and its result reaches the caller unchanged. Only the token the request carried is forgotten: a
1620 // late refusal of an older token leaves a newer one alone.
1621 template <typename Handler>
1622 void send(network::HttpRequest request, Handler handler) {
1623 std::string authorization;
1624 for (const auto& [name, value] : request.headers_) {
1625 if (name == "authorization") {
1626 authorization = value;
1627 }
1628 }
1629 http_->async_request(
1630 std::move(request),
1631 [self = shared_from_this(), authorization = std::move(authorization),
1632 handler = std::move(handler)](Result<network::HttpResponse> result) mutable {
1633 if (result && refuses_token(result.value())) {
1634 // Queued before the handler runs; every operation starts with a post to the strand, so
1635 // the next one finds the token gone.
1636 net::post(self->strand_, [self, authorization = std::move(authorization)] {
1637 self->forget_refused_token(authorization);
1638 });
1639 }
1640 std::move(handler)(std::move(result));
1641 }
1642 );
1643 }
1644
1645 // Tests whether a reply, of any status, states `return_code` `8005` or `8010`, as a number or as text.
1646 // The body is parsed only if it holds either code or a backslash, which may escape it.
1647 static bool refuses_token(const network::HttpResponse& response) {
1648 const auto& body = response.body();
1649 if (
1650 body.find("8005") == std::string::npos && body.find("8010") == std::string::npos &&
1651 body.find('\\') == std::string::npos
1652 ) {
1653 return false;
1654 }
1655 boost::system::error_code ec;
1656 const auto document = json::parse(body, ec);
1657 if (ec || !document.is_object()) {
1658 return false;
1659 }
1660 const auto* code = document.as_object().if_contains("return_code");
1661 if (!code) {
1662 return false;
1663 }
1664 const auto refused = [](std::uint64_t value) {
1665 return value == 8005 || value == 8010;
1666 };
1667 return (code->is_int64() && code->as_int64() >= 0 && refused(static_cast<std::uint64_t>(code->as_int64()))) ||
1668 (code->is_uint64() && refused(code->as_uint64())) ||
1669 (code->is_string() && (code->as_string() == "8005" || code->as_string() == "8010"));
1670 }
1671
1672 // Forgets the held token if it is the one a refused request carried (its `authorization` value).
1673 void forget_refused_token(const std::string& authorization) {
1674 if (!token_.access_token_.empty() && authorization == "Bearer " + token_.access_token_) {
1675 token_ = KiwoomRest{};
1676 }
1677 }
1678
1679 // Returns a response's declared payload, or the error ending it.
1680 //
1681 // Applies the HTTP status check, the JSON parse, and Kiwoom's own `return_code` before a parser
1682 // looks at any field, so a declared failure is never read as data. Only an order reply states an
1683 // operation: for every other caller the default keeps a refusal from being recognized.
1684 static Result<json::object> document(
1685 Result<network::HttpResponse> response, KiwoomOrderOperation operation = KiwoomOrderOperation::UNCLASSIFIED,
1686 bool demo = false
1687 ) {
1688 if (!response) {
1689 return Result<json::object>(std::move(response.error()));
1690 }
1691 if (response.value().result_int() < 200 || response.value().result_int() >= 300) {
1692 return Result<json::object>(kiwoom_http_error(response.value()));
1693 }
1694 BrokerError parse_error;
1695 auto parsed = broker_detail::parse_object(response.value(), parse_error);
1696 if (!parsed) {
1697 return Result<json::object>(std::move(parse_error));
1698 }
1699 if (auto refused = kiwoom_recognized_refusal(response.value().result_int(), *parsed, operation, demo)) {
1700 return Result<json::object>(std::move(*refused));
1701 }
1702 if (auto declared = kiwoom_declared_error(*parsed)) {
1703 return Result<json::object>(std::move(*declared));
1704 }
1705 return Result<json::object>(std::move(*parsed));
1706 }
1707
1708 // Refuses an instrument this adapter's domestic endpoints cannot address.
1709 static std::optional<BrokerError> validate_instrument(const InstrumentId& instrument) {
1710 if (
1711 instrument.country_ == Country::KR && broker_detail::valid_symbol(instrument.symbol_) &&
1712 (instrument.symbol_.size() == 6 || instrument.symbol_.size() == 7)
1713 ) {
1714 return std::nullopt;
1715 }
1716 BrokerError error;
1717 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1718 error.reached_broker_ = false;
1719 error.broker_code_ = "invalid_instrument";
1720 error.message_ =
1721 "this adapter covers Kiwoom's domestic market, whose instruments are addressed by a six- or "
1722 "seven-character code";
1723 return error;
1724 }
1725
1726 // Builds the `{"stk_cd": ...}` body every market-data endpoint takes, with the tape suffix.
1727 std::string symbol_body(const InstrumentId& instrument) const {
1728 json::object body;
1729 body["stk_cd"] = config_.tape_symbol(instrument.symbol_);
1730 return json::serialize(body);
1731 }
1732
1733 // Issues one market-data read and hands the response to `parse`.
1734 template <typename T, typename Handler, typename Parse>
1735 void start_market_read(
1736 InstrumentId instrument, std::string api_id, std::string path, Handler completion, Parse parse
1737 ) {
1738 if (auto invalid = validate_instrument(instrument)) {
1739 deliver(std::move(completion), Result<T>(std::move(*invalid)));
1740 return;
1741 }
1742 ensure_token(TokenHandler(
1743 [self = shared_from_this(), instrument = std::move(instrument), api_id = std::move(api_id),
1744 path = std::move(path), completion = std::move(completion),
1745 parse](std::optional<BrokerError> token_error) mutable {
1746 if (token_error) {
1747 self->deliver(std::move(completion), Result<T>(std::move(*token_error)));
1748 return;
1749 }
1750 auto request =
1751 self->make_request(api_id, path, self->symbol_body(instrument), network::RateLimitGroup::MARKET_DATA);
1752 self->send(
1753 std::move(request),
1754 [self, instrument = std::move(instrument), completion = std::move(completion),
1755 parse](Result<network::HttpResponse> result) mutable {
1756 self->deliver(std::move(completion), parse(std::move(instrument), std::move(result)));
1757 }
1758 );
1759 }
1760 ));
1761 }
1762
1763 // Normalizes `ka10007` into a quote.
1764 //
1765 // The last price, the volume and the top of the book all come off one response, so the quote
1766 // carries a `top_of_book_` — which neither shipped adapter fills, because neither KIS's nor
1767 // Toss's quote endpoint publishes one. Kiwoom's does, in the same response, at no extra request.
1768 static Result<QuoteSnapshot> parse_quote(InstrumentId instrument, Result<network::HttpResponse> result) {
1769 auto body = document(std::move(result));
1770 if (!body) {
1771 return Result<QuoteSnapshot>(std::move(body.error()));
1772 }
1773 try {
1774 const auto& row = body.value();
1775 QuoteSnapshot quote;
1776 quote.instrument_ = std::move(instrument);
1777 quote.currency_ = Currency::krw();
1778 const auto last = detail::magnitude(row, "cur_prc");
1779 if (!last) {
1780 throw std::runtime_error("missing or unreadable field: cur_prc");
1781 }
1782 quote.last_price_ = *last;
1783 quote.volume_ = detail::magnitude(row, "trde_qty");
1784 quote.received_at_ = std::chrono::system_clock::now();
1785 const auto date = detail::compact_date(detail::text_field(row, "date"));
1786 if (date) {
1787 quote.exchange_time_ = detail::seoul_timestamp(*date, detail::text_field(row, "tm"));
1788 }
1789 TopOfBook top;
1790 top.ask_price_ = detail::magnitude(row, "sel_1bid");
1791 top.ask_quantity_ = detail::magnitude(row, "sel_1bid_req");
1792 top.bid_price_ = detail::magnitude(row, "buy_1bid");
1793 top.bid_quantity_ = detail::magnitude(row, "buy_1bid_req");
1794 if (top.ask_price_ || top.bid_price_) {
1795 quote.top_of_book_ = top;
1796 }
1797 return Result<QuoteSnapshot>(std::move(quote));
1798 } catch (const std::exception& exception) {
1799 return Result<QuoteSnapshot>(protocol_error("invalid_quote_response", exception));
1800 }
1801 }
1802
1803 // Normalizes `ka10007`'s price bounds.
1804 //
1805 // KRX sets a limit on every listed equity, so both bounds are expected; a blank or zero bound is
1806 // reported as absent rather than as a bound of nothing.
1807 static Result<PriceLimits> parse_price_limits(InstrumentId instrument, Result<network::HttpResponse> result) {
1808 static_cast<void>(instrument);
1809 auto body = document(std::move(result));
1810 if (!body) {
1811 return Result<PriceLimits>(std::move(body.error()));
1812 }
1813 try {
1814 const auto& row = body.value();
1815 PriceLimits limits;
1816 limits.currency_ = Currency::krw();
1817 limits.upper_ = positive(detail::magnitude(row, "upl_pric"));
1818 limits.lower_ = positive(detail::magnitude(row, "lst_pric"));
1819 const auto date = detail::compact_date(detail::text_field(row, "date"));
1820 if (date) {
1821 limits.exchange_time_ = detail::seoul_timestamp(*date, detail::text_field(row, "tm"));
1822 }
1823 return Result<PriceLimits>(std::move(limits));
1824 } catch (const std::exception& exception) {
1825 return Result<PriceLimits>(protocol_error("invalid_price_limit_response", exception));
1826 }
1827 }
1828
1829 // Normalizes `ka10004` into the ten levels each side.
1830 //
1831 // Kiwoom names the first level differently from the rest — `sel_fpr_bid` and `buy_fpr_bid` for
1832 // level one, `sel_2th_pre_bid` through `sel_10th_pre_bid` for the others — so the field names are
1833 // built rather than listed, and level one is spelled out.
1834 static Result<DepthSnapshot> parse_depth(InstrumentId instrument, Result<network::HttpResponse> result) {
1835 auto body = document(std::move(result));
1836 if (!body) {
1837 return Result<DepthSnapshot>(std::move(body.error()));
1838 }
1839 try {
1840 const auto& row = body.value();
1841 DepthSnapshot book;
1842 book.instrument_ = std::move(instrument);
1843 book.currency_ = Currency::krw();
1844 book.received_at_ = std::chrono::system_clock::now();
1845 book.exchange_time_ = detail::seoul_timestamp(today_in_seoul(), detail::text_field(row, "bid_req_base_tm"));
1846 append_level(book.asks_, row, "sel_fpr_bid", "sel_fpr_req");
1847 append_level(book.bids_, row, "buy_fpr_bid", "buy_fpr_req");
1848 for (int level = 2; level <= 10; ++level) {
1849 const std::string suffix = std::to_string(level) + "th_pre_";
1850 append_level(book.asks_, row, "sel_" + suffix + "bid", "sel_" + suffix + "req");
1851 append_level(book.bids_, row, "buy_" + suffix + "bid", "buy_" + suffix + "req");
1852 }
1853 order_depth(book);
1854 return Result<DepthSnapshot>(std::move(book));
1855 } catch (const std::exception& exception) {
1856 return Result<DepthSnapshot>(protocol_error("invalid_depth_response", exception));
1857 }
1858 }
1859
1860 // Appends one book level, skipping the empty ones Kiwoom pads a thin book with.
1861 static void append_level(
1862 std::vector<DepthLevel>& side, const json::object& row, const std::string& price_key,
1863 const std::string& quantity_key
1864 ) {
1865 const auto price = detail::magnitude(row, price_key);
1866 const auto quantity = detail::magnitude(row, quantity_key);
1867 if (!price || price->coefficient() == 0) {
1868 return;
1869 }
1870 DepthLevel level;
1871 level.price_ = *price;
1872 level.quantity_ = quantity ? *quantity : Decimal64();
1873 side.push_back(level);
1874 }
1875
1876 // Returns a decimal only when it is strictly positive, which is how Kiwoom spells "no value".
1877 static std::optional<Decimal64> positive(std::optional<Decimal64> value) {
1878 if (!value || value->coefficient() <= 0) {
1879 return std::nullopt;
1880 }
1881 return value;
1882 }
1883
1884 // Returns an order's trigger from `key`, or nothing.
1885 //
1886 // `ka10075`'s `stop_pric` and `kt00007`'s `cond_uv` are both documented as "스톱지정가주문
1887 // 스톱가", and `kt00007`'s own example carries `"0000000000"` on a market order -- so an ordinary
1888 // order reports zero, and a positive value is recorded **whatever the row's basis**, for the
1889 // reason `OrderSnapshot::trigger_price_` gives. An empty, zero or unreadable value leaves the
1890 // trigger unreported rather than failing the listing: a trigger is one fact about one order, and
1891 // the row is still the order, which must stay cancellable.
1892 static std::optional<Decimal64> reported_trigger(const json::object& row, std::string_view key) {
1893 try {
1894 return positive(detail::magnitude(row, key));
1895 } catch (const std::exception&) {
1896 return std::nullopt;
1897 }
1898 }
1899
1900 // Builds a `PROTOCOL` failure from a parser exception.
1901 static BrokerError protocol_error(const char* code, const std::exception& exception) {
1902 BrokerError error;
1903 error.category_ = ErrorCategory::PROTOCOL;
1904 error.broker_code_ = code;
1905 error.message_ = exception.what();
1906 return error;
1907 }
1908
1909 // Delivers `result` to `handler` on the strand, exactly once.
1910 template <typename Handler, typename T>
1911 void deliver(Handler handler, Result<T> result) {
1912 if (!result) {
1913 note_rate_limit(result.error());
1914 }
1915 auto executor = net::get_associated_executor(handler, strand_);
1916 net::dispatch(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
1917 std::move(handler)(std::move(result));
1918 });
1919 }
1920
1921 // Holds admission after one of Kiwoom's three ceilings refused a request.
1922 //
1923 // Kiwoom documents the ceilings separately — per API (`1700`), account-wide (`1701`) and per API
1924 // group (`1702`) — but states **no allowance and no retry-after** with any of them, so there is
1925 // nothing to correct the budget *to*. Admission is held for a second and the refusal is counted;
1926 // the configured budget is left exactly as the caller set it, for the reason the KIS adapter
1927 // gives: reducing a stated budget from a guess is the silent downgrade this library refuses
1928 // everywhere else. `KiwoomRateLimitLayer` is what tells a caller watching the refusals *which*
1929 // ceiling to lower.
1930 void note_rate_limit(const BrokerError& error) {
1931 if (!error_category_is_rate_limit(error.category_)) {
1932 return;
1933 }
1934 auto* limiter = http_->rate_limits();
1935 if (limiter == nullptr) {
1936 return;
1937 }
1938 limiter->hold(
1939 error.retry_after_ ?
1940 std::chrono::duration_cast<network::RateLimitController::Duration>(*error.retry_after_) :
1941 std::chrono::duration_cast<network::RateLimitController::Duration>(std::chrono::seconds(1))
1942 );
1943 }
1944
1945 // Issues the recent-execution read, whose parser needs the requested count.
1946 void start_trades(InstrumentId instrument, int count, TradesHandler completion) {
1947 using Prints = std::vector<TradePrint>;
1948 if (count <= 0) {
1949 BrokerError error;
1950 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1951 error.reached_broker_ = false;
1952 error.broker_code_ = "invalid_count";
1953 error.message_ = "a recent-execution request must ask for at least one print";
1954 deliver(std::move(completion), Result<Prints>(std::move(error)));
1955 return;
1956 }
1957 if (auto invalid = validate_instrument(instrument)) {
1958 deliver(std::move(completion), Result<Prints>(std::move(*invalid)));
1959 return;
1960 }
1961 ensure_token(TokenHandler(
1962 [self = shared_from_this(), instrument = std::move(instrument), count,
1963 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1964 if (token_error) {
1965 self->deliver(std::move(completion), Result<Prints>(std::move(*token_error)));
1966 return;
1967 }
1968 auto request = self->make_request(
1969 "ka10003", "/api/dostk/stkinfo", self->symbol_body(instrument), network::RateLimitGroup::MARKET_DATA
1970 );
1971 self->send(
1972 std::move(request),
1973 [self, count, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1974 self->deliver(std::move(completion), parse_trades(std::move(result), count));
1975 }
1976 );
1977 }
1978 ));
1979 }
1980
1981 // Normalizes `ka10003`'s recent executions, newest first as Kiwoom sends them.
1982 //
1983 // Kiwoom reports a print's time as `HHmmss` with no date, so the KST calendar day is supplied
1984 // from the clock. A print is intraday by construction, so this is the day it happened on — the
1985 // same reasoning the KIS adapter records for the same field.
1986 static Result<std::vector<TradePrint>> parse_trades(Result<network::HttpResponse> result, int count) {
1987 using Prints = std::vector<TradePrint>;
1988 auto body = document(std::move(result));
1989 if (!body) {
1990 return Result<Prints>(std::move(body.error()));
1991 }
1992 try {
1993 const auto rows = body.value().if_contains("cntr_infr");
1994 if (!rows || !rows->is_array()) {
1995 throw std::runtime_error("missing array field: cntr_infr");
1996 }
1997 const auto today = today_in_seoul();
1998 Prints prints;
1999 for (const auto& value : rows->as_array()) {
2000 if (!value.is_object()) {
2001 throw std::runtime_error("cntr_infr row is not an object");
2002 }
2003 if (static_cast<int>(prints.size()) >= count) {
2004 break;
2005 }
2006 const auto& row = value.as_object();
2007 const auto price = detail::magnitude(row, "cur_prc");
2008 const auto quantity = detail::magnitude(row, "cntr_trde_qty");
2009 if (!price || !quantity) {
2010 continue;
2011 }
2012 TradePrint print;
2013 print.price_ = *price;
2014 print.quantity_ = *quantity;
2015 print.currency_ = Currency::krw();
2016 print.exchange_time_ = detail::seoul_timestamp(today, detail::text_field(row, "tm"));
2017 prints.push_back(print);
2018 }
2019 return Result<Prints>(std::move(prints));
2020 } catch (const std::exception& exception) {
2021 return Result<Prints>(protocol_error("invalid_trades_response", exception));
2022 }
2023 }
2024
2025 // Issues the reference-data read, which takes the bare symbol rather than a tape-suffixed one.
2026 void start_instrument(InstrumentId instrument, InstrumentHandler completion) {
2027 if (auto invalid = validate_instrument(instrument)) {
2028 deliver(std::move(completion), Result<Instrument>(std::move(*invalid)));
2029 return;
2030 }
2031 ensure_token(TokenHandler(
2032 [self = shared_from_this(), instrument = std::move(instrument),
2033 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2034 if (token_error) {
2035 self->deliver(std::move(completion), Result<Instrument>(std::move(*token_error)));
2036 return;
2037 }
2038 // `ka10100` documents `stk_cd` as 종목코드 6자리 and names no tape, unlike every
2039 // market-data endpoint. Reference data is not a price, so it has no book to come off.
2040 json::object body;
2041 body["stk_cd"] = instrument.symbol_;
2042 auto request = self->make_request(
2043 "ka10100", "/api/dostk/stkinfo", json::serialize(body), network::RateLimitGroup::REFERENCE
2044 );
2045 self->send(
2046 std::move(request),
2047 [self, instrument = std::move(instrument),
2048 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2049 self->deliver(std::move(completion), parse_instrument(std::move(instrument), std::move(result)));
2050 }
2051 );
2052 }
2053 ));
2054 }
2055
2056 // Normalizes `ka10100` into reference data.
2057 static Result<Instrument> parse_instrument(InstrumentId instrument, Result<network::HttpResponse> result) {
2058 auto body = document(std::move(result));
2059 if (!body) {
2060 return Result<Instrument>(std::move(body.error()));
2061 }
2062 try {
2063 const auto& row = body.value();
2064 Instrument subject;
2065 subject.id_ = std::move(instrument);
2066 subject.name_ = detail::text_field(row, "name");
2067 subject.currency_ = Currency::krw();
2068 subject.segment_ = kiwoom_market_segment(detail::text_field(row, "marketCode"));
2069 subject.type_ = SecurityType::STOCK;
2070 subject.status_ = kiwoom_status(detail::text_field(row, "auditInfo"));
2071 subject.shares_outstanding_ = positive(detail::magnitude(row, "listCount"));
2072 subject.listed_on_ = detail::stated_compact_date(row, "regDay");
2073 subject.price_rule_ = krx::price_rule_for(subject.type_);
2074 return Result<Instrument>(std::move(subject));
2075 } catch (const std::exception& exception) {
2076 return Result<Instrument>(protocol_error("invalid_instrument_response", exception));
2077 }
2078 }
2079
2080 // Maps Kiwoom's `marketCode` to a normalized segment.
2081 //
2082 // `0` is 거래소 (KOSPI) and `10` is 코스닥, which `ka10099` documents as its 시장구분 values. The
2083 // rest of that list — K-OTC, 코넥스, ETN, ELW and the funds — has no `MarketSegment::Known`
2084 // member, so the raw code is preserved through `market_segment` rather than collapsed into one
2085 // of the two this library does know.
2086 static MarketSegment kiwoom_market_segment(std::string_view code) {
2087 if (code == "0") {
2088 return market_segment("KOSPI");
2089 }
2090 if (code == "10") {
2091 return market_segment("KOSDAQ");
2092 }
2093 return market_segment(code);
2094 }
2095
2096 // Reads a listing state from `ka10100`'s `auditInfo`.
2097 //
2098 // Kiwoom publishes 감리구분 as a Korean phrase — the field lists `정상`, `관리종목`, `거래정지`,
2099 // `단기과열`, `투자주의`, `투자경고`, and the `ka10099` example writes `투자주의환기종목` — and publishes no
2100 // delisting date and no `SCHEDULED` state at all. Everything it reports is a listed instrument
2101 // under some degree of supervision (a halt included), so the honest reading is `ACTIVE` for the
2102 // phrases it publishes and `UNKNOWN` for any other: supervision is not delisting, and inventing a
2103 // `DELISTED` from a warning would be worse than saying nothing.
2104 static InstrumentStatus kiwoom_status(std::string_view audit) {
2105 for (
2106 const std::string_view listed :
2107 {"정상", "관리종목", "거래정지", "단기과열", "투자주의", "투자경고", "투자주의환기종목"}
2108 ) {
2109 if (audit == listed) {
2110 return InstrumentStatus::ACTIVE;
2111 }
2112 }
2113 return InstrumentStatus::UNKNOWN;
2114 }
2115
2116 // What a paged listing should do after one page.
2117 enum class PageStep {
2118 // Kiwoom offered no further page: the listing is complete.
2119 FINISH,
2120 // Kiwoom offered another page and this walk may fetch it.
2121 CONTINUE,
2122 // Kiwoom still offered another page and this walk stopped: the listing is incomplete.
2123 INCOMPLETE,
2124 };
2125
2126 // One bar request spanning however many Kiwoom pages it needs.
2127 struct BarOperation {
2128 BarQuery query_;
2129 std::vector<Bar> descending_;
2130 // The upper bound for the next page, as a KST calendar date.
2131 Date date_{};
2132 std::string next_key_;
2133 // Whether Kiwoom said another page exists, which is not the same as having its key.
2134 bool more_{false};
2135 int pages_{0};
2136 BarsHandler completion_;
2137
2138 BarOperation(BarQuery query, BarsHandler completion)
2139 : query_(std::move(query)), completion_(std::move(completion)) {}
2140 };
2141
2142 // Validates a bar request and starts walking Kiwoom's pages.
2143 void start_bars(BarQuery query, BarsHandler completion) {
2144 if (auto invalid = validate_bar_query(query)) {
2145 deliver(std::move(completion), Result<BarSeries>(std::move(*invalid)));
2146 return;
2147 }
2148 auto operation = std::make_shared<BarOperation>(std::move(query), std::move(completion));
2149 const auto bound = operation->query_.before_ ? *operation->query_.before_ : std::chrono::system_clock::now();
2150 operation->date_ = seoul_date_of(bound);
2151 request_bars(operation);
2152 }
2153
2154 // Refuses a bar request Kiwoom cannot answer, before any I/O.
2155 static std::optional<BrokerError> validate_bar_query(const BarQuery& query) {
2156 BrokerError error;
2157 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2158 error.reached_broker_ = false;
2159 if (auto invalid = validate_instrument(query.instrument_)) {
2160 return invalid;
2161 }
2162 if (query.count_ <= 0) {
2163 error.broker_code_ = "invalid_count";
2164 error.message_ = "a bar request must ask for at least one bar";
2165 return error;
2166 }
2167 return unsupported_bar_interval(query.interval_);
2168 }
2169
2170 // Issues one page of a bar request.
2171 void request_bars(std::shared_ptr<BarOperation> operation) {
2172 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
2173 if (token_error) {
2174 self->deliver(std::move(operation->completion_), Result<BarSeries>(std::move(*token_error)));
2175 return;
2176 }
2177 json::object body;
2178 body["stk_cd"] = self->config_.tape_symbol(operation->query_.instrument_.symbol_);
2179 if (operation->query_.interval_ == BarInterval::ONE_MINUTE) {
2180 body["tic_scope"] = "1";
2181 }
2182 // `upd_stkpc_tp`: `1` asks for prices adjusted for corporate actions, `0` for raw ones.
2183 // `BarQuery::adjusted_` exists because the brokers disagree about how to spell it, and
2184 // Kiwoom's spelling is the opposite of KIS's `FID_ORG_ADJ_PRC`.
2185 body["upd_stkpc_tp"] = operation->query_.adjusted_ ? "1" : "0";
2186 body["base_dt"] = detail::compact_text(operation->date_);
2187 auto request = self->make_request(
2188 chart_api_id(operation->query_.interval_), "/api/dostk/chart", json::serialize(body),
2189 network::RateLimitGroup::MARKET_DATA, operation->next_key_
2190 );
2191 self->send(std::move(request), [self, operation](Result<network::HttpResponse> result) mutable {
2192 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
2193 self->handle_bars_page(operation, std::move(result));
2194 });
2195 });
2196 }));
2197 }
2198
2199 // Accumulates one page of bars and either continues or finishes.
2200 void handle_bars_page(const std::shared_ptr<BarOperation>& operation, Result<network::HttpResponse> result) {
2201 if (!result) {
2202 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(result.error())));
2203 return;
2204 }
2205 const auto next_key = continuation_key(result.value());
2206 auto body = document(std::move(result));
2207 if (!body) {
2208 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(body.error())));
2209 return;
2210 }
2211 const std::size_t before = operation->descending_.size();
2212 try {
2213 const auto rows = body.value().if_contains(chart_rows_field(operation->query_.interval_));
2214 if (!rows || !rows->is_array()) {
2215 throw std::runtime_error(std::string("missing array field: ") + chart_rows_field(operation->query_.interval_));
2216 }
2217 for (const auto& value : rows->as_array()) {
2218 if (!value.is_object()) {
2219 throw std::runtime_error("chart row is not an object");
2220 }
2221 operation->descending_.push_back(parse_bar(value.as_object(), operation->query_.interval_));
2222 }
2223 } catch (const std::exception& exception) {
2224 deliver(std::move(operation->completion_), Result<BarSeries>(protocol_error("invalid_bars_response", exception)));
2225 return;
2226 }
2227
2228 switch (advance_bars(*operation, std::move(next_key), before)) {
2229 case PageStep::FINISH:
2230 finish_bars(operation);
2231 return;
2232 case PageStep::INCOMPLETE:
2233 deliver(std::move(operation->completion_), Result<BarSeries>(incomplete_listing("bars", operation->pages_)));
2234 return;
2235 case PageStep::CONTINUE:
2236 request_bars(operation);
2237 return;
2238 }
2239 }
2240
2241 // Records the page's continuation key and returns whether the walk should stop.
2242 //
2243 // **The key is recorded before the decision is taken, not after it**, and that ordering is the
2244 // point of this being one function. `finish_bars` reads `next_key_` to decide whether the series
2245 // carries a continuation cursor, and the walk stops with data still available precisely when
2246 // `count_` is satisfied -- which is exactly when a caller needs that cursor to page further
2247 // back. Assigning the key only on the path that continues left the *previous* page's key here,
2248 // so a satisfied request reported a stale cursor or none.
2249 //
2250 // A page that returned nothing also ends the walk. Without that, a broker answering `Y` with an
2251 // empty array would spend the whole page budget learning nothing.
2252 static PageStep advance_bars(BarOperation& operation, std::optional<std::string> next_key, std::size_t before) {
2253 operation.more_ = next_key.has_value();
2254 operation.next_key_ = next_key ? std::move(*next_key) : std::string();
2255 ++operation.pages_;
2256 const bool grew = operation.descending_.size() > before;
2257 const bool satisfied = static_cast<int>(operation.descending_.size()) >= operation.query_.count_;
2258 if (satisfied || !operation.more_) {
2259 return PageStep::FINISH;
2260 }
2261 // **Kiwoom offered more and the count is not satisfied.** Either this walk fetches the next
2262 // page or the series is short of what was asked for -- and a short series is not a finished
2263 // one. Returning it would be the listing defect in another place: a caller reads `bars_.size()`
2264 // and cannot tell "this is all there is" from "the walk gave up".
2265 //
2266 // A keyless page is the same thing arriving differently: Kiwoom offered a page and no way to
2267 // ask for it.
2268 if (operation.next_key_.empty() || !grew || operation.pages_ >= page_budget_) {
2269 return PageStep::INCOMPLETE;
2270 }
2271 return PageStep::CONTINUE;
2272 }
2273
2274 // Normalizes one chart row.
2275 //
2276 // A minute row stamps `cntr_tm` as `yyyyMMddHHmmss`; every other interval stamps `dt` as
2277 // `yyyyMMdd`. `cur_prc` is the period's close and, like every market-data price, carries a
2278 // direction prefix rather than a sign.
2279 static Bar parse_bar(const json::object& row, BarInterval interval) {
2280 Bar bar;
2281 if (interval == BarInterval::ONE_MINUTE) {
2282 const auto stamp = detail::text_field(row, "cntr_tm");
2283 if (stamp.size() != 14) {
2284 throw std::runtime_error("invalid minute bar timestamp");
2285 }
2286 const auto date = detail::compact_date(std::string_view(stamp).substr(0, 8));
2287 const auto timestamp = date ? detail::seoul_timestamp(*date, std::string_view(stamp).substr(8)) : std::nullopt;
2288 if (!timestamp) {
2289 throw std::runtime_error("invalid minute bar timestamp");
2290 }
2291 bar.timestamp_ = *timestamp;
2292 } else {
2293 const auto date = detail::compact_date(detail::text_field(row, "dt"));
2294 const auto timestamp = date ? detail::seoul_timestamp(*date, "000000") : std::nullopt;
2295 if (!timestamp) {
2296 throw std::runtime_error("invalid bar date");
2297 }
2298 bar.timestamp_ = *timestamp;
2299 }
2300 const auto high = detail::magnitude(row, "high_pric");
2301 const auto low = detail::magnitude(row, "low_pric");
2302 const auto close = detail::magnitude(row, "cur_prc");
2303 if (!high || !low || !close) {
2304 throw std::runtime_error("bar row is missing a price");
2305 }
2306 bar.high_ = *high;
2307 bar.low_ = *low;
2308 bar.close_ = *close;
2309 bar.volume_ = detail::required_magnitude(row, "trde_qty");
2310 bar.open_ = detail::magnitude(row, "open_pric");
2311 bar.traded_value_ = detail::magnitude(row, "trde_prica");
2312 return bar;
2313 }
2314
2315 // Reverses the accumulation, trims to the requested count, and returns the series.
2316 //
2317 // Pure, and separate from the completion for that reason: what a walk *produced* is the thing
2318 // worth checking, and checking it should not require a strand, a socket or a completion token.
2319 static BarSeries compose_bars(BarOperation& operation) {
2320 BarSeries series;
2321 series.instrument_ = operation.query_.instrument_;
2322 series.interval_ = operation.query_.interval_;
2323 series.currency_ = Currency::krw();
2324 series.received_at_ = std::chrono::system_clock::now();
2325 // What was asked for is what was sent (`upd_stkpc_tp`), and the series has to say which prices
2326 // it carries: the field defaults to `true`, so a raw request whose result never set it would
2327 // hand a caller unadjusted prices labelled as adjusted.
2328 series.adjusted_ = operation.query_.adjusted_;
2329 // Every bar is stamped at its open: a period bar by its trading date, and a minute bar by the
2330 // start of its minute (`ka10080`'s `cntr_tm` is "봉의 시작시간"; a session's first rows are 08:00:00
2331 // and 09:00:00, and the minute in progress carries its own minute).
2332 series.stamp_ = BarStamp::OPEN;
2333
2334 auto& rows = operation.descending_;
2335 if (static_cast<int>(rows.size()) > operation.query_.count_) {
2336 rows.resize(static_cast<std::size_t>(operation.query_.count_));
2337 }
2338 series.bars_.assign(rows.rbegin(), rows.rend());
2339 // The oldest bar in hand, which is what a caller passes back as `before_` to page further
2340 // back. Emitted only when Kiwoom said there is more *and* a caller could act on it: an
2341 // exhausted history reports no cursor rather than one that would return nothing, and a minute
2342 // series reports none because `base_dt` is a date and cannot resume inside a day. A minute
2343 // walk that cannot satisfy its count fails instead; see `advance_bars`.
2344 const bool resumable = operation.query_.interval_ != BarInterval::ONE_MINUTE;
2345 if (!series.bars_.empty() && operation.more_ && resumable) {
2346 series.next_cursor_ = format_iso8601_utc(series.bars_.front().timestamp_);
2347 }
2348 return series;
2349 }
2350
2351 // Composes the series and delivers it.
2352 void finish_bars(const std::shared_ptr<BarOperation>& operation) {
2353 deliver(std::move(operation->completion_), Result<BarSeries>(compose_bars(*operation)));
2354 }
2355
2356 // Returns the KST calendar date an instant falls on.
2357 static Date seoul_date_of(std::chrono::system_clock::time_point instant) {
2358 const std::time_t raw = std::chrono::system_clock::to_time_t(
2359 std::chrono::time_point_cast<std::chrono::seconds>(instant + std::chrono::hours(9))
2360 );
2361 std::tm parts{};
2362#ifdef _WIN32
2363 gmtime_s(&parts, &raw);
2364#else
2365 gmtime_r(&raw, &parts);
2366#endif
2367 Date date;
2368 date.year_ = parts.tm_year + 1900;
2369 date.month_ = parts.tm_mon + 1;
2370 date.day_ = parts.tm_mday;
2371 return date;
2372 }
2373
2374 // Records the page's continuation key and says what the walk should do next.
2375 //
2376 // One function for the three account listings, because the decision is the same for all of them
2377 // and the consequence of getting it wrong is the same too. It is separate from the handlers so
2378 // that the decision can be exercised without a socket.
2379 static PageStep advance_page(std::string& next_key_slot, int& pages, bool grew, std::optional<std::string> next_key) {
2380 ++pages;
2381 if (!next_key) {
2382 return PageStep::FINISH;
2383 }
2384 // Kiwoom offered another page. Either this walk fetches it or the listing is incomplete --
2385 // there is no third answer, including when the key it offered is unusable.
2386 if (next_key->empty() || !grew || pages >= page_budget_) {
2387 return PageStep::INCOMPLETE;
2388 }
2389 next_key_slot = std::move(*next_key);
2390 return PageStep::CONTINUE;
2391 }
2392
2393 // Returns the failure a listing that stopped while more remained should end with.
2394 //
2395 // **A guard that bounds a walk must not also decide the walk finished.** Kiwoom says `cont-yn: Y`
2396 // with a `next-key` exactly when there is another page, so stopping on the page budget -- or on a
2397 // page that added no rows while Kiwoom still offered another -- leaves rows unread. Returning
2398 // what was gathered would hand a *partial* answer to code that cannot tell: a working-order
2399 // listing missing a resting sell understates what `RiskGuard` deducts, and partial holdings
2400 // understate exposure, which is the permissive direction for a position ceiling.
2401 //
2402 // Bars are the exception and do not come through here: `BarSeries` carries `next_cursor_`, so a
2403 // bar walk can say "there is more" in the value itself. Holdings, working orders and order
2404 // history have nowhere to say it, so they fail instead.
2405 static BrokerError incomplete_listing(std::string_view what, int pages) {
2406 BrokerError error;
2407 error.category_ = ErrorCategory::PROTOCOL;
2408 error.broker_code_ = "incomplete_listing";
2409 error.reached_broker_ = true;
2410 error.message_ = std::string("Kiwoom still offered another page of ") + std::string(what) + " after " +
2411 std::to_string(pages) + " page(s); the listing is incomplete and is refused rather than returned in part";
2412 return error;
2413 }
2414
2415 // One holdings request spanning however many `kt00018` pages it needs.
2416 struct HoldingsOperation {
2417 HoldingsSnapshot snapshot_;
2418 std::string next_key_;
2419 int pages_{0};
2420 bool totals_seen_{false};
2421 HoldingsHandler completion_;
2422
2423 explicit HoldingsOperation(HoldingsHandler completion) : completion_(std::move(completion)) {}
2424 };
2425
2426 // Validates the configured holdings venue and starts paging.
2427 void start_holdings(HoldingsHandler completion) {
2428 if (auto invalid = validate_holdings_venue()) {
2429 deliver(std::move(completion), Result<HoldingsSnapshot>(std::move(*invalid)));
2430 return;
2431 }
2432 auto operation = std::make_shared<HoldingsOperation>(std::move(completion));
2433 request_holdings(operation);
2434 }
2435
2436 // Refuses a holdings venue `kt00018` cannot express.
2437 //
2438 // `kt00018`'s `dmst_stex_tp` documents `KRX` and `NXT` and no all-venue value, so there is
2439 // nothing for `COMBINED` or `UNSPECIFIED` to be sent as. Resolving either to one of the two
2440 // would answer a different question from the one asked and would do it silently, which this
2441 // library refuses to do — and holdings are what the sellable guard and every position ceiling are
2442 // measured against. See `KiwoomConfig::holdings_venue_`.
2443 // Refuses an instruction that can open or enlarge a position while the holdings scope is unstated.
2444 //
2445 // Nothing once the operator has asserted what `dmst_stex_tp` means: the assertion is what this
2446 // refusal exists to demand, so honouring it is the whole point rather than a weakening. It does
2447 // **not** promise a holdings read has succeeded -- see `KiwoomConfig::holdings_position_scope_`
2448 // for what an assertion does and does not claim, and note that the runner's own portfolio gate is
2449 // a separate rule that still applies.
2450 // Returns what `trde_able_qty` on a `kt00018` row is evidence of, given what the operator asserted.
2451 //
2452 // **A named decision with one caller**, rather than three lines inside the paging branch that
2453 // completes a snapshot. That branch is unreachable without a live HTTP round trip, so a rule
2454 // written there is a rule no test can drive. A decision worth making is worth naming
2455 // (`validate_amendment`), and this is the same shape.
2456 //
2457 // The coverage is the operator's assertion and nothing more. The resting treatment is this
2458 // library's own conservative rule either way and is deliberately not a caller's to state:
2459 // deducting a resting sell Kiwoom had also deducted refuses a trade, while not deducting one
2460 // sells the same shares twice, and only the first error is recoverable. `verified_` stays false
2461 // because an assertion is not a measurement.
2462 static SellableBasis holdings_sellable_basis(KiwoomSellableScope scope) {
2463 return SellableBasis{
2468 false,
2469 };
2470 }
2471
2472 static std::optional<BrokerError> holdings_scope_refusal(KiwoomPositionScope scope) {
2473 if (!kiwoom_position_scope_asserted(scope)) {
2475 }
2476 return std::nullopt;
2477 }
2478
2479 std::optional<BrokerError> validate_holdings_venue() const {
2480 if (config_.holdings_venue_ == Venue::KRX || config_.holdings_venue_ == Venue::NXT) {
2481 return std::nullopt;
2482 }
2483 BrokerError error;
2484 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2485 error.reached_broker_ = false;
2486 error.broker_code_ = "holdings_venue_required";
2487 error.message_ =
2488 "Kiwoom's balance inquiry names one venue and publishes no combined value, and whether that "
2489 "selects which positions are listed or only how they are valued is not stated; set "
2490 "KiwoomConfig::holdings_venue_ to Venue::KRX or Venue::NXT deliberately, having read its "
2491 "documentation";
2492 return error;
2493 }
2494
2495 // Issues one page of the holdings inquiry.
2496 void request_holdings(std::shared_ptr<HoldingsOperation> operation) {
2497 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
2498 if (token_error) {
2499 self->deliver(std::move(operation->completion_), Result<HoldingsSnapshot>(std::move(*token_error)));
2500 return;
2501 }
2502 auto request = self->make_request(
2503 "kt00018", "/api/dostk/acnt", self->holdings_body(), network::RateLimitGroup::ACCOUNT, operation->next_key_
2504 );
2505 self->send(std::move(request), [self, operation](Result<network::HttpResponse> result) mutable {
2506 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
2507 self->handle_holdings_page(operation, std::move(result));
2508 });
2509 });
2510 }));
2511 }
2512
2513 // Builds `kt00018`'s body: one summed listing, from the configured venue.
2514 std::string holdings_body() const {
2515 json::object body;
2516 // `1:합산` asks Kiwoom to sum the lots of one instrument into one row; `2:개별` reports them
2517 // separately. Summed is what this library asks for -- but the specification's own example
2518 // answers a `qry_tp: "1"` request with *two* `A005930` rows, so asking is not the same as
2519 // getting, and `append_holdings_page` refuses a listing that comes back split rather than
2520 // trusting the request. See `duplicate_symbol` there for why that matters.
2521 body["qry_tp"] = "1";
2522 body["dmst_stex_tp"] = exchange_code(config_.holdings_venue_);
2523 return json::serialize(body);
2524 }
2525
2526 // Accumulates one page of holdings and either continues or completes.
2527 void handle_holdings_page(const std::shared_ptr<HoldingsOperation>& operation, Result<network::HttpResponse> result) {
2528 if (!result) {
2529 deliver(std::move(operation->completion_), Result<HoldingsSnapshot>(std::move(result.error())));
2530 return;
2531 }
2532 const auto next_key = continuation_key(result.value());
2533 auto body = document(std::move(result));
2534 if (!body) {
2535 deliver(std::move(operation->completion_), Result<HoldingsSnapshot>(std::move(body.error())));
2536 return;
2537 }
2538 const std::size_t before = operation->snapshot_.positions_.size();
2539 try {
2540 append_holdings_page(operation->snapshot_, operation->totals_seen_, body.value());
2541 } catch (const std::exception& exception) {
2542 deliver(
2543 std::move(operation->completion_),
2544 Result<HoldingsSnapshot>(protocol_error("invalid_holdings_response", exception))
2545 );
2546 return;
2547 }
2548 const bool grew = operation->snapshot_.positions_.size() > before;
2549 switch (advance_page(operation->next_key_, operation->pages_, grew, std::move(next_key))) {
2550 case PageStep::FINISH:
2551 operation->snapshot_.received_at_ = std::chrono::system_clock::now();
2552 // **What the `trde_able_qty` figures on these rows are evidence of, per the operator's own
2553 // assertion and nothing more.** `WHOLE_HOLDING` only when somebody has stated that the
2554 // venue parameter does not restrict the figure; unestablished otherwise, which makes
2555 // `RiskGuard` refuse a checked sell rather than measure one against a number that may
2556 // describe one book out of two. The *resting* treatment is this library's conservative rule
2557 // either way and is not a caller's to assert: deducting a resting sell Kiwoom had also
2558 // deducted refuses a trade, where the opposite sells the same shares twice.
2559 operation->snapshot_.sellable_basis_ = holdings_sellable_basis(config_.holdings_sellable_scope_);
2560 deliver(std::move(operation->completion_), Result<HoldingsSnapshot>(std::move(operation->snapshot_)));
2561 return;
2562 case PageStep::INCOMPLETE:
2563 deliver(
2564 std::move(operation->completion_), Result<HoldingsSnapshot>(incomplete_listing("holdings", operation->pages_))
2565 );
2566 return;
2567 case PageStep::CONTINUE:
2568 request_holdings(operation);
2569 return;
2570 }
2571 }
2572
2573 // Appends one `kt00018` page's rows and, on the first page only, its totals.
2574 //
2575 // **A symbol that appears twice fails the snapshot.** The request asks for a summed listing
2576 // (`qry_tp: "1"`), and the specification's own response example answers exactly that request
2577 // with two `A005930` rows carrying 3 and 8 shares -- so a split listing is a real possibility
2578 // and not a hypothetical. It is refused rather than accepted for a reason that costs money:
2579 // `Portfolio` reads the *first* matching row's `sellable_quantity_`, so a split holding would
2580 // report 3 sellable shares where Kiwoom said 11, and which 3 would depend on row order.
2581 // Summing them instead is not this library's call to make -- whether two lots' *sellable*
2582 // quantities add is a statement about what the broker meant, which the specification does not
2583 // settle. So the snapshot fails loudly, once, with the symbol named.
2584 //
2585 // **The totals come from Kiwoom's summary fields and are never summed from the rows**, which is
2586 // what `HoldingsTotals` documents: a paged listing can return part of the positions beside an
2587 // account-wide summary, so the two need not agree and the broker's own figure is the one to
2588 // report. Only the first page's summary is taken, because every page repeats it.
2589 static void append_holdings_page(HoldingsSnapshot& snapshot, bool& totals_seen, const json::object& page) {
2590 if (!totals_seen) {
2591 HoldingsTotals totals;
2592 totals.currency_ = Currency::krw();
2593 totals.purchase_value_ = detail::magnitude_or_zero(page, "tot_pur_amt");
2594 totals.market_value_ = detail::magnitude_or_zero(page, "tot_evlt_amt");
2595 totals.unrealized_profit_loss_ = detail::signed_or_zero(page, "tot_evlt_pl");
2596 snapshot.totals_.push_back(totals);
2597 totals_seen = true;
2598 }
2599 const auto rows = page.if_contains("acnt_evlt_remn_indv_tot");
2600 if (!rows) {
2601 return;
2602 }
2603 if (!rows->is_array()) {
2604 throw std::runtime_error("acnt_evlt_remn_indv_tot is not an array");
2605 }
2606 for (const auto& value : rows->as_array()) {
2607 if (!value.is_object()) {
2608 throw std::runtime_error("holdings row is not an object");
2609 }
2610 auto position = parse_holding(value.as_object());
2611 if (duplicate_symbol(snapshot, position.instrument_.symbol_)) {
2612 throw std::runtime_error(
2613 "holdings listing reports " + position.instrument_.symbol_ +
2614 " on more than one row although it was requested summed (qry_tp=1)"
2615 );
2616 }
2617 snapshot.positions_.push_back(std::move(position));
2618 }
2619 }
2620
2621 // Returns whether `symbol` already has a row in `snapshot`.
2622 static bool duplicate_symbol(const HoldingsSnapshot& snapshot, const std::string& symbol) {
2623 for (const auto& position : snapshot.positions_) {
2624 if (position.instrument_.symbol_ == symbol) {
2625 return true;
2626 }
2627 }
2628 return false;
2629 }
2630
2631 // Normalizes one `kt00018` position row.
2632 static HoldingPosition parse_holding(const json::object& row) {
2633 HoldingPosition position;
2634 position.instrument_.country_ = Country::KR;
2635 // A holding is reported without a venue, so it carries the identity venue -- the combined one
2636 // -- and not whichever book `dmst_stex_tp` named. An identity that carried the request's venue
2637 // would stop matching the same instrument's working orders and quotes.
2638 position.instrument_.venue_ = Venue::COMBINED;
2639 position.instrument_.symbol_ = detail::bare_symbol(detail::text_field(row, "stk_cd"));
2640 position.name_ = detail::text_field(row, "stk_nm");
2641 position.quantity_ = detail::required_magnitude(row, "rmnd_qty");
2642 position.sellable_quantity_ = detail::magnitude(row, "trde_able_qty");
2643 position.average_purchase_price_ = detail::magnitude_or_zero(row, "pur_pric");
2644 position.last_price_ = detail::magnitude_or_zero(row, "cur_prc");
2645 position.purchase_value_ = Money{detail::magnitude_or_zero(row, "pur_amt"), Currency::krw()};
2646 position.market_value_ = Money{detail::magnitude_or_zero(row, "evlt_amt"), Currency::krw()};
2647 position.unrealized_profit_loss_ = Money{detail::signed_or_zero(row, "evltv_prft"), Currency::krw()};
2648 // `prft_rt` is a percentage with a sign; the normalized field is a fraction.
2649 if (const auto percent = detail::signed_value(row, "prft_rt")) {
2650 position.unrealized_return_ = broker_detail::percent_to_ratio(detail::text_field(row, "prft_rt"));
2651 }
2652 return position;
2653 }
2654
2655 // Issues the deposit inquiry and reduces it to what the port asked for.
2656 void start_buying_power(Currency currency, BuyingPowerHandler completion) {
2657 if (!(currency == Currency::krw())) {
2658 BrokerError error;
2659 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2660 error.reached_broker_ = false;
2661 error.broker_code_ = "unsupported_currency";
2662 error.message_ = "Kiwoom's domestic deposit inquiry answers in won";
2663 deliver(std::move(completion), Result<BuyingPower>(std::move(error)));
2664 return;
2665 }
2666 start_deposit(DepositHandler(
2667 [self = shared_from_this(), completion = std::move(completion)](Result<KiwoomDeposit> result) mutable {
2668 if (!result) {
2669 self->deliver(std::move(completion), Result<BuyingPower>(std::move(result.error())));
2670 return;
2671 }
2672 BuyingPower power;
2673 power.cash_ = Money{result.value().spendable_, result.value().currency_};
2674 power.received_at_ = result.value().received_at_;
2675 self->deliver(std::move(completion), Result<BuyingPower>(std::move(power)));
2676 }
2677 ));
2678 }
2679
2680 // Issues `kt00001` 예수금상세현황요청.
2681 void start_deposit(DepositHandler completion) {
2682 ensure_token(TokenHandler(
2683 [self = shared_from_this(), completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2684 if (token_error) {
2685 self->deliver(std::move(completion), Result<KiwoomDeposit>(std::move(*token_error)));
2686 return;
2687 }
2688 json::object body;
2689 // `3:추정조회` includes today's unsettled activity; `2:일반조회` does not. The estimate is
2690 // what a figure named "what may be spent" has to mean intraday.
2691 body["qry_tp"] = "3";
2692 auto request =
2693 self->make_request("kt00001", "/api/dostk/acnt", json::serialize(body), network::RateLimitGroup::ACCOUNT);
2694 self->send(
2695 std::move(request), [self, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2696 self->deliver(std::move(completion), parse_deposit(std::move(result)));
2697 }
2698 );
2699 }
2700 ));
2701 }
2702
2703 // Normalizes `kt00001` into Kiwoom's own deposit detail.
2704 static Result<KiwoomDeposit> parse_deposit(Result<network::HttpResponse> result) {
2705 auto body = document(std::move(result));
2706 if (!body) {
2707 return Result<KiwoomDeposit>(std::move(body.error()));
2708 }
2709 try {
2710 const auto& row = body.value();
2711 KiwoomDeposit deposit;
2712 deposit.currency_ = Currency::krw();
2713 deposit.received_at_ = std::chrono::system_clock::now();
2714 const auto spendable = detail::signed_value(row, "100stk_ord_alow_amt");
2715 if (!spendable) {
2716 throw std::runtime_error("missing or unreadable field: 100stk_ord_alow_amt");
2717 }
2718 deposit.spendable_ = *spendable;
2719 deposit.orderable_ = detail::signed_or_zero(row, "ord_alow_amt");
2720 deposit.deposit_ = detail::signed_or_zero(row, "entr");
2721 deposit.settled_deposit_ = detail::signed_or_zero(row, "d2_entra");
2722 deposit.substitute_amount_ = detail::signed_or_zero(row, "repl_amt");
2723 deposit.withdrawable_ = detail::signed_or_zero(row, "pymn_alow_amt");
2724 return Result<KiwoomDeposit>(std::move(deposit));
2725 } catch (const std::exception& exception) {
2726 return Result<KiwoomDeposit>(protocol_error("invalid_deposit_response", exception));
2727 }
2728 }
2729
2730 // Issues `kt00010` 주문인출가능금액요청 for one instrument.
2731 void start_orderable_amount(
2732 InstrumentId instrument, OrderSide side, std::optional<Decimal64> price, OrderableHandler completion
2733 ) {
2734 if (auto invalid = validate_instrument(instrument)) {
2735 deliver(std::move(completion), Result<KiwoomOrderableAmount>(std::move(*invalid)));
2736 return;
2737 }
2738 ensure_token(TokenHandler(
2739 [self = shared_from_this(), instrument = std::move(instrument), side, price = std::move(price),
2740 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2741 if (token_error) {
2742 self->deliver(std::move(completion), Result<KiwoomOrderableAmount>(std::move(*token_error)));
2743 return;
2744 }
2745 json::object body;
2746 body["stk_cd"] = instrument.symbol_;
2747 body["trde_tp"] = side == OrderSide::SELL ? "1" : "2";
2748 body["uv"] = price ? price->str() : "";
2749 auto request =
2750 self->make_request("kt00010", "/api/dostk/acnt", json::serialize(body), network::RateLimitGroup::ACCOUNT);
2751 self->send(
2752 std::move(request), [self, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2753 self->deliver(std::move(completion), parse_orderable_amount(std::move(result)));
2754 }
2755 );
2756 }
2757 ));
2758 }
2759
2760 // Normalizes `kt00010` into the per-margin-tier amounts and quantities.
2761 static Result<KiwoomOrderableAmount> parse_orderable_amount(Result<network::HttpResponse> result) {
2762 auto body = document(std::move(result));
2763 if (!body) {
2764 return Result<KiwoomOrderableAmount>(std::move(body.error()));
2765 }
2766 try {
2767 const auto& row = body.value();
2768 KiwoomOrderableAmount orderable;
2769 orderable.currency_ = Currency::krw();
2770 orderable.received_at_ = std::chrono::system_clock::now();
2771 // The amounts stay signed: a deposit figure can genuinely be negative when the account is
2772 // in 미수, and none of them is a price, so no direction prefix applies to them. The
2773 // quantities cannot be negative and are read as magnitudes.
2774 orderable.orderable_cash_ = detail::signed_or_zero(row, "ord_alowa");
2775 orderable.withdrawable_ = detail::signed_or_zero(row, "wthd_alowa");
2776 orderable.settled_deposit_ = detail::signed_or_zero(row, "d2entra");
2777 orderable.margin_reduction_applies_ = detail::text_field(row, "profa_rdex_aplc_tp") == "1";
2778 for (const int percent : {20, 30, 40, 50, 60, 100}) {
2779 KiwoomMarginTier tier;
2780 tier.margin_percent_ = percent;
2781 const std::string prefix = "profa_" + std::to_string(percent) + "ord_alow";
2782 tier.amount_ = detail::signed_value(row, prefix + "_amt");
2783 tier.quantity_ = detail::magnitude(row, prefix + "q");
2784 orderable.tiers_.push_back(tier);
2785 }
2786 KiwoomMarginTier reduced;
2787 reduced.margin_percent_ = 60;
2788 reduced.reduced_ = true;
2789 reduced.amount_ = detail::signed_value(row, "profa_rdex_60ord_alow_amt");
2790 reduced.quantity_ = detail::magnitude(row, "profa_rdex_60ord_alowq");
2791 orderable.tiers_.push_back(reduced);
2792 return Result<KiwoomOrderableAmount>(std::move(orderable));
2793 } catch (const std::exception& exception) {
2794 return Result<KiwoomOrderableAmount>(protocol_error("invalid_orderable_amount_response", exception));
2795 }
2796 }
2797
2798 // Issues `ka00001` 계좌번호조회, which answers with the one account the credential drives.
2799 void start_accounts(AccountsHandler completion) {
2800 using Accounts = std::vector<KiwoomAccountInfo>;
2801 ensure_token(TokenHandler(
2802 [self = shared_from_this(), completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2803 if (token_error) {
2804 self->deliver(std::move(completion), Result<Accounts>(std::move(*token_error)));
2805 return;
2806 }
2807 auto request = self->make_request("ka00001", "/api/dostk/acnt", "{}", network::RateLimitGroup::ACCOUNT);
2808 self->send(
2809 std::move(request), [self, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2810 self->deliver(std::move(completion), parse_accounts(std::move(result)));
2811 }
2812 );
2813 }
2814 ));
2815 }
2816
2817 // Normalizes `ka00001` into a listing of one.
2818 //
2819 // A listing rather than a single value, because that is the port's shape — and the shape is
2820 // honest here: Kiwoom answers with the account the credential drives and there is no other to
2821 // choose between.
2822 static Result<std::vector<KiwoomAccountInfo>> parse_accounts(Result<network::HttpResponse> result) {
2823 using Accounts = std::vector<KiwoomAccountInfo>;
2824 auto body = document(std::move(result));
2825 if (!body) {
2826 return Result<Accounts>(std::move(body.error()));
2827 }
2828 try {
2829 const auto number = detail::text_field(body.value(), "acctNo");
2830 if (number.empty()) {
2831 throw std::runtime_error("missing string field: acctNo");
2832 }
2833 Accounts accounts;
2834 accounts.push_back(KiwoomAccountInfo{number});
2835 return Result<Accounts>(std::move(accounts));
2836 } catch (const std::exception& exception) {
2837 return Result<Accounts>(protocol_error("invalid_accounts_response", exception));
2838 }
2839 }
2840
2841 // Returns an error when a quantity is not a whole number of shares.
2842 //
2843 // `allow_zero` is Kiwoom's all-remaining value on an amendment, which it documents as the
2844 // quantity `0`. A *placement* of zero shares is still refused.
2845 static std::optional<BrokerError> validate_quantity(const Decimal64& quantity, bool allow_zero = false) {
2846 const bool positive = quantity.coefficient() > 0;
2847 if ((positive || (allow_zero && quantity.coefficient() == 0)) && quantity.scale() == 0) {
2848 return std::nullopt;
2849 }
2850 BrokerError error;
2851 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2852 error.reached_broker_ = false;
2853 error.broker_code_ = "invalid_quantity";
2854 error.message_ = allow_zero ?
2855 "a Kiwoom amendment quantity must be a whole number of shares, or zero for all remaining" :
2856 "a Kiwoom order quantity must be a positive whole number of shares";
2857 return error;
2858 }
2859
2860 // Returns an error when a price does not match its price basis.
2861 //
2862 // `carries_caller_price`, not `== LIMIT`: 조건부지정가 is a limit instruction until the close, and
2863 // treating it as unpriced is how KIS's adapter once transmitted `ORD_UNPR="0"` — an order at zero
2864 // rather than at the stated limit.
2865 static std::optional<BrokerError> validate_price(OrderType type, const std::optional<Decimal64>& price) {
2866 BrokerError error;
2867 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2868 error.reached_broker_ = false;
2869 error.broker_code_ = "invalid_price";
2870 if (carries_caller_price(type)) {
2871 if (!price) {
2872 error.message_ = "a Kiwoom order of this price basis requires a price";
2873 return error;
2874 }
2875 if (price->coefficient() <= 0) {
2876 error.message_ = "a Kiwoom order price must be positive";
2877 return error;
2878 }
2879 if (price->scale() != 0) {
2880 error.message_ = "a Kiwoom domestic order price must be a whole number of won";
2881 return error;
2882 }
2883 return std::nullopt;
2884 }
2885 if (price) {
2886 error.message_ =
2887 "Kiwoom takes no price for this basis; a market, best-limit, primary-limit, mid-price or "
2888 "closing-price order is priced by the book";
2889 return error;
2890 }
2891 return std::nullopt;
2892 }
2893
2894 // Returns an error when a Kiwoom order names no venue.
2895 //
2896 // **Kiwoom documents `dmst_stex_tp` with no default**, so unlike KIS there is no "omitted means
2897 // KRX" rule this adapter could record and journal. An order that names no venue is refused before
2898 // any I/O rather than sent to a venue this library chose, because recovery has to be able to say
2899 // where an order went and a guessed venue makes that a fabrication.
2900 static std::optional<BrokerError> validate_venue(Venue venue) {
2901 if (venue == Venue::KRX || venue == Venue::NXT || venue == Venue::COMBINED) {
2902 return std::nullopt;
2903 }
2904 BrokerError error;
2905 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2906 error.reached_broker_ = false;
2907 error.broker_code_ = "venue_required";
2908 error.message_ =
2909 "Kiwoom requires dmst_stex_tp on every order and documents no default; set "
2910 "OrderRequest::venue_ to KRX, NXT or COMBINED (Kiwoom's SOR), or, for a strategy runner, "
2911 "bind it with a default route (live::bind / bind_journaled, SessionExecutor)";
2912 return error;
2913 }
2914
2915 // The identity venue this adapter reports every Korean instrument at.
2916 static constexpr Venue instrument_venue() {
2917 return Venue::COMBINED;
2918 }
2919
2920 // Returns an error when an order cannot be represented as a Kiwoom instruction.
2921 static std::optional<BrokerError> validate_order(
2922 KiwoomPositionScope scope, const OrderRequest& order, std::string& division
2923 ) {
2924 if (auto error = unsupported_client_order_id(order)) {
2925 return error;
2926 }
2927 if (auto error = validate_instrument(order.instrument_)) {
2928 return error;
2929 }
2930 // Kiwoom reports every Korean instrument at one identity venue, and a holding carries no venue
2931 // at all -- so an order whose `instrument_.venue_` said anything else would not be the same
2932 // `InstrumentId` as its own holding, and `Portfolio::working_quantity` would read zero resting
2933 // quantity for it. A caller who set it there means *routing*, which is `OrderRequest::venue_`.
2934 if (order.instrument_.venue_ != instrument_venue()) {
2935 BrokerError error;
2936 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2937 error.reached_broker_ = false;
2938 error.broker_code_ = "invalid_instrument";
2939 error.message_ =
2940 "this adapter identifies a Korean instrument by its combined venue; set "
2941 "OrderRequest::venue_ to route the order to a particular exchange instead of naming one on "
2942 "the instrument";
2943 return error;
2944 }
2945 if (auto error = validate_quantity(order.quantity_)) {
2946 return error;
2947 }
2948 if (auto error = validate_price(order.type_, order.price_)) {
2949 return error;
2950 }
2951 if (auto error = invalid_trigger(order.type_, order.trigger_price_)) {
2952 return error;
2953 }
2954 if (auto error = validate_venue(order.venue_)) {
2955 return error;
2956 }
2957 if (auto error = order_division(order.type_, order.time_in_force_, order.session_, division)) {
2958 return error;
2959 }
2960 // **Last**, so a caller hears about their own order's problems before this one. An order that
2961 // is malformed is malformed whatever this library knows about the account, and reporting the
2962 // holdings gap first would bury the mistake the caller can actually fix.
2963 return holdings_scope_refusal(scope);
2964 }
2965
2966 // Returns an error when an amendment cannot be represented as a Kiwoom instruction.
2967 //
2968 // Its own function for the reason the KIS adapter gives: the decision a test needs to exercise is
2969 // the one the submission path takes, not one a test re-derives from the same inputs.
2970 static std::optional<BrokerError> validate_amendment(
2971 KiwoomPositionScope scope, const KiwoomAmendment& amendment, bool cancel
2972 ) {
2973 if (auto error = validate_quantity(amendment.quantity_, true)) {
2974 return error;
2975 }
2976 if (auto error = validate_venue(amendment.venue_)) {
2977 return error;
2978 }
2979 BrokerError error;
2980 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2981 error.reached_broker_ = false;
2982 if (amendment.order_.order_number_.empty()) {
2983 error.broker_code_ = "invalid_order_reference";
2984 error.message_ = "a Kiwoom amendment requires the original order number";
2985 return error;
2986 }
2987 if (amendment.order_.symbol_.empty()) {
2988 // kt10002 and kt10003 both require `stk_cd` beside `orig_ord_no`. A reference that lost the
2989 // symbol cannot address an order at all, which is why `KiwoomOrderRef` carries both.
2990 error.broker_code_ = "invalid_order_reference";
2991 error.message_ =
2992 "a Kiwoom amendment requires the order's symbol beside its number; both are part of the "
2993 "reference this adapter issues";
2994 return error;
2995 }
2996 if (cancel && amendment.price_) {
2997 error.broker_code_ = "invalid_price";
2998 error.message_ = "Kiwoom's cancellation carries a quantity and no price";
2999 return error;
3000 }
3001 if (cancel && amendment.condition_price_) {
3002 // `kt10003` has no trigger field, so a stated trigger cannot be sent -- and acknowledging
3003 // the instruction after dropping it would report success for a change that did not happen,
3004 // which is the same failure refusing a price on a cancellation exists to stop. The
3005 // normalized helpers never set this, so no port path is affected.
3006 error.broker_code_ = "invalid_condition_price";
3007 error.message_ =
3008 "Kiwoom's cancellation carries a quantity and no trigger price, so it cannot change an "
3009 "order's stop condition on the way out; cancel the order and place a new one instead";
3010 return error;
3011 }
3012 if (!cancel && amendment.price_ && amendment.price_->scale() != 0) {
3013 error.broker_code_ = "invalid_price";
3014 error.message_ = "a Kiwoom domestic order price must be a whole number of won";
3015 return error;
3016 }
3017 // Only the value: whether the order's basis wants a trigger at all is decided where the basis
3018 // is known, `BrokerTraits<KiwoomClient>::to_amendment`, because `kt10002` carries none.
3019 if (!cancel && amendment.condition_price_ && !valid_trigger_value(*amendment.condition_price_)) {
3020 error.broker_code_ = "invalid_trigger_price";
3021 error.message_ = "a Kiwoom trigger price must be a positive whole number of won";
3022 return error;
3023 }
3024 if (!cancel) {
3025 // Last, and cancellations excepted; see `unestablished_holdings_scope`. A replacement can
3026 // move a resting buy to a fillable price, which opens or enlarges the position this library
3027 // cannot measure. A cancellation only ever reduces what is resting.
3028 return holdings_scope_refusal(scope);
3029 }
3030 return std::nullopt;
3031 }
3032
3033 // Builds `kt10000`/`kt10001`'s body. The side selects the endpoint, not a field.
3034 static network::HttpRequest place_order_request(
3035 const KiwoomClient& client, const OrderRequest& order, std::string_view division
3036 ) {
3037 json::object body;
3038 body["dmst_stex_tp"] = exchange_code(order.venue_);
3039 body["stk_cd"] = order.instrument_.symbol_;
3040 body["ord_qty"] = order.quantity_.str();
3041 // An unpriced basis is sent with an empty `ord_uv` rather than a zero: `carries_caller_price`
3042 // decides which, and a zero would be a price the caller did not state.
3043 body["ord_uv"] = order.price_ ? order.price_->str() : "";
3044 body["trde_tp"] = std::string(division);
3045 // `cond_uv` is the stop trigger. `invalid_trigger` has restricted it to `28`, so every other
3046 // body carries the `""` it always has.
3047 body["cond_uv"] = order.trigger_price_ ? order.trigger_price_->str() : "";
3048 return client.make_request(
3049 order.side_ == OrderSide::BUY ? "kt10000" : "kt10001", "/api/dostk/ordr", json::serialize(body),
3051 );
3052 }
3053
3054 // Builds `kt10002`'s or `kt10003`'s body.
3055 static network::HttpRequest amend_order_request(
3056 const KiwoomClient& client, const KiwoomAmendment& amendment, bool cancel
3057 ) {
3058 json::object body;
3059 body["dmst_stex_tp"] = exchange_code(amendment.venue_);
3060 body["orig_ord_no"] = amendment.order_.order_number_;
3061 body["stk_cd"] = amendment.order_.symbol_;
3062 if (cancel) {
3063 body["cncl_qty"] = amendment.quantity_.str();
3064 } else {
3065 body["mdfy_qty"] = amendment.quantity_.str();
3066 body["mdfy_uv"] = amendment.price_ ? amendment.price_->str() : "";
3067 body["mdfy_cond_uv"] = amendment.condition_price_ ? amendment.condition_price_->str() : "";
3068 }
3069 return client.make_request(
3070 cancel ? "kt10003" : "kt10002", "/api/dostk/ordr", json::serialize(body), network::RateLimitGroup::TRADING
3071 );
3072 }
3073
3074 // Validates and submits a placement.
3075 void start_place_order(OrderRequest order, OrderAckHandler completion) {
3076 std::string division;
3077 if (auto invalid = validate_order(config_.holdings_position_scope_, order, division)) {
3078 deliver(std::move(completion), Result<KiwoomOrderAck>(std::move(*invalid)));
3079 return;
3080 }
3081 ensure_token(TokenHandler(
3082 [self = shared_from_this(), order = std::move(order), division = std::move(division),
3083 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3084 if (token_error) {
3085 self->deliver(std::move(completion), Result<KiwoomOrderAck>(std::move(*token_error)));
3086 return;
3087 }
3088 auto request = place_order_request(*self, order, division);
3089 const std::string symbol = order.instrument_.symbol_;
3090 self->send(
3091 std::move(request),
3092 [self, symbol, demo = self->config_.is_demo_,
3093 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3094 self->deliver(
3095 std::move(completion), parse_order_ack(symbol, std::move(result), KiwoomOrderOperation::PLACE, demo)
3096 );
3097 }
3098 );
3099 }
3100 ));
3101 }
3102
3103 // Validates and submits a modification or a cancellation.
3104 void start_amend_order(KiwoomAmendment amendment, bool cancel, OrderAckHandler completion) {
3105 if (auto invalid = validate_amendment(config_.holdings_position_scope_, amendment, cancel)) {
3106 deliver(std::move(completion), Result<KiwoomOrderAck>(std::move(*invalid)));
3107 return;
3108 }
3109 ensure_token(TokenHandler(
3110 [self = shared_from_this(), amendment = std::move(amendment), cancel,
3111 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3112 if (token_error) {
3113 self->deliver(std::move(completion), Result<KiwoomOrderAck>(std::move(*token_error)));
3114 return;
3115 }
3116 auto request = amend_order_request(*self, amendment, cancel);
3117 const std::string symbol = amendment.order_.symbol_;
3118 const auto operation = cancel ? KiwoomOrderOperation::CANCEL : KiwoomOrderOperation::AMEND;
3119 self->send(
3120 std::move(request),
3121 [self, symbol, operation, demo = self->config_.is_demo_,
3122 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3123 self->deliver(std::move(completion), parse_order_ack(symbol, std::move(result), operation, demo));
3124 }
3125 );
3126 }
3127 ));
3128 }
3129
3130 // Normalizes an order response into an acknowledgement and a reference.
3131 //
3132 // The symbol comes from the request rather than the response, because Kiwoom's order responses
3133 // carry `ord_no` and the venue and no `stk_cd` at all — and the reference needs the symbol to be
3134 // usable for a later amendment. `operation` and `demo` describe the request this reply answers;
3135 // left out, no refusal is recognized.
3136 static Result<KiwoomOrderAck> parse_order_ack(
3137 const std::string& symbol, Result<network::HttpResponse> result,
3138 KiwoomOrderOperation operation = KiwoomOrderOperation::UNCLASSIFIED, bool demo = false
3139 ) {
3140 auto body = document(std::move(result), operation, demo);
3141 if (!body) {
3142 return Result<KiwoomOrderAck>(std::move(body.error()));
3143 }
3144 try {
3145 const auto& row = body.value();
3146 const auto number = detail::text_field(row, "ord_no");
3147 if (number.empty()) {
3148 throw std::runtime_error("missing string field: ord_no");
3149 }
3150 KiwoomOrderAck ack;
3151 ack.ack_.order_id_ = number;
3152 ack.ack_.accepted_at_ = std::chrono::system_clock::now();
3153 ack.order_ = KiwoomOrderRef{number, symbol};
3154 ack.base_order_number_ = detail::text_field(row, "base_orig_ord_no");
3155 if (auto quantity = detail::magnitude(row, "mdfy_qty")) {
3156 ack.amended_quantity_ = *quantity;
3157 } else if (auto canceled = detail::magnitude(row, "cncl_qty")) {
3158 ack.amended_quantity_ = *canceled;
3159 }
3160 return Result<KiwoomOrderAck>(std::move(ack));
3161 } catch (const std::exception& exception) {
3162 return Result<KiwoomOrderAck>(protocol_error("invalid_order_response", exception));
3163 }
3164 }
3165
3166 // One amendable-order listing spanning however many `ka10075` pages it needs.
3167 struct OpenOrderOperation {
3168 KiwoomOpenOrderPage page_;
3169 std::string next_key_;
3170 int pages_{0};
3171 OpenOrderHandler completion_;
3172
3173 explicit OpenOrderOperation(OpenOrderHandler completion) : completion_(std::move(completion)) {}
3174 };
3175
3176 // Starts the amendable-order listing.
3177 void start_open_orders(OpenOrderHandler completion) {
3178 auto operation = std::make_shared<OpenOrderOperation>(std::move(completion));
3179 request_open_orders(operation);
3180 }
3181
3182 // Issues one page of `ka10075` 미체결요청.
3183 void request_open_orders(std::shared_ptr<OpenOrderOperation> operation) {
3184 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
3185 if (token_error) {
3186 self->deliver(std::move(operation->completion_), Result<KiwoomOpenOrderPage>(std::move(*token_error)));
3187 return;
3188 }
3189 json::object body;
3190 body["all_stk_tp"] = "0";
3191 body["trde_tp"] = "0";
3192 body["stk_cd"] = "";
3193 // `0 : 통합` -- unlike the balance inquiry, the unfilled listing *does* publish an
3194 // all-venue value, so a working order resting at either venue is listed. Nothing is
3195 // scoped here and nothing needs to be.
3196 body["stex_tp"] = "0";
3197 auto request = self->make_request(
3198 "ka10075", "/api/dostk/acnt", json::serialize(body), network::RateLimitGroup::ACCOUNT, operation->next_key_
3199 );
3200 self->send(std::move(request), [self, operation](Result<network::HttpResponse> result) mutable {
3201 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
3202 self->handle_open_orders_page(operation, std::move(result));
3203 });
3204 });
3205 }));
3206 }
3207
3208 // Accumulates one page of amendable orders and either continues or completes.
3209 void handle_open_orders_page(
3210 const std::shared_ptr<OpenOrderOperation>& operation, Result<network::HttpResponse> result
3211 ) {
3212 if (!result) {
3213 deliver(std::move(operation->completion_), Result<KiwoomOpenOrderPage>(std::move(result.error())));
3214 return;
3215 }
3216 const auto next_key = continuation_key(result.value());
3217 auto body = document(std::move(result));
3218 if (!body) {
3219 deliver(std::move(operation->completion_), Result<KiwoomOpenOrderPage>(std::move(body.error())));
3220 return;
3221 }
3222 const std::size_t before = operation->page_.orders_.size();
3223 try {
3224 const auto rows = body.value().if_contains("oso");
3225 if (rows != nullptr) {
3226 if (!rows->is_array()) {
3227 throw std::runtime_error("oso is not an array");
3228 }
3229 for (const auto& value : rows->as_array()) {
3230 if (!value.is_object()) {
3231 throw std::runtime_error("oso row is not an object");
3232 }
3233 operation->page_.orders_.push_back(parse_open_order(value.as_object()));
3234 }
3235 }
3236 } catch (const std::exception& exception) {
3237 deliver(
3238 std::move(operation->completion_),
3239 Result<KiwoomOpenOrderPage>(protocol_error("invalid_open_orders_response", exception))
3240 );
3241 return;
3242 }
3243 const bool grew = operation->page_.orders_.size() > before;
3244 switch (advance_page(operation->next_key_, operation->pages_, grew, std::move(next_key))) {
3245 case PageStep::FINISH:
3246 operation->page_.received_at_ = std::chrono::system_clock::now();
3247 deliver(std::move(operation->completion_), Result<KiwoomOpenOrderPage>(std::move(operation->page_)));
3248 return;
3249 case PageStep::INCOMPLETE:
3250 deliver(
3251 std::move(operation->completion_),
3252 Result<KiwoomOpenOrderPage>(incomplete_listing("working orders", operation->pages_))
3253 );
3254 return;
3255 case PageStep::CONTINUE:
3256 request_open_orders(operation);
3257 return;
3258 }
3259 }
3260
3261 // Returns the side a row states, and throws when it states none this adapter can read.
3262 //
3263 // Throwing fails the listing, which is deliberate and is the one place this adapter does *not*
3264 // tolerate an unrecognized value. Everywhere else an unknown wire value becomes `UNKNOWN` with
3265 // the raw text preserved, because both specifications require a client to tolerate one and a
3266 // single odd row must not cost a whole listing. `OrderSide` has no `UNKNOWN`: the choice is
3267 // between failing and asserting a side, and asserting the wrong one puts a resting sell into the
3268 // picture as a buy, where `RiskGuard` will not deduct it from what may be sold. A listing that
3269 // fails is a poll that fails, which the runner already treats as a reason to hold.
3270 static OrderSide read_side(const std::string& label) {
3271 if (const auto side = normalized_order_side(label)) {
3272 return *side;
3273 }
3274 throw std::runtime_error(
3275 "order row states a side this adapter cannot read: '" + label + "'; it names neither 매수 nor 매도"
3276 );
3277 }
3278
3279 // Normalizes one `ka10075` unfilled row.
3280 static KiwoomOpenOrder parse_open_order(const json::object& row) {
3281 KiwoomOpenOrder open_order;
3282 const auto number = detail::text_field(row, "ord_no");
3283 const auto symbol = detail::bare_symbol(detail::text_field(row, "stk_cd"));
3284 open_order.order_ref_ = KiwoomOrderRef{number, symbol};
3285 open_order.original_order_number_ = detail::text_field(row, "orig_ord_no");
3286 open_order.amendable_quantity_ = detail::magnitude(row, "oso_qty");
3287 open_order.shape_name_ = detail::text_field(row, "trde_tp");
3288
3289 OrderSnapshot& order = open_order.order_;
3290 order.order_id_ = number;
3291 order.instrument_.country_ = Country::KR;
3292 order.instrument_.venue_ = instrument_venue();
3293 order.instrument_.symbol_ = symbol;
3294 order.name_ = detail::text_field(row, "stk_nm");
3295 order.currency_ = Currency::krw();
3296 order.side_ = read_side(detail::text_field(row, "io_tp_nm"));
3297 apply_shape(open_order.shape_name_, order);
3298 order.status_ = normalized_order_status(detail::text_field(row, "ord_stt"));
3299 order.venue_ = listed_venue(detail::text_field(row, "stex_tp"), detail::text_field(row, "sor_yn"));
3300 order.quantity_ = detail::required_magnitude(row, "ord_qty");
3301 order.price_ = positive(detail::magnitude(row, "ord_pric"));
3302 order.trigger_price_ = reported_trigger(row, "stop_pric");
3303 // `tm` is `HHmmss` with no date. The calendar day is today in Seoul, and only assumed: the demo
3304 // server has listed an order of the previous day after midnight. The history path takes its date
3305 // from the request; where both carry the order, a sweep drops this row and keeps the dated one.
3306 order.ordered_at_ = detail::seoul_timestamp(today_in_seoul(), detail::text_field(row, "tm"));
3307 order.ordered_date_assumed_ = true;
3308 order.execution_.filled_quantity_ = detail::required_magnitude(row, "cntr_qty");
3309 resolve_open_status(open_order.amendable_quantity_, order);
3310 return open_order;
3311 }
3312
3313 // Refuses to report an order closed on a row that says quantity is still outstanding.
3314 //
3315 // ## The contradiction
3316 //
3317 // `normalized_order_status` is shared with the history parser, so it maps `체결` to `FILLED` and
3318 // `취소` to `CANCELED` -- correct there, and on *this* endpoint those words would contradict the
3319 // row they arrive on. `ka10075` is the 미체결 listing, its array is `oso`, and `oso_qty` is the
3320 // quantity still outstanding. The specification documents `ord_stt` here with the single value
3321 // `접수`, so nothing establishes that Kiwoom ever sends the other two on this inquiry.
3322 //
3323 // **This is therefore a defensive rule, not a repair of an observed incident.** What is
3324 // established is only that if such a row arrived, the adapter would mishandle it, and that the
3325 // response carries the field needed to refuse to.
3326 //
3327 // ## Why a wrong answer here is not cosmetic
3328 //
3329 // `strategy::order_is_open` is false for `FILLED` and `CANCELED`, and
3330 // `Portfolio::working_quantity` skips any row that is not open. A resting order reported closed
3331 // would read as **zero** resting quantity: no sellable deduction, no working-order component in
3332 // the position ceiling, and a reconciliation that plans a second order beside the one already
3333 // out.
3334 //
3335 // ## The rule
3336 //
3337 // A word and a number disagree, and only one of them can be checked, so the number wins:
3338 // a positive `oso_qty` means the order is still open whatever `ord_stt` says. Which open status
3339 // follows from the filled quantity, the same way KIS's parser answers the same question --
3340 // `PARTIAL_FILLED` where something has filled, `PENDING` where nothing has. A row reporting
3341 // nothing outstanding keeps whatever the broker said, so this narrows a contradiction rather than
3342 // refusing to believe the broker.
3343 //
3344 // Applied here rather than inside `normalized_order_status`, because the contradicting quantity
3345 // exists only on this endpoint and the history parser reads those words legitimately.
3346 //
3347 // The two statuses tested are the two `normalized_order_status` can produce that mean the order
3348 // is over, named here rather than asked of `strategy::order_is_open`: an adapter must not depend
3349 // on the strategy layer, and `core/` is where the two layers may meet.
3350 static void resolve_open_status(const std::optional<Decimal64>& amendable, OrderSnapshot& order) {
3351 const bool reported_over = order.status_ == OrderStatus::FILLED || order.status_ == OrderStatus::CANCELED;
3352 if (!reported_over) {
3353 return;
3354 }
3355 if (!amendable || amendable->coefficient() <= 0) {
3356 return;
3357 }
3358 order.status_ =
3359 order.execution_.filled_quantity_.coefficient() > 0 ? OrderStatus::PARTIAL_FILLED : OrderStatus::PENDING;
3360 }
3361
3362 // Writes the three normalized shape facts from Kiwoom's Korean label.
3363 //
3364 // **`OrderSnapshot::shape_code_` is deliberately left empty.** Its documentation calls it "the
3365 // broker's own order-shape code, preserved verbatim", and Kiwoom does not send a code on a read
3366 // path at all — it sends a Korean display name, which `Code<8>` cannot hold. Writing the numeric
3367 // code this adapter *inferred* from the name would put something the broker never sent into a
3368 // field defined as what it did. The raw label is kept on `KiwoomOpenOrder::shape_name_` instead.
3369 //
3370 // A label the table does not know leaves all three fields `UNKNOWN` and does not fail the row,
3371 // because both specifications this library follows require a client to tolerate a value it does
3372 // not recognize, and one odd row must not fail a whole listing.
3373 static void apply_shape(std::string_view label, OrderSnapshot& order) {
3374 const auto* row = shape_by_name(label);
3375 if (row == nullptr) {
3376 return;
3377 }
3378 order.type_ = row->type_;
3379 order.time_in_force_ = row->time_in_force_;
3380 order.session_ = row->session_;
3381 }
3382
3383 // What `close_cancelled_originals` needs of a `kt00007` row beyond its normalized snapshot.
3384 struct HistoryLink {
3385 // The order a completed cancellation row names in `ori_ord`; empty for any other row.
3386 std::string cancels_;
3387 // Whether the row is an ordinary order (`mdfy_cncl` empty or 일반), not a cancel or a modification.
3388 bool plain_{false};
3389 // `ord_remnq`, or nothing if absent or unreadable.
3390 std::optional<Decimal64> remaining_;
3391 };
3392
3393 // One order-history listing spanning however many `kt00007` pages it needs.
3394 struct HistoryOperation {
3395 KiwoomHistoryQuery query_;
3396 OrderPage page_;
3397 // One per row of `page_.orders_`, for `close_cancelled_originals`.
3398 std::vector<HistoryLink> links_;
3399 std::string next_key_;
3400 int pages_{0};
3401 OrderPageHandler completion_;
3402
3403 HistoryOperation(KiwoomHistoryQuery query, OrderPageHandler completion)
3404 : query_(std::move(query)), completion_(std::move(completion)) {}
3405 };
3406
3407 // Starts the order-history listing for one calendar date.
3408 void start_order_history(KiwoomHistoryQuery query, OrderPageHandler completion) {
3409 if (!is_valid_date(query.date_)) {
3410 BrokerError error;
3411 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3412 error.reached_broker_ = false;
3413 error.broker_code_ = "invalid_date";
3414 error.message_ = "a Kiwoom order-history inquiry requires a valid Gregorian date";
3415 deliver(std::move(completion), Result<OrderPage>(std::move(error)));
3416 return;
3417 }
3418 auto operation = std::make_shared<HistoryOperation>(std::move(query), std::move(completion));
3419 request_order_history(operation);
3420 }
3421
3422 // Issues one page of `kt00007` 계좌별주문체결내역상세요청.
3423 void request_order_history(std::shared_ptr<HistoryOperation> operation) {
3424 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
3425 if (token_error) {
3426 self->deliver(std::move(operation->completion_), Result<OrderPage>(std::move(*token_error)));
3427 return;
3428 }
3429 json::object body;
3430 body["ord_dt"] = detail::compact_text(operation->query_.date_);
3431 // `1:주문순` lists in order-number order, which is the order the rows were created in.
3432 body["qry_tp"] = "1";
3433 body["stk_bond_tp"] = "1";
3434 body["sell_tp"] = "0";
3435 body["stk_cd"] = operation->query_.symbol_;
3436 body["fr_ord_no"] = "";
3437 // `%` is 전체: every venue. Unlike the balance inquiry, this one publishes an all-venue
3438 // value, so a history listing is never scoped to one book.
3439 body["dmst_stex_tp"] = "%";
3440 auto request = self->make_request(
3441 "kt00007", "/api/dostk/acnt", json::serialize(body), network::RateLimitGroup::ACCOUNT, operation->next_key_
3442 );
3443 self->send(std::move(request), [self, operation](Result<network::HttpResponse> result) mutable {
3444 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
3445 self->handle_order_history_page(operation, std::move(result));
3446 });
3447 });
3448 }));
3449 }
3450
3451 // Accumulates one page of order history and either continues or completes.
3452 void handle_order_history_page(
3453 const std::shared_ptr<HistoryOperation>& operation, Result<network::HttpResponse> result
3454 ) {
3455 if (!result) {
3456 deliver(std::move(operation->completion_), Result<OrderPage>(std::move(result.error())));
3457 return;
3458 }
3459 const auto next_key = continuation_key(result.value());
3460 auto body = document(std::move(result));
3461 if (!body) {
3462 deliver(std::move(operation->completion_), Result<OrderPage>(std::move(body.error())));
3463 return;
3464 }
3465 const std::size_t before = operation->page_.orders_.size();
3466 try {
3467 const auto rows = body.value().if_contains("acnt_ord_cntr_prps_dtl");
3468 if (rows != nullptr) {
3469 if (!rows->is_array()) {
3470 throw std::runtime_error("acnt_ord_cntr_prps_dtl is not an array");
3471 }
3472 for (const auto& value : rows->as_array()) {
3473 if (!value.is_object()) {
3474 throw std::runtime_error("order history row is not an object");
3475 }
3476 operation->page_.orders_.push_back(
3477 parse_history_row(value.as_object(), operation->query_.date_, config_.is_demo_)
3478 );
3479 operation->links_.push_back(history_link(value.as_object(), config_.is_demo_));
3480 }
3481 }
3482 } catch (const std::exception& exception) {
3483 deliver(
3484 std::move(operation->completion_),
3485 Result<OrderPage>(protocol_error("invalid_order_history_response", exception))
3486 );
3487 return;
3488 }
3489 const bool grew = operation->page_.orders_.size() > before;
3490 switch (advance_page(operation->next_key_, operation->pages_, grew, std::move(next_key))) {
3491 case PageStep::FINISH:
3492 operation->page_.received_at_ = std::chrono::system_clock::now();
3493 // Every page has been walked, so there is no cursor for a caller to continue from.
3494 // `has_history_cursor` says the same thing at compile time.
3495 operation->page_.next_cursor_.reset();
3496 // After the last page: a cancellation and its original may be on different pages.
3497 close_cancelled_originals(operation->page_.orders_, operation->links_);
3498 deliver(std::move(operation->completion_), Result<OrderPage>(std::move(operation->page_)));
3499 return;
3500 case PageStep::INCOMPLETE:
3501 deliver(
3502 std::move(operation->completion_), Result<OrderPage>(incomplete_listing("order history", operation->pages_))
3503 );
3504 return;
3505 case PageStep::CONTINUE:
3506 request_order_history(operation);
3507 return;
3508 }
3509 }
3510
3511 // Reads a `kt00007` row's link to the order it cancels.
3512 //
3513 // A cancellation row is `mdfy_cncl` 취소확인, the documented word. The demo server writes 취소 with
3514 // `acpt_tp` 주문완료 instead (observed 2026-10-06 and 2026-10-08); that tuple counts on the demo only,
3515 // since a bare 취소 names the kind of amendment, not a completed one.
3516 static HistoryLink history_link(const json::object& row, bool demo) {
3517 HistoryLink link;
3518 const auto amendment = detail::text_field(row, "mdfy_cncl");
3519 link.plain_ = amendment.empty() || amendment == "일반";
3520 link.remaining_ = detail::magnitude(row, "ord_remnq");
3521 const bool cancellation =
3522 amendment == "취소확인" || (demo && amendment == "취소" && detail::text_field(row, "acpt_tp") == "주문완료");
3523 if (cancellation) {
3524 const auto original = detail::text_field(row, "ori_ord");
3525 if (original.find_first_not_of('0') != std::string::npos) {
3526 link.cancels_ = original;
3527 }
3528 }
3529 return link;
3530 }
3531
3532 // Marks an original order `CANCELED` when a cancellation row names it and nothing of it remains.
3533 //
3534 // `kt00007` keeps the original's own row as an ordinary order with no state word for the
3535 // cancellation (`acpt_tp` 주문완료 on the demo), so without this it reads `UNKNOWN` and never ends.
3536 // The original must be the only row with that number, plain, of the same symbol and side, with
3537 // `ord_remnq` present and zero (a refused or pending cancel leaves a remainder) and less filled than
3538 // ordered (a cancel that lost to a full fill stays `FILLED`). Its `cntr_qty` stays the filled quantity.
3539 static void close_cancelled_originals(std::vector<OrderSnapshot>& orders, const std::vector<HistoryLink>& links) {
3540 for (std::size_t cancel = 0; cancel < orders.size() && cancel < links.size(); ++cancel) {
3541 if (links[cancel].cancels_.empty()) {
3542 continue;
3543 }
3544 std::optional<std::size_t> found;
3545 bool ambiguous = false;
3546 for (std::size_t at = 0; at < orders.size() && at < links.size(); ++at) {
3547 if (orders[at].order_id_ != links[cancel].cancels_) {
3548 continue;
3549 }
3550 ambiguous = ambiguous || found.has_value();
3551 found = at;
3552 }
3553 if (!found || ambiguous) {
3554 continue;
3555 }
3556 auto& original = orders[*found];
3557 const auto& link = links[*found];
3558 if (
3559 !link.plain_ || !link.remaining_ || link.remaining_->coefficient() != 0 ||
3560 original.instrument_.symbol_ != orders[cancel].instrument_.symbol_ || original.side_ != orders[cancel].side_ ||
3561 !decimal_less(original.execution_.filled_quantity_, original.quantity_)
3562 ) {
3563 continue;
3564 }
3565 original.status_ = OrderStatus::CANCELED;
3566 }
3567 }
3568
3569 // Normalizes one `kt00007` row.
3570 static OrderSnapshot parse_history_row(const json::object& row, const Date& date, bool demo = false) {
3571 OrderSnapshot order;
3572 order.order_id_ = detail::text_field(row, "ord_no");
3573 order.instrument_.country_ = Country::KR;
3574 order.instrument_.venue_ = instrument_venue();
3575 // `kt00007` prefixes the symbol with `A` where `ka10075` does not, so a listing that kept the
3576 // prefix would build an `InstrumentId` that did not compare equal to the same instrument's
3577 // working order or holding.
3578 order.instrument_.symbol_ = detail::bare_symbol(detail::text_field(row, "stk_cd"));
3579 order.name_ = detail::text_field(row, "stk_nm");
3580 order.currency_ = Currency::krw();
3581 order.side_ = read_side(detail::text_field(row, "io_tp_nm"));
3582 // The label vocabulary here differs from `ka10075`'s -- 지정가 rather than 보통 -- and
3583 // `shape_by_name` searches both columns so the two listings agree about one order. The demo
3584 // server writes 보통가 for an ordinary limit order (observed 2026-10-06 and 2026-10-13); that
3585 // spelling counts on the demo only, as its cancellation words do.
3586 const auto label = detail::text_field(row, "trde_tp");
3587 apply_shape(demo && label == "보통가" ? std::string_view("보통") : std::string_view(label), order);
3588 order.status_ = history_status(row);
3589 order.venue_ = normalized_venue(detail::text_field(row, "dmst_stex_tp"));
3590 order.quantity_ = detail::required_magnitude(row, "ord_qty");
3591 order.price_ = positive(detail::magnitude(row, "ord_uv"));
3592 order.trigger_price_ = reported_trigger(row, "cond_uv");
3593 order.ordered_at_ = detail::seoul_timestamp(date, detail::text_field(row, "ord_tm"));
3594 order.execution_.filled_quantity_ = detail::required_magnitude(row, "cntr_qty");
3595 if (const auto average = positive(detail::magnitude(row, "cntr_uv"))) {
3596 order.execution_.average_filled_price_ = average;
3597 }
3598 return order;
3599 }
3600
3601 // Reads a history row's lifecycle state.
3602 //
3603 // `kt00007` publishes two columns and neither alone is the answer: `acpt_tp` 접수구분 says the
3604 // order was received, and `mdfy_cncl` 정정취소 says whether this row is a 정정확인 or a 취소확인.
3605 // A cancellation confirmation is a cancelled order, and nothing else on the row says so.
3606 //
3607 // A fill is read from the quantities rather than from a word, because `kt00007` publishes no
3608 // 체결 state at all — `ord_remnq` 주문잔량 is what remains.
3609 static OrderStatus history_status(const json::object& row) {
3610 const auto amendment = detail::text_field(row, "mdfy_cncl");
3611 if (amendment == "취소확인") {
3612 return OrderStatus::CANCELED;
3613 }
3614 if (amendment == "정정확인") {
3615 return OrderStatus::REPLACED;
3616 }
3617 const auto filled = detail::required_magnitude(row, "cntr_qty");
3618 const auto remaining = detail::magnitude(row, "ord_remnq");
3619 if (filled.coefficient() > 0) {
3620 if (remaining && remaining->coefficient() == 0) {
3621 return OrderStatus::FILLED;
3622 }
3623 return OrderStatus::PARTIAL_FILLED;
3624 }
3625 return normalized_order_status(detail::text_field(row, "acpt_tp"));
3626 }
3627};
3628
3645public:
3654 ssl::context& context, KiwoomConfig config, network::HttpClientOptions options = {},
3655 std::shared_ptr<network::TokenStore> store = nullptr
3656 )
3657 : store_(std::move(store)),
3658 identity_(store_ ? config.token_identity() : std::string()),
3659 client_(std::make_shared<KiwoomClient>(ioc_.get_executor(), context, std::move(config), options)) {
3660 client_->store_managed_ = store_ != nullptr;
3661 }
3662
3669 return run<QuoteSnapshot>(
3670 [&](auto&& sink) {
3671 client_->async_quote(std::move(instrument), std::move(sink));
3672 },
3673 "quote"
3674 );
3675 }
3676
3683 return run<PriceLimits>(
3684 [&](auto&& sink) {
3685 client_->async_price_limits(std::move(instrument), std::move(sink));
3686 },
3687 "price limits"
3688 );
3689 }
3690
3697 return run<DepthSnapshot>(
3698 [&](auto&& sink) {
3699 client_->async_depth(std::move(instrument), std::move(sink));
3700 },
3701 "depth"
3702 );
3703 }
3704
3712 return run<std::vector<TradePrint>>(
3713 [&](auto&& sink) {
3714 client_->async_trades(std::move(instrument), count, std::move(sink));
3715 },
3716 "trades"
3717 );
3718 }
3719
3726 return run<Instrument>(
3727 [&](auto&& sink) {
3728 client_->async_instrument(std::move(subject), std::move(sink));
3729 },
3730 "instrument"
3731 );
3732 }
3733
3740 return run<BarSeries>(
3741 [&](auto&& sink) {
3742 client_->async_bars(std::move(query), std::move(sink));
3743 },
3744 "bars"
3745 );
3746 }
3747
3752 const KiwoomConfig& config() const noexcept {
3753 return client_->config();
3754 }
3755
3762 return run<HoldingsSnapshot>(
3763 [&](auto&& sink) {
3764 client_->async_holdings(account, std::move(sink));
3765 },
3766 "holdings"
3767 );
3768 }
3769
3777 return run<BuyingPower>(
3778 [&](auto&& sink) {
3779 client_->async_buying_power(currency, account, std::move(sink));
3780 },
3781 "buying power"
3782 );
3783 }
3784
3790 return run<KiwoomDeposit>(
3791 [&](auto&& sink) {
3792 client_->async_deposit(std::move(sink));
3793 },
3794 "deposit"
3795 );
3796 }
3797
3806 InstrumentId instrument, OrderSide side, std::optional<Decimal64> price = std::nullopt
3807 ) {
3808 return run<KiwoomOrderableAmount>(
3809 [&](auto&& sink) {
3810 client_->async_orderable_amount(std::move(instrument), side, std::move(price), std::move(sink));
3811 },
3812 "orderable amount"
3813 );
3814 }
3815
3821 return run<std::vector<KiwoomAccountInfo>>(
3822 [&](auto&& sink) {
3823 client_->async_accounts(std::move(sink));
3824 },
3825 "accounts"
3826 );
3827 }
3828
3837 return run<KiwoomOrderAck>(
3838 [&](auto&& sink) {
3839 client_->async_place_order(account, std::move(order), std::move(sink));
3840 },
3841 "place order"
3842 );
3843 }
3844
3853 return run<KiwoomOrderAck>(
3854 [&](auto&& sink) {
3855 client_->async_replace_order(account, std::move(amendment), std::move(sink));
3856 },
3857 "replace order"
3858 );
3859 }
3860
3869 return run<KiwoomOrderAck>(
3870 [&](auto&& sink) {
3871 client_->async_cancel_order(account, std::move(amendment), std::move(sink));
3872 },
3873 "cancel order"
3874 );
3875 }
3876
3883 return run<KiwoomOpenOrderPage>(
3884 [&](auto&& sink) {
3885 client_->async_open_orders(account, std::move(sink));
3886 },
3887 "open orders"
3888 );
3889 }
3890
3898 return run<OrderPage>(
3899 [&](auto&& sink) {
3900 client_->async_order_history(account, std::move(query), std::move(sink));
3901 },
3902 "order history"
3903 );
3904 }
3905
3907 void close() {
3908 client_->close();
3909 }
3910
3920 return client_->rate_limit_stats();
3921 }
3922
3928 return client_->token();
3929 }
3930
3937 return client_->adopt_token(std::move(token));
3938 }
3939
3940private:
3941 friend struct KiwoomClientTestAccess;
3942
3943 // Runs one call: with a store, prepares the token first and discards one Kiwoom refused during the call.
3944 template <typename T, typename Start>
3945 Result<T> run(Start start, std::string_view operation) {
3946 if (!store_) {
3947 return drive<T>(std::move(start), operation);
3948 }
3949 const auto request = [this] {
3950 return drive<KiwoomRest>(
3951 [this](auto&& sink) {
3952 client_->async_ensure_token(std::move(sink));
3953 },
3954 "token request"
3955 );
3956 };
3957 if (auto error = network::token_store_detail::prepare(*store_, identity_, *client_, request)) {
3958 return Result<T>(std::move(*error));
3959 }
3960 const auto carried = client_->token();
3961 auto result = drive<T>(std::move(start), operation);
3962 network::token_store_detail::discard_refused(*store_, identity_, carried, client_->token());
3963 return result;
3964 }
3965
3966 // Drives one asynchronous operation to completion on the private loop.
3967 template <typename T, typename Start>
3968 Result<T> drive(Start start, std::string_view operation) {
3969 std::optional<Result<T>> result;
3970 ioc_.restart();
3971 start([&result](Result<T> value) {
3972 result.emplace(std::move(value));
3973 });
3974 ioc_.run();
3975 if (!result) {
3976 BrokerError error;
3977 error.category_ = ErrorCategory::TRANSPORT;
3978 error.broker_code_ = "event_loop_stopped";
3979 error.message_ = "event loop stopped before " + std::string(operation) + " completion";
3980 return Result<T>(std::move(error));
3981 }
3982 return std::move(*result);
3983 }
3984
3985 std::shared_ptr<network::TokenStore> store_;
3986 std::string identity_;
3987 net::io_context ioc_;
3988 std::shared_ptr<KiwoomClient> client_;
3989};
3990
3991} // namespace algotradelib::kiwoom
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
static Currency krw()
Returns Korean won.
Definition types.hpp:402
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::uint8_t scale() const noexcept
Returns the scale.
Definition types.hpp:549
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
Decimal64()=default
Constructs zero.
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
A blocking Kiwoom client: each call runs a KiwoomClient request on a private event loop and returns i...
Definition client.hpp:3644
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns today's upper and lower price bound.
Definition client.hpp:3682
bool adopt_token(KiwoomRest token)
Uses a token issued earlier; see KiwoomClient::adopt_token.
Definition client.hpp:3936
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns recent executions, newest first.
Definition client.hpp:3711
const KiwoomConfig & config() const noexcept
Returns the configuration; see KiwoomClient::config.
Definition client.hpp:3752
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:3919
void close()
Closes the client for good; see KiwoomClient::close.
Definition client.hpp:3907
Result< BuyingPower > buying_power(Currency currency, KiwoomAccount account)
Returns what the bound credential's account may spend.
Definition client.hpp:3776
Result< KiwoomOrderAck > replace_order(KiwoomAccount account, KiwoomAmendment amendment)
Modifies an existing order. The outcome can be unknown after an error; see KiwoomClient::async_replac...
Definition client.hpp:3852
KiwoomRest token() const
Returns the access token; see KiwoomClient::token.
Definition client.hpp:3927
Result< OrderPage > order_history(KiwoomAccount account, KiwoomHistoryQuery query)
Returns one day of order history.
Definition client.hpp:3897
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns the resting orders on both sides of the book.
Definition client.hpp:3696
Result< KiwoomOrderableAmount > orderable_amount(InstrumentId instrument, OrderSide side, std::optional< Decimal64 > price=std::nullopt)
Returns what may be ordered of one instrument, per margin tier.
Definition client.hpp:3805
Result< KiwoomOrderAck > cancel_order(KiwoomAccount account, KiwoomAmendment amendment)
Cancels an existing order. The outcome can be unknown after an error; see KiwoomClient::async_cancel_...
Definition client.hpp:3868
Result< BarSeries > bars(BarQuery query)
Returns bars; see KiwoomClient::async_bars.
Definition client.hpp:3739
KiwoomBlockingClient(ssl::context &context, KiwoomConfig config, network::HttpClientOptions options={}, std::shared_ptr< network::TokenStore > store=nullptr)
Constructs a client.
Definition client.hpp:3653
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the current normalized quote or a structured error.
Definition client.hpp:3668
Result< std::vector< KiwoomAccountInfo > > accounts()
Returns the one account the bound credential drives.
Definition client.hpp:3820
Result< KiwoomOpenOrderPage > open_orders(KiwoomAccount account)
Returns every order still open to amendment.
Definition client.hpp:3882
Result< KiwoomDeposit > deposit()
Returns Kiwoom's own fuller deposit detail.
Definition client.hpp:3789
Result< KiwoomOrderAck > place_order(KiwoomAccount account, OrderRequest order)
Submits a new order. The outcome can be unknown after an error; see KiwoomClient::async_place_order.
Definition client.hpp:3836
Result< Instrument > instrument(InstrumentId subject)
Returns static reference data for one instrument.
Definition client.hpp:3725
Result< HoldingsSnapshot > holdings(KiwoomAccount account)
Returns the holdings for KiwoomConfig::holdings_venue_; see KiwoomClient::async_holdings.
Definition client.hpp:3761
The asynchronous Kiwoom REST client: market data, account inquiries and orders for domestic stocks.
Definition client.hpp:882
void close()
Closes the client for good: pending requests, and later ones that would send, complete with CANCELLED...
Definition client.hpp:1424
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests static reference data for one instrument, from ka10100 종목정보 조회.
Definition client.hpp:1028
net::any_completion_handler< void(Result< KiwoomOrderAck >)> OrderAckHandler
Completion handler for one Kiwoom order acknowledgement.
Definition client.hpp:907
auto async_buying_power(Currency currency, KiwoomAccount account, CompletionToken &&token)
Requests what the account may spend, from kt00001 예수금상세현황요청.
Definition client.hpp:1116
net::any_completion_handler< void(Result< KiwoomDeposit >)> DepositHandler
Completion handler for Kiwoom's own fuller deposit detail.
Definition client.hpp:901
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests the resting orders on both sides of the book, from ka10004 주식호가요청.
Definition client.hpp:986
net::any_completion_handler< void(Result< DepthSnapshot >)> DepthHandler
Completion handler for one normalized order book.
Definition client.hpp:889
auto async_open_orders(KiwoomAccount account, CompletionToken &&token)
Requests every order still open to amendment, paging ka10075 미체결요청.
Definition client.hpp:1302
bool adopt_token(KiwoomRest token)
Uses a token issued earlier for the same app key and environment instead of requesting one.
Definition client.hpp:1376
auto async_ensure_token(CompletionToken &&token)
Requests an access token unless the held one stays valid for five more minutes, as any request does f...
Definition client.hpp:1392
auto async_order_history(KiwoomAccount account, KiwoomHistoryQuery query, CompletionToken &&token)
Requests one day of order history, paging kt00007 계좌별주문체결내역상세요청.
Definition client.hpp:1322
net::any_completion_handler< void(Result< PriceLimits >)> PriceLimitsHandler
Completion handler for one instrument's price bounds.
Definition client.hpp:891
net::any_completion_handler< void(Result< KiwoomOrderableAmount >)> OrderableHandler
Completion handler for Kiwoom's per-margin-tier orderable amounts and quantities.
Definition client.hpp:903
KiwoomRest token() const
Returns the access token the client holds, to reuse in another client or a later process (adopt_token...
Definition client.hpp:1356
net::any_completion_handler< void(Result< std::vector< TradePrint > >)> TradesHandler
Completion handler for recent executions.
Definition client.hpp:893
void forget_token()
Drops the held token: the next request asks for one.
Definition client.hpp:1415
auto async_cancel_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Cancels an order, all or part of it (kt10003).
Definition client.hpp:1283
net::any_completion_handler< void(Result< BarSeries >)> BarsHandler
Completion handler for one normalized bar series.
Definition client.hpp:887
net::any_completion_handler< void(Result< HoldingsSnapshot >)> HoldingsHandler
Completion handler for one normalized holdings snapshot.
Definition client.hpp:897
net::any_completion_handler< void(Result< KiwoomOpenOrderPage >)> OpenOrderHandler
Completion handler for one page of modifiable or cancellable orders.
Definition client.hpp:909
net::any_completion_handler< void(Result< KiwoomRest >)> TokenResultHandler
The completion handler type of async_ensure_token.
Definition client.hpp:916
net::any_completion_handler< void(std::optional< BrokerError >)> TokenHandler
Internal completion handler for a shared access-token refresh.
Definition client.hpp:913
net::any_completion_handler< void(Result< BuyingPower >)> BuyingPowerHandler
Completion handler for one normalized buying-power reading.
Definition client.hpp:899
net::any_completion_handler< void(Result< Instrument >)> InstrumentHandler
Completion handler for one instrument's reference data.
Definition client.hpp:895
auto async_deposit(CompletionToken &&token)
Requests Kiwoom's own fuller deposit detail, which async_buying_power reads one field of.
Definition client.hpp:1134
auto async_replace_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Amends an order's quantity, price or trigger price (kt10002).
Definition client.hpp:1252
const KiwoomConfig & config() const noexcept
Returns the configuration (the session reads its holdings assertions from it).
Definition client.hpp:1070
auto async_bars(BarQuery query, CompletionToken &&token)
Requests bars, following Kiwoom's continuation pages from before_'s Korean date (or today).
Definition client.hpp:1055
auto async_place_order(KiwoomAccount account, OrderRequest order, CompletionToken &&token)
Places an order (kt10000 buy, kt10001 sell).
Definition client.hpp:1226
net::strand< net::any_io_executor > get_executor() const noexcept
Returns the client's strand.
Definition client.hpp:1078
net::any_completion_handler< void(Result< QuoteSnapshot >)> QuoteHandler
Completion handler for one normalized quote.
Definition client.hpp:885
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests today's upper and lower price bound, from the same ka10007 response.
Definition client.hpp:964
auto async_orderable_amount(InstrumentId instrument, OrderSide side, std::optional< Decimal64 > price, CompletionToken &&token)
Requests what may be ordered of one instrument, per margin tier (kt00010).
Definition client.hpp:1155
auto async_accounts(CompletionToken &&token)
Requests the one account the bound credential drives, from ka00001 계좌번호조회.
Definition client.hpp:1183
auto async_holdings(KiwoomAccount account, CompletionToken &&token)
Requests the holdings kt00018 lists for KiwoomConfig::holdings_venue_ (refused before sending until i...
Definition client.hpp:1096
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:1341
KiwoomClient(net::any_io_executor executor, ssl::context &context, KiwoomConfig config, network::HttpClientOptions options={})
Constructs a client; nothing is sent until the first request.
Definition client.hpp:925
net::any_completion_handler< void(Result< std::vector< KiwoomAccountInfo > >)> AccountsHandler
Completion handler for the one account the bound credential drives.
Definition client.hpp:905
net::any_completion_handler< void(Result< OrderPage >)> OrderPageHandler
Completion handler for one normalized page of order history.
Definition client.hpp:911
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests recent executions, newest first, from ka10003 체결정보요청.
Definition client.hpp:1009
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests and normalizes a current quote, from ka10007 시세표성정보요청.
Definition client.hpp:942
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 Kiwoom Securities REST API client.
Definition auth.hpp:12
const char * exchange_code(Venue venue) noexcept
Returns Kiwoom's dmst_stex_tp value for a venue.
Definition client.hpp:635
Date today_in_seoul()
Returns today's date in Korea (UTC+9), the date Kiwoom requests are made in.
Definition client.hpp:157
KiwoomSellableScope
What a Kiwoom holdings row's tradable quantity (trde_able_qty) covers; undocumented,...
Definition config.hpp:139
@ WHOLE_HOLDING
Asserted: it covers every share held of the instrument, on any venue.
Definition config.hpp:143
std::optional< BrokerError > unsupported_bar_interval(BarInterval interval)
Refuses a bar interval this client requests no chart for (chart_api_id).
Definition client.hpp:792
bool valid_trigger_value(const Decimal64 &trigger)
Tests whether a trigger price is one Kiwoom can carry (cond_uv, mdfy_cond_uv).
Definition client.hpp:229
std::optional< BrokerError > unestablished_holdings_scope()
Makes the error that refuses a new order or an amendment while KiwoomConfig::holdings_position_scope_...
Definition client.hpp:185
std::optional< BrokerError > kiwoom_declared_error(const boost::json::object &document)
Reads the failure a Kiwoom response declares in its body (Kiwoom reports business failures with HTTP ...
Definition errors.hpp:99
Venue normalized_venue(std::string_view code) noexcept
Converts a venue Kiwoom names on a response (stex_tp, dmst_stex_tp).
Definition client.hpp:665
constexpr const char * chart_rows_field(BarInterval interval) noexcept
Returns the array field a bar interval's chart endpoint returns its rows in.
Definition client.hpp:766
Venue listed_venue(std::string_view stex_tp, std::string_view sor_yn) noexcept
Returns the venue of a working-order row (ka10075) from its stex_tp and sor_yn.
Definition client.hpp:688
KiwoomOrderOperation
Which order instruction a reply answers.
Definition errors.hpp:140
@ CANCEL
A cancellation (kt10003).
Definition errors.hpp:148
@ UNCLASSIFIED
Not an order request, or one this client does not classify.
Definition errors.hpp:142
const KiwoomOrderShapeRow * shape_by_name(std::string_view name) noexcept
Looks up an order shape by the Korean name a response gives (either listing's spelling).
Definition client.hpp:604
constexpr std::array< KiwoomOrderShapeRow, 21 > kOrderShapes
Kiwoom's order-type (trde_tp) table, from its API specification.
Definition client.hpp:533
std::optional< BrokerError > invalid_trigger(OrderType type, const std::optional< Decimal64 > &trigger)
Checks that a trigger price is present exactly when the order type takes one (only STOP_LIMIT,...
Definition client.hpp:243
std::optional< BrokerError > unsupported_client_order_id(const OrderRequest &order)
Refuses an idempotency key, which Kiwoom does not offer (an order carrying client_order_id_ is refuse...
Definition client.hpp:210
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
OrderStatus normalized_order_status(std::string_view text) noexcept
Reads an order status from Kiwoom's Korean word.
Definition client.hpp:718
std::optional< BrokerError > order_division(OrderType type, TimeInForce time_in_force, OrderSession session, std::string &division)
Finds Kiwoom's order-type code for an order shape.
Definition client.hpp:567
const KiwoomOrderShapeRow * shape_by_code(std::string_view code) noexcept
Looks up an order shape by Kiwoom's numeric trde_tp code.
Definition client.hpp:621
KiwoomPositionScope
What the venue named on a Kiwoom holdings request (kt00018's dmst_stex_tp) means for the positions it...
Definition config.hpp:103
constexpr const char * chart_api_id(BarInterval interval) noexcept
Returns the api-id of the chart endpoint for a bar interval.
Definition client.hpp:740
std::optional< OrderSide > normalized_order_side(std::string_view text) noexcept
Reads the side from Kiwoom's free-text io_tp_nm (such as +매수, 현금매도, 매수정정), by whether it contains 매수 ...
Definition client.hpp:702
std::optional< BrokerError > kiwoom_recognized_refusal(int http_status, const boost::json::object &document, KiwoomOrderOperation operation, bool demo)
Reads the refusal a cash-order reply states, for the replies this client recognizes as one.
Definition errors.hpp:206
constexpr Venue kiwoom_effective_route(Venue asked) noexcept
Returns the venue a Kiwoom order reaches: the one it names (Kiwoom requires one, so an order naming n...
Definition client.hpp:656
PriceRule price_rule_for(SecurityType type)
Returns the KRX price grid for a kind of security listed on KRX.
Definition krx.hpp:52
HTTP and WebSocket transport, OAuth tokens, and request pacing.
RateLimitGroup
The traffic class of a request, for rate limiting and queue priority. The broker adapter that builds ...
@ MARKET_DATA
Quotes, bars, order book and trades.
@ ACCOUNT
Holdings, working orders, order history and buying power.
@ TRADING
Order placement, amendment and cancellation. HttpClientOptions::fresh_connection_for_orders_ applies ...
@ REFERENCE
Instrument reference data and trading calendars.
@ AUTH
Access-token issue and refresh.
BrokerError token_unusable_error()
Returns the error of a call whose token stopped being usable while it ran on a client with a store: A...
http::response< http::string_body > HttpResponse
The HTTP response type the transport clients return.
void quote(S &strategy, Ctx &context, const QuoteEvent &event)
Calls strategy.on_quote(context, event) if the strategy declares on_quote; otherwise does nothing.
Definition concept.hpp:331
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
@ OPEN
The timestamp is the first instant of the period.
MarketSegment market_segment(std::string_view code)
Maps a broker's segment code to a MarketSegment.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
@ AUTHENTICATION
The credentials or token were refused.
Definition types.hpp:956
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
Definition types.hpp:2007
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
Definition types.hpp:2009
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
Definition types.hpp:2005
@ MID_PRICE
중간가: priced at the midpoint of the spread.
Definition types.hpp:2011
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
Definition types.hpp:2015
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
constexpr bool carries_trigger_price(OrderType type) noexcept
Tests whether an order type takes a trigger price.
Definition types.hpp:2065
constexpr bool carries_caller_price(OrderType type) noexcept
Tests whether an order type takes a price from the caller.
Definition types.hpp:2039
InstrumentStatus
Whether an instrument is listed, awaiting listing, or delisted.
constexpr std::string_view bar_interval_name(BarInterval interval) noexcept
Returns a short name for an interval, such as "1m", "5m", "1h" or "1d".
constexpr bool error_category_is_rate_limit(ErrorCategory category) noexcept
Tests whether an error of this category is a broker asking the caller to slow down,...
Definition types.hpp:983
OrderSession
The trading session an order is submitted into.
Definition types.hpp:2130
@ AFTER_HOURS
After the close, at that session's close (장후 시간외).
Definition types.hpp:2141
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
@ AFTER_HOURS_AUCTION
The after-hours single-price auction (시간외 단일가).
Definition types.hpp:2143
@ PRE_MARKET
Before the open, at the previous session's close (장전 시간외).
Definition types.hpp:2139
@ GTP
NXT's GTP session.
Definition types.hpp:2147
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
BarInterval
The period one bar covers.
@ FIVE_MINUTES
Five minutes.
@ THIRTY_MINUTES
Thirty minutes.
@ FIFTEEN_MINUTES
Fifteen minutes.
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
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
Definition types.hpp:2088
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
std::string format_iso8601_utc(std::chrono::system_clock::time_point value)
Formats an instant as an ISO 8601 timestamp in UTC, such as 2026-10-06T00:30:00Z.
Definition types.hpp:2741
void order_depth(DepthSnapshot &book)
Sorts a book's levels best first: bids descending, asks ascending.
What bars to fetch.
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
A calendar date with no time of day or time zone.
Definition types.hpp:1412
unsigned month_
The month, 1-12; zero means unset.
Definition types.hpp:1416
int year_
The year.
Definition types.hpp:1414
unsigned day_
The day of the month, 1-31; zero means unset.
Definition types.hpp:1418
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
The broker's acknowledgement that it accepted an instruction.
Definition types.hpp:2383
std::string order_id_
The order number the broker assigned.
Definition types.hpp:2385
An order to place, in broker-neutral form.
Definition types.hpp:2216
std::optional< std::string > client_order_id_
An idempotency key, if the broker offers one; never generated by the library.
Definition types.hpp:2257
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
Definition types.hpp:1197
@ UNESTABLISHED
Not established; RiskGuard refuses.
Definition types.hpp:1195
@ DEDUCT
Subtract every resting sell from the figure.
Definition types.hpp:1215
One account Kiwoom's ka00001 reports for the bound credential.
Definition client.hpp:48
std::string account_number_
The account number as Kiwoom reported it, for display.
Definition client.hpp:50
The Kiwoom account selector, which is empty: no Kiwoom endpoint takes an account number,...
Definition client.hpp:36
friend bool operator==(const KiwoomAccount &, const KiwoomAccount &)
Compares two selectors (the arguments are not used); always equal, since a Kiwoom credential drives e...
Definition client.hpp:42
An amendment or cancellation of a Kiwoom order.
Definition client.hpp:73
Venue venue_
The venue the order rests on, as listed (Kiwoom's dmst_stex_tp): KRX, NXT or COMBINED (SOR)....
Definition client.hpp:80
KiwoomOrderRef order_
The order to amend, which carries the symbol Kiwoom requires beside the order number.
Definition client.hpp:75
Decimal64 quantity_
The quantity affected, or zero for everything still resting (Kiwoom evaluates 0 when it processes the...
Definition client.hpp:85
std::optional< Decimal64 > price_
The new price, on a modification; absent on an unpriced basis, and refused on a cancellation.
Definition client.hpp:87
std::optional< Decimal64 > condition_price_
The new trigger price (mdfy_cond_uv), for amending a stop-limit (28) order; must be empty on a cancel...
Definition client.hpp:92
Kiwoom credentials (app key and secret key), demo or real account, the market-data tape,...
Definition config.hpp:155
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
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
Venue holdings_venue_
The venue holdings requests (kt00018) name: Venue::KRX or Venue::NXT. No default: holdings requests a...
Definition config.hpp:183
Kiwoom's deposit detail (kt00001), as reported; buying_power reads spendable_ from it,...
Definition client.hpp:809
Decimal64 orderable_
ord_alow_amt 주문가능금액: orderable including what margin and 대용금 allow.
Definition client.hpp:816
Decimal64 withdrawable_
pymn_alow_amt 출금가능금액: what may be withdrawn.
Definition client.hpp:824
Decimal64 spendable_
What the account can buy paying in full, without credit (100stk_ord_alow_amt); BuyingPower::cash_ is ...
Definition client.hpp:814
Decimal64 deposit_
entr 예수금: the cash deposit.
Definition client.hpp:818
std::chrono::system_clock::time_point received_at_
When the figures arrived, on this machine's clock.
Definition client.hpp:828
Decimal64 substitute_amount_
repl_amt 대용금: securities pledged as collateral, which is not cash.
Definition client.hpp:822
Currency currency_
The currency every figure above is in, which is won.
Definition client.hpp:826
Decimal64 settled_deposit_
d2_entra D+2 추정예수금: the deposit once today's trades settle.
Definition client.hpp:820
A Kiwoom order-history query: one date (kt00007 takes no range, so a multi-day query is refused).
Definition client.hpp:146
Date date_
The single 주문일자 to list.
Definition client.hpp:148
std::string symbol_
Restrict to one symbol, which Kiwoom expresses as stk_cd. Empty lists every symbol.
Definition client.hpp:150
One margin tier of Kiwoom's kt00010 answer: what may be ordered at that 증거금률.
Definition client.hpp:832
std::optional< Decimal64 > quantity_
profa_NNord_alowq: the orderable quantity at this rate. Empty as for amount_.
Definition client.hpp:840
int margin_percent_
The margin rate the row applies to, as a percentage: 20, 30, 40, 50, 60 or 100.
Definition client.hpp:834
bool reduced_
Whether this row is the 증거금감면 (reduced-margin) variant of its rate.
Definition client.hpp:836
std::optional< Decimal64 > amount_
The orderable amount at this margin rate (profa_NNord_alow_amt), if Kiwoom reported one.
Definition client.hpp:838
One page of Kiwoom orders that remain modifiable or cancellable.
Definition client.hpp:135
std::vector< KiwoomOpenOrder > orders_
The rows on this page.
Definition client.hpp:137
std::chrono::system_clock::time_point received_at_
When the page arrived, on this machine's clock.
Definition client.hpp:139
One Kiwoom order that is still open to modification or cancellation.
Definition client.hpp:116
std::optional< Decimal64 > amendable_quantity_
How much Kiwoom says is still unfilled, oso_qty, and therefore still amendable.
Definition client.hpp:124
KiwoomOrderRef order_ref_
The reference an amendment must address.
Definition client.hpp:120
OrderSnapshot order_
The order's normalized state.
Definition client.hpp:118
std::string original_order_number_
Kiwoom's orig_ord_no: which earlier order this one superseded. Lineage, not an address.
Definition client.hpp:122
std::string shape_name_
Kiwoom's order-type name on the row (trde_tp), verbatim, such as 보통 or 시장가.
Definition client.hpp:131
Kiwoom's acknowledgement of an accepted order, amendment or cancellation.
Definition client.hpp:101
OrderAck ack_
The normalized acknowledgement, whose accepted_at_ is local receipt.
Definition client.hpp:103
KiwoomOrderRef order_
The reference a later amendment must address.
Definition client.hpp:105
std::optional< Decimal64 > amended_quantity_
The quantity Kiwoom echoed on an amendment, mdfy_qty or cncl_qty. Empty on a placement.
Definition client.hpp:112
std::string base_order_number_
Kiwoom's base_orig_ord_no (모주문번호) on an amendment: the order the amendment chain began with,...
Definition client.hpp:110
A Kiwoom order's address: order number and symbol, both of which amendments and cancellations require...
Definition client.hpp:59
std::string order_number_
Kiwoom's ord_no.
Definition client.hpp:61
std::string symbol_
Kiwoom's stk_cd, which its amendment endpoints require beside the order number.
Definition client.hpp:63
One row of Kiwoom's order-type table: the numeric request code, the Korean names its listings report,...
Definition client.hpp:509
const char * code_
The numeric trde_tp a request carries, or null for a shape this library cannot send.
Definition client.hpp:511
bool requestable_
Whether this adapter may send the code, as opposed to reading it.
Definition client.hpp:523
OrderSession session_
The normalized session.
Definition client.hpp:521
TimeInForce time_in_force_
The normalized execution condition.
Definition client.hpp:519
OrderType type_
The normalized price basis.
Definition client.hpp:517
const char * alternate_name_
The name kt00007 and kt00009 use, or null where it is the same as name_.
Definition client.hpp:515
const char * name_
The name kt10000, ka10075 and ka10076 use.
Definition client.hpp:513
What may be ordered of one instrument, per margin tier (kt00010), reachable through session....
Definition client.hpp:850
std::vector< KiwoomMarginTier > tiers_
Always seven 증거금률 tiers: 20, 30, 40, 50, 60 and 100 %, then the 60 % 증거금감면 tier (reduced_)....
Definition client.hpp:855
Decimal64 settled_deposit_
d2entra D+2 추정예수금.
Definition client.hpp:861
bool margin_reduction_applies_
profa_rdex_aplc_tp: whether the 증거금감면 tiers are the ones in force (1) or not (0).
Definition client.hpp:863
Decimal64 withdrawable_
wthd_alowa 인출가능금액.
Definition client.hpp:859
Currency currency_
The currency every amount above is in, which is won.
Definition client.hpp:865
Decimal64 orderable_cash_
ord_alowa 주문가능현금: the cash available to order with.
Definition client.hpp:857
std::chrono::system_clock::time_point received_at_
When the figures arrived, on this machine's clock.
Definition client.hpp:867
A Kiwoom REST access token (au10001's token) and its expiry (expires_dt).
Definition config.hpp:383
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
void from_json(const json::object &document)
Reads a token response.
Definition oauth.hpp:166
std::string access_token_
The bearer token; do not log it.
Definition oauth.hpp:152
Deadlines, size limits and pacing for an HTTP client.
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...