algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
client.hpp
1#pragma once
2
3#include "../../network/calendar_cache.hpp"
4#include "../common/adapter.hpp"
5#include "../common/krx.hpp"
6#include "./config.hpp"
7
8#include <boost/asio/any_completion_handler.hpp>
9#include <boost/asio/associated_executor.hpp>
10#include <boost/asio/async_result.hpp>
11#include <boost/asio/dispatch.hpp>
12#include <boost/asio/post.hpp>
13#include <boost/asio/strand.hpp>
14
15#include <array>
16#include <cstdlib>
17#include <deque>
18#include <fstream>
19#include <iterator>
20#include <memory>
21#include <optional>
22#include <stdexcept>
23#include <string>
24#include <string_view>
25#include <utility>
26#include <vector>
27
28namespace algotradelib::kis {
29
31struct KisAccount {
33 std::string account_number_;
35 std::string product_code_;
36
42 void from_env() {
43 const char* account_number = std::getenv("KIS_CANO");
44 if (!account_number) {
45 throw std::runtime_error("KIS_CANO not set (8-digit account number)");
46 }
47 const char* product_code = std::getenv("KIS_ACNT_PRDT_CD");
48 account_number_ = account_number;
49 product_code_ = product_code ? product_code : "01";
50 }
51
63 void from_json(const std::string& filename) {
64 std::ifstream ifs(filename);
65 if (!ifs.is_open()) {
66 throw std::runtime_error("Cannot open KIS credential file: " + filename);
67 }
68 const std::string content(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>{});
69 from_json_text(content, "file " + filename);
70 }
71
81 void from_json_text(std::string_view text, const std::string& origin) {
82 boost::system::error_code ec;
83 const auto document = boost::json::parse(text, ec);
84 if (ec || !document.is_object()) {
85 throw std::runtime_error("Failed to parse KIS credentials " + origin);
86 }
87 const auto field = [&](const char* name, std::size_t digits) -> std::optional<std::string> {
88 const auto* value = document.as_object().if_contains(name);
89 if (value == nullptr) {
90 return std::nullopt;
91 }
92 if (!value->is_string() || !broker_detail::decimal_digits(value->get_string(), digits)) {
93 throw std::runtime_error(
94 "KIS credential " + origin + " has a " + name + " that is not " + std::to_string(digits) +
95 " digits in a string"
96 );
97 }
98 return std::string(value->get_string());
99 };
100 auto number = field("account_number", 8);
101 if (!number) {
102 throw std::runtime_error("KIS credential " + origin + " has no account_number");
103 }
104 const auto product = field("account_product_code", 2);
105 account_number_ = std::move(*number);
106 product_code_ = product ? *product : "01";
107 }
108};
109
113 std::string branch_number_;
115 std::string order_number_;
116};
117
154
169
192
196 std::vector<KisOpenOrder> orders_;
198 std::chrono::system_clock::time_point received_at_;
199};
200
208
214 const auto seoul = std::chrono::system_clock::now() + std::chrono::hours(9);
215 const std::time_t raw =
216 std::chrono::system_clock::to_time_t(std::chrono::time_point_cast<std::chrono::seconds>(seoul));
217 std::tm parts{};
218#ifdef _WIN32
219 gmtime_s(&parts, &raw);
220#else
221 gmtime_r(&raw, &parts);
222#endif
223 return Date{
224 parts.tm_year + 1900,
225 static_cast<unsigned>(parts.tm_mon + 1),
226 static_cast<unsigned>(parts.tm_mday),
227 };
228}
229
242
251inline KisRateLimitLayer kis_rate_limit_layer(std::string_view code) {
252 if (code == "EGW00201") {
254 }
255 return code == "EGW00215" ? KisRateLimitLayer::LEDGER : KisRateLimitLayer::NONE;
256}
257
269inline std::optional<BrokerError> unsupported_client_order_id(const OrderRequest& order) {
270 if (!order.client_order_id_) {
271 return std::nullopt;
272 }
273 BrokerError error;
275 error.reached_broker_ = false;
276 error.broker_code_ = "idempotency_key_unsupported";
277 error.message_ =
278 "KIS offers no client-supplied idempotency key for individual customers; clear "
279 "client_order_id_ and reconcile through an order inquiry after a transport failure";
280 return error;
281}
282
289inline constexpr bool publishes_bar_interval(BarInterval interval) noexcept {
290 switch (interval) {
291 case BarInterval::ONE_MINUTE:
292 case BarInterval::ONE_DAY:
293 case BarInterval::ONE_WEEK:
294 case BarInterval::ONE_MONTH:
295 case BarInterval::ONE_YEAR:
296 return true;
301 return false;
302 }
303 return false;
304}
305
311inline std::optional<BrokerError> unsupported_bar_interval(BarInterval interval) {
312 if (publishes_bar_interval(interval)) {
313 return std::nullopt;
314 }
315 BrokerError error;
317 error.reached_broker_ = false;
318 error.broker_code_ = "unsupported_interval";
319 error.message_ = std::string("KIS publishes no chart for ") + std::string(bar_interval_name(interval)) +
320 " bars; its minute chart is one minute only";
321 return error;
322}
323
324class KisBlockingClient;
325
339class KisClient : public std::enable_shared_from_this<KisClient> {
340public:
342 using QuoteHandler = net::any_completion_handler<void(Result<QuoteSnapshot>)>;
343
345 using BarsHandler = net::any_completion_handler<void(Result<BarSeries>)>;
346
348 using DepthHandler = net::any_completion_handler<void(Result<DepthSnapshot>)>;
349
351 using PriceLimitsHandler = net::any_completion_handler<void(Result<PriceLimits>)>;
352
354 using TradesHandler = net::any_completion_handler<void(Result<std::vector<TradePrint>>)>;
355
357 using CalendarHandler = net::any_completion_handler<void(Result<TradingCalendar>)>;
358
360 using InstrumentHandler = net::any_completion_handler<void(Result<Instrument>)>;
361
363 using HoldingsHandler = net::any_completion_handler<void(Result<HoldingsSnapshot>)>;
365 using BuyingPowerHandler = net::any_completion_handler<void(Result<BuyingPower>)>;
366
368 using OrderAckHandler = net::any_completion_handler<void(Result<KisOrderAck>)>;
369
371 using OpenOrderHandler = net::any_completion_handler<void(Result<KisOpenOrderPage>)>;
372
374 using OrderPageHandler = net::any_completion_handler<void(Result<OrderPage>)>;
375
377 using TokenHandler = net::any_completion_handler<void(std::optional<BrokerError>)>;
378
380 using TokenResultHandler = net::any_completion_handler<void(Result<KisRest>)>;
381
391 net::any_io_executor executor, ssl::context& context, KisConfig config, network::HttpClientOptions options = {}
392 )
393 : strand_(net::make_strand(std::move(executor))),
394 config_(std::move(config)),
395 http_(
396 std::make_shared<network::AsyncHttpClient>(
397 strand_, context, config_.rest_host(), config_.rest_port(), transport_options(std::move(options), config_)
398 )
399 ) {}
400
416 template <typename CompletionToken>
417 auto async_bars(BarQuery query, CompletionToken&& token) {
418 return net::async_initiate<CompletionToken, void(Result<BarSeries>)>(
419 [self = shared_from_this(), query = std::move(query)](auto&& handler) mutable {
420 auto completion = BarsHandler(std::forward<decltype(handler)>(handler));
421 net::post(self->strand_, [self, query = std::move(query), completion = std::move(completion)]() mutable {
422 self->start_bars(std::move(query), std::move(completion));
423 });
424 },
425 token
426 );
427 }
428
436 template <typename CompletionToken>
437 auto async_instrument(InstrumentId instrument, CompletionToken&& token) {
438 return net::async_initiate<CompletionToken, void(Result<Instrument>)>(
439 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
440 auto completion = InstrumentHandler(std::forward<decltype(handler)>(handler));
441 net::post(
442 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
443 self->start_instrument(std::move(instrument), std::move(completion));
444 }
445 );
446 },
447 token
448 );
449 }
450
463 template <typename CompletionToken>
464 auto async_calendar(Date from, bool refresh, CompletionToken&& token) {
465 return net::async_initiate<CompletionToken, void(Result<TradingCalendar>)>(
466 [self = shared_from_this(), from, refresh](auto&& handler) mutable {
467 auto completion = CalendarHandler(std::forward<decltype(handler)>(handler));
468 net::post(self->strand_, [self, from, refresh, completion = std::move(completion)]() mutable {
469 self->start_calendar(from, refresh, std::move(completion));
470 });
471 },
472 token
473 );
474 }
475
483 template <typename CompletionToken>
484 auto async_price_limits(InstrumentId instrument, CompletionToken&& token) {
485 return net::async_initiate<CompletionToken, void(Result<PriceLimits>)>(
486 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
487 auto completion = PriceLimitsHandler(std::forward<decltype(handler)>(handler));
488 net::post(
489 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
490 self->start_market_read(
491 std::move(instrument), "/uapi/domestic-stock/v1/quotations/inquire-price", "FHKST01010100",
492 std::move(completion), parse_price_limits
493 );
494 }
495 );
496 },
497 token
498 );
499 }
500
510 template <typename CompletionToken>
511 auto async_trades(InstrumentId instrument, int count, CompletionToken&& token) {
512 return net::async_initiate<CompletionToken, void(Result<std::vector<TradePrint>>)>(
513 [self = shared_from_this(), instrument = std::move(instrument), count](auto&& handler) mutable {
514 auto completion = TradesHandler(std::forward<decltype(handler)>(handler));
515 net::post(
516 self->strand_,
517 [self, instrument = std::move(instrument), count, completion = std::move(completion)]() mutable {
518 self->start_market_read(
519 std::move(instrument), "/uapi/domestic-stock/v1/quotations/inquire-ccnl", "FHKST01010300",
520 std::move(completion), [count](InstrumentId subject, Result<network::HttpResponse> response) {
521 return parse_trades(std::move(subject), std::move(response), count);
522 }
523 );
524 }
525 );
526 },
527 token
528 );
529 }
530
538 template <typename CompletionToken>
539 auto async_depth(InstrumentId instrument, CompletionToken&& token) {
540 return net::async_initiate<CompletionToken, void(Result<DepthSnapshot>)>(
541 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
542 auto completion = DepthHandler(std::forward<decltype(handler)>(handler));
543 net::post(
544 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
545 self->start_depth(std::move(instrument), std::move(completion));
546 }
547 );
548 },
549 token
550 );
551 }
552
560 template <typename CompletionToken>
561 auto async_quote(InstrumentId instrument, CompletionToken&& token) {
562 return net::async_initiate<CompletionToken, void(Result<QuoteSnapshot>)>(
563 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
564 auto completion = QuoteHandler(std::forward<decltype(handler)>(handler));
565 net::post(
566 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
567 self->start_quote(std::move(instrument), std::move(completion));
568 }
569 );
570 },
571 token
572 );
573 }
574
583 template <typename CompletionToken>
584 auto async_buying_power(Currency currency, KisAccount account, CompletionToken&& token) {
585 return net::async_initiate<CompletionToken, void(Result<BuyingPower>)>(
586 [self = shared_from_this(), currency, account = std::move(account)](auto&& handler) mutable {
587 auto completion = BuyingPowerHandler(std::forward<decltype(handler)>(handler));
588 net::post(
589 self->strand_, [self, currency, account = std::move(account), completion = std::move(completion)]() mutable {
590 self->start_buying_power(currency, std::move(account), std::move(completion));
591 }
592 );
593 },
594 token
595 );
596 }
597
605 template <typename CompletionToken>
606 auto async_holdings(KisAccount account, CompletionToken&& token) {
607 return net::async_initiate<CompletionToken, void(Result<HoldingsSnapshot>)>(
608 [self = shared_from_this(), account = std::move(account)](auto&& handler) mutable {
609 auto completion = HoldingsHandler(std::forward<decltype(handler)>(handler));
610 net::post(self->strand_, [self, account = std::move(account), completion = std::move(completion)]() mutable {
611 self->start_holdings(std::move(account), std::move(completion));
612 });
613 },
614 token
615 );
616 }
617
644 template <typename CompletionToken>
645 auto async_place_order(KisAccount account, OrderRequest order, CompletionToken&& token) {
646 return net::async_initiate<CompletionToken, void(Result<KisOrderAck>)>(
647 [self = shared_from_this(), account = std::move(account), order = std::move(order)](auto&& handler) mutable {
648 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
649 net::post(
650 self->strand_,
651 [self, account = std::move(account), order = std::move(order), completion = std::move(completion)]() mutable {
652 self->start_place_order(std::move(account), std::move(order), std::move(completion));
653 }
654 );
655 },
656 token
657 );
658 }
659
671 template <typename CompletionToken>
672 auto async_replace_order(KisAccount account, KisAmendment amendment, CompletionToken&& token) {
673 return net::async_initiate<CompletionToken, void(Result<KisOrderAck>)>(
674 [self = shared_from_this(), account = std::move(account),
675 amendment = std::move(amendment)](auto&& handler) mutable {
676 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
677 net::post(
678 self->strand_,
679 [self, account = std::move(account), amendment = std::move(amendment),
680 completion = std::move(completion)]() mutable {
681 self->start_amend_order(std::move(account), std::move(amendment), false, std::move(completion));
682 }
683 );
684 },
685 token
686 );
687 }
688
707 template <typename CompletionToken>
708 auto async_cancel_order(KisAccount account, KisAmendment amendment, CompletionToken&& token) {
709 return net::async_initiate<CompletionToken, void(Result<KisOrderAck>)>(
710 [self = shared_from_this(), account = std::move(account),
711 amendment = std::move(amendment)](auto&& handler) mutable {
712 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
713 net::post(
714 self->strand_,
715 [self, account = std::move(account), amendment = std::move(amendment),
716 completion = std::move(completion)]() mutable {
717 self->start_amend_order(std::move(account), std::move(amendment), true, std::move(completion));
718 }
719 );
720 },
721 token
722 );
723 }
724
738 template <typename CompletionToken>
739 auto async_open_orders(KisAccount account, CompletionToken&& token) {
740 return net::async_initiate<CompletionToken, void(Result<KisOpenOrderPage>)>(
741 [self = shared_from_this(), account = std::move(account)](auto&& handler) mutable {
742 auto completion = OpenOrderHandler(std::forward<decltype(handler)>(handler));
743 net::post(self->strand_, [self, account = std::move(account), completion = std::move(completion)]() mutable {
744 self->start_open_orders(std::move(account), std::move(completion));
745 });
746 },
747 token
748 );
749 }
750
763 template <typename CompletionToken>
764 auto async_order_history(KisAccount account, KisHistoryRange range, CompletionToken&& token) {
765 return net::async_initiate<CompletionToken, void(Result<OrderPage>)>(
766 [self = shared_from_this(), account = std::move(account), range](auto&& handler) mutable {
767 auto completion = OrderPageHandler(std::forward<decltype(handler)>(handler));
768 net::post(
769 self->strand_, [self, account = std::move(account), range, completion = std::move(completion)]() mutable {
770 self->start_order_history(std::move(account), range, std::move(completion));
771 }
772 );
773 },
774 token
775 );
776 }
777
787 const auto* limiter = http_->rate_limits();
788 return limiter ? &limiter->stats() : nullptr;
789 }
790
802 KisRest token() const {
803 return token_;
804 }
805
823 if (!token.valid()) {
824 return false;
825 }
826 token_ = std::move(token);
827 return true;
828 }
829
839 if (calendar.country_ != Country::KR || calendar.days_.empty()) {
840 return false;
841 }
842 for (const auto& day : calendar.days_) {
843 if (!is_valid_date(day.date_)) {
844 return false;
845 }
846 }
847 calendar_ = std::move(calendar);
848 return true;
849 }
850
858 template <typename CompletionToken>
859 auto async_ensure_token(CompletionToken&& token) {
860 return net::async_initiate<CompletionToken, void(Result<KisRest>)>(
861 [self = shared_from_this()](auto&& handler) mutable {
862 auto completion = TokenResultHandler(std::forward<decltype(handler)>(handler));
863 net::post(self->strand_, [self, completion = std::move(completion)]() mutable {
864 self->request_token(
865 TokenHandler([self, completion = std::move(completion)](std::optional<BrokerError> error) mutable {
866 self->deliver(
867 std::move(completion), error ? Result<KisRest>(std::move(*error)) : Result<KisRest>(self->token_)
868 );
869 })
870 );
871 });
872 },
873 token
874 );
875 }
876
883 token_ = KisRest{};
884 }
885
892 void close() {
893 http_->close();
894 }
895
896private:
897 friend struct KisClientTestAccess;
898 friend class KisBlockingClient;
899
900 // The transport's options, with KIS's choice of `fresh_connection_for_orders_` when the caller made none: the demo server has closed a connection that carried an order, unannounced, under a second after the reply.
901 static network::HttpClientOptions transport_options(network::HttpClientOptions options, const KisConfig& config) {
902 if (!options.fresh_connection_for_orders_.has_value()) {
903 options.fresh_connection_for_orders_ = config.is_demo_;
904 }
905 return options;
906 }
907
908 net::strand<net::any_io_executor> strand_;
909 KisConfig config_;
910 std::shared_ptr<network::AsyncHttpClient> http_;
911 KisRest token_;
912 TradingCalendar calendar_;
913 bool refreshing_{false};
914 std::deque<TokenHandler> token_waiters_;
915 // Set by a blocking client with a token store, which prepares every token under the store's lock.
916 bool store_managed_{false};
917
918 struct HoldingsOperation {
919 KisAccount account_;
920 HoldingsSnapshot snapshot_;
921 std::string foreign_cursor_;
922 std::string domestic_cursor_;
923 std::size_t page_count_{0};
924 HoldingsHandler completion_;
925
926 HoldingsOperation(KisAccount selected_account, HoldingsHandler selected_completion)
927 : account_(std::move(selected_account)), completion_(std::move(selected_completion)) {}
928 };
929
930 // One bar request spanning however many KIS pages it needs.
931 struct BarOperation {
932 BarQuery query_;
933 std::vector<Bar> descending_;
934 // Upper bound for the next page, as a KST calendar date and time.
935 Date date_{};
936 std::string time_;
937 int pages_{0};
938 bool minutes_{false};
939 BarsHandler completion_;
940
941 BarOperation(BarQuery query, BarsHandler completion)
942 : query_(std::move(query)), completion_(std::move(completion)) {}
943 };
944
945 // Bars KIS returns per page, per endpoint.
946 static constexpr int period_page_limit_ = 100;
947 static constexpr int today_minute_page_limit_ = 30;
948 static constexpr int daily_minute_page_limit_ = 120;
949
950 // Most pages one bar request may consume, for the reason paging is bounded.
951 static constexpr int bar_page_budget_ = 50;
952
953 // Validates a bar request and starts walking KIS's inputs.
954 void start_bars(BarQuery query, BarsHandler completion) {
955 if (auto invalid = validate_bar_query(query)) {
956 deliver(std::move(completion), Result<BarSeries>(std::move(*invalid)));
957 return;
958 }
959
960 auto operation = std::make_shared<BarOperation>(std::move(query), std::move(completion));
961 operation->minutes_ = operation->query_.interval_ == BarInterval::ONE_MINUTE;
962 const auto bound = operation->query_.before_ ? *operation->query_.before_ : std::chrono::system_clock::now();
963 korea_calendar(bound, operation->date_, operation->time_);
964
965 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
966 if (token_error) {
967 self->deliver(std::move(operation->completion_), Result<BarSeries>(std::move(*token_error)));
968 return;
969 }
970 self->request_bars(operation);
971 }));
972 }
973
974 // Returns an error when KIS cannot answer the request as described.
975 static std::optional<BrokerError> validate_bar_query(const BarQuery& query) {
976 BrokerError error;
977 error.category_ = ErrorCategory::INVALID_ARGUMENT;
978 error.reached_broker_ = false;
979 if (query.instrument_.country_ != Country::KR) {
980 error.broker_code_ = "invalid_instrument";
981 error.message_ = "KIS bars currently cover Korean equities only";
982 return error;
983 }
984 if (!valid_domestic_symbol(query.instrument_.symbol_)) {
985 error.broker_code_ = "invalid_instrument";
986 error.message_ = "KIS bar symbol must contain six letters or digits, or seven for an ETN";
987 return error;
988 }
989 if (query.count_ < 1) {
990 error.broker_code_ = "invalid_count";
991 error.message_ = "bar request must ask for at least one bar";
992 return error;
993 }
994 // The session's guard (`BrokerTraits::validate_bars`) asks the same; a caller of this client does not go
995 // through the session.
996 return unsupported_bar_interval(query.interval_);
997 }
998
999 // Returns KIS's `FID_PERIOD_DIV_CODE` for a period interval.
1000 static const char* period_code(BarInterval interval) {
1001 switch (interval) {
1002 case BarInterval::ONE_WEEK:
1003 return "W";
1004 case BarInterval::ONE_MONTH:
1005 return "M";
1006 case BarInterval::ONE_YEAR:
1007 return "Y";
1008 case BarInterval::ONE_DAY:
1009 case BarInterval::ONE_MINUTE:
1010 // Refused before any request (`unsupported_bar_interval`).
1011 case BarInterval::FIVE_MINUTES:
1012 case BarInterval::FIFTEEN_MINUTES:
1013 case BarInterval::THIRTY_MINUTES:
1014 case BarInterval::ONE_HOUR:
1015 break;
1016 }
1017 return "D";
1018 }
1019
1020 // Returns the fewest calendar days one bar of `interval` can span.
1021 //
1022 // A period request asks KIS for a *date range* and KIS answers with at most 100
1023 // rows, so the range has to be sized to hold about one page of bars. Sizing it in
1024 // bars is not possible and sizing it as a fixed number of days is wrong: 100
1025 // calendar days is at most 100 daily bars, but only about fourteen weekly bars,
1026 // three monthly ones, and a quarter of a yearly one. A fixed span would have made
1027 // a request for a hundred monthly bars take thirty pages and a hundred yearly
1028 // bars exceed the page budget outright, returning a fraction of what was asked
1029 // for and reporting nothing wrong.
1030 //
1031 // The multiplier is the *shortest* a bar of that interval can be, so a range
1032 // never holds more than a page and the row cap cannot truncate it from an end
1033 // this code has not established.
1034 static constexpr int shortest_days_per_bar(BarInterval interval) {
1035 switch (interval) {
1036 case BarInterval::ONE_WEEK:
1037 return 7;
1038 case BarInterval::ONE_MONTH:
1039 return 28;
1040 case BarInterval::ONE_YEAR:
1041 return 365;
1042 case BarInterval::ONE_DAY:
1043 case BarInterval::ONE_MINUTE:
1044 // Refused before any request (`unsupported_bar_interval`).
1045 case BarInterval::FIVE_MINUTES:
1046 case BarInterval::FIFTEEN_MINUTES:
1047 case BarInterval::THIRTY_MINUTES:
1048 case BarInterval::ONE_HOUR:
1049 break;
1050 }
1051 return 1;
1052 }
1053
1054 // Splits an instant into the KST calendar date and `HHMMSS` KIS asks for.
1055 static void korea_calendar(std::chrono::system_clock::time_point value, Date& date, std::string& time) {
1056 const auto seoul = value + std::chrono::hours(9);
1057 const std::time_t raw =
1058 std::chrono::system_clock::to_time_t(std::chrono::time_point_cast<std::chrono::seconds>(seoul));
1059 std::tm parts{};
1060#ifdef _WIN32
1061 gmtime_s(&parts, &raw);
1062#else
1063 gmtime_r(&raw, &parts);
1064#endif
1065 date.year_ = parts.tm_year + 1900;
1066 date.month_ = static_cast<unsigned>(parts.tm_mon + 1);
1067 date.day_ = static_cast<unsigned>(parts.tm_mday);
1068 char buffer[7];
1069 std::snprintf(buffer, sizeof(buffer), "%02d%02d%02d", parts.tm_hour, parts.tm_min, parts.tm_sec);
1070 time.assign(buffer, 6);
1071 }
1072
1073 // Returns the calendar day before `date`, without a calendar of trading days.
1074 static Date previous_day(const Date& date) {
1075 Date earlier = date;
1076 if (earlier.day_ > 1) {
1077 --earlier.day_;
1078 return earlier;
1079 }
1080 if (earlier.month_ > 1) {
1081 --earlier.month_;
1082 } else {
1083 earlier.month_ = 12;
1084 --earlier.year_;
1085 }
1086 static constexpr unsigned days_per_month[] = {
1087 31,
1088 28,
1089 31,
1090 30,
1091 31,
1092 30,
1093 31,
1094 31,
1095 30,
1096 31,
1097 30,
1098 31,
1099 };
1100 unsigned days = days_per_month[earlier.month_ - 1];
1101 const bool leap = earlier.year_ % 4 == 0 && (earlier.year_ % 100 != 0 || earlier.year_ % 400 == 0);
1102 if (earlier.month_ == 2 && leap) {
1103 ++days;
1104 }
1105 earlier.day_ = days;
1106 return earlier;
1107 }
1108
1109 // Sends the next page, choosing the endpoint the interval and bound imply.
1110 void request_bars(const std::shared_ptr<BarOperation>& operation) {
1111 network::HttpRequest request;
1112 // Bars are the traffic a trading reserve exists to hold back.
1113 request.group_ = network::RateLimitGroup::MARKET_DATA;
1114 request.method_ = http::verb::get;
1115
1116 std::string transaction;
1117 if (!operation->minutes_) {
1118 // A period request selects bars by date range, oldest bound included. The
1119 // range has to be sized in calendar days, and how many calendar days a page
1120 // of bars spans depends entirely on the interval.
1121 Date from = operation->date_;
1122 const int span = period_page_limit_ * shortest_days_per_bar(operation->query_.interval_);
1123 for (int step = 0; step < span && from.year_ > 1; ++step) {
1124 from = previous_day(from);
1125 }
1126 request.target_ = "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice" +
1127 market_query(config_, operation->query_.instrument_.symbol_) + "&FID_INPUT_DATE_1=" + compact_date(from) +
1128 "&FID_INPUT_DATE_2=" + compact_date(operation->date_) +
1129 "&FID_PERIOD_DIV_CODE=" + period_code(operation->query_.interval_) +
1130 // KIS spells this the other way round from every reading of its name:
1131 // `0` asks for adjusted prices and `1` for raw ones.
1132 "&FID_ORG_ADJ_PRC=" + std::string(operation->query_.adjusted_ ? "0" : "1");
1133 transaction = "FHKST03010100";
1134 } else if (today_in_korea(operation->date_)) {
1135 request.target_ = "/uapi/domestic-stock/v1/quotations/inquire-time-itemchartprice" +
1136 market_query(config_, operation->query_.instrument_.symbol_) + "&FID_INPUT_HOUR_1=" + operation->time_ +
1137 "&FID_PW_DATA_INCU_YN=Y&FID_ETC_CLS_CODE=";
1138 transaction = "FHKST03010200";
1139 } else {
1140 request.target_ = "/uapi/domestic-stock/v1/quotations/inquire-time-dailychartprice" +
1141 market_query(config_, operation->query_.instrument_.symbol_) +
1142 "&FID_INPUT_DATE_1=" + compact_date(operation->date_) + "&FID_INPUT_HOUR_1=" + operation->time_ +
1143 "&FID_PW_DATA_INCU_YN=Y&FID_FAKE_TICK_INCU_YN=N";
1144 transaction = "FHKST03010230";
1145 }
1146
1147 request.headers_ = {
1148 {"authorization", "Bearer " + token_.access_token_},
1149 {"appkey", config_.key()},
1150 {"appsecret", config_.secret()},
1151 {"tr_id", transaction},
1152 {"custtype", "P"},
1153 {"content-type", "application/json; charset=utf-8"},
1154 };
1155
1156 ++operation->pages_;
1157 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
1158 self->handle_bars_page(operation, std::move(result));
1159 });
1160 }
1161
1162 // Returns whether `date` is today in Seoul, which decides the minute endpoint.
1163 static bool today_in_korea(const Date& date) {
1164 Date today{};
1165 std::string ignored;
1166 korea_calendar(std::chrono::system_clock::now(), today, ignored);
1167 return today == date;
1168 }
1169
1170 // Accumulates one page and either continues or finishes the request.
1171 void handle_bars_page(const std::shared_ptr<BarOperation>& operation, Result<network::HttpResponse> result) {
1172 const auto before = operation->descending_.size();
1173 if (
1174 auto failure = parse_bars_page(std::move(result), operation->query_, operation->minutes_, operation->descending_)
1175 ) {
1176 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(*failure)));
1177 return;
1178 }
1179
1180 const bool empty_page = operation->descending_.size() == before;
1181 const int collected = static_cast<int>(operation->descending_.size());
1182 const bool satisfied = collected >= operation->query_.count_;
1183 const bool spent = operation->pages_ >= bar_page_budget_;
1184 if (satisfied || empty_page || spent) {
1185 finish_bars(operation);
1186 return;
1187 }
1188
1189 // Step the bound to just before the oldest bar this page returned. Within a
1190 // session that walks backwards a page at a time; once the session start is
1191 // passed KIS returns nothing and the empty-page guard above ends the request.
1192 // The date check below is the second line of defence, for a bound that crosses
1193 // midnight: a minute request never steps to another calendar day, because
1194 // choosing the previous *trading* day needs a calendar this request does not have.
1195 const auto& oldest = operation->descending_.back();
1196 Date date{};
1197 std::string time;
1198 korea_calendar(oldest.timestamp_ - std::chrono::seconds(1), date, time);
1199 if (operation->minutes_ && !(date == operation->date_)) {
1200 finish_bars(operation);
1201 return;
1202 }
1203 operation->date_ = date;
1204 operation->time_ = time;
1205 request_bars(operation);
1206 }
1207
1208 // Parses one page into `into`, or returns the error that ends the request.
1209 //
1210 // Takes the accumulation by reference rather than an operation, so the
1211 // normalization is a pure function of a response and can be tested as one.
1212 //
1213 // **A row not strictly older than the oldest already accumulated is dropped.** Pages arrive newest
1214 // first and each is bounded just before the previous page's oldest bar, but KIS's minute bound does not
1215 // always exclude that bar: a read of 005930 before 2026-09-01 13:22 KST (주식일별분봉조회, 120 a page)
1216 // returned the bar at each page join twice, identical, at 11:23 and 09:24, while reads starting at other
1217 // minutes repeated nothing. A series with a repeated timestamp is not a series:
1218 // the runner's bar cache refuses a bar that is not later than the last (`SeriesBuffer::push` throws), so
1219 // a backtest fed it stopped on the first repeat. Dropping the repeat is safe whatever the bound's rule
1220 // is, and a page that brings nothing older counts as empty, which ends the request rather than asking
1221 // for the same page again.
1222 static std::optional<BrokerError> parse_bars_page(
1223 Result<network::HttpResponse> result, const BarQuery& query, bool minutes, std::vector<Bar>& into
1224 ) {
1225 if (!result) {
1226 return std::move(result.error());
1227 }
1228 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
1229 return kis_http_error(result.value());
1230 }
1231 BrokerError parse_error;
1232 auto document = broker_detail::parse_object(result.value(), parse_error);
1233 if (!document) {
1234 return parse_error;
1235 }
1236 try {
1237 if (auto declared = kis_declared_error(*document)) {
1238 return declared;
1239 }
1240 const auto rows = document->if_contains("output2");
1241 if (!rows || !rows->is_array()) {
1242 throw std::runtime_error("missing array field: output2");
1243 }
1244 for (const auto& value : rows->as_array()) {
1245 if (!value.is_object()) {
1246 throw std::runtime_error("bar entry is not an object");
1247 }
1248 const auto& row = value.as_object();
1249 // KIS pads a page with blank rows rather than shortening it.
1250 if (broker_detail::json_string(row, "stck_bsop_date").empty()) {
1251 continue;
1252 }
1253 auto bar = parse_bar(row, query, minutes);
1254 if (!into.empty() && !(bar.timestamp_ < into.back().timestamp_)) {
1255 continue;
1256 }
1257 into.push_back(std::move(bar));
1258 }
1259 return std::nullopt;
1260 } catch (const std::exception& exception) {
1261 BrokerError error;
1262 error.category_ = ErrorCategory::PROTOCOL;
1263 error.broker_code_ = "invalid_bar_response";
1264 error.message_ = exception.what();
1265 return error;
1266 }
1267 }
1268
1269 // Normalizes one KIS bar.
1270 //
1271 // A period bar is reported by its trading date, so its timestamp marks the
1272 // period's open. A minute bar's `stck_cntg_hour` is the start of its minute: a
1273 // day's continuous trading (to 15:20:00) ends with a 15:19 row and no 15:20 row.
1274 //
1275 // `mod_yn` marks a trading day on which nothing traded, so the bar has no open.
1276 // An absent open is preserved as absent rather than becoming zero or the
1277 // previous close, which is the only honest reading of a day with no trade.
1278 static Bar parse_bar(const json::object& row, const BarQuery& query, bool minutes) {
1279 static_cast<void>(query);
1280 Bar bar;
1281 const auto date = broker_detail::json_string(row, "stck_bsop_date");
1282 const auto time = minutes ? broker_detail::json_string(row, "stck_cntg_hour") : "000000";
1283 const auto timestamp = korea_timestamp(date, time);
1284 if (!timestamp) {
1285 throw std::runtime_error("invalid bar timestamp");
1286 }
1287 bar.timestamp_ = *timestamp;
1288 bar.high_ = Decimal64::parse(broker_detail::json_string(row, "stck_hgpr"));
1289 bar.low_ = Decimal64::parse(broker_detail::json_string(row, "stck_lwpr"));
1290 bar.close_ = Decimal64::parse(broker_detail::json_string(row, minutes ? "stck_prpr" : "stck_clpr"));
1291 bar.volume_ = Decimal64::parse(broker_detail::json_string(row, minutes ? "cntg_vol" : "acml_vol"));
1292 if (const auto value = row.if_contains("acml_tr_pbmn"); value && value->is_string()) {
1293 const std::string traded(value->as_string());
1294 if (!traded.empty()) {
1295 bar.traded_value_ = Decimal64::parse(traded);
1296 }
1297 }
1298 const auto unchanged = row.if_contains("mod_yn");
1299 const bool no_trade = unchanged && unchanged->is_string() && std::string_view(unchanged->as_string()) == "Y";
1300 if (!no_trade) {
1301 bar.open_ = Decimal64::parse(broker_detail::json_string(row, "stck_oprc"));
1302 }
1303 return bar;
1304 }
1305
1306 // Reverses the accumulation, trims to the requested count, and completes.
1307 void finish_bars(const std::shared_ptr<BarOperation>& operation) {
1308 auto series = compose_bars(*operation);
1309 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(series)));
1310 }
1311
1312 // The series a finished walk delivers.
1313 static BarSeries compose_bars(BarOperation& operation) {
1314 BarSeries series;
1315 series.instrument_ = operation.query_.instrument_;
1316 series.interval_ = operation.query_.interval_;
1317 // A period bar is reported by its trading date and a minute bar by the start of its
1318 // minute: both mark the period's open.
1319 series.stamp_ = BarStamp::OPEN;
1320 series.currency_ = Currency::krw();
1321 series.adjusted_ = operation.query_.adjusted_;
1322 series.received_at_ = std::chrono::system_clock::now();
1323
1324 auto& bars = operation.descending_;
1325 if (static_cast<int>(bars.size()) > operation.query_.count_) {
1326 bars.resize(static_cast<std::size_t>(operation.query_.count_));
1327 }
1328 series.bars_.assign(bars.rbegin(), bars.rend());
1329 if (!series.bars_.empty() && static_cast<int>(series.bars_.size()) < operation.query_.count_) {
1330 series.next_cursor_ = format_iso8601_utc(series.bars_.front().timestamp_);
1331 }
1332 return series;
1333 }
1334
1335 // Requests reference data, which KIS addresses differently from market data.
1336 //
1337 // `search-stock-info` takes a product-type code and a product number rather than
1338 // the market division every quotation endpoint takes, so it does not go through
1339 // the shared market-data helper.
1340 void start_instrument(InstrumentId instrument, InstrumentHandler completion) {
1341 if (instrument.country_ != Country::KR || !valid_domestic_symbol(instrument.symbol_)) {
1342 BrokerError error;
1343 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1344 error.reached_broker_ = false;
1345 error.broker_code_ = "invalid_instrument";
1346 error.message_ = "KIS reference data covers Korean equities addressed by product number";
1347 deliver(std::move(completion), Result<Instrument>(std::move(error)));
1348 return;
1349 }
1350
1351 ensure_token(TokenHandler(
1352 [self = shared_from_this(), instrument = std::move(instrument),
1353 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1354 if (token_error) {
1355 self->deliver(std::move(completion), Result<Instrument>(std::move(*token_error)));
1356 return;
1357 }
1358 network::HttpRequest request;
1359 // Reference data is the lowest-priority traffic there is.
1360 request.group_ = network::RateLimitGroup::REFERENCE;
1361 request.method_ = http::verb::get;
1362 // 300 covers 주식, ETF, ETN, and ELW, which is the whole equity universe
1363 // this library addresses.
1364 request.target_ = "/uapi/domestic-stock/v1/quotations/search-stock-info?PRDT_TYPE_CD=300&PDNO=" +
1365 broker_detail::query_encode(instrument.symbol_);
1366 request.headers_ = {
1367 {"authorization", "Bearer " + self->token_.access_token_},
1368 {"appkey", self->config_.key()},
1369 {"appsecret", self->config_.secret()},
1370 {"tr_id", "CTPF1002R"},
1371 {"custtype", "P"},
1372 {"content-type", "application/json; charset=utf-8"},
1373 };
1374 self->send(
1375 std::move(request),
1376 [self, instrument = std::move(instrument),
1377 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1378 self->deliver(std::move(completion), parse_instrument(std::move(instrument), std::move(result)));
1379 }
1380 );
1381 }
1382 ));
1383 }
1384
1385 // Normalizes KIS's reference data for one instrument.
1386 //
1387 // The identity comes from the instrument the caller asked about, not from `pdno`:
1388 // KIS returns that zero-padded and prefixed — `00000A000660` for `000660` — so
1389 // parsing a symbol back out of it would be inventing a rule KIS has not stated.
1390 //
1391 // KIS reports a listing date per market rather than one date, and blanks the ones
1392 // that do not apply, so the date is taken from the market the instrument is listed
1393 // on. It publishes no listing *status* at all, so `status_` stays `UNKNOWN` rather
1394 // than being inferred from the presence of a delisting date — a future delisting
1395 // date belongs to an instrument that is still trading.
1396 //
1397 // `price_rule_` is the library's own grid: the quote's `aspr_unit` is the tick at one price, not
1398 // the ladder.
1399 static Result<Instrument> parse_instrument(InstrumentId requested, Result<network::HttpResponse> result) {
1400 auto document = market_document(std::move(result));
1401 if (!document) {
1402 return Result<Instrument>(std::move(document.error()));
1403 }
1404 try {
1405 const auto output = document.value().if_contains("output");
1406 if (!output || !output->is_object()) {
1407 throw std::runtime_error("missing object field: output");
1408 }
1409 const auto& row = output->as_object();
1410
1411 Instrument instrument;
1412 instrument.id_ = std::move(requested);
1413 instrument.name_ = broker_detail::json_string(row, "prdt_name");
1414 instrument.english_name_ = broker_detail::json_string(row, "prdt_eng_name");
1415 // KIS's 표준상품번호 is the KRX standard code, which is also the ISIN. KIS does not
1416 // say so in as many words, but it documents the field as twelve characters for
1417 // both domestic and foreign instruments, which is the ISIN's length and not the
1418 // length of any domestic-only code.
1419 instrument.isin_ = broker_detail::json_string(row, "std_pdno");
1420 const auto market = broker_detail::json_string(row, "mket_id_cd");
1421 instrument.segment_ = kis_market_segment(market);
1422 instrument.type_ = kis_security_type(broker_detail::json_string(row, "scty_grp_id_cd"));
1423 instrument.currency_ = Currency::krw();
1424 instrument.shares_outstanding_ = positive_decimal(row, "lstg_stqt");
1425 instrument.listed_on_ = compact_date_field(row, listing_date_field(market));
1426 instrument.delisted_on_ = compact_date_field(row, delisting_date_field(market));
1427 instrument.price_rule_ = krx::price_rule_for(instrument.type_);
1428 return Result<Instrument>(std::move(instrument));
1429 } catch (const std::exception& exception) {
1430 BrokerError error;
1431 error.category_ = ErrorCategory::PROTOCOL;
1432 error.broker_code_ = "invalid_reference_response";
1433 error.message_ = exception.what();
1434 return Result<Instrument>(std::move(error));
1435 }
1436 }
1437
1438 // Maps KIS's market identifier, preserving one this library has not normalized.
1439 static MarketSegment kis_market_segment(std::string_view code) {
1440 if (code == "STK") {
1441 return market_segment("KOSPI");
1442 }
1443 if (code == "KSQ") {
1444 return market_segment("KOSDAQ");
1445 }
1446 // KONEX has no normalized segment, so its own code is preserved instead of
1447 // being collapsed into one of the two that do.
1448 return market_segment(code);
1449 }
1450
1451 // Maps KIS's security group to a normalized type.
1452 //
1453 // KIS's group covers instruments far beyond equities — futures, options, gold,
1454 // ship-investment companies — and the ones with no normalized counterpart stay
1455 // `UNKNOWN` rather than being forced into a nearby value. An ELW is the notable
1456 // one: it is a warrant, but not the 신주인수권 Toss's `STOCK_WARRANTS` means.
1457 static SecurityType kis_security_type(std::string_view group) {
1458 if (group == "ST" || group == "KN") {
1459 return SecurityType::STOCK;
1460 }
1461 if (group == "FS") {
1462 return SecurityType::FOREIGN_STOCK;
1463 }
1464 if (group == "DR") {
1465 return SecurityType::DEPOSITARY_RECEIPT;
1466 }
1467 if (group == "IF") {
1468 return SecurityType::INFRASTRUCTURE_FUND;
1469 }
1470 if (group == "RT") {
1471 return SecurityType::REIT;
1472 }
1473 if (group == "EF") {
1474 return SecurityType::ETF;
1475 }
1476 if (group == "FE") {
1477 return SecurityType::FOREIGN_ETF;
1478 }
1479 if (group == "EN") {
1480 return SecurityType::ETN;
1481 }
1482 if (group == "SW" || group == "SR") {
1483 return SecurityType::STOCK_WARRANT;
1484 }
1485 return SecurityType::UNKNOWN;
1486 }
1487
1488 // Returns which listing-date column applies to `market`.
1489 static const char* listing_date_field(std::string_view market) {
1490 if (market == "KSQ") {
1491 return "kosdaq_mket_lstg_dt";
1492 }
1493 if (market == "STK") {
1494 return "scts_mket_lstg_dt";
1495 }
1496 return "frbd_mket_lstg_dt";
1497 }
1498
1499 // Returns which delisting-date column applies to `market`.
1500 static const char* delisting_date_field(std::string_view market) {
1501 if (market == "KSQ") {
1502 return "kosdaq_mket_lstg_abol_dt";
1503 }
1504 if (market == "STK") {
1505 return "scts_mket_lstg_abol_dt";
1506 }
1507 return "frbd_mket_lstg_abol_dt";
1508 }
1509
1510 // Reads a `YYYYMMDD` field that KIS blanks when it does not apply.
1511 //
1512 // Three answers. **Not stated**: the key is absent, `null`, `""` -- the `주식기본조회` sheet's own
1513 // example for an inapplicable date -- or `"00000000"`. The last is an inference, not a documented
1514 // convention for this sheet: the same workbook uses `"00000000"` as its no-date value in
1515 // `장내채권 기본조회` and `해외주식 상품기본정보`, and a zero date is no calendar date under any
1516 // reading, so treating it as KIS's blank invents nothing that could be mistaken for a date.
1517 // **Stated**: eight ASCII digits forming a real date. **Unreadable**: anything else, including a
1518 // value that is not a string.
1519 //
1520 // Every character is checked as a digit before any arithmetic. This used `std::stoi` per
1521 // component, which takes a numeric prefix, so `"1996122x"` read as 1996-12-02 -- a different,
1522 // valid date instead of an unreadable one.
1523 static StatedDate compact_date_field(const json::object& row, std::string_view key) {
1524 const auto value = row.if_contains(key);
1525 if (!value || value->is_null()) {
1526 return StatedDate{};
1527 }
1528 if (!value->is_string()) {
1529 return StatedDate::unreadable();
1530 }
1531 const std::string_view text(value->as_string());
1532 if (text.empty() || text == "00000000") {
1533 return StatedDate{};
1534 }
1535 const auto date = broker_detail::compact_date(text);
1536 return date ? StatedDate::stated(*date) : StatedDate::unreadable();
1537 }
1538
1539 // One calendar request spanning however many continuation pages it needs.
1540 struct CalendarOperation {
1541 Date from_{};
1542 TradingCalendar calendar_;
1543 std::string search_cursor_;
1544 std::string next_cursor_;
1545 int pages_{0};
1546 CalendarHandler completion_;
1547
1548 CalendarOperation(Date from, CalendarHandler completion) : from_(from), completion_(std::move(completion)) {}
1549 };
1550
1551 // Most continuation pages one calendar request may consume.
1552 static constexpr int calendar_page_budget_ = 20;
1553
1554 // Answers from the cache when it covers `from`, and otherwise fetches once.
1555 //
1556 // The cache exists because of the broker's once-a-day request, not as an
1557 // optimization, so it is consulted before anything else and is only bypassed when
1558 // the caller asks for a refresh explicitly.
1559 void start_calendar(Date from, bool refresh, CalendarHandler completion) {
1560 if (!is_valid_date(from)) {
1561 BrokerError error;
1562 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1563 error.reached_broker_ = false;
1564 error.broker_code_ = "invalid_date";
1565 error.message_ = "calendar request requires a valid Gregorian date";
1566 deliver(std::move(completion), Result<TradingCalendar>(std::move(error)));
1567 return;
1568 }
1569 if (!refresh && calendar_covers(calendar_, from)) {
1570 deliver(std::move(completion), Result<TradingCalendar>(calendar_));
1571 return;
1572 }
1573
1574 auto operation = std::make_shared<CalendarOperation>(from, std::move(completion));
1575 operation->calendar_.country_ = Country::KR;
1576 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
1577 if (token_error) {
1578 self->deliver(std::move(operation->completion_), Result<TradingCalendar>(std::move(*token_error)));
1579 return;
1580 }
1581 self->request_calendar(operation);
1582 }));
1583 }
1584
1585 // Returns whether the cached calendar already answers for `from` onwards.
1586 static bool calendar_covers(const TradingCalendar& calendar, const Date& from) {
1587 const auto covered = calendar.covered();
1588 // A row for `from` itself, not only a span around it: a row dropped as unreadable leaves a hole
1589 // inside the span, and serving the cache for that day would keep answering "not covered" at
1590 // every poll without asking KIS again -- so a repaired response could never restore the day.
1591 // This relies on KIS listing *every* calendar day, weekends and holidays included, which its
1592 // response does (each row carries a weekday code); a weekend `from` is therefore still covered.
1593 return covered && !(from < covered->first) && !(covered->second < from) &&
1594 calendar.is_trading_day(from).has_value();
1595 }
1596
1597 // How many rows of the listing have been consumed: the days kept and the rows dropped as
1598 // unreadable. Pagination measures progress by this, not by days kept alone.
1599 static std::size_t calendar_rows_consumed(const TradingCalendar& calendar) {
1600 return calendar.days_.size() + calendar.unreadable_days_;
1601 }
1602
1603 // Sends one calendar page, continuing from the cursors KIS returned.
1604 void request_calendar(const std::shared_ptr<CalendarOperation>& operation) {
1605 network::HttpRequest request;
1606 // The calendar is reference data, the lowest-priority traffic there is.
1607 request.group_ = network::RateLimitGroup::REFERENCE;
1608 request.method_ = http::verb::get;
1609 request.target_ = "/uapi/domestic-stock/v1/quotations/chk-holiday?BASS_DT=" + compact_date(operation->from_) +
1610 "&CTX_AREA_NK=" + broker_detail::query_encode(operation->next_cursor_) +
1611 "&CTX_AREA_FK=" + broker_detail::query_encode(operation->search_cursor_);
1612 request.headers_ = {
1613 {"authorization", "Bearer " + token_.access_token_},
1614 {"appkey", config_.key()},
1615 {"appsecret", config_.secret()},
1616 {"tr_id", "CTCA0903R"},
1617 {"tr_cont", operation->pages_ == 0 ? "" : "N"},
1618 {"custtype", "P"},
1619 {"content-type", "application/json; charset=utf-8"},
1620 };
1621
1622 ++operation->pages_;
1623 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
1624 self->handle_calendar_page(operation, std::move(result));
1625 });
1626 }
1627
1628 // Accumulates one page and either continues or finishes and caches.
1629 void handle_calendar_page(const std::shared_ptr<CalendarOperation>& operation, Result<network::HttpResponse> result) {
1630 // Progress is rows *consumed*, not rows kept: a page whose every date was unreadable adds no
1631 // day, and reading that as the end of the listing would drop the pages after it -- today's row
1632 // among them, possibly.
1633 const auto before = calendar_rows_consumed(operation->calendar_);
1634 const bool more = result && continuation_pending(result.value());
1635 std::string search = operation->search_cursor_;
1636 std::string next = operation->next_cursor_;
1637
1638 if (auto failure = parse_calendar_page(std::move(result), operation->calendar_, search, next)) {
1639 deliver(std::move(operation->completion_), Result<TradingCalendar>(std::move(*failure)));
1640 return;
1641 }
1642
1643 const bool empty_page = calendar_rows_consumed(operation->calendar_) == before;
1644 const bool repeated = next == operation->next_cursor_ && search == operation->search_cursor_;
1645 if (!more || empty_page || repeated || operation->pages_ >= calendar_page_budget_) {
1646 operation->calendar_.received_at_ = std::chrono::system_clock::now();
1647 calendar_ = operation->calendar_;
1648 deliver(std::move(operation->completion_), Result<TradingCalendar>(calendar_));
1649 return;
1650 }
1651
1652 operation->search_cursor_ = std::move(search);
1653 operation->next_cursor_ = std::move(next);
1654 request_calendar(operation);
1655 }
1656
1657 // Parses one calendar page.
1658 //
1659 // KIS reports four related flags per date — a banking business day, a securities
1660 // business day, a market-open day, and a settlement day. Only `opnd_yn` is
1661 // normalized, because it is the one KIS itself directs callers to use before
1662 // placing an order: "주문을 넣고자 할 경우 개장일여부(opnd_yn)를 사용". The other three
1663 // stay unread rather than being folded into one meaning.
1664 //
1665 // **A row whose `bass_dt` is not a readable date produces no day and is counted** in
1666 // `TradingCalendar::unreadable_days_`. The sheet documents `bass_dt` as required, eight characters,
1667 // `YYYYMMDD`, so there is no blank to honour: empty, absent, non-string, a wrong length, a numeric
1668 // prefix and an impossible day are all damage. Dropping the row rather than failing the page is
1669 // deliberate -- a page carries weeks, and failing it for one future row would lose today's row with
1670 // it. Rows are staged and appended only once the whole page parses, so a page that does fail
1671 // leaves `calendar` as it was.
1672 static std::optional<BrokerError> parse_calendar_page(
1673 Result<network::HttpResponse> result, TradingCalendar& calendar, std::string& search_cursor,
1674 std::string& next_cursor
1675 ) {
1676 auto document = market_document(std::move(result));
1677 if (!document) {
1678 return std::move(document.error());
1679 }
1680 try {
1681 const auto rows = document.value().if_contains("output");
1682 if (!rows || !rows->is_array()) {
1683 throw std::runtime_error("missing array field: output");
1684 }
1685 std::vector<TradingDay> staged;
1686 std::size_t unreadable = 0;
1687 for (const auto& value : rows->as_array()) {
1688 if (!value.is_object()) {
1689 throw std::runtime_error("calendar entry is not an object");
1690 }
1691 const auto& row = value.as_object();
1692 const auto stated = row.if_contains("bass_dt");
1693 const auto date =
1694 stated && stated->is_string() ? broker_detail::compact_date(stated->as_string()) : std::nullopt;
1695 if (!date) {
1696 ++unreadable;
1697 continue;
1698 }
1699 TradingDay day;
1700 day.date_ = *date;
1701 day.open_ = broker_detail::json_string(row, "opnd_yn") == "Y";
1702 staged.push_back(day);
1703 }
1704 read_calendar_cursors(document.value(), search_cursor, next_cursor);
1705 calendar.days_.insert(calendar.days_.end(), staged.begin(), staged.end());
1706 calendar.unreadable_days_ += unreadable;
1707 return std::nullopt;
1708 } catch (const std::exception& exception) {
1709 BrokerError error;
1710 error.category_ = ErrorCategory::PROTOCOL;
1711 error.broker_code_ = "invalid_calendar_response";
1712 error.message_ = exception.what();
1713 return error;
1714 }
1715 }
1716
1717 // Reads the calendar continuation cursors, which KIS names without the 100 suffix.
1718 static void read_calendar_cursors(
1719 const json::object& document, std::string& search_cursor, std::string& next_cursor
1720 ) {
1721 if (const auto value = document.if_contains("ctx_area_fk"); value && value->is_string()) {
1722 search_cursor = std::string(value->as_string());
1723 }
1724 if (const auto value = document.if_contains("ctx_area_nk"); value && value->is_string()) {
1725 next_cursor = std::string(value->as_string());
1726 }
1727 }
1728
1729 // Issues one authenticated market-data GET for a single instrument.
1730 //
1731 // The single-instrument reads differ only in path, transaction id, and parser, so
1732 // the validation, token handling, and traffic class live here once.
1733 template <typename Handler, typename Parse>
1734 void start_market_read(
1735 InstrumentId instrument, std::string path, std::string transaction, Handler completion, Parse parse
1736 ) {
1737 using ResultType = decltype(parse(InstrumentId{}, Result<network::HttpResponse>(BrokerError{})));
1738 if (instrument.country_ != Country::KR || !valid_domestic_symbol(instrument.symbol_)) {
1739 BrokerError error;
1740 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1741 error.reached_broker_ = false;
1742 error.broker_code_ = "invalid_instrument";
1743 error.message_ = "KIS market data covers Korean equities addressed by product number";
1744 deliver(std::move(completion), ResultType(std::move(error)));
1745 return;
1746 }
1747
1748 ensure_token(TokenHandler(
1749 [self = shared_from_this(), instrument = std::move(instrument), path = std::move(path),
1750 transaction = std::move(transaction), completion = std::move(completion),
1751 parse](std::optional<BrokerError> token_error) mutable {
1752 if (token_error) {
1753 self->deliver(std::move(completion), ResultType(std::move(*token_error)));
1754 return;
1755 }
1756 network::HttpRequest request;
1757 // Market data is the traffic the trading reserve holds back.
1758 request.group_ = network::RateLimitGroup::MARKET_DATA;
1759 request.method_ = http::verb::get;
1760 request.target_ = path + market_query(self->config_, instrument.symbol_);
1761 request.headers_ = {
1762 {"authorization", "Bearer " + self->token_.access_token_},
1763 {"appkey", self->config_.key()},
1764 {"appsecret", self->config_.secret()},
1765 {"tr_id", transaction},
1766 {"custtype", "P"},
1767 {"content-type", "application/json; charset=utf-8"},
1768 };
1769 self->send(
1770 std::move(request),
1771 [self, instrument = std::move(instrument), completion = std::move(completion),
1772 parse](Result<network::HttpResponse> result) mutable {
1773 self->deliver(std::move(completion), parse(std::move(instrument), std::move(result)));
1774 }
1775 );
1776 }
1777 ));
1778 }
1779
1780 // Returns a market-data response's declared payload, or the error ending it.
1781 //
1782 // Applies the HTTP status check, the JSON parse, and KIS's own `rt_cd` before a
1783 // parser looks at any field, so a declared failure is never read as data.
1784 static Result<json::object> market_document(Result<network::HttpResponse> response) {
1785 if (!response) {
1786 return Result<json::object>(std::move(response.error()));
1787 }
1788 if (response.value().result_int() < 200 || response.value().result_int() >= 300) {
1789 return Result<json::object>(kis_http_error(response.value()));
1790 }
1791 BrokerError parse_error;
1792 auto document = broker_detail::parse_object(response.value(), parse_error);
1793 if (!document) {
1794 return Result<json::object>(std::move(parse_error));
1795 }
1796 try {
1797 if (auto declared = kis_declared_error(*document)) {
1798 return Result<json::object>(std::move(*declared));
1799 }
1800 } catch (const std::exception& exception) {
1801 BrokerError error;
1802 error.category_ = ErrorCategory::PROTOCOL;
1803 error.broker_code_ = "invalid_market_response";
1804 error.message_ = exception.what();
1805 return Result<json::object>(std::move(error));
1806 }
1807 return Result<json::object>(std::move(*document));
1808 }
1809
1810 // Normalizes KIS's price bounds from its current-price inquiry.
1811 //
1812 // KRX sets a limit on every listed equity, so both bounds are expected here; a
1813 // blank or zero bound is reported as absent rather than as a bound of nothing.
1814 static Result<PriceLimits> parse_price_limits(InstrumentId instrument, Result<network::HttpResponse> result) {
1815 static_cast<void>(instrument);
1816 auto document = market_document(std::move(result));
1817 if (!document) {
1818 return Result<PriceLimits>(std::move(document.error()));
1819 }
1820 try {
1821 const auto output = document.value().if_contains("output");
1822 if (!output || !output->is_object()) {
1823 throw std::runtime_error("missing object field: output");
1824 }
1825 const auto& row = output->as_object();
1826 PriceLimits limits;
1827 limits.currency_ = Currency::krw();
1828 limits.upper_ = positive_decimal(row, "stck_mxpr");
1829 limits.lower_ = positive_decimal(row, "stck_llam");
1830 return Result<PriceLimits>(std::move(limits));
1831 } catch (const std::exception& exception) {
1832 BrokerError error;
1833 error.category_ = ErrorCategory::PROTOCOL;
1834 error.broker_code_ = "invalid_price_limit_response";
1835 error.message_ = exception.what();
1836 return Result<PriceLimits>(std::move(error));
1837 }
1838 }
1839
1840 // Reads a decimal that KIS leaves blank or zero when it has no value.
1841 static std::optional<Decimal64> positive_decimal(const json::object& row, std::string_view key) {
1842 const auto value = row.if_contains(key);
1843 if (!value || !value->is_string()) {
1844 return std::nullopt;
1845 }
1846 const std::string text(value->as_string());
1847 if (text.empty()) {
1848 return std::nullopt;
1849 }
1850 const auto parsed = Decimal64::parse(text);
1851 if (parsed.coefficient() == 0) {
1852 return std::nullopt;
1853 }
1854 return parsed;
1855 }
1856
1857 // Normalizes KIS's recent executions, newest first as KIS sends them.
1858 //
1859 // KIS reports an execution's time as `HHMMSS` with no date, so the KST calendar
1860 // day is supplied from the clock. A print is intraday by construction, so this is
1861 // the day it happened on.
1862 static Result<std::vector<TradePrint>> parse_trades(
1863 InstrumentId instrument, Result<network::HttpResponse> result, int count
1864 ) {
1865 static_cast<void>(instrument);
1866 auto document = market_document(std::move(result));
1867 if (!document) {
1868 return Result<std::vector<TradePrint>>(std::move(document.error()));
1869 }
1870 try {
1871 const auto rows = document.value().if_contains("output");
1872 if (!rows || !rows->is_array()) {
1873 throw std::runtime_error("missing array field: output");
1874 }
1875 Date today{};
1876 std::string ignored;
1877 korea_calendar(std::chrono::system_clock::now(), today, ignored);
1878 const auto date = compact_date(today);
1879
1880 std::vector<TradePrint> prints;
1881 prints.reserve(rows->as_array().size());
1882 for (const auto& value : rows->as_array()) {
1883 if (!value.is_object()) {
1884 throw std::runtime_error("execution entry is not an object");
1885 }
1886 const auto& row = value.as_object();
1887 const auto time = broker_detail::json_string(row, "stck_cntg_hour");
1888 // KIS pads a short window with blank rows rather than shortening it.
1889 if (time.empty()) {
1890 continue;
1891 }
1892 TradePrint print;
1893 print.price_ = Decimal64::parse(broker_detail::json_string(row, "stck_prpr"));
1894 print.quantity_ = Decimal64::parse(broker_detail::json_string(row, "cntg_vol"));
1895 print.currency_ = Currency::krw();
1896 print.exchange_time_ = korea_timestamp(date, time);
1897 if (!print.exchange_time_) {
1898 throw std::runtime_error("invalid execution time");
1899 }
1900 prints.push_back(std::move(print));
1901 if (count > 0 && static_cast<int>(prints.size()) >= count) {
1902 break;
1903 }
1904 }
1905 return Result<std::vector<TradePrint>>(std::move(prints));
1906 } catch (const std::exception& exception) {
1907 BrokerError error;
1908 error.category_ = ErrorCategory::PROTOCOL;
1909 error.broker_code_ = "invalid_execution_response";
1910 error.message_ = exception.what();
1911 return Result<std::vector<TradePrint>>(std::move(error));
1912 }
1913 }
1914
1915 // Validates the instrument and requests its book.
1916 void start_depth(InstrumentId instrument, DepthHandler completion) {
1917 if (instrument.country_ != Country::KR || !valid_domestic_symbol(instrument.symbol_)) {
1918 BrokerError error;
1919 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1920 error.reached_broker_ = false;
1921 error.broker_code_ = "invalid_instrument";
1922 error.message_ = "KIS order book covers Korean equities addressed by product number";
1923 deliver(std::move(completion), Result<DepthSnapshot>(std::move(error)));
1924 return;
1925 }
1926
1927 ensure_token(TokenHandler(
1928 [self = shared_from_this(), instrument = std::move(instrument),
1929 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1930 if (token_error) {
1931 self->deliver(std::move(completion), Result<DepthSnapshot>(std::move(*token_error)));
1932 return;
1933 }
1934 network::HttpRequest request;
1935 // The book is polling traffic, held back by the trading reserve.
1936 request.group_ = network::RateLimitGroup::MARKET_DATA;
1937 request.method_ = http::verb::get;
1938 request.target_ = "/uapi/domestic-stock/v1/quotations/inquire-asking-price-exp-ccn" +
1939 market_query(self->config_, instrument.symbol_);
1940 request.headers_ = {
1941 {"authorization", "Bearer " + self->token_.access_token_},
1942 {"appkey", self->config_.key()},
1943 {"appsecret", self->config_.secret()},
1944 {"tr_id", "FHKST01010200"},
1945 {"custtype", "P"},
1946 {"content-type", "application/json; charset=utf-8"},
1947 };
1948 self->send(
1949 std::move(request),
1950 [self, instrument = std::move(instrument),
1951 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1952 self->deliver(std::move(completion), parse_depth(std::move(instrument), std::move(result)));
1953 }
1954 );
1955 }
1956 ));
1957 }
1958
1959 // Normalizes one KIS order book.
1960 //
1961 // KIS numbers its levels into flat fields — `askp1` through `askp10` with
1962 // `askp_rsqn1` through `askp_rsqn10`, and the same for bids — rather than sending
1963 // arrays. A level whose price is absent, blank, or zero is a level that is not
1964 // resting, and is skipped rather than recorded as an offer at nothing.
1965 //
1966 // The after-hours totals KIS also reports (`ovtm_total_askp_rsqn` and its
1967 // siblings) and its expected-execution columns are deliberately not normalized:
1968 // Toss publishes no counterpart. They are dropped here, not exposed.
1969 static Result<DepthSnapshot> parse_depth(InstrumentId instrument, Result<network::HttpResponse> result) {
1970 if (!result) {
1971 return Result<DepthSnapshot>(std::move(result.error()));
1972 }
1973 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
1974 return Result<DepthSnapshot>(kis_http_error(result.value()));
1975 }
1976 BrokerError parse_error;
1977 auto document = broker_detail::parse_object(result.value(), parse_error);
1978 if (!document) {
1979 return Result<DepthSnapshot>(std::move(parse_error));
1980 }
1981 try {
1982 if (auto declared = kis_declared_error(*document)) {
1983 return Result<DepthSnapshot>(std::move(*declared));
1984 }
1985 const auto output = document->if_contains("output1");
1986 if (!output || !output->is_object()) {
1987 throw std::runtime_error("missing object field: output1");
1988 }
1989 const auto& row = output->as_object();
1990
1991 DepthSnapshot book;
1992 book.instrument_ = std::move(instrument);
1993 book.currency_ = Currency::krw();
1994 for (int level = 1; level <= depth_levels_; ++level) {
1995 append_level(row, "askp", "askp_rsqn", level, book.asks_);
1996 append_level(row, "bidp", "bidp_rsqn", level, book.bids_);
1997 }
1998 order_depth(book);
1999 if (const auto hour = row.if_contains("aspr_acpt_hour"); hour && hour->is_string()) {
2000 const std::string time(hour->as_string());
2001 Date today{};
2002 std::string ignored;
2003 korea_calendar(std::chrono::system_clock::now(), today, ignored);
2004 book.exchange_time_ = korea_timestamp(compact_date(today), time);
2005 }
2006 book.received_at_ = std::chrono::system_clock::now();
2007 return Result<DepthSnapshot>(std::move(book));
2008 } catch (const std::exception& exception) {
2009 BrokerError error;
2010 error.category_ = ErrorCategory::PROTOCOL;
2011 error.broker_code_ = "invalid_orderbook_response";
2012 error.message_ = exception.what();
2013 return Result<DepthSnapshot>(std::move(error));
2014 }
2015 }
2016
2017 // How many resting levels KIS publishes on each side.
2018 static constexpr int depth_levels_ = 10;
2019
2020 // Reads one numbered level, skipping a level that is not resting.
2021 static void append_level(
2022 const json::object& row, std::string_view price_prefix, std::string_view quantity_prefix, int level,
2023 std::vector<DepthLevel>& levels
2024 ) {
2025 const auto suffix = std::to_string(level);
2026 const auto price = row.if_contains(std::string(price_prefix) + suffix);
2027 const auto quantity = row.if_contains(std::string(quantity_prefix) + suffix);
2028 if (!price || !price->is_string() || !quantity || !quantity->is_string()) {
2029 return;
2030 }
2031 const std::string price_text(price->as_string());
2032 const std::string quantity_text(quantity->as_string());
2033 if (price_text.empty() || quantity_text.empty()) {
2034 return;
2035 }
2036 const auto value = Decimal64::parse(price_text);
2037 if (value.coefficient() == 0) {
2038 return;
2039 }
2040 levels.push_back(DepthLevel{value, Decimal64::parse(quantity_text)});
2041 }
2042
2043 void start_quote(InstrumentId instrument, QuoteHandler completion) {
2044 if (instrument.country_ != Country::KR || !broker_detail::valid_symbol(instrument.symbol_)) {
2045 BrokerError error;
2046 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2047 error.reached_broker_ = false;
2048 error.broker_code_ = "invalid_instrument";
2049 error.message_ = "KIS quote currently supports Korean equity symbols only";
2050 complete(std::move(completion), Result<QuoteSnapshot>(std::move(error)));
2051 return;
2052 }
2053
2054 ensure_token(TokenHandler(
2055 [self = shared_from_this(), instrument = std::move(instrument),
2056 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2057 if (token_error) {
2058 self->complete(std::move(completion), Result<QuoteSnapshot>(std::move(*token_error)));
2059 return;
2060 }
2061 self->request_quote(std::move(instrument), std::move(completion));
2062 }
2063 ));
2064 }
2065
2066 void start_buying_power(Currency currency, KisAccount account, BuyingPowerHandler completion) {
2067 auto invalid = validate_account(account);
2068 if (!invalid && !(currency == Currency::krw())) {
2069 // The domestic inquiry answers in won. Answering a dollar request with a won figure under a
2070 // dollar label is a silent downgrade, which this library refuses, and KIS's foreign-currency
2071 // buying power is a different endpoint answering a different question.
2072 BrokerError error;
2073 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2074 error.reached_broker_ = false;
2075 error.broker_code_ = "unsupported_currency";
2076 error.message_ = "the KIS domestic buying-power inquiry answers in KRW only, not " + currency.str();
2077 invalid = std::move(error);
2078 }
2079 if (invalid) {
2080 complete_buying_power(std::move(completion), Result<BuyingPower>(std::move(*invalid)));
2081 return;
2082 }
2083 ensure_token(TokenHandler(
2084 [self = shared_from_this(), account = std::move(account),
2085 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2086 if (token_error) {
2087 self->complete_buying_power(std::move(completion), Result<BuyingPower>(std::move(*token_error)));
2088 return;
2089 }
2090 self->request_buying_power(std::move(account), std::move(completion));
2091 }
2092 ));
2093 }
2094
2095 void request_buying_power(KisAccount account, BuyingPowerHandler completion) {
2096 send(
2097 buying_power_request(config_, token_.access_token_, account),
2098 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2099 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
2100 self->complete_buying_power(std::move(completion), parse_buying_power(std::move(result)));
2101 });
2102 }
2103 );
2104 }
2105
2106 // Builds the account-level buying-power request.
2107 //
2108 // **`PDNO` and `ORD_UNPR` are deliberately empty**, which is how KIS is asked for the amount
2109 // without a quantity: "PDNO, ORD_UNPR 공란 입력 시, 매수수량 없이 매수금액만 조회됨". Both are
2110 // marked required, so they are sent as empty values rather than omitted.
2111 //
2112 // `ORD_DVSN` is `01`, market. The division only shapes the *quantity* answer, through the
2113 // instrument's margin rate, and no quantity is being asked for here -- but the field is required,
2114 // and `01` is the one KIS's own documentation tells a caller to use when the answer must reflect
2115 // margin rather than ignore it.
2116 //
2117 // `CMA_EVLU_AMT_ICLD_YN` and `OVRS_ICLD_YN` are both `N`, and that is a decision rather than a
2118 // default. Including a CMA valuation or overseas balances would make the figure larger than the
2119 // won an order can actually spend, and a buying-power check exists to be conservative. A caller
2120 // wanting the wider figure asks this client directly.
2121 static network::HttpRequest buying_power_request(
2122 const KisConfig& config, std::string_view access_token, const KisAccount& account
2123 ) {
2124 network::HttpRequest request;
2125 request.group_ = network::RateLimitGroup::ACCOUNT;
2126 request.method_ = http::verb::get;
2127 request.target_ =
2128 "/uapi/domestic-stock/v1/trading/inquire-psbl-order"
2129 "?CANO=" +
2130 account.account_number_ + "&ACNT_PRDT_CD=" + account.product_code_ +
2131 "&PDNO=&ORD_UNPR=&ORD_DVSN=01&CMA_EVLU_AMT_ICLD_YN=N&OVRS_ICLD_YN=N";
2132 request.headers_ = {
2133 {"authorization", "Bearer " + std::string(access_token)},
2134 {"appkey", config.key()},
2135 {"appsecret", config.secret()},
2136 {"tr_id", config.is_demo_ ? "VTTC8908R" : "TTTC8908R"},
2137 {"custtype", "P"},
2138 {"content-type", "application/json; charset=utf-8"},
2139 };
2140 return request;
2141 }
2142
2143 // Normalizes KIS's buying power.
2144 //
2145 // **`nrcvb_buy_amt` is the field, not `max_buy_amt`.** The 미수-free amount is what Toss's
2146 // `cashBuyingPower` means -- both answer "what can be bought without credit" -- while the maximum
2147 // includes 미수 and means something the other broker never reports. Normalizing the larger number
2148 // would make one library type mean cash at one broker and cash-plus-credit at the other, which is
2149 // exactly what a broker-neutral type must not do, and it would do it in the direction that
2150 // permits more.
2151 static Result<BuyingPower> parse_buying_power(Result<network::HttpResponse> response) {
2152 auto document = market_document(std::move(response));
2153 if (!document) {
2154 return Result<BuyingPower>(std::move(document.error()));
2155 }
2156 try {
2157 const auto output = document.value().if_contains("output");
2158 if (!output || !output->is_object()) {
2159 throw std::runtime_error("missing object field: output");
2160 }
2161 BuyingPower power;
2162 power.cash_ = Money{
2163 Decimal64::parse(broker_detail::json_string(output->as_object(), "nrcvb_buy_amt")),
2164 Currency::krw(),
2165 };
2166 // KIS states no timestamp for the figure, so the honest stamp is when it arrived.
2167 power.received_at_ = std::chrono::system_clock::now();
2168 return Result<BuyingPower>(std::move(power));
2169 } catch (const std::exception& exception) {
2170 BrokerError error;
2171 error.category_ = ErrorCategory::PROTOCOL;
2172 error.broker_code_ = "invalid_buying_power_response";
2173 error.message_ = exception.what();
2174 return Result<BuyingPower>(std::move(error));
2175 }
2176 }
2177
2178 void complete_buying_power(BuyingPowerHandler handler, Result<BuyingPower> result) {
2179 deliver(std::move(handler), std::move(result));
2180 }
2181
2182 void start_holdings(KisAccount account, HoldingsHandler completion) {
2183 if (auto invalid = validate_account(account)) {
2184 complete_holdings(std::move(completion), Result<HoldingsSnapshot>(std::move(*invalid)));
2185 return;
2186 }
2187
2188 auto operation = std::make_shared<HoldingsOperation>(std::move(account), std::move(completion));
2189 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
2190 if (token_error) {
2191 self->finish_holdings(operation, Result<HoldingsSnapshot>(std::move(*token_error)));
2192 return;
2193 }
2194 self->request_holdings(operation);
2195 }));
2196 }
2197
2198 // Lets a request through with a valid token, and otherwise requests one, unless a store manages the
2199 // token: one requested here, mid-call, would bypass the store's lock, so the call fails locally instead.
2200 // With a store, the token's validity is read once and nothing past this branch reads it again.
2201 void ensure_token(TokenHandler handler) {
2202 if (store_managed_) {
2203 if (token_.valid()) {
2204 std::move(handler)(std::nullopt);
2205 } else {
2206 std::move(handler)(network::token_unusable_error());
2207 }
2208 return;
2209 }
2210 request_token(std::move(handler));
2211 }
2212
2213 void request_token(TokenHandler handler) {
2214 if (token_.valid()) {
2215 std::move(handler)(std::nullopt);
2216 return;
2217 }
2218 token_waiters_.push_back(std::move(handler));
2219 if (refreshing_) {
2220 return;
2221 }
2222 refreshing_ = true;
2223
2224 network::HttpRequest request;
2225 // Every other request waits behind a token refresh, including a cancellation.
2226 request.group_ = network::RateLimitGroup::AUTH;
2227 request.method_ = http::verb::post;
2228 request.target_ = "/oauth2/tokenP";
2229 request.body_ = config_.to_jsonbody();
2230 request.headers_.emplace_back("content-type", "application/json");
2231 http_->async_request(std::move(request), [self = shared_from_this()](Result<network::HttpResponse> result) mutable {
2232 net::post(self->strand_, [self, result = std::move(result)]() mutable {
2233 self->finish_token(std::move(result));
2234 });
2235 });
2236 }
2237
2238 void finish_token(Result<network::HttpResponse> result) {
2239 refreshing_ = false;
2240 std::optional<BrokerError> failure;
2241 if (!result) {
2242 failure = std::move(result.error());
2243 } else if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2244 failure = kis_http_error(result.value());
2245 failure->category_ = ErrorCategory::AUTHENTICATION;
2246 } else {
2247 BrokerError parse_error;
2248 auto document = broker_detail::parse_object(result.value(), parse_error);
2249 if (!document) {
2250 failure = std::move(parse_error);
2251 } else {
2252 try {
2253 token_.from_json(*document);
2254 } catch (const std::exception& exception) {
2255 BrokerError error;
2256 error.category_ = ErrorCategory::AUTHENTICATION;
2257 error.broker_code_ = "invalid_token_response";
2258 error.message_ = exception.what();
2259 failure = std::move(error);
2260 }
2261 }
2262 }
2263
2264 if (failure) {
2265 // The waiters asked for something else, and none of their requests was sent. See the same
2266 // marking in the Toss client: an unmarked authentication failure reads to a runner as the
2267 // broker refusing an order it never received, spending rate-limit budget on nothing.
2268 failure->reached_broker_ = false;
2269 }
2270 auto waiters = std::move(token_waiters_);
2271 token_waiters_.clear();
2272 for (auto& waiter : waiters) {
2273 if (failure) {
2274 std::move(waiter)(*failure);
2275 } else {
2276 std::move(waiter)(std::nullopt);
2277 }
2278 }
2279 }
2280
2281 // Returns the query fragment naming the tape to read and the instrument to read.
2282 //
2283 // **Every domestic market-data request in this adapter builds this pair, and after
2284 // this function exists there is exactly one place that does** -- so
2285 // `FID_COND_MRKT_DIV_CODE` appears once in this file rather than six times, and a
2286 // seventh endpoint cannot quietly disagree with the other six about which book it
2287 // reads. That is what went wrong before: five verbs sent `J` unconditionally while
2288 // the quote derived its code from the instrument, so a caller's last price and
2289 // their bars described different markets, and `Context::last_price` -- which the
2290 // exposure ceiling is measured against -- was written from both.
2291 //
2292 // The symbol is percent-encoded here for every caller. The quote path used to
2293 // interpolate it raw; a Korean six-digit code encodes to itself, so this changes
2294 // no request that has ever been sent, and it removes a difference that had no
2295 // reason to exist.
2296 static std::string market_query(const KisConfig& config, const std::string& symbol) {
2297 return "?FID_COND_MRKT_DIV_CODE=" + std::string(market_division_code(config.market_tape_)) +
2298 "&FID_INPUT_ISCD=" + broker_detail::query_encode(symbol);
2299 }
2300
2301 void request_quote(InstrumentId instrument, QuoteHandler completion) {
2302 // **The tape is a setting, not a property of the instrument.** This used to read
2303 // `instrument.venue_`, which made the quote the one verb that honoured it while the
2304 // other six sent `J` -- so a caller's last price and their bars described different
2305 // books. It was also unreachable for anything tradeable: `validate_order` refuses an
2306 // order whose instrument names a venue other than the combined one, so an instrument
2307 // marked KRX or NXT could be quoted and never traded.
2308 network::HttpRequest request;
2309 // Quote polling is the traffic a reserve exists to hold back.
2310 request.group_ = network::RateLimitGroup::MARKET_DATA;
2311 request.method_ = http::verb::get;
2312 request.target_ = "/uapi/domestic-stock/v1/quotations/inquire-price" + market_query(config_, instrument.symbol_);
2313 request.headers_ = {
2314 {"authorization", "Bearer " + token_.access_token_},
2315 {"appkey", config_.key()},
2316 {"appsecret", config_.secret()},
2317 {"tr_id", "FHKST01010100"},
2318 {"custtype", "P"},
2319 {"content-type", "application/json; charset=utf-8"},
2320 };
2321 send(
2322 std::move(request),
2323 [self = shared_from_this(), instrument = std::move(instrument),
2324 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
2325 net::post(
2326 self->strand_,
2327 [self, instrument = std::move(instrument), completion = std::move(completion),
2328 result = std::move(result)]() mutable {
2329 self->complete(std::move(completion), parse_quote(std::move(instrument), std::move(result)));
2330 }
2331 );
2332 }
2333 );
2334 }
2335
2336 void request_holdings(const std::shared_ptr<HoldingsOperation>& operation) {
2337 auto request = make_holdings_request(
2338 operation->account_, config_, token_.access_token_, operation->foreign_cursor_, operation->domestic_cursor_,
2339 operation->page_count_ > 0
2340 );
2341 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
2342 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
2343 self->handle_holdings_page(operation, std::move(result));
2344 });
2345 });
2346 }
2347
2348 static network::HttpRequest make_holdings_request(
2349 const KisAccount& account, const KisConfig& config, std::string_view access_token, std::string_view foreign_cursor,
2350 std::string_view domestic_cursor, bool continuation
2351 ) {
2352 network::HttpRequest request;
2353 // Holdings rank above polling but may not spend the trading reserve.
2354 request.group_ = network::RateLimitGroup::ACCOUNT;
2355 request.method_ = http::verb::get;
2356 request.target_ =
2357 "/uapi/domestic-stock/v1/trading/inquire-balance"
2358 "?CANO=" +
2359 account.account_number_ + "&ACNT_PRDT_CD=" + account.product_code_ +
2360 "&AFHR_FLPR_YN=Y&OFL_YN=&INQR_DVSN=01&UNPR_DVSN=01&FUND_STTL_ICLD_YN=N"
2361 "&FNCG_AMT_AUTO_RDPT_YN=N&PRCS_DVSN=00&CTX_AREA_FK100=" +
2362 broker_detail::query_encode(foreign_cursor) + "&CTX_AREA_NK100=" + broker_detail::query_encode(domestic_cursor);
2363 request.headers_ = {
2364 {"authorization", "Bearer " + std::string(access_token)},
2365 {"appkey", config.key()},
2366 {"appsecret", config.secret()},
2367 {"tr_id", config.is_demo_ ? "VTTC8434R" : "TTTC8434R"},
2368 {"tr_cont", continuation ? "N" : ""},
2369 {"custtype", "P"},
2370 {"content-type", "application/json; charset=utf-8"},
2371 };
2372 return request;
2373 }
2374
2375 static std::optional<BrokerError> append_holdings_page(
2376 HoldingsSnapshot& snapshot, std::size_t& page_count, std::string& foreign_cursor, std::string& domestic_cursor,
2377 HoldingsSnapshot page, std::string next_foreign_cursor, std::string next_domestic_cursor, bool has_next
2378 ) {
2379 if (has_next) {
2380 const bool cursor_did_not_advance =
2381 next_foreign_cursor == foreign_cursor && next_domestic_cursor == domestic_cursor;
2382 if (
2383 page_count + 1 >= 100 || (next_foreign_cursor.empty() && next_domestic_cursor.empty()) || cursor_did_not_advance
2384 ) {
2385 BrokerError error;
2386 error.category_ = ErrorCategory::PROTOCOL;
2387 error.broker_code_ = "invalid_pagination";
2388 error.message_ = "KIS holdings continuation did not advance";
2389 return error;
2390 }
2391 }
2392
2393 snapshot.positions_.insert(
2394 snapshot.positions_.end(), std::make_move_iterator(page.positions_.begin()),
2395 std::make_move_iterator(page.positions_.end())
2396 );
2397 if (!page.totals_.empty()) {
2398 snapshot.totals_ = std::move(page.totals_);
2399 }
2400 ++page_count;
2401 if (has_next) {
2402 foreign_cursor = std::move(next_foreign_cursor);
2403 domestic_cursor = std::move(next_domestic_cursor);
2404 }
2405 return std::nullopt;
2406 }
2407
2408 void handle_holdings_page(const std::shared_ptr<HoldingsOperation>& operation, Result<network::HttpResponse> result) {
2409 if (!result) {
2410 finish_holdings(operation, Result<HoldingsSnapshot>(std::move(result.error())));
2411 return;
2412 }
2413
2414 const auto continuation = result.value().base().find("tr_cont");
2415 const bool has_next =
2416 continuation != result.value().base().end() && (continuation->value() == "M" || continuation->value() == "F");
2417 std::string foreign_cursor;
2418 std::string domestic_cursor;
2419 auto page = parse_holdings_page(std::move(result), foreign_cursor, domestic_cursor);
2420 if (!page) {
2421 finish_holdings(operation, Result<HoldingsSnapshot>(std::move(page.error())));
2422 return;
2423 }
2424
2425 auto pagination_error = append_holdings_page(
2426 operation->snapshot_, operation->page_count_, operation->foreign_cursor_, operation->domestic_cursor_,
2427 std::move(page.value()), std::move(foreign_cursor), std::move(domestic_cursor), has_next
2428 );
2429 if (pagination_error) {
2430 finish_holdings(operation, Result<HoldingsSnapshot>(std::move(*pagination_error)));
2431 return;
2432 }
2433
2434 if (has_next) {
2435 request_holdings(operation);
2436 return;
2437 }
2438
2439 operation->snapshot_.received_at_ = std::chrono::system_clock::now();
2440 // **What `ord_psbl_qty` on these rows is evidence of, and it is a treatment rather than a
2441 // measurement.** The workbook gives 주문가능수량 an empty Description column, so whether the
2442 // figure is already reduced by resting sell orders is unestablished. `DEDUCT` is therefore the conservative rule
2443 // this library applies, not a claim that KIS reports a gross figure: deducting resting sells
2444 // that the broker had also deducted over-refuses a trade, where the other error sells the same
2445 // shares twice. `verified_` stays false to say exactly that nobody has measured it.
2446 operation->snapshot_.sellable_basis_ = SellableBasis{
2447 SellableBasis::Coverage::WHOLE_HOLDING,
2448 SellableBasis::RestingTreatment::DEDUCT,
2449 false,
2450 };
2451 finish_holdings(operation, Result<HoldingsSnapshot>(std::move(operation->snapshot_)));
2452 }
2453
2454 static Result<QuoteSnapshot> parse_quote(InstrumentId instrument, Result<network::HttpResponse> result) {
2455 if (!result) {
2456 return Result<QuoteSnapshot>(std::move(result.error()));
2457 }
2458 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2459 return Result<QuoteSnapshot>(kis_http_error(result.value()));
2460 }
2461 BrokerError parse_error;
2462 auto document = broker_detail::parse_object(result.value(), parse_error);
2463 if (!document) {
2464 return Result<QuoteSnapshot>(std::move(parse_error));
2465 }
2466 try {
2467 const auto result_code = broker_detail::json_string(*document, "rt_cd");
2468 if (result_code != "0") {
2469 BrokerError error;
2470 error.category_ = ErrorCategory::PROTOCOL;
2471 if (const auto code = document->if_contains("msg_cd"); code && code->is_string()) {
2472 error.broker_code_ = code->as_string().c_str();
2473 }
2474 if (const auto message = document->if_contains("msg1"); message && message->is_string()) {
2475 error.message_ = message->as_string().c_str();
2476 }
2477 return Result<QuoteSnapshot>(std::move(error));
2478 }
2479 const auto output = document->if_contains("output");
2480 if (!output || !output->is_object()) {
2481 throw std::runtime_error("missing object field: output");
2482 }
2483 if (
2484 const auto symbol = output->as_object().if_contains("stck_shrn_iscd");
2485 symbol && symbol->is_string() && symbol->as_string() != instrument.symbol_
2486 ) {
2487 throw std::runtime_error("quote response symbol does not match request");
2488 }
2489 QuoteSnapshot quote;
2490 quote.instrument_ = std::move(instrument);
2491 quote.last_price_ = Decimal64::parse(broker_detail::json_string(output->as_object(), "stck_prpr"));
2492 quote.currency_ = Currency::krw();
2493 quote.received_at_ = std::chrono::system_clock::now();
2494 return Result<QuoteSnapshot>(std::move(quote));
2495 } catch (const std::exception& exception) {
2496 BrokerError error;
2497 error.category_ = ErrorCategory::PROTOCOL;
2498 error.broker_code_ = "invalid_quote_response";
2499 error.message_ = exception.what();
2500 return Result<QuoteSnapshot>(std::move(error));
2501 }
2502 }
2503
2504 static Result<HoldingsSnapshot> parse_holdings(Result<network::HttpResponse> result) {
2505 std::string foreign_cursor;
2506 std::string domestic_cursor;
2507 return parse_holdings_page(std::move(result), foreign_cursor, domestic_cursor);
2508 }
2509
2510 static Result<HoldingsSnapshot> parse_holdings_page(
2511 Result<network::HttpResponse> result, std::string& foreign_cursor, std::string& domestic_cursor
2512 ) {
2513 if (!result) {
2514 return Result<HoldingsSnapshot>(std::move(result.error()));
2515 }
2516 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2517 return Result<HoldingsSnapshot>(kis_http_error(result.value()));
2518 }
2519 BrokerError parse_error;
2520 auto document = broker_detail::parse_object(result.value(), parse_error);
2521 if (!document) {
2522 return Result<HoldingsSnapshot>(std::move(parse_error));
2523 }
2524 try {
2525 const auto result_code = broker_detail::json_string(*document, "rt_cd");
2526 if (result_code != "0") {
2527 BrokerError error;
2528 error.category_ = ErrorCategory::PROTOCOL;
2529 if (const auto code = document->if_contains("msg_cd"); code && code->is_string()) {
2530 error.broker_code_ = code->as_string().c_str();
2531 }
2532 if (const auto message = document->if_contains("msg1"); message && message->is_string()) {
2533 error.message_ = message->as_string().c_str();
2534 }
2535 return Result<HoldingsSnapshot>(std::move(error));
2536 }
2537
2538 const auto positions = document->if_contains("output1");
2539 const auto summaries = document->if_contains("output2");
2540 if (!positions || !positions->is_array()) {
2541 throw std::runtime_error("missing array field: output1");
2542 }
2543 if (!summaries || !summaries->is_array()) {
2544 throw std::runtime_error("missing array field: output2");
2545 }
2546
2547 HoldingsSnapshot snapshot;
2548 for (const auto& value : positions->as_array()) {
2549 if (!value.is_object()) {
2550 throw std::runtime_error("output1 item is not an object");
2551 }
2552 const auto& output = value.as_object();
2553 HoldingPosition position;
2554 position.instrument_ = InstrumentId{
2555 Country::KR,
2556 instrument_venue(),
2557 broker_detail::json_string(output, "pdno"),
2558 };
2559 position.name_ = broker_detail::json_string(output, "prdt_name");
2560 position.quantity_ = Decimal64::parse(broker_detail::json_string(output, "hldg_qty"));
2561 position.sellable_quantity_ = Decimal64::parse(broker_detail::json_string(output, "ord_psbl_qty"));
2562 position.average_purchase_price_ = Decimal64::parse(broker_detail::json_string(output, "pchs_avg_pric"));
2563 position.last_price_ = Decimal64::parse(broker_detail::json_string(output, "prpr"));
2564 position.purchase_value_ =
2565 Money{Decimal64::parse(broker_detail::json_string(output, "pchs_amt")), Currency::krw()};
2566 position.market_value_ =
2567 Money{Decimal64::parse(broker_detail::json_string(output, "evlu_amt")), Currency::krw()};
2568 position.unrealized_profit_loss_ =
2569 Money{Decimal64::parse(broker_detail::json_string(output, "evlu_pfls_amt")), Currency::krw()};
2570 position.unrealized_return_ =
2571 broker_detail::percent_to_ratio(broker_detail::json_string(output, "evlu_pfls_rt"));
2572 snapshot.positions_.push_back(std::move(position));
2573 }
2574
2575 if (!summaries->as_array().empty()) {
2576 const auto& value = summaries->as_array().front();
2577 if (!value.is_object()) {
2578 throw std::runtime_error("output2 item is not an object");
2579 }
2580 const auto& output = value.as_object();
2581 snapshot.totals_.push_back(
2582 HoldingsTotals{
2583 Currency::krw(),
2584 Decimal64::parse(broker_detail::json_string(output, "pchs_amt_smtl_amt")),
2585 Decimal64::parse(broker_detail::json_string(output, "evlu_amt_smtl_amt")),
2586 Decimal64::parse(broker_detail::json_string(output, "evlu_pfls_smtl_amt")),
2587 }
2588 );
2589 }
2590
2591 if (const auto value = document->if_contains("ctx_area_fk100"); value && value->is_string()) {
2592 foreign_cursor = value->as_string().c_str();
2593 }
2594 if (const auto value = document->if_contains("ctx_area_nk100"); value && value->is_string()) {
2595 domestic_cursor = value->as_string().c_str();
2596 }
2597 return Result<HoldingsSnapshot>(std::move(snapshot));
2598 } catch (const std::exception& exception) {
2599 BrokerError error;
2600 error.category_ = ErrorCategory::PROTOCOL;
2601 error.broker_code_ = "invalid_holdings_response";
2602 error.message_ = exception.what();
2603 return Result<HoldingsSnapshot>(std::move(error));
2604 }
2605 }
2606
2607 // Mutable state shared across a paginated modifiable-order inquiry.
2608 struct OpenOrderOperation {
2609 KisAccount account_;
2610 KisOpenOrderPage page_;
2611 std::string foreign_cursor_;
2612 std::string domestic_cursor_;
2613 std::size_t page_count_{0};
2614 OpenOrderHandler completion_;
2615
2616 // Captures the selected account and final completion handler.
2617 OpenOrderOperation(KisAccount selected_account, OpenOrderHandler selected_completion)
2618 : account_(std::move(selected_account)), completion_(std::move(selected_completion)) {}
2619 };
2620
2621 // Mutable state shared across a paginated order-history inquiry.
2622 struct OrderHistoryOperation {
2623 KisAccount account_;
2624 KisHistoryRange range_;
2625 OrderPage page_;
2626 std::string foreign_cursor_;
2627 std::string domestic_cursor_;
2628 std::size_t page_count_{0};
2629 OrderPageHandler completion_;
2630
2631 // Captures the inquiry inputs and final completion handler.
2632 OrderHistoryOperation(
2633 KisAccount selected_account, KisHistoryRange selected_range, OrderPageHandler selected_completion
2634 )
2635 : account_(std::move(selected_account)), range_(selected_range), completion_(std::move(selected_completion)) {}
2636 };
2637
2638 // Returns an error when the account selector cannot address a KIS account.
2639 static std::optional<BrokerError> validate_account(const KisAccount& account) {
2640 if (
2641 broker_detail::decimal_digits(account.account_number_, 8) &&
2642 broker_detail::decimal_digits(account.product_code_, 2)
2643 ) {
2644 return std::nullopt;
2645 }
2646 BrokerError error;
2647 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2648 error.reached_broker_ = false;
2649 error.broker_code_ = "invalid_account";
2650 error.message_ = "KIS account number must contain eight digits and product code two digits";
2651 return error;
2652 }
2653
2654 // Returns an error when a quantity is not a positive whole number of shares.
2655 static std::optional<BrokerError> validate_quantity(const Decimal64& quantity) {
2656 if (quantity.coefficient() > 0 && quantity.scale() == 0) {
2657 return std::nullopt;
2658 }
2659 BrokerError error;
2660 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2661 error.reached_broker_ = false;
2662 error.broker_code_ = "invalid_quantity";
2663 error.message_ = "KIS order quantity must be a positive whole number of shares";
2664 return error;
2665 }
2666
2667 // Returns an error when a price does not match its order type.
2668 //
2669 // A limit order without a price and a market order carrying a price are both
2670 // rejected before any network I/O, because either would make the transmitted
2671 // order differ from the one the caller described.
2672 static std::optional<BrokerError> validate_price(OrderType type, const std::optional<Decimal64>& price) {
2673 BrokerError error;
2674 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2675 error.reached_broker_ = false;
2676 error.broker_code_ = "invalid_price";
2677 // `carries_caller_price`, not `== LIMIT`. 조건부지정가 (`02`) is a limit
2678 // instruction until the close and this refused the price it needs while
2679 // admitting one without, which `make_place_order_request` then sent as
2680 // `ORD_UNPR="0"` -- an order at zero rather than at the stated limit.
2681 if (carries_caller_price(type)) {
2682 if (!price) {
2683 error.message_ = "KIS order of this price basis requires a price";
2684 return error;
2685 }
2686 if (price->coefficient() <= 0) {
2687 error.message_ = "KIS order price must be positive";
2688 return error;
2689 }
2690 if (price->scale() != 0) {
2691 error.message_ = "KIS domestic order price must be a whole number of won";
2692 return error;
2693 }
2694 return std::nullopt;
2695 }
2696 if (price) {
2697 error.message_ =
2698 "KIS takes no price for this basis; a market, best-limit, primary-limit, "
2699 "mid-price or closing-price order is priced by the book";
2700 return error;
2701 }
2702 return std::nullopt;
2703 }
2704
2705 // Returns whether `trigger` is a value KIS's `CNDT_PRIC` can carry: positive, whole won.
2706 static bool valid_trigger_value(const Decimal64& trigger) {
2707 return trigger.coefficient() > 0 && trigger.scale() == 0;
2708 }
2709
2710 // Returns an error when a trigger price does not match its order type.
2711 //
2712 // `22` 스톱지정가 needs one -- the 주식주문(현금) sheet documents `CNDT_PRIC` as "스탑지정가호가
2713 // 주문 (ORD_DVSN이 22) 사용 시에만 필수" -- and every other code has nowhere to put one, so a
2714 // trigger stated on it would be dropped and the order sent as something the caller did not
2715 // describe. Neither is sent: a stated condition is honoured or refused, never dropped.
2716 //
2717 // Nothing about the trigger's direction or its relation to the limit is checked: the sheet
2718 // documents neither, and a local rule KIS does not state would refuse orders KIS accepts.
2719 static std::optional<BrokerError> validate_trigger(OrderType type, const std::optional<Decimal64>& trigger) {
2720 BrokerError error;
2721 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2722 error.reached_broker_ = false;
2723 error.broker_code_ = "invalid_trigger_price";
2724 if (carries_trigger_price(type)) {
2725 if (!trigger) {
2726 error.message_ = "a KIS stop-limit order (22) requires a trigger price in CNDT_PRIC";
2727 return error;
2728 }
2729 if (!valid_trigger_value(*trigger)) {
2730 error.message_ = "a KIS trigger price must be a positive whole number of won";
2731 return error;
2732 }
2733 return std::nullopt;
2734 }
2735 if (trigger) {
2736 error.message_ =
2737 "KIS takes a trigger price only on a stop-limit order (22); on this basis it would be "
2738 "dropped";
2739 return error;
2740 }
2741 return std::nullopt;
2742 }
2743
2744 // One row of KIS's `ORD_DVSN` table: a wire code and the three facts it means.
2745 //
2746 // `ORD_DVSN` is a product, not a name. `16` is a best-limit order that is
2747 // filled-or-killed in the regular session; `45` is a best-limit order that is
2748 // immediate-or-cancel in the after-market. Holding the table as rows of the
2749 // product is what lets an adapter answer "which code is this combination" and
2750 // "which combination is this code" from one transcription, in both
2751 // directions, without either being derived from the other.
2752 //
2753 // `venues_` is a bitmask because the three venues publish *different* code
2754 // sets for the same combination set: the sheet lists `01` (시장가) under
2755 // `[KRX]` and `[SOR]` and not under `[NXT]`, and lists `27`-`29` (GTP) under
2756 // `[NXT]` alone. A combination is not "supported by KIS"; it is supported at a
2757 // venue.
2758 struct OrderShapeRow {
2759 const char* code_;
2760 OrderType type_;
2761 TimeInForce time_in_force_;
2762 OrderSession session_;
2763 unsigned venues_;
2764 bool requestable_;
2765 };
2766
2767 static constexpr unsigned kKrx = 1u << 0;
2768 static constexpr unsigned kNxt = 1u << 1;
2769 static constexpr unsigned kSor = 1u << 2;
2770
2771 // KIS's `ORD_DVSN` table, transcribed from the API workbook dated `20260916`.
2772 //
2773 // Two sheets contribute and they do not agree, which is why both are named
2774 // here rather than one being trusted for both directions:
2775 //
2776 // - `주식주문(현금)` is the **request** table. It carries `41`-`47` (KRX
2777 // 애프터마켓) and `27`-`29` (NXT GTP), and does *not* carry `07`.
2778 // - `주식정정취소가능주문조회` is a **response** table. It carries `07`
2779 // (시간외 단일가) and carries neither `41`-`47` nor `27`-`29`.
2780 //
2781 // So the set this adapter must *read* is the union and the set it may *send*
2782 // is the request sheet's alone. `requestable_` is that distinction: a row with
2783 // `false` is normalized on a response and refused on a request, because
2784 // sending a code the order sheet does not publish is guessing.
2785 //
2786 // A combination absent from this table is refused before any network I/O, and
2787 // a code absent from it reads as `UNKNOWN` with the raw code preserved. Neither
2788 // is approximated by a neighbouring value.
2789 static constexpr std::array<OrderShapeRow, 28> kOrderShapes{{
2790 // Each row: code, type, condition, session, venues, requestable.
2791 {"00", OrderType::LIMIT, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2792 {"01", OrderType::MARKET, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kSor, true},
2793 {"02", OrderType::CONDITIONAL_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, kKrx, true},
2794 {"03", OrderType::BEST_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2795 {"04", OrderType::PRIMARY_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2796 {"05", OrderType::CLOSING_PRICE, TimeInForce::DAY, OrderSession::PRE_MARKET, kKrx, true},
2797 {"06", OrderType::CLOSING_PRICE, TimeInForce::DAY, OrderSession::AFTER_HOURS, kKrx, true},
2798 // Response-only: the order sheet does not publish 07. Reading 시간외 단일가
2799 // as a *limit* in an auction session is an inference, not something either
2800 // sheet states -- they name the auction without giving its price rule. It is
2801 // the reading that makes the code factor, and the field it would be wrong
2802 // about is one this library cannot send anyway.
2803 {"07", OrderType::LIMIT, TimeInForce::DAY, OrderSession::AFTER_HOURS_AUCTION, kKrx, false},
2804 {"11", OrderType::LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2805 {"12", OrderType::LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2806 {"13", OrderType::MARKET, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2807 {"14", OrderType::MARKET, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2808 {"15", OrderType::BEST_LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2809 {"16", OrderType::BEST_LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, kKrx | kNxt | kSor, true},
2810 {"21", OrderType::MID_PRICE, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kNxt, true},
2811 {"22", OrderType::STOP_LIMIT, TimeInForce::DAY, OrderSession::REGULAR, kKrx | kNxt, true},
2812 {"23", OrderType::MID_PRICE, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::REGULAR, kKrx | kNxt, true},
2813 {"24", OrderType::MID_PRICE, TimeInForce::FILL_OR_KILL, OrderSession::REGULAR, kKrx | kNxt, true},
2814 {"27", OrderType::LIMIT, TimeInForce::DAY, OrderSession::GTP, kNxt, true},
2815 {"28", OrderType::BEST_LIMIT, TimeInForce::DAY, OrderSession::GTP, kNxt, true},
2816 {"29", OrderType::PRIMARY_LIMIT, TimeInForce::DAY, OrderSession::GTP, kNxt, true},
2817 {"41", OrderType::LIMIT, TimeInForce::DAY, OrderSession::AFTER_MARKET, kKrx, true},
2818 {"42", OrderType::LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::AFTER_MARKET, kKrx, true},
2819 {"43", OrderType::LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::AFTER_MARKET, kKrx, true},
2820 {"44", OrderType::BEST_LIMIT, TimeInForce::DAY, OrderSession::AFTER_MARKET, kKrx, true},
2821 {"45", OrderType::BEST_LIMIT, TimeInForce::IMMEDIATE_OR_CANCEL, OrderSession::AFTER_MARKET, kKrx, true},
2822 {"46", OrderType::BEST_LIMIT, TimeInForce::FILL_OR_KILL, OrderSession::AFTER_MARKET, kKrx, true},
2823 {"47", OrderType::PRIMARY_LIMIT, TimeInForce::DAY, OrderSession::AFTER_MARKET, kKrx, true},
2824 }};
2825
2826 // Returns the venue bit an `EXCG_ID_DVSN_CD` value stands for.
2827 static constexpr unsigned venue_bit(Venue venue) {
2828 switch (venue) {
2829 case Venue::KRX:
2830 return kKrx;
2831 case Venue::NXT:
2832 return kNxt;
2833 // The combined book is routed across both venues, which is what KIS calls
2834 // SOR. See `exchange_code` for why this is an explicit value rather than
2835 // an omitted field.
2836 case Venue::COMBINED:
2837 return kSor;
2838 // Nothing was asked for, so nothing is sent, and the sheet says an
2839 // omitted `EXCG_ID_DVSN_CD` proceeds as KRX. The code set checked is
2840 // therefore KRX's -- the one the order will actually meet.
2841 case Venue::UNSPECIFIED:
2842 return kKrx;
2843 }
2844 return kKrx;
2845 }
2846
2847 // Maps a normalized order shape to KIS's `ORD_DVSN` code for a venue.
2848 //
2849 // A combination this library has no code for, or has a code for at another
2850 // venue, is rejected with `INVALID_ARGUMENT` before any token fetch or socket
2851 // write. It is never sent under a neighbouring code: a condition the caller
2852 // stated is honoured or refused, and the failure
2853 // this replaces was silent — a market order bound for NXT was sent as `01`,
2854 // which the sheet lists under `[KRX]` and `[SOR]` and not under `[NXT]`.
2855 static std::optional<BrokerError> order_division(
2856 OrderType type, TimeInForce time_in_force, OrderSession session, Venue venue, std::string& division
2857 ) {
2858 BrokerError error;
2859 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2860 error.reached_broker_ = false;
2861 error.broker_code_ = "unsupported_order";
2862
2863 const auto* matched = static_cast<const OrderShapeRow*>(nullptr);
2864 for (const auto& row : kOrderShapes) {
2865 if (row.type_ == type && row.time_in_force_ == time_in_force && row.session_ == session) {
2866 matched = &row;
2867 break;
2868 }
2869 }
2870 if (matched == nullptr) {
2871 error.message_ = std::string("KIS publishes no order code for this combination of price basis, ") +
2872 "validity condition and session";
2873 return error;
2874 }
2875 if (!matched->requestable_) {
2876 error.message_ = std::string("KIS reports order code ") + matched->code_ +
2877 " on an inquiry but does not publish it as a placeable order";
2878 return error;
2879 }
2880 if ((matched->venues_ & venue_bit(venue)) == 0) {
2881 error.message_ = std::string("KIS order code ") + matched->code_ + " is not offered at " + exchange_code(venue) +
2882 "; the venue publishes its own set of order codes";
2883 return error;
2884 }
2885 division = matched->code_;
2886 return std::nullopt;
2887 }
2888
2889 // Returns whether a symbol has one of KIS's domestic product-number forms.
2890 //
2891 // KIS documents `PDNO` as a six-character stock code, or seven characters for
2892 // an ETN. Both lengths are accepted so an ETN order is not rejected locally
2893 // for a length the broker itself documents.
2894 static bool valid_domestic_symbol(std::string_view symbol) {
2895 if (symbol.size() != 6 && symbol.size() != 7) {
2896 return false;
2897 }
2898 for (const char ch : symbol) {
2899 const bool valid = (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
2900 if (!valid) {
2901 return false;
2902 }
2903 }
2904 return true;
2905 }
2906
2907 // Returns whether an order reference can address a KIS order for amendment.
2908 //
2909 // The order number is always required and always ten digits. The branch
2910 // number may be empty: KIS's own documented `order-rvsecncl` request example
2911 // sends `KRX_FWDG_ORD_ORGNO` blank, so requiring it would reject a usage the
2912 // broker publishes. When it is supplied it must be the documented five
2913 // digits, which is what an acknowledgement or an open-order row returns.
2914 static bool valid_order_reference(const KisOrderRef& order) {
2915 if (!broker_detail::decimal_digits(order.order_number_, 10)) {
2916 return false;
2917 }
2918 return order.branch_number_.empty() || broker_detail::decimal_digits(order.branch_number_, 5);
2919 }
2920
2921 // Returns an error when the order cannot be represented as a KIS cash order.
2922 static std::optional<BrokerError> validate_order(
2923 const KisConfig& config, const OrderRequest& order, std::string& division
2924 ) {
2925 if (auto error = unsupported_client_order_id(order)) {
2926 return error;
2927 }
2928 if (order.instrument_.country_ != Country::KR) {
2929 BrokerError error;
2930 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2931 error.reached_broker_ = false;
2932 error.broker_code_ = "invalid_instrument";
2933 error.message_ = "KIS cash orders currently support Korean equities only";
2934 return error;
2935 }
2936 // KIS reports every Korean instrument at one identity venue, and a holding
2937 // carries no venue at all -- so an order whose `instrument_.venue_` said
2938 // anything else would not be the same `InstrumentId` as its own holding, and
2939 // `Portfolio::working_quantity` would read zero resting quantity for it.
2940 // A caller who set it there means *routing*, which is `OrderRequest::venue_`;
2941 // refused rather than routed on, because routing on it silently is exactly
2942 // how the resting quantity would go missing.
2943 if (order.instrument_.venue_ != instrument_venue()) {
2944 BrokerError error;
2945 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2946 error.reached_broker_ = false;
2947 error.broker_code_ = "invalid_instrument";
2948 error.message_ =
2949 "KIS identifies a Korean instrument by its combined venue; set OrderRequest::venue_ to "
2950 "route the order to a particular exchange instead of naming one on the instrument";
2951 return error;
2952 }
2953 if (!valid_domestic_symbol(order.instrument_.symbol_)) {
2954 BrokerError error;
2955 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2956 error.reached_broker_ = false;
2957 error.broker_code_ = "invalid_instrument";
2958 error.message_ = "KIS domestic order symbol must contain six letters or digits, or seven for an ETN";
2959 return error;
2960 }
2961 if (auto error = validate_quantity(order.quantity_)) {
2962 return error;
2963 }
2964 if (auto error = validate_price(order.type_, order.price_)) {
2965 return error;
2966 }
2967 if (auto error = validate_trigger(order.type_, order.trigger_price_)) {
2968 return error;
2969 }
2970 if (auto error = validate_venue(config, order.venue_)) {
2971 return error;
2972 }
2973 return order_division(order.type_, order.time_in_force_, order.session_, order.venue_, division);
2974 }
2975
2976 // Returns an error when an amendment cannot be represented as a KIS instruction.
2977 //
2978 // The counterpart of `validate_order`, and it exists as its own function for
2979 // the same reason: the decision a test needs to exercise is the one the
2980 // submission path takes, not one a test re-derives from the same inputs. A
2981 // shim that called `order_division` directly would agree with a submission
2982 // path that had stopped calling it -- which is not hypothetical, because the
2983 // first version of the amendment test did exactly that and survived the
2984 // mutation it had been written to catch.
2985 static std::optional<BrokerError> validate_amendment(
2986 const KisConfig& config, const KisAmendment& amendment, std::string& division, bool cancel = false
2987 ) {
2988 if (auto error = validate_quantity(amendment.quantity_)) {
2989 return error;
2990 }
2991 if (auto error = validate_price(amendment.type_, amendment.price_)) {
2992 return error;
2993 }
2994 // A modification states the order it leaves behind, so its trigger is held to the placement
2995 // rule. A cancellation is not refused for its trigger at all: `make_amend_order_request` sends
2996 // `CNDT_PRIC` only when it is a valid trigger for a `22` shape, so a stop order whose trigger
2997 // KIS never reported back can still be withdrawn.
2998 if (!cancel) {
2999 if (auto error = validate_trigger(amendment.type_, amendment.trigger_price_)) {
3000 return error;
3001 }
3002 }
3003 // The amendment carries its own condition and session. Sending `DAY` here,
3004 // as this did, re-shaped the order: an immediate-or-cancel order amended to
3005 // a new price arrived as a plain day order at that price.
3006 if (auto error = validate_venue(config, amendment.venue_)) {
3007 return error;
3008 }
3009 return order_division(amendment.type_, amendment.time_in_force_, amendment.session_, amendment.venue_, division);
3010 }
3011
3012 // Returns KIS's `EXCG_ID_DVSN_CD` value for a normalized venue, or `""` to
3013 // omit the field.
3014 //
3015 // `Venue::COMBINED` maps to `SOR`, which is what KIS calls routing an order
3016 // across both books. `Venue::UNSPECIFIED` omits the field and takes the
3017 // broker's documented default of KRX, and those are not the same thing: one
3018 // asks for something and the other asks for nothing.
3019 //
3020 // This reads `OrderRequest::venue_`, never the instrument's. Routing is not
3021 // part of an instrument's identity, and an order whose identity carried a
3022 // route would stop matching its own holding.
3023 //
3024 // The sheet's demo restriction -- 모의투자는 KRX만 가능 -- **is** enforced,
3025 // by `validate_venue` above, and `transmitted_exchange` omits the field
3026 // entirely on a demo account. It was not enforced until it became clear
3027 // that making `COMBINED` mean `SOR` had turned the most ordinary demo order
3028 // into one the account would refuse, after its POST.
3029 // Returns an error when a venue is unusable on this configuration.
3030 //
3031 // Both KIS order sheets say `모의투자는 KRX만 가능`: a demo account routes to
3032 // the Korea Exchange and nowhere else. That restriction is per credential
3033 // rather than per broker, so it is a **run-time** error
3034 // rather than a compile-time capability -- one binary must not claim
3035 // different things for a live key and a demo key.
3036 //
3037 // It is checked here because it became reachable. `Venue::COMBINED` is the
3038 // default `venue_` of every `InstrumentId`, and it now sends `SOR`; before
3039 // that it omitted the field and KIS routed the order to KRX, so an ordinary
3040 // demo order worked by accident. Sending `SOR` and learning the restriction
3041 // from the response would break every default demo placement, and would
3042 // break it *after* a POST this library may never replay.
3043 //
3044 // Routing is opt-in, so a demo account that names **no** venue is the ordinary
3045 // case and is fine: the field is omitted and KIS applies its documented
3046 // default of KRX. An explicit `KRX` is fine for the same reason. `NXT` and
3047 // `COMBINED` are refused, because each names something the account cannot
3048 // reach -- `COMBINED` is SOR, which routes across venues the demo
3049 // environment does not have.
3050 //
3051 // **This is why there is no separate "which code set does a demo request
3052 // satisfy" step.** There was one, and a surviving mutation showed it could not
3053 // change any outcome: once this refuses `NXT` and `COMBINED`, the only venues a
3054 // demo request can carry are `UNSPECIFIED` and `KRX`, and both already select
3055 // KRX's code set. A branch describing a state that cannot happen is worse than
3056 // no branch, because a reader who sees it believes it can.
3057 static std::optional<BrokerError> validate_venue(const KisConfig& config, Venue venue) {
3058 if (!config.is_demo_ || venue == Venue::UNSPECIFIED || venue == Venue::KRX) {
3059 return std::nullopt;
3060 }
3061 BrokerError error;
3062 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3063 error.reached_broker_ = false;
3064 error.broker_code_ = "venue_unavailable";
3065 error.message_ =
3066 "KIS demo accounts trade on KRX only; the requested venue is unavailable on this "
3067 "configuration";
3068 return error;
3069 }
3070
3071 // Returns the `EXCG_ID_DVSN_CD` value to transmit, or `""` to omit the field.
3072 //
3073 // Omitted on a demo account: there is one venue, KIS documents an omitted
3074 // field as proceeding at KRX, and naming a venue the sheet says demo does not
3075 // support is how the default demo order broke.
3076 static const char* transmitted_exchange(const KisConfig& config, Venue venue) {
3077 return config.is_demo_ ? "" : exchange_code(venue);
3078 }
3079
3080 static const char* exchange_code(Venue venue) {
3081 switch (venue) {
3082 case Venue::KRX:
3083 return "KRX";
3084 case Venue::NXT:
3085 return "NXT";
3086 case Venue::COMBINED:
3087 return "SOR";
3088 case Venue::UNSPECIFIED:
3089 return "";
3090 }
3091 return "";
3092 }
3093
3094 // Builds the authenticated KIS cash-order POST request.
3095 static network::HttpRequest make_place_order_request(
3096 const KisAccount& account, const KisConfig& config, std::string_view access_token, const OrderRequest& order,
3097 std::string_view division
3098 ) {
3099 json::object body{
3100 {"CANO", account.account_number_},
3101 {"ACNT_PRDT_CD", account.product_code_},
3102 {"PDNO", order.instrument_.symbol_},
3103 {"ORD_DVSN", std::string(division)},
3104 {"ORD_QTY", order.quantity_.str()},
3105 {"ORD_UNPR", order.price_ ? order.price_->str() : std::string("0")},
3106 };
3107 // Only when stated, which `validate_trigger` has restricted to `22`. The sheet marks the field
3108 // optional, and leaving it off every other body keeps those byte-identical to what KIS has
3109 // always been sent.
3110 if (order.trigger_price_) {
3111 body.emplace("CNDT_PRIC", order.trigger_price_->str());
3112 }
3113 if (const auto* exchange = transmitted_exchange(config, order.venue_); *exchange != '\0') {
3114 body.emplace("EXCG_ID_DVSN_CD", exchange);
3115 }
3116
3117 const bool buy = order.side_ == OrderSide::BUY;
3118 network::HttpRequest request;
3119 // An order is what the reserve is held for.
3120 request.group_ = network::RateLimitGroup::TRADING;
3121 request.method_ = http::verb::post;
3122 request.target_ = "/uapi/domestic-stock/v1/trading/order-cash";
3123 request.body_ = json::serialize(body);
3124 request.headers_ = {
3125 {"authorization", "Bearer " + std::string(access_token)},
3126 {"appkey", config.key()},
3127 {"appsecret", config.secret()},
3128 {"tr_id", buy ? (config.is_demo_ ? "VTTC0012U" : "TTTC0012U") : (config.is_demo_ ? "VTTC0011U" : "TTTC0011U")},
3129 {"custtype", "P"},
3130 {"content-type", "application/json; charset=utf-8"},
3131 };
3132 return request;
3133 }
3134
3135 // Builds the authenticated KIS modification or cancellation POST request.
3136 static network::HttpRequest make_amend_order_request(
3137 const KisAccount& account, const KisConfig& config, std::string_view access_token, const KisAmendment& amendment,
3138 bool cancel, std::string_view division
3139 ) {
3140 json::object body{
3141 {"CANO", account.account_number_},
3142 {"ACNT_PRDT_CD", account.product_code_},
3143 {"KRX_FWDG_ORD_ORGNO", amendment.order_.branch_number_},
3144 {"ORGN_ODNO", amendment.order_.order_number_},
3145 {"ORD_DVSN", std::string(division)},
3146 {"RVSE_CNCL_DVSN_CD", cancel ? "02" : "01"},
3147 {"ORD_QTY", amendment.quantity_.str()},
3148 {"ORD_UNPR", amendment.price_ ? amendment.price_->str() : std::string("0")},
3149 {"QTY_ALL_ORD_YN", amendment.all_remaining_ ? "Y" : "N"},
3150 };
3151 // On a modification `validate_amendment` has already required this exactly for `22`. On a
3152 // cancellation nothing was refused, so the same test decides whether to restate it.
3153 if (
3154 amendment.trigger_price_ && carries_trigger_price(amendment.type_) &&
3155 valid_trigger_value(*amendment.trigger_price_)
3156 ) {
3157 body.emplace("CNDT_PRIC", amendment.trigger_price_->str());
3158 }
3159 // The 주식주문(정정취소) sheet publishes `EXCG_ID_DVSN_CD` and the same
3160 // per-venue `ORD_DVSN` sets as the placement sheet, and this never sent it:
3161 // an amendment to an order living at NXT was addressed to KRX, the sheet's
3162 // documented default for an omitted field.
3163 if (const auto* exchange = transmitted_exchange(config, amendment.venue_); *exchange != '\0') {
3164 body.emplace("EXCG_ID_DVSN_CD", exchange);
3165 }
3166
3167 network::HttpRequest request;
3168 // A modification and a cancellation share the order endpoint and its priority.
3169 request.group_ = network::RateLimitGroup::TRADING;
3170 request.method_ = http::verb::post;
3171 request.target_ = "/uapi/domestic-stock/v1/trading/order-rvsecncl";
3172 request.body_ = json::serialize(body);
3173 request.headers_ = {
3174 {"authorization", "Bearer " + std::string(access_token)},
3175 {"appkey", config.key()},
3176 {"appsecret", config.secret()},
3177 {"tr_id", config.is_demo_ ? "VTTC0013U" : "TTTC0013U"},
3178 {"custtype", "P"},
3179 {"content-type", "application/json; charset=utf-8"},
3180 };
3181 return request;
3182 }
3183
3184 // Builds the error for a non-2xx KIS response: the generic one, plus KIS's own code from the body.
3185 //
3186 // KIS answers its per-second limit (`EGW00201`) with HTTP 500 and a JSON body, so the generic error
3187 // left `broker_code_` empty and the limit unclassified (observed on reads, 2026-10-02). The code is
3188 // read from `msg_cd`, or the token endpoint's `error_code`. `classify_rate` also maps a rate code to
3189 // `RATE_LIMIT`, as `kis_declared_error` does for a 2xx body. **The order path passes `false`:** an
3190 // HTTP 5xx on an order stays indeterminate, held until the order list resolves it, because a rate
3191 // limit is retried and a retry of an order KIS had in fact processed would double it. An order
3192 // refused this way has not been observed.
3193 static BrokerError kis_http_error(const network::HttpResponse& response, bool classify_rate = true) {
3194 auto error = broker_detail::http_error(response);
3195 boost::system::error_code ec;
3196 const auto document = json::parse(response.body(), ec);
3197 if (ec || !document.is_object()) {
3198 return error;
3199 }
3200 for (const char* field : {"msg_cd", "error_code"}) {
3201 if (const auto* code = document.as_object().if_contains(field); code && code->is_string()) {
3202 error.broker_code_ = code->as_string().c_str();
3203 break;
3204 }
3205 }
3206 if (classify_rate && kis_rate_limit_layer(error.broker_code_) != KisRateLimitLayer::NONE) {
3207 error.category_ = ErrorCategory::RATE_LIMIT;
3208 }
3209 return error;
3210 }
3211
3212 // Returns KIS's declared failure for a response whose `rt_cd` is not `0`.
3213 static std::optional<BrokerError> kis_declared_error(const json::object& document) {
3214 if (broker_detail::json_string(document, "rt_cd") == "0") {
3215 return std::nullopt;
3216 }
3217 BrokerError error;
3218 error.category_ = ErrorCategory::PROTOCOL;
3219 if (const auto code = document.if_contains("msg_cd"); code && code->is_string()) {
3220 error.broker_code_ = code->as_string().c_str();
3221 }
3222 if (const auto message = document.if_contains("msg1"); message && message->is_string()) {
3223 error.message_ = message->as_string().c_str();
3224 }
3225
3226 // KIS reports a rate limit in the response body rather than as HTTP 429 with
3227 // a Retry-After header, so it has to be recognized here or it reaches the
3228 // caller as an ordinary protocol failure.
3229 if (kis_rate_limit_layer(error.broker_code_) != KisRateLimitLayer::NONE) {
3230 error.category_ = ErrorCategory::RATE_LIMIT;
3231 }
3232 return error;
3233 }
3234
3235 // Sends a request that carries the access token, and forgets that token if KIS refuses it.
3236 //
3237 // KIS refuses an invalid token with `EGW00121` and an expired one with `EGW00123`, in a 2xx body
3238 // (`kis_declared_error`) or a non-2xx one (`kis_http_error`). Kept, the token would be sent until
3239 // its stated expiry and every request would fail; forgotten, the next request asks for a new one.
3240 // The refused request is not sent again and its result reaches the caller unchanged. Only the token
3241 // the request carried is forgotten: a late refusal of an older token leaves a newer one alone.
3242 template <typename Handler>
3243 void send(network::HttpRequest request, Handler handler) {
3244 std::string authorization;
3245 for (const auto& [name, value] : request.headers_) {
3246 if (name == "authorization") {
3247 authorization = value;
3248 }
3249 }
3250 http_->async_request(
3251 std::move(request),
3252 [self = shared_from_this(), authorization = std::move(authorization),
3253 handler = std::move(handler)](Result<network::HttpResponse> result) mutable {
3254 if (result && refuses_token(result.value())) {
3255 // Queued before the handler runs; every operation starts with a post to the strand, so
3256 // the next one finds the token gone.
3257 net::post(self->strand_, [self, authorization = std::move(authorization)] {
3258 self->forget_refused_token(authorization);
3259 });
3260 }
3261 std::move(handler)(std::move(result));
3262 }
3263 );
3264 }
3265
3266 // Tests whether a reply, of any status, states `EGW00121` or `EGW00123` in the field
3267 // `kis_http_error` reads its code from. The body is parsed only if it holds the codes' prefix or a
3268 // backslash, which may escape it.
3269 static bool refuses_token(const network::HttpResponse& response) {
3270 const auto& body = response.body();
3271 if (body.find("EGW0012") == std::string::npos && body.find('\\') == std::string::npos) {
3272 return false;
3273 }
3274 boost::system::error_code ec;
3275 const auto document = json::parse(body, ec);
3276 if (ec || !document.is_object()) {
3277 return false;
3278 }
3279 for (const char* field : {"msg_cd", "error_code"}) {
3280 if (const auto* code = document.as_object().if_contains(field); code && code->is_string()) {
3281 return code->as_string() == "EGW00121" || code->as_string() == "EGW00123";
3282 }
3283 }
3284 return false;
3285 }
3286
3287 // Forgets the held token if it is the one a refused request carried (its `authorization` value).
3288 void forget_refused_token(const std::string& authorization) {
3289 if (!token_.access_token_.empty() && authorization == "Bearer " + token_.access_token_) {
3290 token_ = KisRest{};
3291 }
3292 }
3293
3294 // Which order instruction a reply answers. Known where the request is built and carried to the
3295 // parser with it; never recovered from the reply.
3296 enum class OrderOperation { UNCLASSIFIED, PLACE, AMEND, CANCEL };
3297
3298 // Tests whether a field is absent or the empty string. Any other type or value is not "nothing".
3299 static bool absent_or_empty(const json::object& object, std::string_view key) {
3300 const auto value = object.if_contains(key);
3301 return !value || (value->is_string() && value->as_string().empty());
3302 }
3303
3304 // Returns the `rt_cd` a refusal this client recognizes carries, for `code` answering `operation`
3305 // from the demo server (`demo`) or the real one, or nothing if `code` is not such a refusal. Each
3306 // code is recognized from the server it was seen from only, with the `rt_cd` it was seen with.
3307 static std::optional<std::string_view> recognized_refusal_status(
3308 OrderOperation operation, std::string_view code, bool demo
3309 ) {
3310 if (!demo) {
3311 if (operation == OrderOperation::PLACE && code == "APBK3061") {
3312 return std::string_view("7");
3313 }
3314 return std::nullopt;
3315 }
3316 if (operation == OrderOperation::PLACE && (code == "40240000" || code == "40570000" || code == "40580000")) {
3317 return std::string_view("1");
3318 }
3319 if (operation == OrderOperation::CANCEL && code == "40330000") {
3320 return std::string_view("1");
3321 }
3322 return std::nullopt;
3323 }
3324
3325 // Returns the refusal a cash-order reply states, for the replies this client recognizes as one.
3326 // From the demo server: a placement answered `40240000` (nothing held to sell), `40570000` (the
3327 // market has not opened) or `40580000` (the market has closed), and a cancellation answered
3328 // `40330000` (nothing left to amend or cancel).
3329 // From the real server: a placement answered `APBK3061` (during the after-market session, only
3330 // after-market order types are accepted). Such a reply is `INVALID_ARGUMENT` with
3331 // `reached_broker_` set, which a runner reads as a rejection; any other declared failure of an
3332 // order keeps the reading `kis_declared_error` gives it (`PROTOCOL`, an unknown outcome, unless it
3333 // is a rate limit).
3334 //
3335 // Each code is recognized from the server it was seen from only. The reply must be HTTP 200 with
3336 // the code, the `rt_cd` it was seen with (`"1"` from the demo server, `"7"` for `APBK3061`), a message, and none of the fields an acknowledgement carries (`output`
3337 // absent, or an object whose `ODNO`, `KRX_FWDG_ORD_ORGNO` and `ORD_TMD` are absent or empty): a
3338 // reply acknowledging an order is never read as a refusal. A refused cancellation says only that the cancellation did nothing, not what
3339 // became of the order it named.
3340 static std::optional<BrokerError> kis_recognized_refusal(
3341 int http_status, const json::object& document, OrderOperation operation, bool demo
3342 ) {
3343 if (http_status != 200) {
3344 return std::nullopt;
3345 }
3346 const auto status = document.if_contains("rt_cd");
3347 const auto code = document.if_contains("msg_cd");
3348 const auto message = document.if_contains("msg1");
3349 if (!code || !code->is_string()) {
3350 return std::nullopt;
3351 }
3352 const auto expected = recognized_refusal_status(operation, std::string_view(code->as_string()), demo);
3353 if (
3354 !expected || !status || !status->is_string() || std::string_view(status->as_string()) != *expected || !message ||
3355 !message->is_string() || message->as_string().empty()
3356 ) {
3357 return std::nullopt;
3358 }
3359 const std::string stated(code->as_string());
3360 const char* name = operation == OrderOperation::PLACE ? "placement" : "cancellation";
3361 if (const auto output = document.if_contains("output")) {
3362 if (!output->is_object()) {
3363 return std::nullopt;
3364 }
3365 for (const char* field : {"ODNO", "KRX_FWDG_ORD_ORGNO", "ORD_TMD"}) {
3366 if (!absent_or_empty(output->as_object(), field)) {
3367 return std::nullopt;
3368 }
3369 }
3370 }
3371 BrokerError error;
3372 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3373 error.reached_broker_ = true;
3374 error.http_status_ = http_status;
3375 error.broker_code_ = stated;
3376 error.message_ = std::string(message->as_string()) + " (recognized refusal: KIS " + (demo ? "demo" : "real") +
3377 ", cash " + name + ", " + stated + ")";
3378 return error;
3379 }
3380
3381 // Parses a KIS order-instruction response into its composite acknowledgement. `operation` and
3382 // `demo` describe the request this reply answers; left out, no refusal is recognized.
3383 static Result<KisOrderAck> parse_order_ack(
3384 Result<network::HttpResponse> result, OrderOperation operation = OrderOperation::UNCLASSIFIED, bool demo = false
3385 ) {
3386 if (!result) {
3387 return Result<KisOrderAck>(std::move(result.error()));
3388 }
3389 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3390 return Result<KisOrderAck>(kis_http_error(result.value(), /*classify_rate=*/false));
3391 }
3392 BrokerError parse_error;
3393 auto document = broker_detail::parse_object(result.value(), parse_error);
3394 if (!document) {
3395 return Result<KisOrderAck>(std::move(parse_error));
3396 }
3397 try {
3398 if (auto refused = kis_recognized_refusal(result.value().result_int(), *document, operation, demo)) {
3399 return Result<KisOrderAck>(std::move(*refused));
3400 }
3401 if (auto declared = kis_declared_error(*document)) {
3402 return Result<KisOrderAck>(std::move(*declared));
3403 }
3404 const auto output = document->if_contains("output");
3405 if (!output || !output->is_object()) {
3406 throw std::runtime_error("missing object field: output");
3407 }
3408 const auto& fields = output->as_object();
3409
3410 KisOrderAck ack;
3411 ack.order_.branch_number_ = broker_detail::json_string(fields, "KRX_FWDG_ORD_ORGNO");
3412 ack.order_.order_number_ = broker_detail::json_string(fields, "ODNO");
3413 ack.broker_order_time_ = broker_detail::json_string(fields, "ORD_TMD");
3414 ack.ack_.order_id_ = ack.order_.order_number_;
3415 ack.ack_.accepted_at_ = std::chrono::system_clock::now();
3416 return Result<KisOrderAck>(std::move(ack));
3417 } catch (const std::exception& exception) {
3418 BrokerError error;
3419 error.category_ = ErrorCategory::PROTOCOL;
3420 error.broker_code_ = "invalid_order_response";
3421 error.message_ = exception.what();
3422 return Result<KisOrderAck>(std::move(error));
3423 }
3424 }
3425
3426 // Validates and starts one KIS cash-order submission.
3427 void start_place_order(KisAccount account, OrderRequest order, OrderAckHandler completion) {
3428 std::string division;
3429 auto invalid = validate_account(account);
3430 if (!invalid) {
3431 invalid = validate_order(config_, order, division);
3432 }
3433 if (invalid) {
3434 complete_order_ack(std::move(completion), Result<KisOrderAck>(std::move(*invalid)));
3435 return;
3436 }
3437
3438 ensure_token(TokenHandler(
3439 [self = shared_from_this(), account = std::move(account), order = std::move(order),
3440 division = std::move(division),
3441 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3442 if (token_error) {
3443 self->complete_order_ack(std::move(completion), Result<KisOrderAck>(std::move(*token_error)));
3444 return;
3445 }
3446 auto request = make_place_order_request(account, self->config_, self->token_.access_token_, order, division);
3447 self->request_order_ack(std::move(request), OrderOperation::PLACE, std::move(completion));
3448 }
3449 ));
3450 }
3451
3452 // Validates and starts one KIS modification or cancellation submission.
3453 void start_amend_order(KisAccount account, KisAmendment amendment, bool cancel, OrderAckHandler completion) {
3454 std::string division;
3455 auto invalid = validate_account(account);
3456 if (!invalid && !valid_order_reference(amendment.order_)) {
3457 BrokerError error;
3458 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3459 error.reached_broker_ = false;
3460 error.broker_code_ = "invalid_order_reference";
3461 error.message_ =
3462 "KIS amendment requires a ten-digit order number and an empty or "
3463 "five-digit branch number";
3464 invalid = std::move(error);
3465 }
3466 if (!invalid) {
3467 invalid = validate_amendment(config_, amendment, division, cancel);
3468 }
3469 if (invalid) {
3470 complete_order_ack(std::move(completion), Result<KisOrderAck>(std::move(*invalid)));
3471 return;
3472 }
3473
3474 ensure_token(TokenHandler(
3475 [self = shared_from_this(), account = std::move(account), amendment = std::move(amendment), cancel,
3476 division = std::move(division),
3477 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3478 if (token_error) {
3479 self->complete_order_ack(std::move(completion), Result<KisOrderAck>(std::move(*token_error)));
3480 return;
3481 }
3482 auto request =
3483 make_amend_order_request(account, self->config_, self->token_.access_token_, amendment, cancel, division);
3484 self->request_order_ack(
3485 std::move(request), cancel ? OrderOperation::CANCEL : OrderOperation::AMEND, std::move(completion)
3486 );
3487 }
3488 ));
3489 }
3490
3491 // Sends an order-writing request and dispatches its parsed acknowledgement. The operation and the
3492 // environment are fixed here, with the request, and travel with its reply.
3493 void request_order_ack(network::HttpRequest request, OrderOperation operation, OrderAckHandler completion) {
3494 send(
3495 std::move(request),
3496 [self = shared_from_this(), operation, demo = config_.is_demo_,
3497 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3498 net::post(
3499 self->strand_,
3500 [self, operation, demo, completion = std::move(completion), result = std::move(result)]() mutable {
3501 self->complete_order_ack(std::move(completion), parse_order_ack(std::move(result), operation, demo));
3502 }
3503 );
3504 }
3505 );
3506 }
3507
3508 // Validates and starts a complete modifiable-order inquiry.
3509 void start_open_orders(KisAccount account, OpenOrderHandler completion) {
3510 auto invalid = validate_account(account);
3511 if (invalid) {
3512 complete_open_orders(std::move(completion), Result<KisOpenOrderPage>(std::move(*invalid)));
3513 return;
3514 }
3515
3516 auto operation = std::make_shared<OpenOrderOperation>(std::move(account), std::move(completion));
3517 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
3518 if (token_error) {
3519 self->complete_open_orders(
3520 std::move(operation->completion_), Result<KisOpenOrderPage>(std::move(*token_error))
3521 );
3522 return;
3523 }
3524 self->request_open_orders(operation);
3525 }));
3526 }
3527
3528 // Builds one page request for KIS orders that remain modifiable.
3529 static network::HttpRequest make_open_orders_request(
3530 const KisAccount& account, const KisConfig& config, std::string_view access_token, std::string_view foreign_cursor,
3531 std::string_view domestic_cursor, bool continuation
3532 ) {
3533 if (config.is_demo_) {
3534 // Demo has no `TTTC0084R`: today's unfilled orders (`CCLD_DVSN=02`) from the daily inquiry.
3535 const auto today = today_in_seoul();
3536 return make_order_history_request(
3537 account, config, access_token, KisHistoryRange{today, today}, foreign_cursor, domestic_cursor, continuation,
3538 "02"
3539 );
3540 }
3541 network::HttpRequest request;
3542 // KIS recommends this inquiry before an amendment, but does not require it: a
3543 // caller tracking its own working orders already holds the amendable quantity,
3544 // and KIS's own examples amend without re-reading it. It ranks above polling and
3545 // stays outside the reserve, which is held for the amendment itself.
3546 request.group_ = network::RateLimitGroup::ACCOUNT;
3547 request.method_ = http::verb::get;
3548 request.target_ =
3549 "/uapi/domestic-stock/v1/trading/inquire-psbl-rvsecncl"
3550 "?CANO=" +
3551 account.account_number_ + "&ACNT_PRDT_CD=" + account.product_code_ +
3552 "&INQR_DVSN_1=0&INQR_DVSN_2=0&CTX_AREA_FK100=" + broker_detail::query_encode(foreign_cursor) +
3553 "&CTX_AREA_NK100=" + broker_detail::query_encode(domestic_cursor);
3554 request.headers_ = {
3555 {"authorization", "Bearer " + std::string(access_token)},
3556 {"appkey", config.key()},
3557 {"appsecret", config.secret()},
3558 {"tr_id", "TTTC0084R"},
3559 {"tr_cont", continuation ? "N" : ""},
3560 {"custtype", "P"},
3561 {"content-type", "application/json; charset=utf-8"},
3562 };
3563 return request;
3564 }
3565
3566 // Sends the next modifiable-order page request for `operation`.
3567 void request_open_orders(const std::shared_ptr<OpenOrderOperation>& operation) {
3568 auto request = make_open_orders_request(
3569 operation->account_, config_, token_.access_token_, operation->foreign_cursor_, operation->domestic_cursor_,
3570 operation->page_count_ > 0
3571 );
3572 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
3573 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
3574 self->handle_open_orders_page(operation, std::move(result));
3575 });
3576 });
3577 }
3578
3579 // Accumulates one modifiable-order page and advances its continuation.
3580 void handle_open_orders_page(
3581 const std::shared_ptr<OpenOrderOperation>& operation, Result<network::HttpResponse> result
3582 ) {
3583 if (!result) {
3584 complete_open_orders(std::move(operation->completion_), Result<KisOpenOrderPage>(std::move(result.error())));
3585 return;
3586 }
3587
3588 const bool has_next = continuation_pending(result.value());
3589 std::string foreign_cursor;
3590 std::string domestic_cursor;
3591 auto page = parse_open_orders_page(std::move(result), foreign_cursor, domestic_cursor, config_.is_demo_);
3592 if (!page) {
3593 complete_open_orders(std::move(operation->completion_), Result<KisOpenOrderPage>(std::move(page.error())));
3594 return;
3595 }
3596
3597 auto pagination_error = advance_cursors(
3598 operation->page_count_, operation->foreign_cursor_, operation->domestic_cursor_, std::move(foreign_cursor),
3599 std::move(domestic_cursor), has_next, "KIS modifiable-order continuation did not advance"
3600 );
3601 if (pagination_error) {
3602 complete_open_orders(std::move(operation->completion_), Result<KisOpenOrderPage>(std::move(*pagination_error)));
3603 return;
3604 }
3605
3606 operation->page_.orders_.insert(
3607 operation->page_.orders_.end(), std::make_move_iterator(page.value().orders_.begin()),
3608 std::make_move_iterator(page.value().orders_.end())
3609 );
3610 if (has_next) {
3611 request_open_orders(operation);
3612 return;
3613 }
3614
3615 operation->page_.received_at_ = std::chrono::system_clock::now();
3616 complete_open_orders(std::move(operation->completion_), Result<KisOpenOrderPage>(std::move(operation->page_)));
3617 }
3618
3619 // Parses one KIS modifiable-order response page and its cursors.
3620 //
3621 // `demo` reads the daily order inquiry's `output1` instead, which is what the request asked for on
3622 // demo, and lists each row with a remaining quantity.
3623 static Result<KisOpenOrderPage> parse_open_orders_page(
3624 Result<network::HttpResponse> result, std::string& foreign_cursor, std::string& domestic_cursor, bool demo = false
3625 ) {
3626 if (!result) {
3627 return Result<KisOpenOrderPage>(std::move(result.error()));
3628 }
3629 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3630 return Result<KisOpenOrderPage>(kis_http_error(result.value()));
3631 }
3632 BrokerError parse_error;
3633 auto document = broker_detail::parse_object(result.value(), parse_error);
3634 if (!document) {
3635 return Result<KisOpenOrderPage>(std::move(parse_error));
3636 }
3637 try {
3638 if (auto declared = kis_declared_error(*document)) {
3639 return Result<KisOpenOrderPage>(std::move(*declared));
3640 }
3641 if (demo) {
3642 auto page = open_orders_from_history(*document);
3643 read_cursors(*document, foreign_cursor, domestic_cursor);
3644 return Result<KisOpenOrderPage>(std::move(page));
3645 }
3646 const auto rows = document->if_contains("output");
3647 if (!rows || !rows->is_array()) {
3648 throw std::runtime_error("missing array field: output");
3649 }
3650
3651 KisOpenOrderPage page;
3652 for (const auto& value : rows->as_array()) {
3653 if (!value.is_object()) {
3654 throw std::runtime_error("output item is not an object");
3655 }
3656 const auto& row = value.as_object();
3657
3658 KisOpenOrder open_order;
3659 open_order.order_ref_.branch_number_ = broker_detail::json_string(row, "ord_gno_brno");
3660 open_order.order_ref_.order_number_ = broker_detail::json_string(row, "odno");
3661 open_order.original_order_.branch_number_ = open_order.order_ref_.branch_number_;
3662 open_order.original_order_.order_number_ = broker_detail::json_string(row, "orgn_odno");
3663 open_order.amendable_quantity_ = Decimal64::parse(broker_detail::json_string(row, "psbl_qty"));
3664 if (const auto* released = row.if_contains("stpm_efct_occr_yn"); released != nullptr && released->is_string()) {
3665 open_order.stop_released_ = std::string(released->get_string());
3666 }
3667
3668 auto& order = open_order.order_;
3669 order.order_id_ = open_order.order_ref_.order_number_;
3670 // `Venue::COMBINED`, exactly as the holdings path writes it, so an order
3671 // and the holding it belongs to remain the same instrument. Where the
3672 // order was actually routed is a different fact and goes in `venue_`.
3673 order.instrument_ = InstrumentId{
3674 Country::KR,
3675 instrument_venue(),
3676 broker_detail::json_string(row, "pdno"),
3677 };
3678 order.venue_ = reported_venue(row);
3679 order.name_ = broker_detail::json_string(row, "prdt_name");
3680 order.side_ = normalized_order_side(broker_detail::json_string(row, "sll_buy_dvsn_cd"));
3681 apply_order_shape(broker_detail::json_string(row, "ord_dvsn_cd"), order);
3682 order.quantity_ = Decimal64::parse(broker_detail::json_string(row, "ord_qty"));
3683 if (carries_caller_price(order.type_)) {
3684 order.price_ = Decimal64::parse(broker_detail::json_string(row, "ord_unpr"));
3685 }
3686 order.trigger_price_ = reported_trigger(row);
3687 order.currency_ = Currency::krw();
3688 order.execution_.filled_quantity_ = Decimal64::parse(broker_detail::json_string(row, "tot_ccld_qty"));
3689 order.execution_.filled_amount_ =
3690 Money{Decimal64::parse(broker_detail::json_string(row, "tot_ccld_amt")), Currency::krw()};
3691 order.status_ =
3692 order.execution_.filled_quantity_.coefficient() > 0 ? OrderStatus::PARTIAL_FILLED : OrderStatus::PENDING;
3693 page.orders_.push_back(std::move(open_order));
3694 }
3695
3696 read_cursors(*document, foreign_cursor, domestic_cursor);
3697 return Result<KisOpenOrderPage>(std::move(page));
3698 } catch (const std::exception& exception) {
3699 BrokerError error;
3700 error.category_ = ErrorCategory::PROTOCOL;
3701 error.broker_code_ = "invalid_open_order_response";
3702 error.message_ = exception.what();
3703 return Result<KisOpenOrderPage>(std::move(error));
3704 }
3705 }
3706
3707 // Validates and starts a complete KIS order-history inquiry.
3708 void start_order_history(KisAccount account, KisHistoryRange range, OrderPageHandler completion) {
3709 auto invalid = validate_account(account);
3710 if (!invalid && (!is_valid_date(range.from_) || !is_valid_date(range.to_) || range.to_ < range.from_)) {
3711 BrokerError error;
3712 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3713 error.reached_broker_ = false;
3714 error.broker_code_ = "invalid_date_range";
3715 error.message_ = "KIS order history requires a valid inclusive calendar range";
3716 invalid = std::move(error);
3717 }
3718 if (invalid) {
3719 complete_order_page(std::move(completion), Result<OrderPage>(std::move(*invalid)));
3720 return;
3721 }
3722
3723 auto operation = std::make_shared<OrderHistoryOperation>(std::move(account), range, std::move(completion));
3724 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
3725 if (token_error) {
3726 self->complete_order_page(std::move(operation->completion_), Result<OrderPage>(std::move(*token_error)));
3727 return;
3728 }
3729 self->request_order_history(operation);
3730 }));
3731 }
3732
3733 // Builds one page request for KIS daily order and execution history.
3734 static network::HttpRequest make_order_history_request(
3735 const KisAccount& account, const KisConfig& config, std::string_view access_token, const KisHistoryRange& range,
3736 std::string_view foreign_cursor, std::string_view domestic_cursor, bool continuation,
3737 std::string_view executions = "00"
3738 ) {
3739 network::HttpRequest request;
3740 // Order history is account monitoring, not order submission.
3741 request.group_ = network::RateLimitGroup::ACCOUNT;
3742 request.method_ = http::verb::get;
3743 request.target_ =
3744 "/uapi/domestic-stock/v1/trading/inquire-daily-ccld"
3745 "?CANO=" +
3746 account.account_number_ + "&ACNT_PRDT_CD=" + account.product_code_ +
3747 "&INQR_STRT_DT=" + compact_date(range.from_) + "&INQR_END_DT=" + compact_date(range.to_) +
3748 "&SLL_BUY_DVSN_CD=00&PDNO=&ORD_GNO_BRNO=&ODNO=&CCLD_DVSN=" + std::string(executions) +
3749 "&INQR_DVSN=00"
3750 "&INQR_DVSN_1=&INQR_DVSN_3=00&EXCG_ID_DVSN_CD=" +
3751 (config.is_demo_ ? "KRX" : "ALL") + "&CTX_AREA_FK100=" + broker_detail::query_encode(foreign_cursor) +
3752 "&CTX_AREA_NK100=" + broker_detail::query_encode(domestic_cursor);
3753 request.headers_ = {
3754 {"authorization", "Bearer " + std::string(access_token)},
3755 {"appkey", config.key()},
3756 {"appsecret", config.secret()},
3757 {"tr_id", config.is_demo_ ? "VTTC0081R" : "TTTC0081R"},
3758 {"tr_cont", continuation ? "N" : ""},
3759 {"custtype", "P"},
3760 {"content-type", "application/json; charset=utf-8"},
3761 };
3762 return request;
3763 }
3764
3765 // Sends the next order-history page request for `operation`.
3766 void request_order_history(const std::shared_ptr<OrderHistoryOperation>& operation) {
3767 auto request = make_order_history_request(
3768 operation->account_, config_, token_.access_token_, operation->range_, operation->foreign_cursor_,
3769 operation->domestic_cursor_, operation->page_count_ > 0
3770 );
3771 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
3772 net::post(self->strand_, [self, operation, result = std::move(result)]() mutable {
3773 self->handle_order_history_page(operation, std::move(result));
3774 });
3775 });
3776 }
3777
3778 // Accumulates one order-history page and advances its continuation.
3779 void handle_order_history_page(
3780 const std::shared_ptr<OrderHistoryOperation>& operation, Result<network::HttpResponse> result
3781 ) {
3782 if (!result) {
3783 complete_order_page(std::move(operation->completion_), Result<OrderPage>(std::move(result.error())));
3784 return;
3785 }
3786
3787 const bool has_next = continuation_pending(result.value());
3788 std::string foreign_cursor;
3789 std::string domestic_cursor;
3790 auto page = parse_order_history_page(std::move(result), foreign_cursor, domestic_cursor);
3791 if (!page) {
3792 complete_order_page(std::move(operation->completion_), Result<OrderPage>(std::move(page.error())));
3793 return;
3794 }
3795
3796 auto pagination_error = advance_cursors(
3797 operation->page_count_, operation->foreign_cursor_, operation->domestic_cursor_, std::move(foreign_cursor),
3798 std::move(domestic_cursor), has_next, "KIS order-history continuation did not advance"
3799 );
3800 if (pagination_error) {
3801 complete_order_page(std::move(operation->completion_), Result<OrderPage>(std::move(*pagination_error)));
3802 return;
3803 }
3804
3805 operation->page_.orders_.insert(
3806 operation->page_.orders_.end(), std::make_move_iterator(page.value().orders_.begin()),
3807 std::make_move_iterator(page.value().orders_.end())
3808 );
3809 if (has_next) {
3810 request_order_history(operation);
3811 return;
3812 }
3813
3814 operation->page_.received_at_ = std::chrono::system_clock::now();
3815 complete_order_page(std::move(operation->completion_), Result<OrderPage>(std::move(operation->page_)));
3816 }
3817
3818 // Builds the order one daily-inquiry row describes.
3819 //
3820 // Shared by the history read and, on demo, the working-order read, so the two cannot describe one
3821 // order differently.
3822 static OrderSnapshot history_row_snapshot(const json::object& row) {
3823 OrderSnapshot order;
3824 order.order_id_ = broker_detail::json_string(row, "odno");
3825 // `Venue::COMBINED`, exactly as the holdings path writes it, so an order
3826 // and the holding it belongs to remain the same instrument. Where the
3827 // order was actually routed is a different fact and goes in `venue_`.
3828 order.instrument_ = InstrumentId{
3829 Country::KR,
3830 instrument_venue(),
3831 broker_detail::json_string(row, "pdno"),
3832 };
3833 order.venue_ = reported_venue(row);
3834 order.name_ = broker_detail::json_string(row, "prdt_name");
3835 order.side_ = normalized_order_side(broker_detail::json_string(row, "sll_buy_dvsn_cd"));
3836 apply_order_shape(broker_detail::json_string(row, "ord_dvsn_cd"), order);
3837 order.quantity_ = Decimal64::parse(broker_detail::json_string(row, "ord_qty"));
3838 if (carries_caller_price(order.type_)) {
3839 order.price_ = Decimal64::parse(broker_detail::json_string(row, "ord_unpr"));
3840 }
3841 order.trigger_price_ = reported_trigger(row);
3842 order.currency_ = Currency::krw();
3843 order.ordered_at_ =
3844 korea_timestamp(broker_detail::json_string(row, "ord_dt"), broker_detail::json_string(row, "ord_tmd"));
3845
3846 const auto filled = Decimal64::parse(broker_detail::json_string(row, "tot_ccld_qty"));
3847 const auto remaining = Decimal64::parse(broker_detail::json_string(row, "rmn_qty"));
3848 const auto rejected = Decimal64::parse(broker_detail::json_string(row, "rjct_qty"));
3849 const bool canceled = broker_detail::json_string(row, "cncl_yn") == "Y";
3850
3851 order.execution_.filled_quantity_ = filled;
3852 order.execution_.filled_amount_ =
3853 Money{Decimal64::parse(broker_detail::json_string(row, "tot_ccld_amt")), Currency::krw()};
3854 if (const auto average = Decimal64::parse(broker_detail::json_string(row, "avg_prvs")); average.coefficient() > 0) {
3855 order.execution_.average_filled_price_ = average;
3856 }
3857 order.status_ = derive_order_status(order.quantity_, filled, remaining, rejected, canceled);
3858 return order;
3859 }
3860
3861 // Lists each daily-inquiry row with a remaining quantity as a working order, for demo.
3862 static KisOpenOrderPage open_orders_from_history(const json::object& document) {
3863 const auto rows = document.if_contains("output1");
3864 if (!rows || !rows->is_array()) {
3865 throw std::runtime_error("missing array field: output1");
3866 }
3867 KisOpenOrderPage page;
3868 for (const auto& value : rows->as_array()) {
3869 if (!value.is_object()) {
3870 throw std::runtime_error("output1 item is not an object");
3871 }
3872 const auto& row = value.as_object();
3873 // `rmn_qty` alone, deliberately not `cncl_yn`. Observed on demo (2026-10-02): an amended
3874 // original and a cancelled order both drop to `rmn_qty` 0 and keep `cncl_yn` `N`; `Y` marks the
3875 // cancel request's own row, which has `rmn_qty` 0 too. A partial cancel has not been seen, and
3876 // hiding a resting order is the error that sends it twice.
3877 const auto remaining = Decimal64::parse(broker_detail::json_string(row, "rmn_qty"));
3878 if (remaining.coefficient() <= 0) {
3879 continue;
3880 }
3881 KisOpenOrder open_order;
3882 open_order.order_ref_.branch_number_ = broker_detail::json_string(row, "ord_gno_brno");
3883 open_order.order_ref_.order_number_ = broker_detail::json_string(row, "odno");
3884 open_order.original_order_.branch_number_ = open_order.order_ref_.branch_number_;
3885 // All zeros (`0000000000`) for an order that amends nothing, not empty (observed on demo).
3886 open_order.original_order_.order_number_ = broker_detail::json_string(row, "orgn_odno");
3887 open_order.amendable_quantity_ = remaining;
3888 open_order.order_ = history_row_snapshot(row);
3889 // As the live listing states it: a row still resting is pending, or partly filled.
3890 open_order.order_.status_ = open_order.order_.execution_.filled_quantity_.coefficient() > 0 ?
3891 OrderStatus::PARTIAL_FILLED :
3892 OrderStatus::PENDING;
3893 page.orders_.push_back(std::move(open_order));
3894 }
3895 return page;
3896 }
3897
3898 // Parses one KIS daily order-history response page and its cursors.
3899 static Result<OrderPage> parse_order_history_page(
3900 Result<network::HttpResponse> result, std::string& foreign_cursor, std::string& domestic_cursor
3901 ) {
3902 if (!result) {
3903 return Result<OrderPage>(std::move(result.error()));
3904 }
3905 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3906 return Result<OrderPage>(kis_http_error(result.value()));
3907 }
3908 BrokerError parse_error;
3909 auto document = broker_detail::parse_object(result.value(), parse_error);
3910 if (!document) {
3911 return Result<OrderPage>(std::move(parse_error));
3912 }
3913 try {
3914 if (auto declared = kis_declared_error(*document)) {
3915 return Result<OrderPage>(std::move(*declared));
3916 }
3917 const auto rows = document->if_contains("output1");
3918 if (!rows || !rows->is_array()) {
3919 throw std::runtime_error("missing array field: output1");
3920 }
3921
3922 OrderPage page;
3923 for (const auto& value : rows->as_array()) {
3924 if (!value.is_object()) {
3925 throw std::runtime_error("output1 item is not an object");
3926 }
3927 page.orders_.push_back(history_row_snapshot(value.as_object()));
3928 }
3929
3930 read_cursors(*document, foreign_cursor, domestic_cursor);
3931 return Result<OrderPage>(std::move(page));
3932 } catch (const std::exception& exception) {
3933 BrokerError error;
3934 error.category_ = ErrorCategory::PROTOCOL;
3935 error.broker_code_ = "invalid_order_history_response";
3936 error.message_ = exception.what();
3937 return Result<OrderPage>(std::move(error));
3938 }
3939 }
3940
3941 // Derives a normalized lifecycle state for one order-history row.
3942 //
3943 // KIS's daily order inquiry reports no status column, so the state is
3944 // reconstructed from the ordered, filled, remaining, and rejected quantities
3945 // together with the cancellation flag. This is the one place where the
3946 // adapter states something KIS did not, so it is isolated and directly
3947 // tested rather than inlined into the response loop.
3948 //
3949 // A cancelled or rejected order keeps its partial fills visible through
3950 // `OrderExecution`, so the terminal state is reported without discarding
3951 // what was executed before it.
3952 static OrderStatus derive_order_status(
3953 const Decimal64& ordered, const Decimal64& filled, const Decimal64& remaining, const Decimal64& rejected,
3954 bool canceled
3955 ) {
3956 if (rejected.coefficient() > 0 && filled.coefficient() == 0) {
3957 return OrderStatus::REJECTED;
3958 }
3959 if (canceled) {
3960 return OrderStatus::CANCELED;
3961 }
3962 // **Nothing remaining and not all filled is an order that ended.** Observed on demo (2026-10-02):
3963 // a cancelled order, and an amended original, drop to `rmn_qty` 0 and keep `cncl_yn` `N` -- the `Y`
3964 // is on the cancel request's own row. Read as open, a cancelled order never looked finished to
3965 // anything waiting on its history (a deferred target, a sent order's confirmation). What filled is
3966 // still read from the fill column.
3967 if (remaining.coefficient() == 0 && !(filled == ordered)) {
3968 return OrderStatus::CANCELED;
3969 }
3970 if (filled.coefficient() == 0) {
3971 return OrderStatus::PENDING;
3972 }
3973 return filled == ordered ? OrderStatus::FILLED : OrderStatus::PARTIAL_FILLED;
3974 }
3975
3976 // Writes the three normalized order facts a KIS `ORD_DVSN` code carries, and
3977 // preserves the code itself.
3978 //
3979 // The code set read here is the **union** of the order sheet's and the
3980 // inquiry sheets', because they differ: the inquiry publishes `07`
3981 // (시간외 단일가), which cannot be placed, and the order sheet publishes
3982 // `41`-`47`, which an inquiry has not been observed to return. A reader that
3983 // knew only the request table would report `UNKNOWN` for a code KIS itself
3984 // had sent.
3985 //
3986 // An unrecognized code leaves all three fields `UNKNOWN` and still reaches
3987 // the caller through `shape_code_`. It does not throw: both specifications
3988 // require a client to tolerate unknown codes, and one odd row must not fail a
3989 // whole listing.
3990 static void apply_order_shape(std::string_view division, OrderSnapshot& order) {
3991 if (const auto code = Code<8>::try_make(division)) {
3992 order.shape_code_ = *code;
3993 }
3994 for (const auto& row : kOrderShapes) {
3995 if (division == row.code_) {
3996 order.type_ = row.type_;
3997 order.time_in_force_ = row.time_in_force_;
3998 order.session_ = row.session_;
3999 return;
4000 }
4001 }
4002 order.type_ = OrderType::UNKNOWN;
4003 order.time_in_force_ = TimeInForce::UNKNOWN;
4004 order.session_ = OrderSession::UNKNOWN;
4005 }
4006
4007 // Maps KIS's `excg_id_dvsn_cd` onto a normalized venue.
4008 //
4009 // Both order inquiries publish this field as required, and this adapter used
4010 // to ignore it and write `Venue::COMBINED` onto every parsed order. That was
4011 // an assertion about where an order lived, made without reading the field
4012 // that says so -- and it is not inert, because an amendment now composes its
4013 // `ORD_DVSN` and its `EXCG_ID_DVSN_CD` from the order's venue.
4014 //
4015 // An unrecognized or absent value is `UNSPECIFIED`, which omits the field on
4016 // a later amendment and so takes the broker's own default, rather than
4017 // naming a venue nothing reported.
4018 // Returns the venue that identifies a KIS instrument.
4019 //
4020 // One function with three callers -- the holdings parse and both order
4021 // parses -- rather than the literal each of them used to hold. `InstrumentId`
4022 // compares its venue, so a holding and an order of the same stock are the
4023 // same instrument only while those three agree, and
4024 // `Portfolio::working_quantity` reads zero resting quantity the moment they
4025 // do not. Toss had exactly that drift between its two parses and nothing
4026 // caught it, so the value is named once here rather than written three times.
4027 //
4028 // KIS reports no venue on a holding, so this is about identity only. Where an
4029 // order *was* routed is `reported_venue` below, and it lives on
4030 // `OrderSnapshot::venue_` rather than on the instrument.
4031 static constexpr Venue instrument_venue() {
4032 return Venue::COMBINED;
4033 }
4034
4035 // Returns an order's trigger from `stpm_cndt_pric`, or nothing.
4036 //
4037 // Both 정정취소가능주문조회 and 주식일별주문체결조회 publish the field on every row, with an
4038 // empty Description column. A positive value is recorded **whatever the row's code**, for the
4039 // reason `OrderSnapshot::trigger_price_` gives: on anything but `22` it is KIS contradicting its
4040 // own code, which a replacement then refuses rather than carrying along. A missing, empty, zero
4041 // or unreadable value is **not** a failure of the listing -- a trigger is one fact about one
4042 // order, and the row is still the order -- and leaves the trigger unreported.
4043 static std::optional<Decimal64> reported_trigger(const json::object& row) {
4044 const auto* value = row.if_contains("stpm_cndt_pric");
4045 if (value == nullptr || !value->is_string()) {
4046 return std::nullopt;
4047 }
4048 try {
4049 const auto trigger = Decimal64::parse(value->get_string());
4050 if (trigger.coefficient() > 0) {
4051 return trigger;
4052 }
4053 } catch (const std::exception&) {
4054 // Unreadable is "not reported", for the reason above.
4055 }
4056 return std::nullopt;
4057 }
4058
4059 static Venue reported_venue(const json::object& row) {
4060 // The workbook spells this field two ways across the sheets that publish
4061 // it -- `excg_id_dvsn_cd` on 주식정정취소가능주문조회 and `excg_id_dvsn_Cd`
4062 // on 주식일별주문체결조회 -- and one of them is presumably a typo in the
4063 // document. Which one is not knowable from here, so both are read.
4064 for (const auto* key : {"excg_id_dvsn_cd", "excg_id_dvsn_Cd"}) {
4065 const auto* value = row.if_contains(key);
4066 if (value != nullptr && value->is_string()) {
4067 return normalized_venue(value->get_string());
4068 }
4069 }
4070 // Absent rather than unrecognized. The sheets mark the field required, so
4071 // this should not happen against a live account; it must not fail the
4072 // listing if it does, because a venue is metadata about an order and not
4073 // the order.
4074 return Venue::UNSPECIFIED;
4075 }
4076
4077 static Venue normalized_venue(std::string_view code) {
4078 if (code == "KRX") {
4079 return Venue::KRX;
4080 }
4081 if (code == "NXT") {
4082 return Venue::NXT;
4083 }
4084 if (code == "SOR") {
4085 return Venue::COMBINED;
4086 }
4087 return Venue::UNSPECIFIED;
4088 }
4089
4090 // Maps a KIS side code or rejects an invalid broker response.
4091 static OrderSide normalized_order_side(std::string_view code) {
4092 if (code == "01") {
4093 return OrderSide::SELL;
4094 }
4095 if (code == "02") {
4096 return OrderSide::BUY;
4097 }
4098 throw std::runtime_error("invalid KIS order side code");
4099 }
4100
4101 // Returns whether the response header requests another continuation page.
4102 static bool continuation_pending(const network::HttpResponse& response) {
4103 const auto continuation = response.base().find("tr_cont");
4104 return continuation != response.base().end() && (continuation->value() == "M" || continuation->value() == "F");
4105 }
4106
4107 // Copies KIS's continuation cursors out of a response document.
4108 static void read_cursors(const json::object& document, std::string& foreign_cursor, std::string& domestic_cursor) {
4109 if (const auto value = document.if_contains("ctx_area_fk100"); value && value->is_string()) {
4110 foreign_cursor = value->as_string().c_str();
4111 }
4112 if (const auto value = document.if_contains("ctx_area_nk100"); value && value->is_string()) {
4113 domestic_cursor = value->as_string().c_str();
4114 }
4115 }
4116
4117 // Advances continuation cursors, rejecting a continuation that cannot end.
4118 //
4119 // An empty, unchanged, or excessively long continuation would loop forever
4120 // against a misbehaving response, so each is reported as a protocol error.
4121 static std::optional<BrokerError> advance_cursors(
4122 std::size_t& page_count, std::string& foreign_cursor, std::string& domestic_cursor, std::string next_foreign_cursor,
4123 std::string next_domestic_cursor, bool has_next, std::string_view message
4124 ) {
4125 if (has_next) {
4126 const bool cursor_did_not_advance =
4127 next_foreign_cursor == foreign_cursor && next_domestic_cursor == domestic_cursor;
4128 if (
4129 page_count + 1 >= 100 || (next_foreign_cursor.empty() && next_domestic_cursor.empty()) || cursor_did_not_advance
4130 ) {
4131 BrokerError error;
4132 error.category_ = ErrorCategory::PROTOCOL;
4133 error.broker_code_ = "invalid_pagination";
4134 error.message_ = std::string(message);
4135 return error;
4136 }
4137 }
4138 ++page_count;
4139 if (has_next) {
4140 foreign_cursor = std::move(next_foreign_cursor);
4141 domestic_cursor = std::move(next_domestic_cursor);
4142 }
4143 return std::nullopt;
4144 }
4145
4146 // Formats a calendar date as KIS's `YYYYMMDD` inquiry bound.
4147 static std::string compact_date(const Date& date) {
4148 char buffer[9];
4149 std::snprintf(buffer, sizeof(buffer), "%04d%02u%02u", date.year_, date.month_, date.day_);
4150 return std::string(buffer);
4151 }
4152
4153 // Combines KIS's `YYYYMMDD` order date and `HHMMSS` order time.
4154 //
4155 // KIS's domestic trading endpoints report Korea Standard Time, so the fixed
4156 // `+09:00` offset is documented broker behaviour rather than an assumption
4157 // about the caller's locale.
4158 static std::optional<std::chrono::system_clock::time_point> korea_timestamp(
4159 std::string_view date, std::string_view time
4160 ) {
4161 if (date.size() != 8 || time.size() != 6) {
4162 return std::nullopt;
4163 }
4164 std::string iso;
4165 iso.reserve(25);
4166 iso.append(date.substr(0, 4))
4167 .append("-")
4168 .append(date.substr(4, 2))
4169 .append("-")
4170 .append(date.substr(6, 2))
4171 .append("T")
4172 .append(time.substr(0, 2))
4173 .append(":")
4174 .append(time.substr(2, 2))
4175 .append(":")
4176 .append(time.substr(4, 2))
4177 .append("+09:00");
4178 return parse_iso8601_timestamp(iso);
4179 }
4180
4181 // Dispatches an order acknowledgement through its associated executor.
4182 // Dispatches one result through its associated executor, exactly once.
4183 //
4184 // Every operation's result passes through here, which makes it the one place a
4185 // broker's own rate-limit refusal can be fed back into this connection's pacer
4186 // without each operation having to remember to do it.
4187 template <typename Handler, typename T>
4188 void deliver(Handler handler, Result<T> result) {
4189 if (!result) {
4190 note_rate_limit(result.error());
4191 }
4192 auto executor = net::get_associated_executor(handler, strand_);
4193 net::dispatch(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
4194 std::move(handler)(std::move(result));
4195 });
4196 }
4197
4198 // Corrects this connection's pacing from a KIS rate-limit refusal.
4199 //
4200 // KIS has two limit layers. A ledger refusal is a cap shared with every other
4201 // customer, so the budget was not the problem and only a wait helps. A personal
4202 // refusal means this key's own allowance was exceeded, but KIS reports no number
4203 // to correct to; so both only hold admission.
4204 void note_rate_limit(const BrokerError& error) {
4205 if (!error_category_is_rate_limit(error.category_)) {
4206 return;
4207 }
4208 auto* limiter = http_->rate_limits();
4209 if (!limiter) {
4210 return;
4211 }
4212
4213 // KIS states no allowance with a refusal, of either layer, so there is nothing
4214 // to correct the budget *to*. Admission is held and the refusal is counted; the
4215 // configured budget is left exactly as the caller set it, because reducing a
4216 // stated budget from a guess is the kind of silent downgrade this library
4217 // refuses everywhere else. A caller watching `broker_rejections_` climb is being
4218 // told to lower it.
4219 limiter->hold(
4220 error.retry_after_ ?
4221 std::chrono::duration_cast<network::RateLimitController::Duration>(*error.retry_after_) :
4222 std::chrono::duration_cast<network::RateLimitController::Duration>(std::chrono::seconds(1))
4223 );
4224 }
4225
4226 void complete_order_ack(OrderAckHandler handler, Result<KisOrderAck> result) {
4227 deliver(std::move(handler), std::move(result));
4228 }
4229
4230 // Dispatches a modifiable-order result through its associated executor.
4231 void complete_open_orders(OpenOrderHandler handler, Result<KisOpenOrderPage> result) {
4232 deliver(std::move(handler), std::move(result));
4233 }
4234
4235 // Dispatches an order-history result through its associated executor.
4236 void complete_order_page(OrderPageHandler handler, Result<OrderPage> result) {
4237 deliver(std::move(handler), std::move(result));
4238 }
4239
4240 void complete(QuoteHandler handler, Result<QuoteSnapshot> result) {
4241 deliver(std::move(handler), std::move(result));
4242 }
4243
4244 void finish_holdings(const std::shared_ptr<HoldingsOperation>& operation, Result<HoldingsSnapshot> result) {
4245 complete_holdings(std::move(operation->completion_), std::move(result));
4246 }
4247
4248 void complete_holdings(HoldingsHandler handler, Result<HoldingsSnapshot> result) {
4249 deliver(std::move(handler), std::move(result));
4250 }
4251};
4252
4271public:
4281 ssl::context& context, KisConfig config, network::HttpClientOptions options = {},
4282 std::shared_ptr<network::TokenStore> store = nullptr, std::shared_ptr<network::CalendarCache> calendars = nullptr
4283 )
4284 : store_(std::move(store)),
4285 identity_(store_ ? config.token_identity() : std::string()),
4286 calendars_(std::move(calendars)),
4287 client_(std::make_shared<KisClient>(ioc_.get_executor(), context, std::move(config), options)) {
4288 client_->store_managed_ = store_ != nullptr;
4289 }
4290
4297 return run<QuoteSnapshot>(
4298 [&](auto&& sink) {
4299 client_->async_quote(std::move(instrument), std::move(sink));
4300 },
4301 "quote"
4302 );
4303 }
4304
4311 return run<Instrument>(
4312 [&](auto&& sink) {
4313 client_->async_instrument(std::move(subject), std::move(sink));
4314 },
4315 "instrument"
4316 );
4317 }
4318
4332 Result<TradingCalendar> calendar(Date from, bool refresh = false) {
4333 const auto request = [&](auto&& sink) {
4334 client_->async_calendar(from, refresh, std::move(sink));
4335 };
4336 if (!calendars_) {
4337 return run<TradingCalendar>(request, "calendar");
4338 }
4339 if (!is_valid_date(from)) {
4340 return drive<TradingCalendar>(request, "calendar");
4341 }
4342 if (!refresh) {
4343 if (KisClient::calendar_covers(client_->calendar_, from)) {
4344 return client_->calendar_;
4345 }
4346 auto loaded = calendars_->load("kis-kr");
4347 const auto received = loaded && loaded.value() ? seoul_date(loaded.value()->received_at_) : Date{};
4348 if (
4349 is_valid_date(received) && received == seoul_date(now_()) && loaded.value()->country_ == Country::KR &&
4350 KisClient::calendar_covers(*loaded.value(), from) && client_->adopt_calendar(std::move(*loaded.value()))
4351 ) {
4352 return client_->calendar_;
4353 }
4354 }
4355 const auto started = seoul_date(now_());
4356 auto result = run<TradingCalendar>(request, "calendar");
4357 if (result && is_valid_date(started) && seoul_date(result.value().received_at_) == started) {
4358 calendars_->publish("kis-kr", result.value());
4359 }
4360 return result;
4361 }
4362
4369 return run<PriceLimits>(
4370 [&](auto&& sink) {
4371 client_->async_price_limits(std::move(instrument), std::move(sink));
4372 },
4373 "price_limits"
4374 );
4375 }
4376
4384 return run<std::vector<TradePrint>>(
4385 [&](auto&& sink) {
4386 client_->async_trades(std::move(instrument), count, std::move(sink));
4387 },
4388 "trades"
4389 );
4390 }
4391
4398 return run<DepthSnapshot>(
4399 [&](auto&& sink) {
4400 client_->async_depth(std::move(instrument), std::move(sink));
4401 },
4402 "depth"
4403 );
4404 }
4405
4412 return run<BarSeries>(
4413 [&](auto&& sink) {
4414 client_->async_bars(std::move(query), std::move(sink));
4415 },
4416 "bars"
4417 );
4418 }
4419
4426 return run<HoldingsSnapshot>(
4427 [&](auto&& sink) {
4428 client_->async_holdings(std::move(account), std::move(sink));
4429 },
4430 "holdings"
4431 );
4432 }
4433
4441 return run<BuyingPower>(
4442 [&](auto&& sink) {
4443 client_->async_buying_power(currency, std::move(account), std::move(sink));
4444 },
4445 "buying_power"
4446 );
4447 }
4448
4460 return run<KisOrderAck>(
4461 [&](auto&& sink) {
4462 client_->async_place_order(std::move(account), std::move(order), std::move(sink));
4463 },
4464 "order placement"
4465 );
4466 }
4467
4476 return run<KisOrderAck>(
4477 [&](auto&& sink) {
4478 client_->async_replace_order(std::move(account), std::move(amendment), std::move(sink));
4479 },
4480 "order modification"
4481 );
4482 }
4483
4492 return run<KisOrderAck>(
4493 [&](auto&& sink) {
4494 client_->async_cancel_order(std::move(account), std::move(amendment), std::move(sink));
4495 },
4496 "order cancellation"
4497 );
4498 }
4499
4507 return run<KisOpenOrderPage>(
4508 [&](auto&& sink) {
4509 client_->async_open_orders(std::move(account), std::move(sink));
4510 },
4511 "modifiable-order inquiry"
4512 );
4513 }
4514
4522 return run<OrderPage>(
4523 [&](auto&& sink) {
4524 client_->async_order_history(std::move(account), range, std::move(sink));
4525 },
4526 "order-history inquiry"
4527 );
4528 }
4529
4535 return client_->rate_limit_stats();
4536 }
4537
4542 KisRest token() const {
4543 return client_->token();
4544 }
4545
4552 return client_->adopt_token(std::move(token));
4553 }
4554
4555private:
4556 friend struct KisClientTestAccess;
4557
4558 // Runs one call: with a store, prepares the token first and discards one KIS refused during the call.
4559 template <typename T, typename Start>
4560 Result<T> run(Start start, std::string_view operation) {
4561 if (!store_) {
4562 return drive<T>(std::move(start), operation);
4563 }
4564 const auto request = [this] {
4565 return drive<KisRest>(
4566 [this](auto&& sink) {
4567 client_->async_ensure_token(std::move(sink));
4568 },
4569 "token request"
4570 );
4571 };
4572 if (auto error = network::token_store_detail::prepare(*store_, identity_, *client_, request)) {
4573 return Result<T>(std::move(*error));
4574 }
4575 const auto carried = client_->token();
4576 auto result = drive<T>(std::move(start), operation);
4577 network::token_store_detail::discard_refused(*store_, identity_, carried, client_->token());
4578 return result;
4579 }
4580
4581 // Drives one asynchronous operation to completion on the private loop.
4582 template <typename T, typename Start>
4583 Result<T> drive(Start start, std::string_view operation) {
4584 std::optional<Result<T>> result;
4585 ioc_.restart();
4586 start([&result](Result<T> value) {
4587 result.emplace(std::move(value));
4588 });
4589 ioc_.run();
4590 if (!result) {
4591 BrokerError error;
4592 error.category_ = ErrorCategory::TRANSPORT;
4593 error.broker_code_ = "event_loop_stopped";
4594 error.message_ = "event loop stopped before " + std::string(operation) + " completion";
4595 return Result<T>(std::move(error));
4596 }
4597 return std::move(*result);
4598 }
4599
4600 // Returns an instant's date in Seoul, or no valid date for an instant within a day of the clock's limits.
4601 static Date seoul_date(std::chrono::system_clock::time_point value) {
4602 using TimePoint = std::chrono::system_clock::time_point;
4603 Date date;
4604 if (value < TimePoint::min() + std::chrono::hours(24) || TimePoint::max() - std::chrono::hours(24) < value) {
4605 return date;
4606 }
4607 std::string ignored;
4608 KisClient::korea_calendar(value, date, ignored);
4609 return date;
4610 }
4611
4612 std::shared_ptr<network::TokenStore> store_;
4613 std::string identity_;
4614 std::shared_ptr<network::CalendarCache> calendars_;
4615 // The clock a calendar's date is checked against.
4616 std::chrono::system_clock::time_point (*now_)() = [] {
4617 return std::chrono::system_clock::now();
4618 };
4619 net::io_context ioc_;
4620 std::shared_ptr<KisClient> client_;
4621};
4622
4623} // namespace algotradelib::kis
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Either a value or a BrokerError.
Definition types.hpp:1058
A blocking KIS client: each call runs a KisClient request on a private event loop and returns its res...
Definition client.hpp:4270
Result< TradingCalendar > calendar(Date from, bool refresh=false)
Returns the trading calendar from a date on; see KisClient::async_calendar (cached).
Definition client.hpp:4332
KisBlockingClient(ssl::context &context, KisConfig config, network::HttpClientOptions options={}, std::shared_ptr< network::TokenStore > store=nullptr, std::shared_ptr< network::CalendarCache > calendars=nullptr)
Constructs a client.
Definition client.hpp:4280
Result< OrderPage > order_history(KisAccount account, KisHistoryRange range)
Returns the orders placed over a date range, with their fills.
Definition client.hpp:4521
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns a quote; see KisClient::async_quote.
Definition client.hpp:4296
Result< KisOrderAck > replace_order(KisAccount account, KisAmendment amendment)
Amends an order's price or quantity; the outcome can be unknown after an error (see KisClient::async_...
Definition client.hpp:4475
Result< BuyingPower > buying_power(Currency currency, KisAccount account)
Returns the account's buying power, in won.
Definition client.hpp:4440
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns an instrument's recent trades.
Definition client.hpp:4383
Result< KisOpenOrderPage > open_orders(KisAccount account)
Returns the orders that can still be amended or cancelled; see KisClient::async_open_orders (includin...
Definition client.hpp:4506
Result< HoldingsSnapshot > holdings(KisAccount account)
Returns the account's holdings.
Definition client.hpp:4425
Result< Instrument > instrument(InstrumentId subject)
Returns an instrument's reference data.
Definition client.hpp:4310
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns an instrument's price band for today.
Definition client.hpp:4368
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics (safe to read between calls).
Definition client.hpp:4534
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns the order book (ten levels a side).
Definition client.hpp:4397
bool adopt_token(KisRest token)
Uses a token issued earlier; see KisClient::adopt_token.
Definition client.hpp:4551
Result< BarSeries > bars(BarQuery query)
Returns bars; see KisClient::async_bars.
Definition client.hpp:4411
KisRest token() const
Returns the access token; see KisClient::token.
Definition client.hpp:4542
Result< KisOrderAck > place_order(KisAccount account, OrderRequest order)
Places a cash order; see KisClient::async_place_order.
Definition client.hpp:4459
Result< KisOrderAck > cancel_order(KisAccount account, KisAmendment amendment)
Cancels an order; the outcome can be unknown after an error, and the order may still rest (see KisCli...
Definition client.hpp:4491
The asynchronous KIS REST client: market data, account inquiries and orders for domestic stocks.
Definition client.hpp:339
auto async_place_order(KisAccount account, OrderRequest order, CompletionToken &&token)
Places a cash order.
Definition client.hpp:645
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests a quote.
Definition client.hpp:561
net::any_completion_handler< void(std::optional< BrokerError >)> TokenHandler
The completion handler type of a token refresh (internal).
Definition client.hpp:377
net::any_completion_handler< void(Result< QuoteSnapshot >)> QuoteHandler
The completion handler type of async_quote.
Definition client.hpp:342
KisRest token() const
Returns the access token the client holds, to reuse in a later process (adopt_token).
Definition client.hpp:802
void close()
Closes the client for good: pending requests, and later ones that would send, complete with CANCELLED...
Definition client.hpp:892
auto async_calendar(Date from, bool refresh, CompletionToken &&token)
Requests the trading calendar from a date on, and caches it for the client's life.
Definition client.hpp:464
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:859
auto async_cancel_order(KisAccount account, KisAmendment amendment, CompletionToken &&token)
Cancels an order (all or part of it, as amendment says).
Definition client.hpp:708
net::any_completion_handler< void(Result< PriceLimits >)> PriceLimitsHandler
The completion handler type of async_price_limits.
Definition client.hpp:351
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests an instrument's recent trades.
Definition client.hpp:511
bool adopt_token(KisRest token)
Uses a token issued earlier for the same app key and environment instead of requesting one.
Definition client.hpp:822
net::any_completion_handler< void(Result< KisOpenOrderPage >)> OpenOrderHandler
The completion handler type of async_open_orders.
Definition client.hpp:371
net::any_completion_handler< void(Result< BarSeries >)> BarsHandler
The completion handler type of async_bars.
Definition client.hpp:345
auto async_holdings(KisAccount account, CompletionToken &&token)
Requests the account's holdings.
Definition client.hpp:606
net::any_completion_handler< void(Result< HoldingsSnapshot >)> HoldingsHandler
The completion handler type of async_holdings.
Definition client.hpp:363
net::any_completion_handler< void(Result< OrderPage >)> OrderPageHandler
The completion handler type of async_order_history.
Definition client.hpp:374
auto async_order_history(KisAccount account, KisHistoryRange range, CompletionToken &&token)
Requests the orders placed over a date range, with their fills.
Definition client.hpp:764
net::any_completion_handler< void(Result< Instrument >)> InstrumentHandler
The completion handler type of async_instrument.
Definition client.hpp:360
KisClient(net::any_io_executor executor, ssl::context &context, KisConfig config, network::HttpClientOptions options={})
Constructs a client; nothing is sent until the first request.
Definition client.hpp:390
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:786
net::any_completion_handler< void(Result< KisOrderAck >)> OrderAckHandler
The completion handler type of the order requests.
Definition client.hpp:368
bool adopt_calendar(TradingCalendar calendar)
Uses a calendar obtained earlier, such as from a network::CalendarCache, instead of requesting one wh...
Definition client.hpp:838
auto async_open_orders(KisAccount account, CompletionToken &&token)
Requests every order that can still be amended or cancelled.
Definition client.hpp:739
net::any_completion_handler< void(Result< DepthSnapshot >)> DepthHandler
The completion handler type of async_depth.
Definition client.hpp:348
net::any_completion_handler< void(Result< std::vector< TradePrint > >)> TradesHandler
The completion handler type of async_trades.
Definition client.hpp:354
net::any_completion_handler< void(Result< TradingCalendar >)> CalendarHandler
The completion handler type of async_calendar.
Definition client.hpp:357
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests an instrument's reference data.
Definition client.hpp:437
net::any_completion_handler< void(Result< BuyingPower >)> BuyingPowerHandler
The completion handler type of async_buying_power.
Definition client.hpp:365
auto async_replace_order(KisAccount account, KisAmendment amendment, CompletionToken &&token)
Amends an order's price or quantity.
Definition client.hpp:672
net::any_completion_handler< void(Result< KisRest >)> TokenResultHandler
The completion handler type of async_ensure_token.
Definition client.hpp:380
auto async_buying_power(Currency currency, KisAccount account, CompletionToken &&token)
Requests the account's buying power (the account-level amount, in won).
Definition client.hpp:584
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests an instrument's price band for today (from its current-price inquiry).
Definition client.hpp:484
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests the order book (ten levels a side).
Definition client.hpp:539
void forget_token()
Drops the held token: the next request asks for one.
Definition client.hpp:882
auto async_bars(BarQuery query, CompletionToken &&token)
Requests bars, reading KIS pages until count_ bars are collected.
Definition client.hpp:417
The Korea Investment & Securities (KIS) Open API client.
Definition auth.hpp:9
constexpr const char * market_division_code(MarketTape tape) noexcept
Returns KIS's FID_COND_MRKT_DIV_CODE for a tape.
Definition config.hpp:40
KisRateLimitLayer
Which of KIS's two request-rate limits a refusal reports.
Definition client.hpp:231
@ LEDGER
An endpoint's own cap shared by all customers (EGW00215; 120 per second for holdings and ETF quotes)....
Definition client.hpp:238
@ NONE
Not a rate-limit refusal.
Definition client.hpp:233
@ PERSONAL
This app key's own per-second limit (EGW00201); lower the budget.
Definition client.hpp:240
KisRateLimitLayer kis_rate_limit_layer(std::string_view code)
Classifies a KIS error code as a rate-limit refusal.
Definition client.hpp:251
Date today_in_seoul()
Returns today's date in Korea (UTC+9), the date KIS requests are made in.
Definition client.hpp:213
std::optional< BrokerError > unsupported_client_order_id(const OrderRequest &order)
Refuses an idempotency key, which KIS does not offer to individual customers.
Definition client.hpp:269
constexpr bool publishes_bar_interval(BarInterval interval) noexcept
Tests whether KIS publishes a chart at an interval.
Definition client.hpp:289
std::optional< BrokerError > unsupported_bar_interval(BarInterval interval)
Refuses a bar interval KIS publishes no chart for (publishes_bar_interval).
Definition client.hpp:311
const char * exchange_code(Venue venue) noexcept
Returns Kiwoom's dmst_stex_tp value for a venue.
Definition client.hpp:635
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
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
@ CANCEL
A cancellation (kt10003).
Definition errors.hpp:148
@ UNCLASSIFIED
Not an order request, or one this client does not classify.
Definition errors.hpp:142
@ PLACE
A placement (kt10000, kt10001).
Definition errors.hpp:144
constexpr std::array< KiwoomOrderShapeRow, 21 > kOrderShapes
Kiwoom's order-type (trde_tp) table, from its API specification.
Definition client.hpp:533
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
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
HTTP and WebSocket transport, OAuth tokens, and request pacing.
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
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
Definition concept.hpp:309
MarketSegment market_segment(std::string_view code)
Maps a broker's segment code to a MarketSegment.
SecurityType
What kind of security an instrument is.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
std::optional< std::chrono::system_clock::time_point > parse_iso8601_timestamp(std::string_view value)
Parses an ISO 8601 timestamp, YYYY-MM-DDTHH:MM:SS[.fraction] followed by Z or a +hh:mm/-hh:mm offset.
Definition types.hpp:2766
@ 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
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
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
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
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
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
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
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
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
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
std::vector< TradingDay > days_
The days the broker reported, ascending. A date outside them is uncovered, not closed.
Definition calendar.hpp:76
Country country_
The market this calendar is for.
Definition calendar.hpp:74
A KIS account: the account number and product code every account request names.
Definition client.hpp:31
void from_json_text(std::string_view text, const std::string &origin)
Loads the account from JSON text in the credential file's format, the same document KisConfig::from_j...
Definition client.hpp:81
void from_env()
Loads the account from the KIS_CANO and (optional, default "01") KIS_ACNT_PRDT_CD environment variabl...
Definition client.hpp:42
std::string product_code_
The two-digit product code (KIS's ACNT_PRDT_CD); "01" for a cash equity account.
Definition client.hpp:35
std::string account_number_
The eight-digit account number (KIS's CANO).
Definition client.hpp:33
void from_json(const std::string &filename)
Loads the account from a credential file's account_number (eight digits) and account_product_code (tw...
Definition client.hpp:63
An amendment or cancellation of a KIS order.
Definition client.hpp:128
bool all_remaining_
Whether the whole remaining quantity is affected (KIS's QTY_ALL_ORD_YN), rather than quantity_.
Definition client.hpp:152
OrderType type_
The order type it should have.
Definition client.hpp:132
KisOrderRef order_
The order to amend or cancel.
Definition client.hpp:130
std::optional< Decimal64 > trigger_price_
The trigger price (KIS's CNDT_PRIC), for a STOP_LIMIT order.
Definition client.hpp:150
OrderSession session_
The session it should be in.
Definition client.hpp:136
Decimal64 quantity_
The quantity affected; KIS requires a positive whole number even with all_remaining_.
Definition client.hpp:140
TimeInForce time_in_force_
The execution condition it should have.
Definition client.hpp:134
std::optional< Decimal64 > price_
The price the order should have: required for an order type that takes one, on a cancellation too.
Definition client.hpp:142
Venue venue_
The venue where the order rests (the codes differ by venue).
Definition client.hpp:138
KIS credentials (app key and secret), demo or real account, and the market-data tape.
Definition config.hpp:83
bool is_demo_
Whether to use KIS's demo (모의투자) endpoints; true unless stated otherwise.
Definition config.hpp:94
The date range of a KIS order-history inquiry, both ends included (Korean dates).
Definition client.hpp:202
KIS's list of orders that can still be amended or cancelled.
Definition client.hpp:194
std::vector< KisOpenOrder > orders_
The orders.
Definition client.hpp:196
std::chrono::system_clock::time_point received_at_
When the list arrived, on this machine's clock.
Definition client.hpp:198
A KIS order that can still be amended or cancelled.
Definition client.hpp:171
KisOrderRef original_order_
The order this one superseded by amendment (KIS's orgn_odno); for no such order, all zeros on demo (d...
Definition client.hpp:180
std::string stop_released_
KIS's stpm_efct_occr_yn (whether a stop order has triggered), verbatim; empty if the row has none.
Definition client.hpp:190
Decimal64 amendable_quantity_
The quantity KIS says may still be amended or cancelled.
Definition client.hpp:182
OrderSnapshot order_
The order.
Definition client.hpp:173
KisOrderRef order_ref_
The reference an amendment or cancellation must address.
Definition client.hpp:175
KIS's acknowledgement of an accepted order, amendment or cancellation.
Definition client.hpp:161
std::string broker_order_time_
KIS's ORD_TMD, verbatim: an HHMMSS time with no date or zone (Korean time).
Definition client.hpp:167
KisOrderRef order_
The reference an amendment or cancellation must address.
Definition client.hpp:165
OrderAck ack_
The acknowledgement; accepted_at_ is when this machine received it.
Definition client.hpp:163
A KIS order's address: branch number and order number, both kept.
Definition client.hpp:111
std::string order_number_
The order number within that branch (KIS's ODNO).
Definition client.hpp:115
std::string branch_number_
The branch that recorded the order (KIS's KRX_FWDG_ORD_ORGNO).
Definition client.hpp:113
A KIS REST access token and its expiry.
Definition config.hpp:281
bool valid() const noexcept
Tests whether the token is set and stays valid for at least five more minutes.
Definition config.hpp:323
Deadlines, size limits and pacing for an HTTP client.
std::optional< bool > fresh_connection_for_orders_
Whether AsyncHttpClient writes every order (RateLimitGroup::TRADING) on a connection no request has u...
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...