algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
client.hpp
1#pragma once
2
3#include "../common/adapter.hpp"
4#include "../common/krx.hpp"
5#include "./config.hpp"
6
7#include <boost/asio/any_completion_handler.hpp>
8#include <boost/asio/associated_executor.hpp>
9#include <boost/asio/async_result.hpp>
10#include <boost/asio/dispatch.hpp>
11#include <boost/asio/post.hpp>
12#include <boost/asio/strand.hpp>
13
14#include <algorithm>
15#include <cstdint>
16#include <cstdio>
17#include <deque>
18#include <limits>
19#include <memory>
20#include <optional>
21#include <stdexcept>
22#include <string>
23#include <type_traits>
24#include <utility>
25#include <vector>
26
28
32 std::string account_number_;
34 std::int64_t sequence_{0};
36 std::string account_type_;
37};
38
42enum class TossOrderScope {
44 OPEN,
47};
48
58 std::int64_t account_sequence_{0};
62 std::optional<std::string> symbol_;
64 std::optional<Date> from_;
66 std::optional<Date> to_;
68 std::optional<std::string> cursor_;
70 std::optional<int> limit_;
71};
72
81 std::string order_id_;
85 std::optional<Decimal64> quantity_;
87 std::optional<Decimal64> price_;
90};
91
97inline std::optional<std::chrono::seconds> retry_after(const network::HttpResponse& response) {
98 const auto seconds = broker_detail::integer_header(response, "Retry-After");
99 if (!seconds) {
100 return std::nullopt;
101 }
102 return std::chrono::seconds(*seconds);
103}
104
110inline std::optional<int> reported_rate_limit(const network::HttpResponse& response) {
111 const auto limit = broker_detail::integer_header(response, "X-RateLimit-Limit");
112 if (!limit || *limit < 1 || *limit > std::numeric_limits<int>::max()) {
113 return std::nullopt;
114 }
115 return static_cast<int>(*limit);
116}
117
124inline std::optional<BrokerError> unsupported_bar_interval(BarInterval interval) {
125 if (interval == BarInterval::ONE_MINUTE || interval == BarInterval::ONE_DAY) {
126 return std::nullopt;
127 }
128 BrokerError error;
130 error.reached_broker_ = false;
131 error.broker_code_ = "unsupported_interval";
132 error.message_ =
133 "Toss publishes one-minute and one-day bars only; gate on "
134 "BrokerCaps<Client>::supports_interval before asking for another";
135 return error;
136}
137
138class TossBlockingClient;
139
149class TossClient : public std::enable_shared_from_this<TossClient> {
150public:
152 using QuoteHandler = net::any_completion_handler<void(Result<QuoteSnapshot>)>;
153
155 using BarsHandler = net::any_completion_handler<void(Result<BarSeries>)>;
156
158 using DepthHandler = net::any_completion_handler<void(Result<DepthSnapshot>)>;
159
161 using PriceLimitsHandler = net::any_completion_handler<void(Result<PriceLimits>)>;
162
164 using TradesHandler = net::any_completion_handler<void(Result<std::vector<TradePrint>>)>;
165
167 using PricesHandler = net::any_completion_handler<void(Result<std::vector<QuoteSnapshot>>)>;
168
170 using CalendarHandler = net::any_completion_handler<void(Result<TradingCalendar>)>;
171
173 using InstrumentHandler = net::any_completion_handler<void(Result<Instrument>)>;
175 using AccountsHandler = net::any_completion_handler<void(Result<std::vector<TossAccount>>)>;
176
178 using HoldingsHandler = net::any_completion_handler<void(Result<HoldingsSnapshot>)>;
180 using BuyingPowerHandler = net::any_completion_handler<void(Result<BuyingPower>)>;
182 using SellableQuantityHandler = net::any_completion_handler<void(Result<Decimal64>)>;
184 using CommissionScheduleHandler = net::any_completion_handler<void(Result<CommissionSchedule>)>;
185
187 using OrderAckHandler = net::any_completion_handler<void(Result<OrderAck>)>;
188
190 using OrderPageHandler = net::any_completion_handler<void(Result<OrderPage>)>;
191
193 using OrderHandler = net::any_completion_handler<void(Result<OrderSnapshot>)>;
194
196 using TokenHandler = net::any_completion_handler<void(std::optional<BrokerError>)>;
197
199 using TokenResultHandler = net::any_completion_handler<void(Result<TossRest>)>;
200
209 net::any_io_executor executor, ssl::context& context, TossConfig config, network::HttpClientOptions options = {}
210 )
211 : strand_(net::make_strand(std::move(executor))),
212 config_(std::move(config)),
213 http_(std::make_shared<network::AsyncHttpClient>(strand_, context, "openapi.tossinvest.com", "443", options)) {}
214
226 template <typename CompletionToken>
227 auto async_bars(BarQuery query, CompletionToken&& token) {
228 return net::async_initiate<CompletionToken, void(Result<BarSeries>)>(
229 [self = shared_from_this(), query = std::move(query)](auto&& handler) mutable {
230 auto completion = BarsHandler(std::forward<decltype(handler)>(handler));
231 net::post(self->strand_, [self, query = std::move(query), completion = std::move(completion)]() mutable {
232 self->start_bars(std::move(query), std::move(completion));
233 });
234 },
235 token
236 );
237 }
238
249 template <typename CompletionToken>
250 auto async_calendar(Country country, std::optional<Date> from, CompletionToken&& token) {
251 return net::async_initiate<CompletionToken, void(Result<TradingCalendar>)>(
252 [self = shared_from_this(), country, from](auto&& handler) mutable {
253 auto completion = CalendarHandler(std::forward<decltype(handler)>(handler));
254 net::post(self->strand_, [self, country, from, completion = std::move(completion)]() mutable {
255 self->start_calendar(country, from, std::move(completion));
256 });
257 },
258 token
259 );
260 }
261
269 template <typename CompletionToken>
270 auto async_instrument(InstrumentId instrument, CompletionToken&& token) {
271 return net::async_initiate<CompletionToken, void(Result<Instrument>)>(
272 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
273 auto completion = InstrumentHandler(std::forward<decltype(handler)>(handler));
274 net::post(
275 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
276 self->start_market_read(
277 std::move(instrument), "/api/v1/stocks?symbols=", std::move(completion), parse_instrument
278 );
279 }
280 );
281 },
282 token
283 );
284 }
285
293 template <typename CompletionToken>
294 auto async_price_limits(InstrumentId instrument, CompletionToken&& token) {
295 return net::async_initiate<CompletionToken, void(Result<PriceLimits>)>(
296 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
297 auto completion = PriceLimitsHandler(std::forward<decltype(handler)>(handler));
298 net::post(
299 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
300 self->start_market_read(
301 std::move(instrument), "/api/v1/price-limits?symbol=", std::move(completion), parse_price_limits
302 );
303 }
304 );
305 },
306 token
307 );
308 }
309
318 template <typename CompletionToken>
319 auto async_trades(InstrumentId instrument, int count, CompletionToken&& token) {
320 return net::async_initiate<CompletionToken, void(Result<std::vector<TradePrint>>)>(
321 [self = shared_from_this(), instrument = std::move(instrument), count](auto&& handler) mutable {
322 auto completion = TradesHandler(std::forward<decltype(handler)>(handler));
323 net::post(
324 self->strand_,
325 [self, instrument = std::move(instrument), count, completion = std::move(completion)]() mutable {
326 // Toss caps this at fifty prints; asking for more would be answered with
327 // fifty anyway, so the cap is applied here rather than silently by the
328 // broker.
329 const int wanted = count < 1 ? 1 : (count > trade_limit_ ? trade_limit_ : count);
330 self->start_market_read(
331 std::move(instrument),
332 "/api/v1/trades?count=" + std::to_string(wanted) + "&symbol=", std::move(completion), parse_trades
333 );
334 }
335 );
336 },
337 token
338 );
339 }
340
348 template <typename CompletionToken>
349 auto async_prices(std::vector<InstrumentId> instruments, CompletionToken&& token) {
350 return net::async_initiate<CompletionToken, void(Result<std::vector<QuoteSnapshot>>)>(
351 [self = shared_from_this(), instruments = std::move(instruments)](auto&& handler) mutable {
352 auto completion = PricesHandler(std::forward<decltype(handler)>(handler));
353 net::post(
354 self->strand_, [self, instruments = std::move(instruments), completion = std::move(completion)]() mutable {
355 self->start_prices(std::move(instruments), std::move(completion));
356 }
357 );
358 },
359 token
360 );
361 }
362
370 template <typename CompletionToken>
371 auto async_depth(InstrumentId instrument, CompletionToken&& token) {
372 return net::async_initiate<CompletionToken, void(Result<DepthSnapshot>)>(
373 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
374 auto completion = DepthHandler(std::forward<decltype(handler)>(handler));
375 net::post(
376 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
377 self->start_depth(std::move(instrument), std::move(completion));
378 }
379 );
380 },
381 token
382 );
383 }
384
393 template <typename CompletionToken>
394 auto async_quote(InstrumentId instrument, CompletionToken&& token) {
395 return net::async_initiate<CompletionToken, void(Result<QuoteSnapshot>)>(
396 [self = shared_from_this(), instrument = std::move(instrument)](auto&& handler) mutable {
397 auto completion = QuoteHandler(std::forward<decltype(handler)>(handler));
398 net::post(
399 self->strand_, [self, instrument = std::move(instrument), completion = std::move(completion)]() mutable {
400 self->start_quote(std::move(instrument), std::move(completion));
401 }
402 );
403 },
404 token
405 );
406 }
407
414 template <typename CompletionToken>
415 auto async_accounts(CompletionToken&& token) {
416 return net::async_initiate<CompletionToken, void(Result<std::vector<TossAccount>>)>(
417 [self = shared_from_this()](auto&& handler) mutable {
418 auto completion = AccountsHandler(std::forward<decltype(handler)>(handler));
419 net::post(self->strand_, [self, completion = std::move(completion)]() mutable {
420 self->start_accounts(std::move(completion));
421 });
422 },
423 token
424 );
425 }
426
435 template <typename CompletionToken>
436 auto async_buying_power(Currency currency, std::int64_t account_sequence, CompletionToken&& token) {
437 return net::async_initiate<CompletionToken, void(Result<BuyingPower>)>(
438 [self = shared_from_this(), currency, account_sequence](auto&& handler) mutable {
439 auto completion = BuyingPowerHandler(std::forward<decltype(handler)>(handler));
440 net::post(self->strand_, [self, currency, account_sequence, completion = std::move(completion)]() mutable {
441 self->start_buying_power(currency, account_sequence, std::move(completion));
442 });
443 },
444 token
445 );
446 }
447
456 template <typename CompletionToken>
457 auto async_sellable_quantity(InstrumentId instrument, std::int64_t account_sequence, CompletionToken&& token) {
458 return net::async_initiate<CompletionToken, void(Result<Decimal64>)>(
459 [self = shared_from_this(), instrument = std::move(instrument), account_sequence](auto&& handler) mutable {
460 auto completion = SellableQuantityHandler(std::forward<decltype(handler)>(handler));
461 net::post(
462 self->strand_,
463 [self, instrument = std::move(instrument), account_sequence, completion = std::move(completion)]() mutable {
464 self->start_sellable_quantity(std::move(instrument), account_sequence, std::move(completion));
465 }
466 );
467 },
468 token
469 );
470 }
471
479 template <typename CompletionToken>
480 auto async_commissions(std::int64_t account_sequence, CompletionToken&& token) {
481 return net::async_initiate<CompletionToken, void(Result<CommissionSchedule>)>(
482 [self = shared_from_this(), account_sequence](auto&& handler) mutable {
483 auto completion = CommissionScheduleHandler(std::forward<decltype(handler)>(handler));
484 net::post(self->strand_, [self, account_sequence, completion = std::move(completion)]() mutable {
485 self->start_commissions(account_sequence, std::move(completion));
486 });
487 },
488 token
489 );
490 }
491
499 template <typename CompletionToken>
500 auto async_holdings(std::int64_t account_sequence, CompletionToken&& token) {
501 return net::async_initiate<CompletionToken, void(Result<HoldingsSnapshot>)>(
502 [self = shared_from_this(), account_sequence](auto&& handler) mutable {
503 auto completion = HoldingsHandler(std::forward<decltype(handler)>(handler));
504 net::post(self->strand_, [self, account_sequence, completion = std::move(completion)]() mutable {
505 self->start_holdings(account_sequence, std::move(completion));
506 });
507 },
508 token
509 );
510 }
511
535 template <typename CompletionToken>
536 auto async_place_order(std::int64_t account_sequence, OrderRequest order, CompletionToken&& token) {
537 return net::async_initiate<CompletionToken, void(Result<OrderAck>)>(
538 [self = shared_from_this(), account_sequence, order = std::move(order)](auto&& handler) mutable {
539 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
540 net::post(
541 self->strand_,
542 [self, account_sequence, order = std::move(order), completion = std::move(completion)]() mutable {
543 self->start_place_order(account_sequence, std::move(order), std::move(completion));
544 }
545 );
546 },
547 token
548 );
549 }
550
567 template <typename CompletionToken>
568 auto async_replace_order(std::int64_t account_sequence, TossAmendment amendment, CompletionToken&& token) {
569 return net::async_initiate<CompletionToken, void(Result<OrderAck>)>(
570 [self = shared_from_this(), account_sequence, amendment = std::move(amendment)](auto&& handler) mutable {
571 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
572 net::post(
573 self->strand_,
574 [self, account_sequence, amendment = std::move(amendment), completion = std::move(completion)]() mutable {
575 self->start_replace_order(account_sequence, std::move(amendment), std::move(completion));
576 }
577 );
578 },
579 token
580 );
581 }
582
597 template <typename CompletionToken>
598 auto async_cancel_order(std::int64_t account_sequence, std::string order_id, CompletionToken&& token) {
599 return net::async_initiate<CompletionToken, void(Result<OrderAck>)>(
600 [self = shared_from_this(), account_sequence, order_id = std::move(order_id)](auto&& handler) mutable {
601 auto completion = OrderAckHandler(std::forward<decltype(handler)>(handler));
602 net::post(
603 self->strand_,
604 [self, account_sequence, order_id = std::move(order_id), completion = std::move(completion)]() mutable {
605 self->start_cancel_order(account_sequence, std::move(order_id), std::move(completion));
606 }
607 );
608 },
609 token
610 );
611 }
612
628 template <typename CompletionToken>
629 auto async_orders(TossOrderQuery query, CompletionToken&& token) {
630 return net::async_initiate<CompletionToken, void(Result<OrderPage>)>(
631 [self = shared_from_this(), query = std::move(query)](auto&& handler) mutable {
632 auto completion = OrderPageHandler(std::forward<decltype(handler)>(handler));
633 net::post(self->strand_, [self, query = std::move(query), completion = std::move(completion)]() mutable {
634 self->start_orders(std::move(query), std::move(completion));
635 });
636 },
637 token
638 );
639 }
640
654 template <typename CompletionToken>
655 auto async_order(std::int64_t account_sequence, std::string order_id, CompletionToken&& token) {
656 return net::async_initiate<CompletionToken, void(Result<OrderSnapshot>)>(
657 [self = shared_from_this(), account_sequence, order_id = std::move(order_id)](auto&& handler) mutable {
658 auto completion = OrderHandler(std::forward<decltype(handler)>(handler));
659 net::post(
660 self->strand_,
661 [self, account_sequence, order_id = std::move(order_id), completion = std::move(completion)]() mutable {
662 self->start_order(account_sequence, std::move(order_id), std::move(completion));
663 }
664 );
665 },
666 token
667 );
668 }
669
679 const auto* limiter = http_->rate_limits();
680 return limiter ? &limiter->stats() : nullptr;
681 }
682
695 TossRest token() const {
696 return token_;
697 }
698
715 if (!token.valid()) {
716 return false;
717 }
718 token_ = std::move(token);
719 return true;
720 }
721
729 template <typename CompletionToken>
730 auto async_ensure_token(CompletionToken&& token) {
731 return net::async_initiate<CompletionToken, void(Result<TossRest>)>(
732 [self = shared_from_this()](auto&& handler) mutable {
733 auto completion = TokenResultHandler(std::forward<decltype(handler)>(handler));
734 net::post(self->strand_, [self, completion = std::move(completion)]() mutable {
735 self->request_token(
736 TokenHandler([self, completion = std::move(completion)](std::optional<BrokerError> error) mutable {
737 self->deliver(
738 std::move(completion), error ? Result<TossRest>(std::move(*error)) : Result<TossRest>(self->token_)
739 );
740 })
741 );
742 });
743 },
744 token
745 );
746 }
747
754 token_ = TossRest{};
755 }
756
758 void close() {
759 http_->close();
760 }
761
762private:
763 friend struct TossClientTestAccess;
764 friend class TossBlockingClient;
765
766 net::strand<net::any_io_executor> strand_;
767 TossConfig config_;
768 std::shared_ptr<network::AsyncHttpClient> http_;
769 TossRest token_;
770 bool refreshing_{false};
771 std::deque<TokenHandler> token_waiters_;
772 // Set by a blocking client with a token store, which prepares every token under the store's lock.
773 bool store_managed_{false};
774
775 // One bar request spanning however many pages Toss needs to answer it.
776 //
777 // `descending_` accumulates pages exactly as Toss sends them — newest first,
778 // each page older than the last — and is reversed once when the operation
779 // finishes. Reversing per page, or inserting at the front, would do the same
780 // work repeatedly for no benefit.
781 struct BarOperation {
782 BarQuery query_;
783 Currency currency_;
784 std::vector<Bar> descending_;
785 std::optional<std::string> before_;
786 std::optional<std::string> last_cursor_;
787 int pages_{0};
788 BarsHandler completion_;
789
790 BarOperation(BarQuery query, BarsHandler completion)
791 : query_(std::move(query)), completion_(std::move(completion)) {
792 if (query_.before_) {
793 before_ = format_iso8601_utc(*query_.before_);
794 }
795 }
796 };
797
798 // Largest number of bars Toss returns in one page.
799 static constexpr int bar_page_limit_ = 200;
800
801 // Most pages one bar request may consume.
802 //
803 // A bound is needed because a broker that kept returning a cursor would
804 // otherwise page forever. Fifty pages is 10,000 bars, far beyond any window a
805 // caller asks for in one call, so reaching it means something is wrong rather
806 // than that the caller was unlucky.
807 static constexpr int bar_page_budget_ = 50;
808
809 // Validates a bar request and starts paging.
810 void start_bars(BarQuery query, BarsHandler completion) {
811 if (auto invalid = validate_bar_query(query)) {
812 deliver(std::move(completion), Result<BarSeries>(std::move(*invalid)));
813 return;
814 }
815
816 auto operation = std::make_shared<BarOperation>(std::move(query), std::move(completion));
817 ensure_token(TokenHandler([self = shared_from_this(), operation](std::optional<BrokerError> token_error) mutable {
818 if (token_error) {
819 self->deliver(std::move(operation->completion_), Result<BarSeries>(std::move(*token_error)));
820 return;
821 }
822 self->request_bars(operation);
823 }));
824 }
825
826 // Returns an error when Toss cannot answer the request as described.
827 static std::optional<BrokerError> validate_bar_query(const BarQuery& query) {
828 BrokerError error;
829 error.category_ = ErrorCategory::INVALID_ARGUMENT;
830 error.reached_broker_ = false;
831 if (!broker_detail::valid_symbol(query.instrument_.symbol_)) {
832 error.broker_code_ = "invalid_instrument";
833 error.message_ = "bar request requires a symbol";
834 return error;
835 }
836 if (query.count_ < 1) {
837 error.broker_code_ = "invalid_count";
838 error.message_ = "bar request must ask for at least one bar";
839 return error;
840 }
841 return unsupported_bar_interval(query.interval_);
842 }
843
844 // Returns Toss's code for a supported interval.
845 static const char* bar_interval_code(BarInterval interval) {
846 return interval == BarInterval::ONE_MINUTE ? "1m" : "1d";
847 }
848
849 // Sends the next page of a bar request.
850 void request_bars(const std::shared_ptr<BarOperation>& operation) {
851 const int outstanding = operation->query_.count_ - static_cast<int>(operation->descending_.size());
852 const int wanted = outstanding > bar_page_limit_ ? bar_page_limit_ : outstanding;
853
854 std::string target =
855 "/api/v1/candles?symbol=" + broker_detail::query_encode(operation->query_.instrument_.symbol_) +
856 "&interval=" + bar_interval_code(operation->query_.interval_) + "&count=" + std::to_string(wanted) +
857 "&adjusted=" + (operation->query_.adjusted_ ? "true" : "false");
858 if (operation->before_) {
859 target += "&before=" + broker_detail::query_encode(*operation->before_);
860 }
861
862 network::HttpRequest request;
863 // Bars are the traffic a trading reserve exists to hold back.
865 request.method_ = http::verb::get;
866 request.target_ = std::move(target);
867 request.headers_.emplace_back("Authorization", "Bearer " + token_.access_token_);
868
869 ++operation->pages_;
870 send(std::move(request), [self = shared_from_this(), operation](Result<network::HttpResponse> result) mutable {
871 self->handle_bars_page(operation, std::move(result));
872 });
873 }
874
875 // Accumulates one page and either continues or finishes the request.
876 void handle_bars_page(const std::shared_ptr<BarOperation>& operation, Result<network::HttpResponse> result) {
877 std::optional<std::string> cursor;
878 auto appended =
879 parse_bars_page(std::move(result), operation->query_, operation->descending_, cursor, operation->currency_);
880 if (appended) {
881 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(*appended)));
882 return;
883 }
884
885 const int collected = static_cast<int>(operation->descending_.size());
886 const bool satisfied = collected >= operation->query_.count_;
887 const bool exhausted = !cursor || cursor->empty();
888 const bool repeated = cursor && operation->last_cursor_ && *cursor == *operation->last_cursor_;
889 const bool spent = operation->pages_ >= bar_page_budget_;
890 if (satisfied || exhausted || repeated || spent) {
891 finish_bars(operation, cursor);
892 return;
893 }
894
895 operation->last_cursor_ = cursor;
896 operation->before_ = cursor;
897 request_bars(operation);
898 }
899
900 // Parses one page into the operation, or returns the error that ends it.
901 //
902 // A page that parses but contains no bar also ends the request: a broker that
903 // returns an empty page while still reporting a cursor would otherwise be paged
904 // forever.
905 //
906 // Takes the accumulation and cursor by reference rather than an operation, so the
907 // normalization is a pure function of a response and can be tested as one.
908 static std::optional<BrokerError> parse_bars_page(
909 Result<network::HttpResponse> result, const BarQuery& query, std::vector<Bar>& into,
910 std::optional<std::string>& cursor, Currency& currency
911 ) {
912 if (!result) {
913 return std::move(result.error());
914 }
915 BrokerError parse_error;
916 auto document = broker_detail::parse_object(result.value(), parse_error);
917 if (!document) {
918 return parse_error;
919 }
920 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
921 return toss_error(result.value(), *document);
922 }
923
924 try {
925 const auto& payload = required_object(*document, "result");
926 const auto rows = payload.if_contains("candles");
927 if (!rows || !rows->is_array()) {
928 throw std::runtime_error("missing array field: candles");
929 }
930 const auto before = into.size();
931 for (const auto& value : rows->as_array()) {
932 if (!value.is_object()) {
933 throw std::runtime_error("candle entry is not an object");
934 }
935 const auto& row = value.as_object();
936 // The currency belongs to the series, so it is read once and then checked:
937 // a page that changed currency mid-series would not be one series.
938 const auto stated = Currency(broker_detail::json_string(row, "currency"));
939 if (into.empty() && before == 0) {
940 currency = stated;
941 } else if (!(stated == currency)) {
942 throw std::runtime_error("candle currency changed within one series");
943 }
944 into.push_back(parse_bar(row, query));
945 }
946 if (into.size() == before) {
947 cursor.reset();
948 return std::nullopt;
949 }
950 if (const auto next = payload.if_contains("nextBefore"); next && next->is_string()) {
951 cursor = std::string(next->as_string());
952 } else {
953 cursor.reset();
954 }
955 return std::nullopt;
956 } catch (const std::exception& exception) {
957 BrokerError error;
958 error.category_ = ErrorCategory::PROTOCOL;
959 error.broker_code_ = "invalid_candle_response";
960 error.message_ = exception.what();
961 return error;
962 }
963 }
964
965 // Normalizes one Toss candle.
966 //
967 // Toss stamps a one-minute bar at the instant it closed, aggregating
968 // `[t - 1m, t)`, and a one-day bar at local midnight, which is its open. The
969 // convention travels in the bar, because reading one as the other is a lookahead
970 // no timestamp can reveal.
971 static Bar parse_bar(const json::object& row, const BarQuery& query) {
972 static_cast<void>(query);
973 Bar bar;
974 const auto timestamp = parse_iso8601_timestamp(broker_detail::json_string(row, "timestamp"));
975 if (!timestamp) {
976 throw std::runtime_error("invalid candle timestamp");
977 }
978 bar.timestamp_ = *timestamp;
979 bar.open_ = Decimal64::parse(broker_detail::json_string(row, "openPrice"));
980 bar.high_ = Decimal64::parse(broker_detail::json_string(row, "highPrice"));
981 bar.low_ = Decimal64::parse(broker_detail::json_string(row, "lowPrice"));
982 bar.close_ = Decimal64::parse(broker_detail::json_string(row, "closePrice"));
983 bar.volume_ = Decimal64::parse(broker_detail::json_string(row, "volume"));
984 return bar;
985 }
986
987 // Reverses the accumulation and trims to the requested count.
988 //
989 // Paging runs backwards from the newest bar, so an overshoot is always at the
990 // old end; the newest `count_` bars are what the caller asked for.
991 void finish_bars(const std::shared_ptr<BarOperation>& operation, const std::optional<std::string>& cursor) {
992 BarSeries series;
993 series.instrument_ = operation->query_.instrument_;
994 series.interval_ = operation->query_.interval_;
995 // Toss stamps a one-minute bar at the instant it closed, aggregating
996 // `[t - 1m, t)`, and a one-day bar at local midnight, which is its open.
997 series.stamp_ = operation->query_.interval_ == BarInterval::ONE_MINUTE ? BarStamp::CLOSE : BarStamp::OPEN;
998 series.currency_ = operation->currency_;
999 series.adjusted_ = operation->query_.adjusted_;
1000 series.received_at_ = std::chrono::system_clock::now();
1001
1002 auto& bars = operation->descending_;
1003 if (static_cast<int>(bars.size()) > operation->query_.count_) {
1004 bars.resize(static_cast<std::size_t>(operation->query_.count_));
1005 }
1006 series.bars_.assign(bars.rbegin(), bars.rend());
1007 if (cursor && !cursor->empty()) {
1008 series.next_cursor_ = *cursor;
1009 }
1010 deliver(std::move(operation->completion_), Result<BarSeries>(std::move(series)));
1011 }
1012
1013 // Returns the `result` member of a market-data response, or the error ending it.
1014 //
1015 // Toss wraps every market-data answer in `result`, sometimes as an object and
1016 // sometimes as a bare array, so the shape check belongs to each parser while the
1017 // status, envelope, and JSON handling belong here once.
1018 static Result<json::value> market_result(Result<network::HttpResponse> response) {
1019 if (!response) {
1020 return Result<json::value>(std::move(response.error()));
1021 }
1022 BrokerError parse_error;
1023 auto document = broker_detail::parse_object(response.value(), parse_error);
1024 if (!document) {
1025 return Result<json::value>(std::move(parse_error));
1026 }
1027 if (response.value().result_int() < 200 || response.value().result_int() >= 300) {
1028 return Result<json::value>(toss_error(response.value(), *document));
1029 }
1030 const auto payload = document->if_contains("result");
1031 if (!payload) {
1032 BrokerError error;
1033 error.category_ = ErrorCategory::PROTOCOL;
1034 error.broker_code_ = "invalid_market_response";
1035 error.message_ = "response carries no result";
1036 return Result<json::value>(std::move(error));
1037 }
1038 return Result<json::value>(std::move(*payload));
1039 }
1040
1041 // Normalizes Toss's reference data for one instrument.
1042 //
1043 // The identity comes from the instrument the caller asked about rather than from
1044 // the response's symbol, so the country and venue the caller stated survive.
1045 //
1046 // `price_rule_` is the library's own grid, not Toss's: Toss names a tick only when it refuses an
1047 // off-tick price, so the rule is chosen from the market rather than normalized from a field.
1048 static Result<Instrument> parse_instrument(InstrumentId requested, Result<network::HttpResponse> result) {
1049 auto payload = market_result(std::move(result));
1050 if (!payload) {
1051 return Result<Instrument>(std::move(payload.error()));
1052 }
1053 try {
1054 if (!payload.value().is_array() || payload.value().as_array().empty()) {
1055 throw std::runtime_error("reference data result is not a non-empty array");
1056 }
1057 const auto& row = payload.value().as_array().front().as_object();
1058 if (broker_detail::json_string(row, "symbol") != requested.symbol_) {
1059 throw std::runtime_error("reference data response symbol does not match request");
1060 }
1061
1062 Instrument instrument;
1063 instrument.id_ = std::move(requested);
1064 instrument.name_ = broker_detail::json_string(row, "name");
1065 instrument.english_name_ = broker_detail::json_string(row, "englishName");
1066 instrument.isin_ = broker_detail::json_string(row, "isinCode");
1067 instrument.segment_ = market_segment(broker_detail::json_string(row, "market"));
1068 instrument.type_ = normalized_security_type(broker_detail::json_string(row, "securityType"));
1069 instrument.status_ = normalized_listing_status(broker_detail::json_string(row, "status"));
1070 instrument.currency_ = Currency(broker_detail::json_string(row, "currency"));
1071 if (const auto value = row.if_contains("isCommonShare"); value && value->is_bool()) {
1072 instrument.common_share_ = value->as_bool();
1073 }
1074 // **A listing date the broker stated and this library cannot read is recorded as unreadable,
1075 // and the row survives.** This used to fail the whole read, because `Instrument` then had
1076 // nowhere to record damage and an empty `delisted_on_` read as "still listed". `StatedDate`
1077 // is that place, and it has no spelling of the old reading, so the refusal would now only
1078 // cost the currency and the price grid of an instrument that is otherwise fully described.
1079 instrument.listed_on_ = stated_calendar_date(row, "listDate");
1080 instrument.delisted_on_ = stated_calendar_date(row, "delistDate");
1081 instrument.shares_outstanding_ = nullable_decimal(row, "sharesOutstanding");
1082 // A cast country keeps the unknown rule.
1083 instrument.price_rule_ = PriceRule::unknown("no price grid is known for this market");
1084 switch (instrument.id_.country_) {
1085 case Country::KR:
1086 instrument.price_rule_ = krx::price_rule_for(instrument.type_);
1087 break;
1088 case Country::US:
1089 instrument.price_rule_ = PriceRule::unconstrained();
1090 break;
1091 }
1092 return Result<Instrument>(std::move(instrument));
1093 } catch (const std::exception& exception) {
1094 return Result<Instrument>(market_error("invalid_reference_response", exception));
1095 }
1096 }
1097
1098 // Maps Toss's security type, tolerating a value this library has not normalized.
1099 static SecurityType normalized_security_type(std::string_view code) {
1100 if (code == "STOCK") {
1101 return SecurityType::STOCK;
1102 }
1103 if (code == "FOREIGN_STOCK") {
1104 return SecurityType::FOREIGN_STOCK;
1105 }
1106 if (code == "DEPOSITARY_RECEIPT") {
1107 return SecurityType::DEPOSITARY_RECEIPT;
1108 }
1109 if (code == "INFRASTRUCTURE_FUND") {
1110 return SecurityType::INFRASTRUCTURE_FUND;
1111 }
1112 if (code == "REIT") {
1113 return SecurityType::REIT;
1114 }
1115 if (code == "ETF") {
1116 return SecurityType::ETF;
1117 }
1118 if (code == "FOREIGN_ETF") {
1119 return SecurityType::FOREIGN_ETF;
1120 }
1121 if (code == "ETN") {
1122 return SecurityType::ETN;
1123 }
1124 if (code == "STOCK_WARRANTS") {
1125 return SecurityType::STOCK_WARRANT;
1126 }
1127 return SecurityType::UNKNOWN;
1128 }
1129
1130 // Maps Toss's listing status, tolerating an unfamiliar value.
1131 //
1132 // Named apart from the order-status mapper on purpose: a listing status and an
1133 // order status are unrelated vocabularies that happen to share a broker field
1134 // name, and overloading on return type alone would not compile anyway.
1135 static InstrumentStatus normalized_listing_status(std::string_view code) {
1136 if (code == "SCHEDULED") {
1137 return InstrumentStatus::SCHEDULED;
1138 }
1139 if (code == "ACTIVE") {
1140 return InstrumentStatus::ACTIVE;
1141 }
1142 if (code == "DELISTED") {
1143 return InstrumentStatus::DELISTED;
1144 }
1145 return InstrumentStatus::UNKNOWN;
1146 }
1147
1148 // Reads a listing or delisting date as one of three answers.
1149 //
1150 // `null` or absent is **not stated** -- Toss documents a `null` `listDate` as 정보 미제공,
1151 // information not provided, and a `null` `delistDate` as the value an active instrument carries --
1152 // a `YYYY-MM-DD` of digits forming a real date is **stated**, and anything else, including a value
1153 // that is not a string, is **unreadable**.
1154 static StatedDate stated_calendar_date(const json::object& row, std::string_view key) {
1155 const auto bound = calendar_bound(row, key);
1156 if (bound.unreadable_) {
1157 return StatedDate::unreadable();
1158 }
1159 return bound.date_ ? StatedDate::stated(*bound.date_) : StatedDate{};
1160 }
1161
1162 // Validates the request and asks for the calendar of one market.
1163 void start_calendar(Country country, std::optional<Date> from, CalendarHandler completion) {
1164 if (from && !is_valid_date(*from)) {
1165 BrokerError error;
1166 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1167 error.reached_broker_ = false;
1168 error.broker_code_ = "invalid_date";
1169 error.message_ = "calendar request requires a valid Gregorian date";
1170 deliver(std::move(completion), Result<TradingCalendar>(std::move(error)));
1171 return;
1172 }
1173
1174 ensure_token(TokenHandler(
1175 [self = shared_from_this(), country, from,
1176 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1177 if (token_error) {
1178 self->deliver(std::move(completion), Result<TradingCalendar>(std::move(*token_error)));
1179 return;
1180 }
1181 network::HttpRequest request;
1182 // The calendar is reference data, the lowest-priority traffic there is.
1183 request.group_ = network::RateLimitGroup::REFERENCE;
1184 request.method_ = http::verb::get;
1185 request.target_ = std::string("/api/v1/market-calendar/") + std::string(market_code(country));
1186 if (from) {
1187 request.target_ += "?date=" + iso_date(*from);
1188 }
1189 request.headers_.emplace_back("Authorization", "Bearer " + self->token_.access_token_);
1190 self->send(
1191 std::move(request),
1192 [self, country, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1193 self->deliver(std::move(completion), parse_calendar(country, std::move(result)));
1194 }
1195 );
1196 }
1197 ));
1198 }
1199
1200 // Normalizes Toss's calendar into the three days it reports.
1201 //
1202 // A day is a trading day when Toss reports trading hours for it. The two markets name the hours
1203 // differently: KR has one `integrated` field, null "둘 다 휴장이면", when both KRX and NXT are
1204 // closed; US has four sessions, all null on a holiday, of which `regularMarket` is the exchange's
1205 // own. So the presence of those hours *is* the answer. The hours themselves are dropped here, not
1206 // filled in `TradingDay`, so this adapter does not declare `BrokerCaps::has_calendar_sessions`.
1207 //
1208 // A `today` without that field at all is refused, not read as closed: reading the KR field on a
1209 // US reply reported every US trading day as closed.
1210 //
1211 // The two days either side are reported as business days, which is why they are
1212 // recorded as open without consulting their hours: Toss has already answered the
1213 // question by calling them that.
1214 static Result<TradingCalendar> parse_calendar(Country country, Result<network::HttpResponse> result) {
1215 auto payload = market_result(std::move(result));
1216 if (!payload) {
1217 return Result<TradingCalendar>(std::move(payload.error()));
1218 }
1219 try {
1220 if (!payload.value().is_object()) {
1221 throw std::runtime_error("calendar result is not an object");
1222 }
1223 const auto& object = payload.value().as_object();
1224 TradingCalendar calendar;
1225 calendar.country_ = country;
1226 const std::string_view hours = calendar_hours_field(country);
1227 append_calendar_day(object, "previousBusinessDay", hours, true, calendar);
1228 append_calendar_day(object, "today", hours, false, calendar);
1229 append_calendar_day(object, "nextBusinessDay", hours, true, calendar);
1230 std::sort(calendar.days_.begin(), calendar.days_.end(), [](const TradingDay& lhs, const TradingDay& rhs) {
1231 return lhs.date_ < rhs.date_;
1232 });
1233 calendar.received_at_ = std::chrono::system_clock::now();
1234 return Result<TradingCalendar>(std::move(calendar));
1235 } catch (const std::exception& exception) {
1236 return Result<TradingCalendar>(market_error("invalid_calendar_response", exception));
1237 }
1238 }
1239
1240 // Reads one reported day, deciding whether the market opens on it.
1241 static void append_calendar_day(
1242 const json::object& object, std::string_view key, std::string_view hours_key, bool business_day,
1243 TradingCalendar& calendar
1244 ) {
1245 const auto value = object.if_contains(key);
1246 if (!value || !value->is_object()) {
1247 return;
1248 }
1249 const auto& row = value->as_object();
1250 const auto date = parse_calendar_date(broker_detail::json_string(row, "date"));
1251 if (!date) {
1252 // A reported day whose date cannot be read produces no row and is counted, as KIS's are --
1253 // failing the response would lose `today` over a damaged neighbour. A day field that is absent
1254 // or not an object is not a reported day, and is skipped above without a count.
1255 ++calendar.unreadable_days_;
1256 return;
1257 }
1258 TradingDay day;
1259 day.date_ = *date;
1260 if (business_day) {
1261 day.open_ = true;
1262 } else {
1263 const auto hours = row.if_contains(hours_key);
1264 if (!hours) {
1265 throw std::runtime_error("calendar day has no " + std::string(hours_key) + " field");
1266 }
1267 day.open_ = !hours->is_null();
1268 }
1269 calendar.days_.push_back(day);
1270 }
1271
1272 // Parses a `YYYY-MM-DD` calendar date, or nothing when the text is not one.
1273 //
1274 // **Every character of every field must be a digit, and that is not pedantry.** `std::stoi` takes
1275 // a numeric prefix, so a shape check alone let `20x6-01-01` through as the year 20 -- a date that
1276 // is valid, plausible and not the one the broker sent, which is worse than no date at all because
1277 // nothing downstream can see that it is wrong. It also threw on `x026-01-01`, turning one bad
1278 // field into a failure of whatever response carried it. Reading the digits here makes both cases
1279 // the same answer: this text is not a date, said once, where a caller can act on it.
1280 static std::optional<Date> parse_calendar_date(std::string_view text) {
1281 if (text.size() != 10 || text[4] != '-' || text[7] != '-') {
1282 return std::nullopt;
1283 }
1284 const auto digits = [&](std::size_t at, std::size_t count) -> std::optional<int> {
1285 int value = 0;
1286 for (std::size_t index = at; index < at + count; ++index) {
1287 const auto character = text[index];
1288 if (character < '0' || character > '9') {
1289 return std::nullopt;
1290 }
1291 value = value * 10 + (character - '0');
1292 }
1293 return value;
1294 };
1295 const auto year = digits(0, 4);
1296 const auto month = digits(5, 2);
1297 const auto day = digits(8, 2);
1298 if (!year || !month || !day) {
1299 return std::nullopt;
1300 }
1301 Date date;
1302 date.year_ = *year;
1303 date.month_ = static_cast<unsigned>(*month);
1304 date.day_ = static_cast<unsigned>(*day);
1305 return is_valid_date(date) ? std::optional<Date>(date) : std::nullopt;
1306 }
1307
1308 // A date bound as the wire gave it: absent, readable, or stated and unreadable.
1309 struct CalendarBound {
1310 std::optional<Date> date_;
1311 bool unreadable_{false};
1312 };
1313
1314 // Reads an optional date bound, holding "the broker said nothing" apart from "the broker said
1315 // something unreadable".
1316 //
1317 // Absent and JSON `null` are the first: `null` is Toss's own spelling for a rate with no scheduled
1318 // change in that direction, and reading it as damage would refuse every open-ended rate it
1319 // publishes. Anything else that does not yield a date is the second -- including a value that is
1320 // not a string at all, which is a bound stated in a form nothing here can read rather than a bound
1321 // withheld.
1322 static CalendarBound calendar_bound(const json::object& row, std::string_view key) {
1323 CalendarBound bound;
1324 const auto value = row.if_contains(key);
1325 if (!value || value->is_null()) {
1326 return bound;
1327 }
1328 if (!value->is_string()) {
1329 bound.unreadable_ = true;
1330 return bound;
1331 }
1332 bound.date_ = parse_calendar_date(value->as_string().c_str());
1333 bound.unreadable_ = !bound.date_;
1334 return bound;
1335 }
1336
1337 // Most executions Toss returns in one request.
1338 static constexpr int trade_limit_ = 50;
1339
1340 // Most instruments Toss quotes in one request.
1341 static constexpr int price_batch_limit_ = 200;
1342
1343 // Issues one authenticated market-data GET for a single instrument.
1344 //
1345 // The three single-instrument reads differ only in their path and their parser,
1346 // so the token handling, the traffic class, and the validation live here once.
1347 template <typename Handler, typename Parse>
1348 void start_market_read(InstrumentId instrument, std::string prefix, Handler completion, Parse parse) {
1349 using ResultType = decltype(parse(InstrumentId{}, Result<network::HttpResponse>(BrokerError{})));
1350 static_assert(!std::is_void<ResultType>::value, "a market-data parser must return a Result");
1351 if (!broker_detail::valid_symbol(instrument.symbol_)) {
1352 BrokerError error;
1353 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1354 error.reached_broker_ = false;
1355 error.broker_code_ = "invalid_instrument";
1356 error.message_ = "market data request requires a symbol";
1357 deliver(std::move(completion), ResultType(std::move(error)));
1358 return;
1359 }
1360
1361 ensure_token(TokenHandler(
1362 [self = shared_from_this(), instrument = std::move(instrument), prefix = std::move(prefix),
1363 completion = std::move(completion), parse](std::optional<BrokerError> token_error) mutable {
1364 if (token_error) {
1365 self->deliver(std::move(completion), ResultType(std::move(*token_error)));
1366 return;
1367 }
1368 network::HttpRequest request;
1369 // Market data is the traffic the trading reserve holds back.
1370 request.group_ = network::RateLimitGroup::MARKET_DATA;
1371 request.method_ = http::verb::get;
1372 request.target_ = prefix + broker_detail::query_encode(instrument.symbol_);
1373 request.headers_.emplace_back("Authorization", "Bearer " + self->token_.access_token_);
1374 self->send(
1375 std::move(request),
1376 [self, instrument = std::move(instrument), completion = std::move(completion),
1377 parse](Result<network::HttpResponse> result) mutable {
1378 self->deliver(std::move(completion), parse(std::move(instrument), std::move(result)));
1379 }
1380 );
1381 }
1382 ));
1383 }
1384
1385 // Normalizes Toss's price bounds.
1386 //
1387 // Both bounds are null in a market without a price limit, and the absence is
1388 // preserved: a bound of zero would read as "this instrument may not trade above
1389 // nothing", which is not what an unlimited market means.
1390 static Result<PriceLimits> parse_price_limits(InstrumentId instrument, Result<network::HttpResponse> result) {
1391 static_cast<void>(instrument);
1392 auto payload = market_result(std::move(result));
1393 if (!payload) {
1394 return Result<PriceLimits>(std::move(payload.error()));
1395 }
1396 try {
1397 if (!payload.value().is_object()) {
1398 throw std::runtime_error("price limit result is not an object");
1399 }
1400 const auto& object = payload.value().as_object();
1401 PriceLimits limits;
1402 limits.currency_ = Currency(broker_detail::json_string(object, "currency"));
1403 limits.upper_ = nullable_decimal(object, "upperLimitPrice");
1404 limits.lower_ = nullable_decimal(object, "lowerLimitPrice");
1405 if (const auto stamp = object.if_contains("timestamp"); stamp && stamp->is_string()) {
1406 limits.exchange_time_ = parse_iso8601_timestamp(stamp->as_string().c_str());
1407 }
1408 return Result<PriceLimits>(std::move(limits));
1409 } catch (const std::exception& exception) {
1410 return Result<PriceLimits>(market_error("invalid_price_limit_response", exception));
1411 }
1412 }
1413
1414 // Normalizes Toss's recent executions.
1415 static Result<std::vector<TradePrint>> parse_trades(InstrumentId instrument, Result<network::HttpResponse> result) {
1416 static_cast<void>(instrument);
1417 auto payload = market_result(std::move(result));
1418 if (!payload) {
1419 return Result<std::vector<TradePrint>>(std::move(payload.error()));
1420 }
1421 try {
1422 if (!payload.value().is_array()) {
1423 throw std::runtime_error("trade result is not an array");
1424 }
1425 const auto& rows = payload.value().as_array();
1426 std::vector<TradePrint> prints;
1427 prints.reserve(rows.size());
1428 for (const auto& value : rows) {
1429 if (!value.is_object()) {
1430 throw std::runtime_error("trade entry is not an object");
1431 }
1432 const auto& row = value.as_object();
1433 TradePrint print;
1434 print.price_ = Decimal64::parse(broker_detail::json_string(row, "price"));
1435 print.quantity_ = Decimal64::parse(broker_detail::json_string(row, "volume"));
1436 print.currency_ = Currency(broker_detail::json_string(row, "currency"));
1437 print.exchange_time_ = parse_iso8601_timestamp(broker_detail::json_string(row, "timestamp"));
1438 if (!print.exchange_time_) {
1439 throw std::runtime_error("invalid trade timestamp");
1440 }
1441 prints.push_back(std::move(print));
1442 }
1443 return Result<std::vector<TradePrint>>(std::move(prints));
1444 } catch (const std::exception& exception) {
1445 return Result<std::vector<TradePrint>>(market_error("invalid_trade_response", exception));
1446 }
1447 }
1448
1449 // Validates a batch and requests every instrument's price in one call.
1450 void start_prices(std::vector<InstrumentId> instruments, PricesHandler completion) {
1451 BrokerError error;
1452 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1453 error.reached_broker_ = false;
1454 if (instruments.empty()) {
1455 error.broker_code_ = "empty_batch";
1456 error.message_ = "a batch price request needs at least one instrument";
1457 deliver(std::move(completion), Result<std::vector<QuoteSnapshot>>(std::move(error)));
1458 return;
1459 }
1460 if (static_cast<int>(instruments.size()) > price_batch_limit_) {
1461 error.broker_code_ = "batch_too_large";
1462 error.message_ =
1463 "Toss quotes at most two hundred instruments per request; a longer list is "
1464 "refused rather than split, because splitting would spend several times the "
1465 "request budget a batch call exists to save";
1466 deliver(std::move(completion), Result<std::vector<QuoteSnapshot>>(std::move(error)));
1467 return;
1468 }
1469
1470 std::string symbols;
1471 for (const auto& instrument : instruments) {
1472 if (!broker_detail::valid_symbol(instrument.symbol_)) {
1473 error.broker_code_ = "invalid_instrument";
1474 error.message_ = "batch price request requires a symbol for every instrument";
1475 deliver(std::move(completion), Result<std::vector<QuoteSnapshot>>(std::move(error)));
1476 return;
1477 }
1478 if (!symbols.empty()) {
1479 symbols += ',';
1480 }
1481 symbols += instrument.symbol_;
1482 }
1483
1484 ensure_token(TokenHandler(
1485 [self = shared_from_this(), instruments = std::move(instruments), symbols = std::move(symbols),
1486 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1487 if (token_error) {
1488 self->deliver(std::move(completion), Result<std::vector<QuoteSnapshot>>(std::move(*token_error)));
1489 return;
1490 }
1491 network::HttpRequest request;
1492 request.group_ = network::RateLimitGroup::MARKET_DATA;
1493 request.method_ = http::verb::get;
1494 request.target_ = "/api/v1/prices?symbols=" + broker_detail::query_encode(symbols);
1495 request.headers_.emplace_back("Authorization", "Bearer " + self->token_.access_token_);
1496 self->send(
1497 std::move(request),
1498 [self, instruments = std::move(instruments),
1499 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1500 self->deliver(std::move(completion), parse_prices(instruments, std::move(result)));
1501 }
1502 );
1503 }
1504 ));
1505 }
1506
1507 // Normalizes a batch of quotes, keeping the caller's instrument identities.
1508 //
1509 // Toss answers with a symbol per row, so each row is matched back to the
1510 // instrument the caller asked about rather than being rebuilt from the symbol
1511 // alone, which would lose the country and venue the caller stated. A row for a
1512 // symbol that was not asked for is a protocol error.
1513 static Result<std::vector<QuoteSnapshot>> parse_prices(
1514 const std::vector<InstrumentId>& requested, Result<network::HttpResponse> result
1515 ) {
1516 auto payload = market_result(std::move(result));
1517 if (!payload) {
1518 return Result<std::vector<QuoteSnapshot>>(std::move(payload.error()));
1519 }
1520 try {
1521 if (!payload.value().is_array()) {
1522 throw std::runtime_error("price result is not an array");
1523 }
1524 const auto& rows = payload.value().as_array();
1525 std::vector<QuoteSnapshot> quotes;
1526 quotes.reserve(rows.size());
1527 for (const auto& value : rows) {
1528 if (!value.is_object()) {
1529 throw std::runtime_error("price entry is not an object");
1530 }
1531 const auto& row = value.as_object();
1532 const auto symbol = broker_detail::json_string(row, "symbol");
1533 const auto match = std::find_if(requested.begin(), requested.end(), [&symbol](const InstrumentId& candidate) {
1534 return candidate.symbol_ == symbol;
1535 });
1536 if (match == requested.end()) {
1537 throw std::runtime_error("price response carries an unrequested symbol");
1538 }
1539 QuoteSnapshot quote;
1540 quote.instrument_ = *match;
1541 quote.last_price_ = Decimal64::parse(broker_detail::json_string(row, "lastPrice"));
1542 quote.currency_ = Currency(broker_detail::json_string(row, "currency"));
1543 if (const auto stamp = row.if_contains("timestamp"); stamp && stamp->is_string()) {
1544 quote.exchange_time_ = parse_iso8601_timestamp(stamp->as_string().c_str());
1545 }
1546 quote.received_at_ = std::chrono::system_clock::now();
1547 quotes.push_back(std::move(quote));
1548 }
1549 return Result<std::vector<QuoteSnapshot>>(std::move(quotes));
1550 } catch (const std::exception& exception) {
1551 return Result<std::vector<QuoteSnapshot>>(market_error("invalid_price_response", exception));
1552 }
1553 }
1554
1555 // Returns a protocol error naming the response that could not be read.
1556 static BrokerError market_error(const char* code, const std::exception& cause) {
1557 BrokerError error;
1558 error.category_ = ErrorCategory::PROTOCOL;
1559 error.broker_code_ = code;
1560 error.message_ = cause.what();
1561 return error;
1562 }
1563
1564 // Validates the instrument and requests its book.
1565 void start_depth(InstrumentId instrument, DepthHandler completion) {
1566 if (!broker_detail::valid_symbol(instrument.symbol_)) {
1567 BrokerError error;
1568 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1569 error.reached_broker_ = false;
1570 error.broker_code_ = "invalid_instrument";
1571 error.message_ = "order book request requires a symbol";
1572 deliver(std::move(completion), Result<DepthSnapshot>(std::move(error)));
1573 return;
1574 }
1575
1576 ensure_token(TokenHandler(
1577 [self = shared_from_this(), instrument = std::move(instrument),
1578 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1579 if (token_error) {
1580 self->deliver(std::move(completion), Result<DepthSnapshot>(std::move(*token_error)));
1581 return;
1582 }
1583 network::HttpRequest request;
1584 // The book is polling traffic, held back by the trading reserve.
1585 request.group_ = network::RateLimitGroup::MARKET_DATA;
1586 request.method_ = http::verb::get;
1587 request.target_ = "/api/v1/orderbook?symbol=" + broker_detail::query_encode(instrument.symbol_);
1588 request.headers_.emplace_back("Authorization", "Bearer " + self->token_.access_token_);
1589 self->send(
1590 std::move(request),
1591 [self, instrument = std::move(instrument),
1592 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1593 self->deliver(std::move(completion), parse_depth(std::move(instrument), std::move(result)));
1594 }
1595 );
1596 }
1597 ));
1598 }
1599
1600 // Normalizes one Toss order book.
1601 //
1602 // The levels are sorted rather than taken in the order they arrive. Toss's
1603 // specification documents `asks` as ascending and its own worked example lists
1604 // them descending, so trusting either would be a guess, and reading the best
1605 // offer off the wrong end of the book makes the spread negative.
1606 static Result<DepthSnapshot> parse_depth(InstrumentId instrument, Result<network::HttpResponse> result) {
1607 if (!result) {
1608 return Result<DepthSnapshot>(std::move(result.error()));
1609 }
1610 BrokerError parse_error;
1611 auto document = broker_detail::parse_object(result.value(), parse_error);
1612 if (!document) {
1613 return Result<DepthSnapshot>(std::move(parse_error));
1614 }
1615 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
1616 return Result<DepthSnapshot>(toss_error(result.value(), *document));
1617 }
1618 try {
1619 const auto& payload = required_object(*document, "result");
1620 DepthSnapshot book;
1621 book.instrument_ = std::move(instrument);
1622 book.currency_ = Currency(broker_detail::json_string(payload, "currency"));
1623 append_levels(payload, "bids", book.bids_);
1624 append_levels(payload, "asks", book.asks_);
1625 order_depth(book);
1626 if (const auto stamp = payload.if_contains("timestamp"); stamp && stamp->is_string()) {
1627 book.exchange_time_ = parse_iso8601_timestamp(stamp->as_string().c_str());
1628 if (!book.exchange_time_) {
1629 throw std::runtime_error("invalid order book timestamp");
1630 }
1631 }
1632 book.received_at_ = std::chrono::system_clock::now();
1633 return Result<DepthSnapshot>(std::move(book));
1634 } catch (const std::exception& exception) {
1635 BrokerError error;
1636 error.category_ = ErrorCategory::PROTOCOL;
1637 error.broker_code_ = "invalid_orderbook_response";
1638 error.message_ = exception.what();
1639 return Result<DepthSnapshot>(std::move(error));
1640 }
1641 }
1642
1643 // Reads one side of the book into `levels`.
1644 static void append_levels(const json::object& payload, std::string_view key, std::vector<DepthLevel>& levels) {
1645 const auto rows = payload.if_contains(key);
1646 if (!rows || !rows->is_array()) {
1647 throw std::runtime_error("missing array field: " + std::string(key));
1648 }
1649 levels.reserve(rows->as_array().size());
1650 for (const auto& value : rows->as_array()) {
1651 if (!value.is_object()) {
1652 throw std::runtime_error("order book entry is not an object");
1653 }
1654 const auto& row = value.as_object();
1655 levels.push_back(
1656 DepthLevel{
1657 Decimal64::parse(broker_detail::json_string(row, "price")),
1658 Decimal64::parse(broker_detail::json_string(row, "volume")),
1659 }
1660 );
1661 }
1662 }
1663
1664 void start_quote(InstrumentId instrument, QuoteHandler completion) {
1665 if (instrument.country_ != Country::KR || !broker_detail::valid_symbol(instrument.symbol_)) {
1666 BrokerError error;
1667 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1668 error.reached_broker_ = false;
1669 error.broker_code_ = "invalid_instrument";
1670 error.message_ = "Toss quote currently supports Korean equity symbols only";
1671 complete(std::move(completion), Result<QuoteSnapshot>(std::move(error)));
1672 return;
1673 }
1674 ensure_token(TokenHandler(
1675 [self = shared_from_this(), instrument = std::move(instrument),
1676 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1677 if (token_error) {
1678 self->complete(std::move(completion), Result<QuoteSnapshot>(std::move(*token_error)));
1679 return;
1680 }
1681 self->request_quote(std::move(instrument), std::move(completion));
1682 }
1683 ));
1684 }
1685
1686 void start_accounts(AccountsHandler completion) {
1687 ensure_token(TokenHandler(
1688 [self = shared_from_this(), completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1689 if (token_error) {
1690 self->complete_accounts(std::move(completion), Result<std::vector<TossAccount>>(std::move(*token_error)));
1691 return;
1692 }
1693 self->request_accounts(std::move(completion));
1694 }
1695 ));
1696 }
1697
1698 void start_buying_power(Currency currency, std::int64_t account_sequence, BuyingPowerHandler completion) {
1699 auto invalid = validate_account_sequence(account_sequence);
1700 if (!invalid && !priced_currency(currency)) {
1701 // Refused here rather than sent: the endpoint answers for the currencies Toss prices, and a
1702 // request for any other is a condition the caller stated that cannot be honored.
1703 BrokerError error;
1704 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1705 error.reached_broker_ = false;
1706 error.broker_code_ = "unsupported_currency";
1707 error.message_ = "Toss prices buying power in KRW and USD only, not " + currency.str();
1708 invalid = std::move(error);
1709 }
1710 if (invalid) {
1711 complete_buying_power(std::move(completion), Result<BuyingPower>(std::move(*invalid)));
1712 return;
1713 }
1714 ensure_token(TokenHandler(
1715 [self = shared_from_this(), currency, account_sequence,
1716 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1717 if (token_error) {
1718 self->complete_buying_power(std::move(completion), Result<BuyingPower>(std::move(*token_error)));
1719 return;
1720 }
1721 self->request_buying_power(currency, account_sequence, std::move(completion));
1722 }
1723 ));
1724 }
1725
1726 void request_buying_power(Currency currency, std::int64_t account_sequence, BuyingPowerHandler completion) {
1727 network::HttpRequest request;
1728 // The same class as holdings: an account read, above polling and below trading.
1729 request.group_ = network::RateLimitGroup::ACCOUNT;
1730 request.method_ = http::verb::get;
1731 request.target_ = "/api/v1/buying-power?currency=" + currency.str();
1732 request.headers_ = {
1733 {"Authorization", "Bearer " + token_.access_token_},
1734 {"X-Tossinvest-Account", std::to_string(account_sequence)},
1735 };
1736 send(
1737 std::move(request),
1738 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1739 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
1740 self->complete_buying_power(std::move(completion), parse_buying_power(std::move(result)));
1741 });
1742 }
1743 );
1744 }
1745
1746 void start_sellable_quantity(
1747 InstrumentId instrument, std::int64_t account_sequence, SellableQuantityHandler completion
1748 ) {
1749 if (auto invalid = validate_account_sequence(account_sequence)) {
1750 complete_sellable_quantity(std::move(completion), Result<Decimal64>(std::move(*invalid)));
1751 return;
1752 }
1753 if (!broker_detail::valid_symbol(instrument.symbol_)) {
1754 BrokerError error;
1755 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1756 error.reached_broker_ = false;
1757 error.broker_code_ = "invalid_instrument";
1758 error.message_ = "sellable-quantity request requires a symbol";
1759 complete_sellable_quantity(std::move(completion), Result<Decimal64>(std::move(error)));
1760 return;
1761 }
1762 ensure_token(TokenHandler(
1763 [self = shared_from_this(), instrument = std::move(instrument), account_sequence,
1764 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1765 if (token_error) {
1766 self->complete_sellable_quantity(std::move(completion), Result<Decimal64>(std::move(*token_error)));
1767 return;
1768 }
1769 self->request_sellable_quantity(std::move(instrument), account_sequence, std::move(completion));
1770 }
1771 ));
1772 }
1773
1774 void request_sellable_quantity(
1775 InstrumentId instrument, std::int64_t account_sequence, SellableQuantityHandler completion
1776 ) {
1777 network::HttpRequest request;
1778 request.group_ = network::RateLimitGroup::ACCOUNT;
1779 request.method_ = http::verb::get;
1780 request.target_ = "/api/v1/sellable-quantity?symbol=" + broker_detail::query_encode(instrument.symbol_);
1781 request.headers_ = {
1782 {"Authorization", "Bearer " + token_.access_token_},
1783 {"X-Tossinvest-Account", std::to_string(account_sequence)},
1784 };
1785 send(
1786 std::move(request),
1787 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1788 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
1789 self->complete_sellable_quantity(std::move(completion), parse_sellable_quantity(std::move(result)));
1790 });
1791 }
1792 );
1793 }
1794
1795 void start_commissions(std::int64_t account_sequence, CommissionScheduleHandler completion) {
1796 if (auto invalid = validate_account_sequence(account_sequence)) {
1797 complete_commissions(std::move(completion), Result<CommissionSchedule>(std::move(*invalid)));
1798 return;
1799 }
1800 ensure_token(TokenHandler(
1801 [self = shared_from_this(), account_sequence,
1802 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1803 if (token_error) {
1804 self->complete_commissions(std::move(completion), Result<CommissionSchedule>(std::move(*token_error)));
1805 return;
1806 }
1807 self->request_commissions(account_sequence, std::move(completion));
1808 }
1809 ));
1810 }
1811
1812 void request_commissions(std::int64_t account_sequence, CommissionScheduleHandler completion) {
1813 network::HttpRequest request;
1814 request.group_ = network::RateLimitGroup::ACCOUNT;
1815 request.method_ = http::verb::get;
1816 request.target_ = "/api/v1/commissions";
1817 request.headers_ = {
1818 {"Authorization", "Bearer " + token_.access_token_},
1819 {"X-Tossinvest-Account", std::to_string(account_sequence)},
1820 };
1821 send(
1822 std::move(request),
1823 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1824 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
1825 self->complete_commissions(std::move(completion), parse_commissions(std::move(result)));
1826 });
1827 }
1828 );
1829 }
1830
1831 void start_holdings(std::int64_t account_sequence, HoldingsHandler completion) {
1832 if (auto invalid = validate_account_sequence(account_sequence)) {
1833 complete_holdings(std::move(completion), Result<HoldingsSnapshot>(std::move(*invalid)));
1834 return;
1835 }
1836 ensure_token(TokenHandler(
1837 [self = shared_from_this(), account_sequence,
1838 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
1839 if (token_error) {
1840 self->complete_holdings(std::move(completion), Result<HoldingsSnapshot>(std::move(*token_error)));
1841 return;
1842 }
1843 self->request_holdings(account_sequence, std::move(completion));
1844 }
1845 ));
1846 }
1847
1848 // Lets a request through with a valid token, and otherwise requests one, unless a store manages the
1849 // token: one requested here, mid-call, would bypass the store's lock, so the call fails locally instead.
1850 // With a store, the token's validity is read once and nothing past this branch reads it again.
1851 void ensure_token(TokenHandler handler) {
1852 if (store_managed_) {
1853 if (token_.valid()) {
1854 std::move(handler)(std::nullopt);
1855 } else {
1856 std::move(handler)(network::token_unusable_error());
1857 }
1858 return;
1859 }
1860 request_token(std::move(handler));
1861 }
1862
1863 // Requests a token unless the held one is valid, coalescing concurrent waiters.
1864 void request_token(TokenHandler handler) {
1865 if (token_.valid()) {
1866 std::move(handler)(std::nullopt);
1867 return;
1868 }
1869 token_waiters_.push_back(std::move(handler));
1870 if (refreshing_) {
1871 return;
1872 }
1873 refreshing_ = true;
1874 network::HttpRequest request;
1875 // Every other request waits behind a token refresh, including a cancellation.
1876 request.group_ = network::RateLimitGroup::AUTH;
1877 request.method_ = http::verb::post;
1878 request.target_ = "/oauth2/token";
1879 request.body_ = config_.to_form_urlencoded_body();
1880 request.headers_.emplace_back("content-type", "application/x-www-form-urlencoded");
1881 http_->async_request(std::move(request), [self = shared_from_this()](Result<network::HttpResponse> result) mutable {
1882 net::post(self->strand_, [self, result = std::move(result)]() mutable {
1883 self->finish_token(std::move(result));
1884 });
1885 });
1886 }
1887
1888 void finish_token(Result<network::HttpResponse> result) {
1889 refreshing_ = false;
1890 std::optional<BrokerError> failure;
1891 if (!result) {
1892 failure = std::move(result.error());
1893 } else {
1894 BrokerError parse_error;
1895 auto document = broker_detail::parse_object(result.value(), parse_error);
1896 if (!document) {
1897 failure = std::move(parse_error);
1898 } else if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
1899 failure = toss_error(result.value(), *document);
1900 failure->category_ = ErrorCategory::AUTHENTICATION;
1901 } else {
1902 try {
1903 token_.from_json(*document);
1904 } catch (const std::exception& exception) {
1905 BrokerError error;
1906 error.category_ = ErrorCategory::AUTHENTICATION;
1907 error.broker_code_ = "invalid_token_response";
1908 error.message_ = exception.what();
1909 failure = std::move(error);
1910 }
1911 }
1912 }
1913 if (failure) {
1914 // **The waiters asked for something else.** A token refresh that fails is handed to every
1915 // caller waiting behind it -- an order, a cancellation, an inquiry -- and none of those
1916 // requests was sent. Left unmarked, an authentication failure reads to a runner as the broker
1917 // refusing an order it never received: a request counted against the rate window, and a later
1918 // valid order refused once credentials recover. What failed was the token request, and that
1919 // is not the instruction this error is about to describe.
1920 failure->reached_broker_ = false;
1921 }
1922 auto waiters = std::move(token_waiters_);
1923 token_waiters_.clear();
1924 for (auto& waiter : waiters) {
1925 if (failure) {
1926 std::move(waiter)(*failure);
1927 } else {
1928 std::move(waiter)(std::nullopt);
1929 }
1930 }
1931 }
1932
1933 void request_quote(InstrumentId instrument, QuoteHandler completion) {
1934 network::HttpRequest request;
1935 // Quote polling is the traffic a reserve exists to hold back.
1936 request.group_ = network::RateLimitGroup::MARKET_DATA;
1937 request.method_ = http::verb::get;
1938 request.target_ = "/api/v1/prices?symbols=" + broker_detail::query_encode(instrument.symbol_);
1939 request.headers_.emplace_back("Authorization", "Bearer " + token_.access_token_);
1940 send(
1941 std::move(request),
1942 [self = shared_from_this(), instrument = std::move(instrument),
1943 completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1944 net::post(
1945 self->strand_,
1946 [self, instrument = std::move(instrument), completion = std::move(completion),
1947 result = std::move(result)]() mutable {
1948 self->complete(std::move(completion), parse_quote(std::move(instrument), std::move(result)));
1949 }
1950 );
1951 }
1952 );
1953 }
1954
1955 void request_accounts(AccountsHandler completion) {
1956 network::HttpRequest request;
1957 // Account discovery runs before a session is bound.
1958 request.group_ = network::RateLimitGroup::ACCOUNT;
1959 request.method_ = http::verb::get;
1960 request.target_ = "/api/v1/accounts";
1961 request.headers_.emplace_back("Authorization", "Bearer " + token_.access_token_);
1962 send(
1963 std::move(request),
1964 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1965 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
1966 self->complete_accounts(std::move(completion), parse_accounts(std::move(result)));
1967 });
1968 }
1969 );
1970 }
1971
1972 void request_holdings(std::int64_t account_sequence, HoldingsHandler completion) {
1973 network::HttpRequest request;
1974 // Holdings rank above polling but may not spend the trading reserve.
1975 request.group_ = network::RateLimitGroup::ACCOUNT;
1976 request.method_ = http::verb::get;
1977 request.target_ = "/api/v1/holdings";
1978 request.headers_ = {
1979 {"Authorization", "Bearer " + token_.access_token_},
1980 {"X-Tossinvest-Account", std::to_string(account_sequence)},
1981 };
1982 send(
1983 std::move(request),
1984 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
1985 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
1986 self->complete_holdings(std::move(completion), parse_holdings(std::move(result)));
1987 });
1988 }
1989 );
1990 }
1991
1992 static Result<QuoteSnapshot> parse_quote(InstrumentId instrument, Result<network::HttpResponse> result) {
1993 if (!result) {
1994 return Result<QuoteSnapshot>(std::move(result.error()));
1995 }
1996 BrokerError parse_error;
1997 auto document = broker_detail::parse_object(result.value(), parse_error);
1998 if (!document) {
1999 return Result<QuoteSnapshot>(std::move(parse_error));
2000 }
2001 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2002 auto error = toss_error(result.value(), *document);
2003 return Result<QuoteSnapshot>(std::move(error));
2004 }
2005 try {
2006 const auto payload = document->if_contains("result");
2007 if (!payload || !payload->is_array() || payload->as_array().empty() || !payload->as_array().front().is_object()) {
2008 throw std::runtime_error("missing non-empty result array");
2009 }
2010 const auto& output = payload->as_array().front().as_object();
2011 if (broker_detail::json_string(output, "symbol") != instrument.symbol_) {
2012 throw std::runtime_error("quote response symbol does not match request");
2013 }
2014 QuoteSnapshot quote;
2015 quote.instrument_ = std::move(instrument);
2016 quote.last_price_ = Decimal64::parse(broker_detail::json_string(output, "lastPrice"));
2017 quote.currency_ = Currency(broker_detail::json_string(output, "currency"));
2018 if (const auto timestamp = output.if_contains("timestamp"); timestamp && timestamp->is_string()) {
2019 quote.exchange_time_ = parse_iso8601_timestamp(timestamp->as_string().c_str());
2020 if (!quote.exchange_time_) {
2021 throw std::runtime_error("invalid timestamp");
2022 }
2023 }
2024 quote.received_at_ = std::chrono::system_clock::now();
2025 return Result<QuoteSnapshot>(std::move(quote));
2026 } catch (const std::exception& exception) {
2027 BrokerError error;
2028 error.category_ = ErrorCategory::PROTOCOL;
2029 error.broker_code_ = "invalid_quote_response";
2030 error.message_ = exception.what();
2031 return Result<QuoteSnapshot>(std::move(error));
2032 }
2033 }
2034
2035 static Result<std::vector<TossAccount>> parse_accounts(Result<network::HttpResponse> result) {
2036 if (!result) {
2037 return Result<std::vector<TossAccount>>(std::move(result.error()));
2038 }
2039 BrokerError parse_error;
2040 auto document = broker_detail::parse_object(result.value(), parse_error);
2041 if (!document) {
2042 return Result<std::vector<TossAccount>>(std::move(parse_error));
2043 }
2044 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2045 auto error = toss_error(result.value(), *document);
2046 return Result<std::vector<TossAccount>>(std::move(error));
2047 }
2048 try {
2049 const auto payload = document->if_contains("result");
2050 if (!payload || !payload->is_array()) {
2051 throw std::runtime_error("missing array field: result");
2052 }
2053 std::vector<TossAccount> accounts;
2054 accounts.reserve(payload->as_array().size());
2055 for (const auto& value : payload->as_array()) {
2056 if (!value.is_object()) {
2057 throw std::runtime_error("account item is not an object");
2058 }
2059 const auto& account = value.as_object();
2060 const auto sequence = broker_detail::json_int64(account, "accountSeq");
2061 if (sequence <= 0) {
2062 throw std::runtime_error("accountSeq must be positive");
2063 }
2064 accounts.push_back(
2066 broker_detail::json_string(account, "accountNo"),
2067 sequence,
2068 broker_detail::json_string(account, "accountType"),
2069 }
2070 );
2071 }
2072 return Result<std::vector<TossAccount>>(std::move(accounts));
2073 } catch (const std::exception& exception) {
2074 BrokerError error;
2075 error.category_ = ErrorCategory::PROTOCOL;
2076 error.broker_code_ = "invalid_accounts_response";
2077 error.message_ = exception.what();
2078 return Result<std::vector<TossAccount>>(std::move(error));
2079 }
2080 }
2081
2082 // Returns whether Toss prices buying power in `currency`.
2083 static bool priced_currency(const Currency& currency) {
2084 return currency == Currency::krw() || currency == Currency::usd();
2085 }
2086
2087 // Normalizes one buying-power reading.
2088 //
2089 // The currency comes from the response rather than from the request, so a broker answering in a
2090 // currency other than the one asked for is carried as it answered rather than relabelled.
2091 static Result<BuyingPower> parse_buying_power(Result<network::HttpResponse> result) {
2092 auto payload = account_payload(result);
2093 if (!payload) {
2094 return Result<BuyingPower>(std::move(payload.error()));
2095 }
2096 try {
2097 if (!payload.value().is_object()) {
2098 throw std::runtime_error("buying power result is not an object");
2099 }
2100 const auto& output = payload.value().as_object();
2101 BuyingPower power;
2102 power.cash_ = Money{
2103 Decimal64::parse(broker_detail::json_string(output, "cashBuyingPower")),
2104 Currency(broker_detail::json_string(output, "currency")),
2105 };
2106 // Toss states no timestamp for this figure, so the honest stamp is when it arrived.
2107 power.received_at_ = std::chrono::system_clock::now();
2108 return Result<BuyingPower>(std::move(power));
2109 } catch (const std::exception& exception) {
2110 return Result<BuyingPower>(account_error("invalid_buying_power_response", exception));
2111 }
2112 }
2113
2114 // Normalizes one instrument's sellable quantity, which Toss may report fractionally.
2115 static Result<Decimal64> parse_sellable_quantity(Result<network::HttpResponse> result) {
2116 auto payload = account_payload(result);
2117 if (!payload) {
2118 return Result<Decimal64>(std::move(payload.error()));
2119 }
2120 try {
2121 if (!payload.value().is_object()) {
2122 throw std::runtime_error("sellable quantity result is not an object");
2123 }
2124 const auto& output = payload.value().as_object();
2125 return Result<Decimal64>(Decimal64::parse(broker_detail::json_string(output, "sellableQuantity")));
2126 } catch (const std::exception& exception) {
2127 return Result<Decimal64>(account_error("invalid_sellable_quantity_response", exception));
2128 }
2129 }
2130
2131 // Normalizes the account's commission schedule.
2132 //
2133 // A row for a market this library does not normalize is **skipped rather than refused**: the
2134 // schedule is a list of what the broker charges where, and one unfamiliar market must not deny a
2135 // caller the rate for the market they trade. That is the same rule the holdings and order paths
2136 // follow for an unrecognized row.
2137 static Result<CommissionSchedule> parse_commissions(Result<network::HttpResponse> result) {
2138 auto payload = account_payload(result);
2139 if (!payload) {
2140 return Result<CommissionSchedule>(std::move(payload.error()));
2141 }
2142 try {
2143 if (!payload.value().is_array()) {
2144 throw std::runtime_error("commission result is not an array");
2145 }
2146 CommissionSchedule schedule;
2147 schedule.rates_.reserve(payload.value().as_array().size());
2148 for (const auto& value : payload.value().as_array()) {
2149 if (!value.is_object()) {
2150 throw std::runtime_error("commission item is not an object");
2151 }
2152 const auto& row = value.as_object();
2153 const auto market = broker_detail::json_string(row, "marketCountry");
2154 CommissionRate rate;
2155 if (market == "KR") {
2156 rate.country_ = Country::KR;
2157 } else if (market == "US") {
2158 rate.country_ = Country::US;
2159 } else if (const auto preserved = market.empty() ? std::nullopt : Code<16>::try_make(market)) {
2160 // Toss's own specification requires a client to accept unknown values of this enum, so a
2161 // new market is a normal thing to be sent. Preserved rather than dropped: a caller can
2162 // see what the broker charges there even though nothing here can price it, and a
2163 // schedule that quietly omitted the row would be a successful, incomplete answer.
2164 //
2165 // The empty string is excluded before `try_make` sees it, and that exclusion is load
2166 // bearing: an empty code stores successfully, and an empty `other_` is how a row says it
2167 // names a *normalized* market -- so a row with no market at all would become a rate for
2168 // whatever `country_` defaults to, which is a Korean commission the broker never
2169 // published.
2170 rate.other_ = *preserved;
2171 } else {
2172 // Not storable, so it cannot be reported under any market honestly. One such row must not
2173 // fail the whole schedule, which is the rule every other listing here follows -- but it
2174 // is counted, so a caller can see the schedule is incomplete rather than reading a
2175 // silently shortened list as the whole answer.
2176 ++schedule.dropped_;
2177 continue;
2178 }
2179 rate.rate_ = Decimal64::parse(broker_detail::json_string(row, "commissionRate"));
2180 // `venue_` stays neutral and `institution_rate_` stays empty, and both are the honest
2181 // reading rather than defaults nobody chose. Toss's schema is
2182 // `[marketCountry, commissionRate, startDate, endDate]`: it names no venue, so the rate
2183 // applies whatever venue a fill reached; and it states one rate without saying whether an
2184 // institution charge sits inside it, which is exactly what an empty `institution_rate_`
2185 // means. A zero there would claim Toss charges no institution fee, which it never said.
2186 // Null means open-ended in that direction, which is how Toss publishes a rate with no
2187 // scheduled change. It is deliberately not read as "today".
2188 const auto from = calendar_bound(row, "startDate");
2189 const auto until = calendar_bound(row, "endDate");
2190 rate.from_ = from.date_;
2191 rate.until_ = until.date_;
2192 rate.from_unreadable_ = from.unreadable_;
2193 rate.until_unreadable_ = until.unreadable_;
2194 if (rate.from_unreadable_ || rate.until_unreadable_) {
2195 // Counted per row rather than per bound: what a caller does about it -- refetch, or state
2196 // the rates by hand -- is the same one decision whichever end of the window was lost.
2197 ++schedule.unreadable_bounds_;
2198 }
2199 schedule.rates_.push_back(std::move(rate));
2200 }
2201 schedule.received_at_ = std::chrono::system_clock::now();
2202 schedule.origin_ = CommissionOrigin::BROKER_PUBLISHED;
2203 // The broker is the source, so the tariff needs nothing from the caller -- but the report
2204 // prints this string, and "which tariff is this" has a real answer here worth printing.
2205 schedule.tariff_ = "tossinvest published commission schedule";
2206 return Result<CommissionSchedule>(std::move(schedule));
2207 } catch (const std::exception& exception) {
2208 return Result<CommissionSchedule>(account_error("invalid_commission_response", exception));
2209 }
2210 }
2211
2212 // Returns the `result` field of an account response, or the error that stopped it.
2213 //
2214 // The three account-capacity reads share one envelope, so they share one unwrapping: transport
2215 // failure, unparseable body, and a non-2xx status all become the error they are, and only a
2216 // successful response yields a payload.
2217 static Result<json::value> account_payload(Result<network::HttpResponse>& result) {
2218 if (!result) {
2219 return Result<json::value>(std::move(result.error()));
2220 }
2221 BrokerError parse_error;
2222 auto document = broker_detail::parse_object(result.value(), parse_error);
2223 if (!document) {
2224 return Result<json::value>(std::move(parse_error));
2225 }
2226 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2227 return Result<json::value>(toss_error(result.value(), *document));
2228 }
2229 const auto payload = document->if_contains("result");
2230 if (!payload) {
2231 BrokerError error;
2232 error.category_ = ErrorCategory::PROTOCOL;
2233 error.broker_code_ = "missing_result";
2234 error.message_ = "response carries no result field";
2235 return Result<json::value>(std::move(error));
2236 }
2237 return Result<json::value>(std::move(*payload));
2238 }
2239
2240 // Builds the protocol error an account-capacity parse failure reports.
2241 static BrokerError account_error(std::string code, const std::exception& exception) {
2242 BrokerError error;
2243 error.category_ = ErrorCategory::PROTOCOL;
2244 error.broker_code_ = std::move(code);
2245 error.message_ = exception.what();
2246 return error;
2247 }
2248
2249 static Result<HoldingsSnapshot> parse_holdings(Result<network::HttpResponse> result) {
2250 if (!result) {
2251 return Result<HoldingsSnapshot>(std::move(result.error()));
2252 }
2253 BrokerError parse_error;
2254 auto document = broker_detail::parse_object(result.value(), parse_error);
2255 if (!document) {
2256 return Result<HoldingsSnapshot>(std::move(parse_error));
2257 }
2258 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
2259 auto error = toss_error(result.value(), *document);
2260 return Result<HoldingsSnapshot>(std::move(error));
2261 }
2262 try {
2263 const auto payload = document->if_contains("result");
2264 if (!payload || !payload->is_object()) {
2265 throw std::runtime_error("missing object field: result");
2266 }
2267 const auto& output = payload->as_object();
2268 const auto items = output.if_contains("items");
2269 if (!items || !items->is_array()) {
2270 throw std::runtime_error("missing array field: items");
2271 }
2272
2273 HoldingsSnapshot snapshot;
2274 snapshot.positions_.reserve(items->as_array().size());
2275 for (const auto& value : items->as_array()) {
2276 if (!value.is_object()) {
2277 throw std::runtime_error("holdings item is not an object");
2278 }
2279 snapshot.positions_.push_back(parse_position(value.as_object()));
2280 }
2281 append_totals(output, snapshot.totals_);
2282 snapshot.received_at_ = std::chrono::system_clock::now();
2283 // Left unestablished deliberately: a Toss holdings row carries no sellable quantity at all
2284 // (`sellable_source` is `INQUIRY`), so this read establishes nothing about a figure it never
2285 // reported. The inquiry that does report one carries its own basis --
2286 // `traits_detail::Normalizers::sellable_inquiry_basis`.
2287 snapshot.sellable_basis_ = SellableBasis{};
2288 return Result<HoldingsSnapshot>(std::move(snapshot));
2289 } catch (const std::exception& exception) {
2290 BrokerError error;
2291 error.category_ = ErrorCategory::PROTOCOL;
2292 error.broker_code_ = "invalid_holdings_response";
2293 error.message_ = exception.what();
2294 return Result<HoldingsSnapshot>(std::move(error));
2295 }
2296 }
2297
2298 // Returns the venue that identifies an instrument at Toss.
2299 //
2300 // One function with two callers — the holdings parse and the order parse —
2301 // because those two disagreed, and an `InstrumentId` compares its venue. Toss
2302 // publishes no per-order venue, so this is about identity only.
2303 static Venue instrument_venue(Country country) {
2304 switch (country) {
2305 case Country::KR:
2306 return Venue::COMBINED;
2307 case Country::US:
2308 return Venue::UNSPECIFIED;
2309 }
2310 return Venue::UNSPECIFIED;
2311 }
2312
2313 // Whether Toss trades `country`'s listings through this client. Each answer below follows from it.
2314 static constexpr bool trades_country(Country country) noexcept {
2315 switch (country) {
2316 case Country::KR:
2317 case Country::US:
2318 return true;
2319 }
2320 return false;
2321 }
2322
2323 // The path segment Toss names a market by (`/api/v1/market-calendar/{KR,US}`).
2324 static constexpr std::string_view market_code(Country country) noexcept {
2325 switch (country) {
2326 case Country::KR:
2327 return "KR";
2328 case Country::US:
2329 return "US";
2330 }
2331 return "";
2332 }
2333
2334 // The session a calendar day's open and close are read from: KR's integrated session, US's regular one.
2335 static constexpr std::string_view calendar_hours_field(Country country) noexcept {
2336 switch (country) {
2337 case Country::KR:
2338 return "integrated";
2339 case Country::US:
2340 return "regularMarket";
2341 }
2342 return "";
2343 }
2344
2345 // Whether Toss takes a limit price in `country` only as a whole number of its currency's units (won).
2346 static constexpr bool prices_in_whole_units(Country country) noexcept {
2347 switch (country) {
2348 case Country::KR:
2349 return true;
2350 case Country::US:
2351 return false;
2352 }
2353 return true;
2354 }
2355
2356 static HoldingPosition parse_position(const json::object& output) {
2357 const auto market_country = broker_detail::json_string(output, "marketCountry");
2358 const auto currency = Currency(broker_detail::json_string(output, "currency"));
2359 Country country;
2360 Venue venue = Venue::UNSPECIFIED;
2361 if (market_country == "KR") {
2362 country = Country::KR;
2363 venue = instrument_venue(Country::KR);
2364 if (!(currency == Currency::krw())) {
2365 throw std::runtime_error("KR holding currency is not KRW");
2366 }
2367 } else if (market_country == "US") {
2368 country = Country::US;
2369 if (!(currency == Currency::usd())) {
2370 throw std::runtime_error("US holding currency is not USD");
2371 }
2372 } else {
2373 throw std::runtime_error("unsupported marketCountry: " + market_country);
2374 }
2375
2376 const auto& market_value = required_object(output, "marketValue");
2377 const auto& profit_loss = required_object(output, "profitLoss");
2378 HoldingPosition position;
2379 position.instrument_ = InstrumentId{country, venue, broker_detail::json_string(output, "symbol")};
2380 position.name_ = broker_detail::json_string(output, "name");
2381 position.quantity_ = Decimal64::parse(broker_detail::json_string(output, "quantity"));
2382 position.average_purchase_price_ = Decimal64::parse(broker_detail::json_string(output, "averagePurchasePrice"));
2383 position.last_price_ = Decimal64::parse(broker_detail::json_string(output, "lastPrice"));
2384 position.purchase_value_ =
2385 Money{Decimal64::parse(broker_detail::json_string(market_value, "purchaseAmount")), currency};
2386 position.market_value_ = Money{Decimal64::parse(broker_detail::json_string(market_value, "amount")), currency};
2387 position.unrealized_profit_loss_ =
2388 Money{Decimal64::parse(broker_detail::json_string(profit_loss, "amount")), currency};
2389 position.unrealized_return_ = Decimal64::parse(broker_detail::json_string(profit_loss, "rate"));
2390 return position;
2391 }
2392
2393 static const json::object& required_object(const json::object& parent, std::string_view key) {
2394 const auto value = parent.if_contains(key);
2395 if (!value || !value->is_object()) {
2396 throw std::runtime_error("missing object field: " + std::string(key));
2397 }
2398 return value->as_object();
2399 }
2400
2401 static std::optional<Decimal64> optional_decimal(const json::object& object, std::string_view key) {
2402 const auto value = object.if_contains(key);
2403 if (!value) {
2404 throw std::runtime_error("missing decimal field: " + std::string(key));
2405 }
2406 if (value->is_null()) {
2407 return std::nullopt;
2408 }
2409 if (!value->is_string()) {
2410 throw std::runtime_error("invalid decimal field: " + std::string(key));
2411 }
2412 return Decimal64::parse(value->as_string().c_str());
2413 }
2414
2415 static void append_totals(const json::object& output, std::vector<HoldingsTotals>& totals) {
2416 const auto& purchase = required_object(output, "totalPurchaseAmount");
2417 const auto& market = required_object(required_object(output, "marketValue"), "amount");
2418 const auto& profit_loss = required_object(required_object(output, "profitLoss"), "amount");
2419 totals.push_back(
2420 HoldingsTotals{
2421 Currency::krw(),
2422 Decimal64::parse(broker_detail::json_string(purchase, "krw")),
2423 Decimal64::parse(broker_detail::json_string(market, "krw")),
2424 Decimal64::parse(broker_detail::json_string(profit_loss, "krw")),
2425 }
2426 );
2427
2428 const auto usd_purchase = optional_decimal(purchase, "usd");
2429 const auto usd_market = optional_decimal(market, "usd");
2430 const auto usd_profit_loss = optional_decimal(profit_loss, "usd");
2431 const bool any_usd = usd_purchase || usd_market || usd_profit_loss;
2432 const bool all_usd = usd_purchase && usd_market && usd_profit_loss;
2433 if (any_usd != all_usd) {
2434 throw std::runtime_error("USD overview fields have inconsistent nullability");
2435 }
2436 if (all_usd) {
2437 totals.push_back(
2438 HoldingsTotals{
2439 Currency::usd(),
2440 *usd_purchase,
2441 *usd_market,
2442 *usd_profit_loss,
2443 }
2444 );
2445 }
2446 }
2447
2448 static BrokerError toss_error(const network::HttpResponse& response, const json::object& document) {
2449 const int status = response.result_int();
2450 BrokerError result;
2451 result.http_status_ = status;
2452 result.category_ = status == 429 ? ErrorCategory::RATE_LIMIT : ErrorCategory::PROTOCOL;
2453 if (result.category_ == ErrorCategory::RATE_LIMIT) {
2454 // Both hints Toss documents on a refusal, read in the one place a refusal is
2455 // built so no call site can forget one of them.
2456 result.retry_after_ = retry_after(response);
2457 result.rate_limit_ = reported_rate_limit(response);
2458 }
2459 const auto error = document.if_contains("error");
2460 if (!error || !error->is_object()) {
2461 result.message_ = "Toss response has no error object";
2462 return result;
2463 }
2464 const auto& object = error->as_object();
2465 if (const auto value = object.if_contains("code"); value && value->is_string()) {
2466 result.broker_code_ = value->as_string().c_str();
2467 }
2468 if (const auto value = object.if_contains("requestId"); value && value->is_string()) {
2469 result.request_id_ = value->as_string().c_str();
2470 }
2471 if (const auto value = object.if_contains("message"); value && value->is_string()) {
2472 result.message_ = value->as_string().c_str();
2473 }
2474 return result;
2475 }
2476
2477 // Returns an error when the account sequence cannot address a Toss account.
2478 static std::optional<BrokerError> validate_account_sequence(std::int64_t account_sequence) {
2479 if (account_sequence > 0) {
2480 return std::nullopt;
2481 }
2482 BrokerError error;
2483 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2484 error.reached_broker_ = false;
2485 error.broker_code_ = "invalid_account";
2486 error.message_ = "Toss account sequence must be positive";
2487 return error;
2488 }
2489
2490 // Returns an error when an order identifier is empty.
2491 static std::optional<BrokerError> validate_order_id(std::string_view order_id) {
2492 if (!order_id.empty()) {
2493 return std::nullopt;
2494 }
2495 BrokerError error;
2496 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2497 error.reached_broker_ = false;
2498 error.broker_code_ = "invalid_order_reference";
2499 error.message_ = "Toss order identifier must not be empty";
2500 return error;
2501 }
2502
2503 // Returns an error when a client order identifier cannot be used as an
2504 // idempotency key.
2505 //
2506 // Toss accepts at most thirty-six characters drawn from letters, digits,
2507 // hyphen, and underscore. A key rejected on the wire would silently remove
2508 // the very guarantee the caller asked for, so it is checked here first.
2509 static std::optional<BrokerError> validate_client_order_id(std::string_view client_order_id) {
2510 bool valid = !client_order_id.empty() && client_order_id.size() <= 36;
2511 for (const char ch : client_order_id) {
2512 const bool allowed =
2513 (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
2514 valid = valid && allowed;
2515 }
2516 if (valid) {
2517 return std::nullopt;
2518 }
2519 BrokerError error;
2520 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2521 error.reached_broker_ = false;
2522 error.broker_code_ = "invalid_client_order_id";
2523 error.message_ = "Toss client order id must be 1-36 characters of letters, digits, hyphen, or underscore";
2524 return error;
2525 }
2526
2527 // Returns an error when a quantity is not a positive whole number of shares, or, where
2528 // `fraction_allowed`, a positive quantity of at most six decimal places.
2529 //
2530 // The raw scale is checked rather than a normalized one, because the request sends
2531 // `quantity.str()`, which keeps it.
2532 static std::optional<BrokerError> validate_quantity(const Decimal64& quantity, bool fraction_allowed = false) {
2533 const auto max_scale = fraction_allowed ? 6 : 0;
2534 if (quantity.coefficient() > 0 && quantity.scale() <= max_scale) {
2535 return std::nullopt;
2536 }
2537 BrokerError error;
2538 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2539 error.reached_broker_ = false;
2540 error.broker_code_ = "invalid_quantity";
2541 error.message_ =
2542 "Toss order quantity must be a positive whole number of shares; Toss accepts a fraction, "
2543 "to six decimal places, only on a US market sell";
2544 return error;
2545 }
2546
2547 // Returns an error when a price does not match its order type.
2548 static std::optional<BrokerError> validate_price(OrderType type, const std::optional<Decimal64>& price) {
2549 BrokerError error;
2550 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2551 error.reached_broker_ = false;
2552 error.broker_code_ = "invalid_price";
2553 if (type == OrderType::LIMIT) {
2554 if (!price) {
2555 error.message_ = "Toss limit order requires a price";
2556 return error;
2557 }
2558 if (price->coefficient() <= 0) {
2559 error.message_ = "Toss limit order price must be positive";
2560 return error;
2561 }
2562 return std::nullopt;
2563 }
2564 if (type == OrderType::MARKET) {
2565 if (price) {
2566 error.message_ = "Toss market order must not carry a price";
2567 return error;
2568 }
2569 return std::nullopt;
2570 }
2571 // A backstop, not a branch describing a reachable state: both callers judge
2572 // the basis first (`validate_order_shape`, `validate_amendment_shape`), so
2573 // this fires only for a caller added without one. It stays because
2574 // returning `nullopt` for an unjudged basis would let the order through.
2575 error.broker_code_ = "unsupported_order";
2576 error.message_ = "Toss orders currently support limit and market orders only";
2577 return error;
2578 }
2579
2580 // Returns an error when Toss cannot express this order shape.
2581 //
2582 // Toss publishes two price bases (`LIMIT`, `MARKET`), one execution condition
2583 // (day-valid), and three sessions, of which two are restricted. Everything
2584 // else this library can name is KIS's, and is rejected here rather than
2585 // approximated: a fill-or-kill order downgraded to a day order is a different
2586 // order, and a mid-price order has no Toss spelling at all.
2587 //
2588 // The restrictions are the spec's own, checked before I/O so a caller learns
2589 // the rule without spending an order on it: the closing auction is US limit
2590 // orders only, and the opening auction is Korean orders only.
2591 static std::optional<BrokerError> validate_order_shape(
2592 OrderType type, TimeInForce time_in_force, OrderSession session, Country country
2593 ) {
2594 BrokerError error;
2595 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2596 error.reached_broker_ = false;
2597
2598 if (type != OrderType::LIMIT && type != OrderType::MARKET) {
2599 error.broker_code_ = "unsupported_order_type";
2600 error.message_ = "Toss accepts a limit or market order only";
2601 return error;
2602 }
2603 if (time_in_force != TimeInForce::DAY) {
2604 error.broker_code_ = "unsupported_time_in_force";
2605 error.message_ =
2606 "Toss orders are day-valid; it publishes no immediate-or-cancel or "
2607 "fill-or-kill condition";
2608 return error;
2609 }
2610
2611 error.broker_code_ = "unsupported_session";
2612 switch (session) {
2614 return std::nullopt;
2616 if (country == Country::US && type == OrderType::LIMIT) {
2617 return std::nullopt;
2618 }
2619 error.message_ = "Toss accepts a closing-auction order only for a US limit order";
2620 return error;
2622 if (country == Country::KR) {
2623 return std::nullopt;
2624 }
2625 error.message_ = "Toss accepts an opening-auction order only for a Korean order";
2626 return error;
2627 default:
2628 error.message_ = "Toss publishes no order code for this trading session";
2629 return error;
2630 }
2631 }
2632
2633 // Returns an error when the order cannot be represented as a Toss order.
2634 static std::optional<BrokerError> validate_order(const OrderRequest& order) {
2635 if (!trades_country(order.instrument_.country_)) {
2636 BrokerError error;
2637 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2638 error.reached_broker_ = false;
2639 error.broker_code_ = "unsupported_market";
2640 error.message_ = "Toss trades Korean and US listings only";
2641 return error;
2642 }
2643 if (!broker_detail::valid_symbol(order.instrument_.symbol_)) {
2644 BrokerError error;
2645 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2646 error.reached_broker_ = false;
2647 error.broker_code_ = "invalid_instrument";
2648 error.message_ = "Toss order symbol contains unsupported characters";
2649 return error;
2650 }
2651 // The identity venue Toss's own parses write, so an order is the same
2652 // `InstrumentId` as its holding and `Portfolio::working_quantity` finds it.
2653 // Anything else on the instrument means routing, and Toss routes nowhere.
2654 if (order.instrument_.venue_ != instrument_venue(order.instrument_.country_)) {
2655 BrokerError error;
2656 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2657 error.reached_broker_ = false;
2658 error.broker_code_ = "invalid_instrument";
2659 error.message_ =
2660 "Toss identifies an instrument by the venue its own listings report; it offers no venue "
2661 "choice, so an order may not name one";
2662 return error;
2663 }
2664 if (order.venue_ != Venue::UNSPECIFIED) {
2665 BrokerError error;
2666 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2667 error.reached_broker_ = false;
2668 error.broker_code_ = "venue_unavailable";
2669 error.message_ = "Toss publishes no venue choice on an order; leave OrderRequest::venue_ unspecified";
2670 return error;
2671 }
2672 if (order.client_order_id_) {
2673 if (auto error = validate_client_order_id(*order.client_order_id_)) {
2674 return error;
2675 }
2676 }
2677 // Toss's trigger orders are a separate conditional-order API this client does not use, and
2678 // `make_place_order_request` has no field for a trigger, so one stated here would be dropped
2679 // and the order acknowledged as a plain limit. The session refuses it too, but a caller of
2680 // this client does not go through the session.
2681 if (order.trigger_price_) {
2682 BrokerError error;
2683 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2684 error.reached_broker_ = false;
2685 error.broker_code_ = "unsupported_trigger_price";
2686 error.message_ = "this Toss client does not place conditional orders, so it takes no trigger price";
2687 return error;
2688 }
2689 // The shape is judged before the price, because whether a price is required
2690 // at all is a fact about the basis. Judged after, a mid-price order was
2691 // refused by `validate_price` as "limit and market orders only" -- the right
2692 // outcome under a code that names the wrong field, and it made
2693 // `validate_order_shape`'s own basis check unreachable from this path.
2694 if (
2695 auto error = validate_order_shape(order.type_, order.time_in_force_, order.session_, order.instrument_.country_)
2696 ) {
2697 return error;
2698 }
2699 // The shape check above refuses every session without a code; this keeps the two from drifting, before
2700 // any token is asked for.
2701 if (session_code(order.session_)[0] == '\0') {
2702 BrokerError error;
2703 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2704 error.reached_broker_ = false;
2705 error.broker_code_ = "unsupported_session";
2706 error.message_ = "Toss publishes no order code for this trading session";
2707 return error;
2708 }
2709 // Toss's one fractional shape (`createOrder`, `fractionalQuantityUsSellOnly`). Its other rule,
2710 // the regular session until an hour before the close, is left to Toss's own `422`.
2711 const bool fraction_allowed =
2712 order.instrument_.country_ == Country::US && order.type_ == OrderType::MARKET && order.side_ == OrderSide::SELL;
2713 if (auto error = validate_quantity(order.quantity_, fraction_allowed)) {
2714 return error;
2715 }
2716 if (auto error = validate_price(order.type_, order.price_)) {
2717 return error;
2718 }
2719 if (prices_in_whole_units(order.instrument_.country_) && order.price_ && order.price_->scale() != 0) {
2720 BrokerError error;
2721 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2722 error.reached_broker_ = false;
2723 error.broker_code_ = "invalid_price";
2724 error.message_ = "Toss Korean limit order price must be a whole number of won";
2725 return error;
2726 }
2727 return std::nullopt;
2728 }
2729
2730 // Returns Toss's wire code for a normalized price basis.
2731 //
2732 // This used to read `type == MARKET ? "MARKET" : "LIMIT"`, which was
2733 // harmless while those were the only two bases and is not now: it would send
2734 // a mid-price or best-limit amendment to Toss as a plain limit order, which
2735 // is a silent downgrade, which this library refuses, and is invisible in the
2736 // request. Every caller validates the basis first, so the remaining cases
2737 // cannot be reached from outside this class; reaching one means a new body
2738 // was built without a validation step, which is a defect here rather than a
2739 // caller's bad input.
2740 static const char* order_type_code(OrderType type) {
2741 switch (type) {
2742 case OrderType::MARKET:
2743 return "MARKET";
2744 case OrderType::LIMIT:
2745 return "LIMIT";
2746 default:
2747 break;
2748 }
2749 throw std::logic_error("Toss order body built from an unvalidated price basis");
2750 }
2751
2752 // Returns an error when Toss cannot express an amendment's price basis.
2753 //
2754 // A modification states a basis and Toss accepts two of them. The placement
2755 // path checks this inside `validate_order_shape`; the modification path had
2756 // no check at all, so the basis reached `order_type_code` unexamined.
2757 static std::optional<BrokerError> validate_amendment_shape(OrderType type) {
2758 if (type == OrderType::LIMIT || type == OrderType::MARKET) {
2759 return std::nullopt;
2760 }
2761 BrokerError error;
2762 error.category_ = ErrorCategory::INVALID_ARGUMENT;
2763 error.reached_broker_ = false;
2764 error.broker_code_ = "unsupported_order_type";
2765 error.message_ = "Toss modifies an order to a limit or market basis only";
2766 return error;
2767 }
2768
2769 // Returns Toss's `timeInForce` wire value for a normalized session.
2770 //
2771 // Toss spells the session on the field it calls `timeInForce`: its own spec
2772 // defines `OPG` as 국내 시가단일가 and `CLS` as the closing auction, which are
2773 // sessions rather than validity conditions. This library keeps the two facts
2774 // apart -- KIS spells both inside one `ORD_DVSN` and would otherwise have to
2775 // put the same fact in a different field -- so the mapping to Toss's wire
2776 // shape happens here, at the adapter boundary, which is where a vendor
2777 // spelling belongs.
2778 //
2779 // A session Toss takes no order in has no code (`""`); `validate_order` refuses it before any I/O.
2780 static const char* session_code(OrderSession session) {
2781 switch (session) {
2783 return "DAY";
2785 return "CLS";
2787 return "OPG";
2788 case OrderSession::UNKNOWN:
2793 case OrderSession::GTP:
2794 return "";
2795 }
2796 return "";
2797 }
2798
2799 // The condition of an order Toss lists, from its session. Toss publishes no execution condition of its
2800 // own, so every session it names is day-valid; an unread one leaves the condition unknown too.
2801 static TimeInForce read_time_in_force(OrderSession session) {
2802 switch (session) {
2803 case OrderSession::UNKNOWN:
2804 return TimeInForce::UNKNOWN;
2812 case OrderSession::GTP:
2813 return TimeInForce::DAY;
2814 }
2815 return TimeInForce::UNKNOWN;
2816 }
2817
2818 // Builds the authenticated Toss order-placement POST request.
2819 static network::HttpRequest make_place_order_request(
2820 std::int64_t account_sequence, std::string_view access_token, const OrderRequest& order
2821 ) {
2822 json::object body{
2823 {"symbol", order.instrument_.symbol_},
2824 {"side", order.side_ == OrderSide::SELL ? "SELL" : "BUY"},
2825 {"orderType", order_type_code(order.type_)},
2826 {"timeInForce", session_code(order.session_)},
2827 {"quantity", order.quantity_.str()},
2828 };
2829 if (order.client_order_id_) {
2830 body.emplace("clientOrderId", *order.client_order_id_);
2831 }
2832 if (order.price_) {
2833 body.emplace("price", order.price_->str());
2834 }
2835 if (order.confirm_high_value_) {
2836 body.emplace("confirmHighValueOrder", true);
2837 }
2838
2839 network::HttpRequest request;
2840 // An order is what the reserve is held for.
2841 request.group_ = network::RateLimitGroup::TRADING;
2842 request.method_ = http::verb::post;
2843 request.target_ = "/api/v1/orders";
2844 request.body_ = json::serialize(body);
2845 request.headers_ = {
2846 {"Authorization", "Bearer " + std::string(access_token)},
2847 {"X-Tossinvest-Account", std::to_string(account_sequence)},
2848 {"Content-Type", "application/json"},
2849 };
2850 return request;
2851 }
2852
2853 // Builds the authenticated Toss order-modification POST request.
2854 static network::HttpRequest make_replace_order_request(
2855 std::int64_t account_sequence, std::string_view access_token, const TossAmendment& amendment
2856 ) {
2857 json::object body{{"orderType", order_type_code(amendment.type_)}};
2858 if (amendment.quantity_) {
2859 body.emplace("quantity", amendment.quantity_->str());
2860 }
2861 if (amendment.price_) {
2862 body.emplace("price", amendment.price_->str());
2863 }
2864 if (amendment.confirm_high_value_) {
2865 body.emplace("confirmHighValueOrder", true);
2866 }
2867
2868 network::HttpRequest request;
2869 // A modification carries an order instruction and ranks with one.
2870 request.group_ = network::RateLimitGroup::TRADING;
2871 request.method_ = http::verb::post;
2872 request.target_ = "/api/v1/orders/" + broker_detail::query_encode(amendment.order_id_) + "/modify";
2873 request.body_ = json::serialize(body);
2874 request.headers_ = {
2875 {"Authorization", "Bearer " + std::string(access_token)},
2876 {"X-Tossinvest-Account", std::to_string(account_sequence)},
2877 {"Content-Type", "application/json"},
2878 };
2879 return request;
2880 }
2881
2882 // Builds the authenticated Toss order-cancellation POST request.
2883 static network::HttpRequest make_cancel_order_request(
2884 std::int64_t account_sequence, std::string_view access_token, std::string_view order_id
2885 ) {
2886 network::HttpRequest request;
2887 // A cancellation is the request that must never queue behind polling.
2888 request.group_ = network::RateLimitGroup::TRADING;
2889 request.method_ = http::verb::post;
2890 request.target_ = "/api/v1/orders/" + broker_detail::query_encode(order_id) + "/cancel";
2891 request.body_ = "{}";
2892 request.headers_ = {
2893 {"Authorization", "Bearer " + std::string(access_token)},
2894 {"X-Tossinvest-Account", std::to_string(account_sequence)},
2895 {"Content-Type", "application/json"},
2896 };
2897 return request;
2898 }
2899
2900 // Builds a Toss order-list request from the supplied filters.
2901 static network::HttpRequest make_orders_request(std::string_view access_token, const TossOrderQuery& query) {
2902 bool open = false;
2903 switch (query.scope_) {
2905 open = true;
2906 break;
2908 break;
2909 }
2910 std::string target = "/api/v1/orders?status=";
2911 target += open ? "OPEN" : "CLOSED";
2912 if (query.symbol_) {
2913 target += "&symbol=" + broker_detail::query_encode(*query.symbol_);
2914 }
2915 if (query.from_) {
2916 target += "&from=" + iso_date(*query.from_);
2917 }
2918 if (query.to_) {
2919 target += "&to=" + iso_date(*query.to_);
2920 }
2921 // Toss documents that an OPEN listing returns every pending order and
2922 // ignores paging, so the paging parameters are omitted rather than sent
2923 // and silently discarded.
2924 if (!open) {
2925 if (query.cursor_) {
2926 target += "&cursor=" + broker_detail::query_encode(*query.cursor_);
2927 }
2928 if (query.limit_) {
2929 target += "&limit=" + std::to_string(*query.limit_);
2930 }
2931 }
2932
2933 network::HttpRequest request;
2934 // Order listings are account monitoring, not order submission.
2935 request.group_ = network::RateLimitGroup::ACCOUNT;
2936 request.method_ = http::verb::get;
2937 request.target_ = std::move(target);
2938 request.headers_ = {
2939 {"Authorization", "Bearer " + std::string(access_token)},
2940 {"X-Tossinvest-Account", std::to_string(query.account_sequence_)},
2941 };
2942 return request;
2943 }
2944
2945 // Builds a Toss request for one order by broker identifier.
2946 static network::HttpRequest make_order_request(
2947 std::int64_t account_sequence, std::string_view access_token, std::string_view order_id
2948 ) {
2949 network::HttpRequest request;
2950 // A single-order inquiry is account monitoring.
2951 request.group_ = network::RateLimitGroup::ACCOUNT;
2952 request.method_ = http::verb::get;
2953 request.target_ = "/api/v1/orders/" + broker_detail::query_encode(order_id);
2954 request.headers_ = {
2955 {"Authorization", "Bearer " + std::string(access_token)},
2956 {"X-Tossinvest-Account", std::to_string(account_sequence)},
2957 };
2958 return request;
2959 }
2960
2961 // Validates and starts one Toss order submission.
2962 void start_place_order(std::int64_t account_sequence, OrderRequest order, OrderAckHandler completion) {
2963 auto invalid = validate_account_sequence(account_sequence);
2964 if (!invalid) {
2965 invalid = validate_order(order);
2966 }
2967 if (invalid) {
2968 complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*invalid)));
2969 return;
2970 }
2971
2972 ensure_token(TokenHandler(
2973 [self = shared_from_this(), account_sequence, order = std::move(order),
2974 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
2975 if (token_error) {
2976 self->complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*token_error)));
2977 return;
2978 }
2979 auto request = make_place_order_request(account_sequence, self->token_.access_token_, order);
2980 self->request_order_ack(std::move(request), std::move(completion));
2981 }
2982 ));
2983 }
2984
2985 // Validates and starts one Toss order modification.
2986 void start_replace_order(std::int64_t account_sequence, TossAmendment amendment, OrderAckHandler completion) {
2987 auto invalid = validate_account_sequence(account_sequence);
2988 if (!invalid) {
2989 invalid = validate_order_id(amendment.order_id_);
2990 }
2991 if (!invalid && amendment.quantity_) {
2992 invalid = validate_quantity(*amendment.quantity_);
2993 }
2994 if (!invalid) {
2995 invalid = validate_amendment_shape(amendment.type_);
2996 }
2997 if (!invalid) {
2998 invalid = validate_price(amendment.type_, amendment.price_);
2999 }
3000 if (invalid) {
3001 complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*invalid)));
3002 return;
3003 }
3004
3005 ensure_token(TokenHandler(
3006 [self = shared_from_this(), account_sequence, amendment = std::move(amendment),
3007 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3008 if (token_error) {
3009 self->complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*token_error)));
3010 return;
3011 }
3012 auto request = make_replace_order_request(account_sequence, self->token_.access_token_, amendment);
3013 self->request_order_ack(std::move(request), std::move(completion));
3014 }
3015 ));
3016 }
3017
3018 // Validates and starts one Toss order cancellation.
3019 void start_cancel_order(std::int64_t account_sequence, std::string order_id, OrderAckHandler completion) {
3020 auto invalid = validate_account_sequence(account_sequence);
3021 if (!invalid) {
3022 invalid = validate_order_id(order_id);
3023 }
3024 if (invalid) {
3025 complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*invalid)));
3026 return;
3027 }
3028
3029 ensure_token(TokenHandler(
3030 [self = shared_from_this(), account_sequence, order_id = std::move(order_id),
3031 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3032 if (token_error) {
3033 self->complete_order_ack(std::move(completion), Result<OrderAck>(std::move(*token_error)));
3034 return;
3035 }
3036 auto request = make_cancel_order_request(account_sequence, self->token_.access_token_, order_id);
3037 self->request_order_ack(std::move(request), std::move(completion));
3038 }
3039 ));
3040 }
3041
3042 // Sends an order-writing request and dispatches its parsed acknowledgement.
3043 void request_order_ack(network::HttpRequest request, OrderAckHandler completion) {
3044 send(
3045 std::move(request),
3046 [self = shared_from_this(), completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3047 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
3048 self->complete_order_ack(std::move(completion), parse_order_ack(std::move(result)));
3049 });
3050 }
3051 );
3052 }
3053
3054 // Validates and starts one filtered Toss order listing.
3055 void start_orders(TossOrderQuery query, OrderPageHandler completion) {
3056 if (auto invalid = validate_account_sequence(query.account_sequence_)) {
3057 complete_order_page(std::move(completion), Result<OrderPage>(std::move(*invalid)));
3058 return;
3059 }
3060 if (query.symbol_ && !broker_detail::valid_symbol(*query.symbol_)) {
3061 BrokerError error;
3062 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3063 error.reached_broker_ = false;
3064 error.broker_code_ = "invalid_instrument";
3065 error.message_ = "Toss order filter symbol contains unsupported characters";
3066 complete_order_page(std::move(completion), Result<OrderPage>(std::move(error)));
3067 return;
3068 }
3069 if (query.limit_ && (*query.limit_ < 1 || *query.limit_ > 100)) {
3070 BrokerError error;
3071 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3072 error.reached_broker_ = false;
3073 error.broker_code_ = "invalid_limit";
3074 error.message_ = "Toss order listing accepts a page size between 1 and 100";
3075 complete_order_page(std::move(completion), Result<OrderPage>(std::move(error)));
3076 return;
3077 }
3078 if (
3079 (query.from_ && !is_valid_date(*query.from_)) || (query.to_ && !is_valid_date(*query.to_)) ||
3080 (query.from_ && query.to_ && *query.to_ < *query.from_)
3081 ) {
3082 BrokerError error;
3083 error.category_ = ErrorCategory::INVALID_ARGUMENT;
3084 error.reached_broker_ = false;
3085 error.broker_code_ = "invalid_date_range";
3086 error.message_ = "Toss order listing requires valid inclusive calendar bounds";
3087 complete_order_page(std::move(completion), Result<OrderPage>(std::move(error)));
3088 return;
3089 }
3090
3091 ensure_token(TokenHandler(
3092 [self = shared_from_this(), query = std::move(query),
3093 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3094 if (token_error) {
3095 self->complete_order_page(std::move(completion), Result<OrderPage>(std::move(*token_error)));
3096 return;
3097 }
3098 auto request = make_orders_request(self->token_.access_token_, query);
3099 self->send(
3100 std::move(request), [self, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3101 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
3102 self->complete_order_page(std::move(completion), parse_orders(std::move(result)));
3103 });
3104 }
3105 );
3106 }
3107 ));
3108 }
3109
3110 // Validates and starts an inquiry for one Toss order.
3111 void start_order(std::int64_t account_sequence, std::string order_id, OrderHandler completion) {
3112 auto invalid = validate_account_sequence(account_sequence);
3113 if (!invalid) {
3114 invalid = validate_order_id(order_id);
3115 }
3116 if (invalid) {
3117 complete_order(std::move(completion), Result<OrderSnapshot>(std::move(*invalid)));
3118 return;
3119 }
3120
3121 ensure_token(TokenHandler(
3122 [self = shared_from_this(), account_sequence, order_id = std::move(order_id),
3123 completion = std::move(completion)](std::optional<BrokerError> token_error) mutable {
3124 if (token_error) {
3125 self->complete_order(std::move(completion), Result<OrderSnapshot>(std::move(*token_error)));
3126 return;
3127 }
3128 auto request = make_order_request(account_sequence, self->token_.access_token_, order_id);
3129 self->send(
3130 std::move(request), [self, completion = std::move(completion)](Result<network::HttpResponse> result) mutable {
3131 net::post(self->strand_, [self, completion = std::move(completion), result = std::move(result)]() mutable {
3132 self->complete_order(std::move(completion), parse_order(std::move(result)));
3133 });
3134 }
3135 );
3136 }
3137 ));
3138 }
3139
3140 // Parses a Toss order-instruction response into an acknowledgement.
3141 static Result<OrderAck> parse_order_ack(Result<network::HttpResponse> result) {
3142 if (!result) {
3143 return Result<OrderAck>(std::move(result.error()));
3144 }
3145 BrokerError parse_error;
3146 auto document = broker_detail::parse_object(result.value(), parse_error);
3147 if (!document) {
3148 return Result<OrderAck>(std::move(parse_error));
3149 }
3150 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3151 auto error = toss_error(result.value(), *document);
3152 return Result<OrderAck>(std::move(error));
3153 }
3154 try {
3155 const auto payload = document->if_contains("result");
3156 if (!payload || !payload->is_object()) {
3157 throw std::runtime_error("missing object field: result");
3158 }
3159 const auto& fields = payload->as_object();
3160
3161 OrderAck ack;
3162 ack.order_id_ = broker_detail::json_string(fields, "orderId");
3163 if (const auto value = fields.if_contains("clientOrderId"); value && value->is_string()) {
3164 ack.client_order_id_ = std::string(value->as_string());
3165 }
3166 ack.accepted_at_ = std::chrono::system_clock::now();
3167 return Result<OrderAck>(std::move(ack));
3168 } catch (const std::exception& exception) {
3169 BrokerError error;
3170 error.category_ = ErrorCategory::PROTOCOL;
3171 error.broker_code_ = "invalid_order_response";
3172 error.message_ = exception.what();
3173 return Result<OrderAck>(std::move(error));
3174 }
3175 }
3176
3177 // Parses one Toss order-list response and its continuation cursor.
3178 static Result<OrderPage> parse_orders(Result<network::HttpResponse> result) {
3179 if (!result) {
3180 return Result<OrderPage>(std::move(result.error()));
3181 }
3182 BrokerError parse_error;
3183 auto document = broker_detail::parse_object(result.value(), parse_error);
3184 if (!document) {
3185 return Result<OrderPage>(std::move(parse_error));
3186 }
3187 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3188 auto error = toss_error(result.value(), *document);
3189 return Result<OrderPage>(std::move(error));
3190 }
3191 try {
3192 const auto payload = document->if_contains("result");
3193 if (!payload || !payload->is_object()) {
3194 throw std::runtime_error("missing object field: result");
3195 }
3196 const auto& output = payload->as_object();
3197 const auto orders = output.if_contains("orders");
3198 if (!orders || !orders->is_array()) {
3199 throw std::runtime_error("missing array field: orders");
3200 }
3201
3202 OrderPage page;
3203 page.orders_.reserve(orders->as_array().size());
3204 for (const auto& value : orders->as_array()) {
3205 if (!value.is_object()) {
3206 throw std::runtime_error("order item is not an object");
3207 }
3208 page.orders_.push_back(parse_order_object(value.as_object()));
3209 }
3210 if (const auto cursor = output.if_contains("nextCursor"); cursor && cursor->is_string()) {
3211 page.next_cursor_ = std::string(cursor->as_string());
3212 }
3213 page.received_at_ = std::chrono::system_clock::now();
3214 return Result<OrderPage>(std::move(page));
3215 } catch (const std::exception& exception) {
3216 BrokerError error;
3217 error.category_ = ErrorCategory::PROTOCOL;
3218 error.broker_code_ = "invalid_orders_response";
3219 error.message_ = exception.what();
3220 return Result<OrderPage>(std::move(error));
3221 }
3222 }
3223
3224 // Parses a Toss single-order response into a normalized snapshot.
3225 static Result<OrderSnapshot> parse_order(Result<network::HttpResponse> result) {
3226 if (!result) {
3227 return Result<OrderSnapshot>(std::move(result.error()));
3228 }
3229 BrokerError parse_error;
3230 auto document = broker_detail::parse_object(result.value(), parse_error);
3231 if (!document) {
3232 return Result<OrderSnapshot>(std::move(parse_error));
3233 }
3234 if (result.value().result_int() < 200 || result.value().result_int() >= 300) {
3235 auto error = toss_error(result.value(), *document);
3236 return Result<OrderSnapshot>(std::move(error));
3237 }
3238 try {
3239 const auto payload = document->if_contains("result");
3240 if (!payload || !payload->is_object()) {
3241 throw std::runtime_error("missing object field: result");
3242 }
3243 return Result<OrderSnapshot>(parse_order_object(payload->as_object()));
3244 } catch (const std::exception& exception) {
3245 BrokerError error;
3246 error.category_ = ErrorCategory::PROTOCOL;
3247 error.broker_code_ = "invalid_order_response";
3248 error.message_ = exception.what();
3249 return Result<OrderSnapshot>(std::move(error));
3250 }
3251 }
3252
3253 // Normalizes one Toss order object.
3254 //
3255 // Toss reports a currency rather than a market country, so the instrument's
3256 // country is taken from that currency. This is a stated broker fact, not an
3257 // inference from the symbol's shape.
3258 //
3259 // Unrecognized order-type, validity, and status codes become their `UNKNOWN`
3260 // value. Toss's specification requires clients to tolerate them, so one
3261 // unfamiliar order must not fail an entire listing.
3262 static OrderSnapshot parse_order_object(const json::object& row) {
3263 const auto currency = Currency(broker_detail::json_string(row, "currency"));
3264
3265 Country country;
3266 if (currency == Currency::krw()) {
3267 country = Country::KR;
3268 } else if (currency == Currency::usd()) {
3269 country = Country::US;
3270 } else {
3271 throw std::runtime_error("unsupported Toss order currency: " + currency.str());
3272 }
3273
3274 OrderSnapshot order;
3275 order.order_id_ = broker_detail::json_string(row, "orderId");
3276 // `instrument_venue`, not `UNSPECIFIED`: `parse_position` writes `COMBINED`
3277 // for the same Korean instrument, and an order and its holding must be the
3278 // same `InstrumentId`, or `Portfolio::working_quantity` finds nothing for a
3279 // Korean Toss order.
3280 order.instrument_ = InstrumentId{
3281 country,
3282 instrument_venue(country),
3283 broker_detail::json_string(row, "symbol"),
3284 };
3285 order.side_ = normalized_order_side(broker_detail::json_string(row, "side"));
3286 order.type_ = normalized_order_type(broker_detail::json_string(row, "orderType"));
3287 const auto time_in_force = broker_detail::json_string(row, "timeInForce");
3288 order.session_ = normalized_session(time_in_force);
3289 // Toss publishes no execution condition of its own, so every order it
3290 // recognizes is day-valid. A `timeInForce` it does not recognize leaves the
3291 // condition unknown as well as the session, rather than asserting `DAY`
3292 // about a value this library could not read.
3293 order.time_in_force_ = read_time_in_force(order.session_);
3294 if (const auto code = Code<8>::try_make(time_in_force)) {
3295 order.shape_code_ = *code;
3296 }
3297 order.status_ = normalized_status(broker_detail::json_string(row, "status"));
3298 order.price_ = nullable_decimal(row, "price");
3299 order.quantity_ = Decimal64::parse(broker_detail::json_string(row, "quantity"));
3300 // An amount-based order states dollars and lets the fill decide the
3301 // quantity. The library does not place one yet, but it must not drop the
3302 // field off one placed through another channel: without it the snapshot
3303 // says an order of some quantity and cannot say what was actually
3304 // committed.
3305 order.order_amount_ = nullable_rounded_decimal(row, "orderAmount");
3306 order.currency_ = currency;
3307 order.ordered_at_ = optional_timestamp(row, "orderedAt");
3308 order.canceled_at_ = optional_timestamp(row, "canceledAt");
3309
3310 const auto execution = row.if_contains("execution");
3311 if (!execution || !execution->is_object()) {
3312 throw std::runtime_error("missing object field: execution");
3313 }
3314 const auto& fills = execution->as_object();
3315 order.execution_.filled_quantity_ = Decimal64::parse(broker_detail::json_string(fills, "filledQuantity"));
3316 order.execution_.average_filled_price_ = optional_decimal(fills, "averageFilledPrice");
3317 order.execution_.filled_amount_ = optional_money(fills, "filledAmount", currency);
3318 order.execution_.commission_ = optional_money(fills, "commission", currency);
3319 order.execution_.tax_ = optional_money(fills, "tax", currency);
3320 order.execution_.filled_at_ = optional_timestamp(fills, "filledAt");
3321 order.execution_.settlement_date_ = optional_date(fills, "settlementDate");
3322 return order;
3323 }
3324
3325 // Maps a Toss order-type code onto a normalized order type.
3326 static OrderType normalized_order_type(std::string_view code) {
3327 if (code == "LIMIT") {
3328 return OrderType::LIMIT;
3329 }
3330 if (code == "MARKET") {
3331 return OrderType::MARKET;
3332 }
3333 return OrderType::UNKNOWN;
3334 }
3335
3336 // Maps a Toss validity code onto a normalized validity condition.
3337 static OrderSession normalized_session(std::string_view code) {
3338 if (code == "DAY") {
3339 return OrderSession::REGULAR;
3340 }
3341 if (code == "CLS") {
3343 }
3344 if (code == "OPG") {
3346 }
3347 return OrderSession::UNKNOWN;
3348 }
3349
3350 // Maps a Toss status code onto a normalized lifecycle state.
3351 static OrderStatus normalized_status(std::string_view code) {
3352 if (code == "PENDING") {
3353 return OrderStatus::PENDING;
3354 }
3355 if (code == "PENDING_CANCEL") {
3356 return OrderStatus::PENDING_CANCEL;
3357 }
3358 if (code == "PENDING_REPLACE") {
3359 return OrderStatus::PENDING_REPLACE;
3360 }
3361 if (code == "PARTIAL_FILLED") {
3362 return OrderStatus::PARTIAL_FILLED;
3363 }
3364 if (code == "FILLED") {
3365 return OrderStatus::FILLED;
3366 }
3367 if (code == "CANCELED") {
3368 return OrderStatus::CANCELED;
3369 }
3370 if (code == "REJECTED") {
3371 return OrderStatus::REJECTED;
3372 }
3373 if (code == "CANCEL_REJECTED") {
3374 return OrderStatus::CANCEL_REJECTED;
3375 }
3376 if (code == "REPLACE_REJECTED") {
3377 return OrderStatus::REPLACE_REJECTED;
3378 }
3379 if (code == "REPLACED") {
3380 return OrderStatus::REPLACED;
3381 }
3382 return OrderStatus::UNKNOWN;
3383 }
3384
3385 // Maps a Toss side code or rejects an invalid broker response.
3386 static OrderSide normalized_order_side(std::string_view code) {
3387 if (code == "BUY") {
3388 return OrderSide::BUY;
3389 }
3390 if (code == "SELL") {
3391 return OrderSide::SELL;
3392 }
3393 throw std::runtime_error("invalid Toss order side code");
3394 }
3395
3396 // Reads a decimal string field that Toss may omit entirely.
3397 //
3398 // Toss marks an order's price as neither required nor always present, unlike
3399 // the execution amounts, which are always sent and merely nullable. Those
3400 // keep the stricter `optional_decimal`, so a genuinely missing execution
3401 // field is still reported as a protocol error.
3402 static std::optional<Decimal64> nullable_decimal(const json::object& object, std::string_view key) {
3403 const auto value = object.if_contains(key);
3404 if (!value || value->is_null()) {
3405 return std::nullopt;
3406 }
3407 if (!value->is_string()) {
3408 throw std::runtime_error("invalid decimal field: " + std::string(key));
3409 }
3410 return Decimal64::parse(std::string_view(value->as_string()));
3411 }
3412
3413 // Reads a nullable decimal string field that Toss computes, rounding a fraction too long for
3414 // `Decimal64`.
3415 //
3416 // Toss has sent `orderAmount` with twenty fractional digits, which `Decimal64::parse` refuses, and
3417 // the refusal failed every order list holding such an order. The fraction is rounded half to even
3418 // to the 18 significant digits a `Decimal64` always holds. The integer part is never rounded: a value
3419 // whose integer part does not fit is still refused.
3420 static std::optional<Decimal64> nullable_rounded_decimal(const json::object& object, std::string_view key) {
3421 const auto value = object.if_contains(key);
3422 if (!value || value->is_null()) {
3423 return std::nullopt;
3424 }
3425 if (!value->is_string()) {
3426 throw std::runtime_error("invalid decimal field: " + std::string(key));
3427 }
3428 return rounded_decimal(std::string_view(value->as_string()));
3429 }
3430
3431 // Parses a decimal exactly, or, when only its fraction is too long to fit, to the nearest value
3432 // with 18 significant digits (ties to even).
3433 //
3434 // The digits are counted from the first nonzero one, so the leading zeros of an amount below one
3435 // cost no precision. A value that cannot keep 18 significant digits within `Decimal64`'s scale, or
3436 // whose integer part does not fit, is refused rather than rounded towards zero.
3437 static Decimal64 rounded_decimal(std::string_view text) {
3438 try {
3439 return Decimal64::parse(text);
3440 } catch (const std::out_of_range&) {
3441 const auto sign = !text.empty() && (text.front() == '-' || text.front() == '+') ? 1U : 0U;
3442 const auto point = text.find('.');
3443 if (point == std::string_view::npos) {
3444 throw;
3445 }
3446 auto whole = text.substr(sign, point - sign);
3447 const auto fraction = text.substr(point + 1);
3448 for (const auto part : {whole, fraction}) {
3449 if (part.find_first_not_of("0123456789") != std::string_view::npos) {
3450 throw std::invalid_argument("decimal value contains an invalid character");
3451 }
3452 }
3453 const auto significant = whole.find_first_not_of('0');
3454 whole = significant == std::string_view::npos ? std::string_view() : whole.substr(significant);
3455 constexpr std::size_t digits = 18;
3456 if (whole.size() > digits) {
3457 throw;
3458 }
3459 std::size_t kept = 0;
3460 if (!whole.empty()) {
3461 kept = std::min(fraction.size(), digits - whole.size());
3462 } else {
3463 const auto leading = fraction.find_first_not_of('0');
3464 if (leading == std::string_view::npos) {
3465 return Decimal64();
3466 }
3467 kept = std::min(fraction.size(), leading + digits);
3468 }
3469 if (kept > std::numeric_limits<std::uint8_t>::max()) {
3470 throw std::out_of_range("decimal scale exceeds Decimal64 range");
3471 }
3472 std::uint64_t magnitude = 0;
3473 for (const auto ch : whole) {
3474 magnitude = magnitude * 10U + static_cast<std::uint64_t>(ch - '0');
3475 }
3476 for (const auto ch : fraction.substr(0, kept)) {
3477 magnitude = magnitude * 10U + static_cast<std::uint64_t>(ch - '0');
3478 }
3479 const auto dropped = fraction.substr(kept);
3480 if (!dropped.empty()) {
3481 const bool beyond_half = dropped.find_first_not_of('0', 1) != std::string_view::npos;
3482 if (dropped.front() > '5' || (dropped.front() == '5' && (beyond_half || magnitude % 2U == 1U))) {
3483 ++magnitude;
3484 }
3485 }
3486 const auto coefficient = static_cast<std::int64_t>(magnitude);
3487 const Decimal64 rounded(
3488 sign == 1U && text.front() == '-' ? -coefficient : coefficient, static_cast<std::uint8_t>(kept)
3489 );
3490 return Decimal64::parse(rounded.str());
3491 }
3492 }
3493
3494 // Reads a nullable decimal string field as an amount in `currency`.
3495 static std::optional<Money> optional_money(
3496 const json::object& object, std::string_view key, const Currency& currency
3497 ) {
3498 const auto amount = optional_decimal(object, key);
3499 if (!amount) {
3500 return std::nullopt;
3501 }
3502 return Money{*amount, currency};
3503 }
3504
3505 // Reads a nullable ISO 8601 timestamp field.
3506 static std::optional<std::chrono::system_clock::time_point> optional_timestamp(
3507 const json::object& object, std::string_view key
3508 ) {
3509 const auto value = object.if_contains(key);
3510 if (!value || value->is_null()) {
3511 return std::nullopt;
3512 }
3513 if (!value->is_string()) {
3514 throw std::runtime_error("invalid timestamp field: " + std::string(key));
3515 }
3516 auto parsed = parse_iso8601_timestamp(std::string_view(value->as_string()));
3517 if (!parsed) {
3518 throw std::runtime_error("invalid timestamp field: " + std::string(key));
3519 }
3520 return parsed;
3521 }
3522
3523 // Reads a nullable `YYYY-MM-DD` calendar date field.
3524 static std::optional<Date> optional_date(const json::object& object, std::string_view key) {
3525 const auto value = object.if_contains(key);
3526 if (!value || value->is_null()) {
3527 return std::nullopt;
3528 }
3529 if (!value->is_string()) {
3530 throw std::runtime_error("invalid date field: " + std::string(key));
3531 }
3532 const std::string_view text(value->as_string());
3533 int year = 0;
3534 unsigned month = 0;
3535 unsigned day = 0;
3536 if (
3537 text.size() != 10 || text[4] != '-' || text[7] != '-' ||
3538 std::sscanf(std::string(text).c_str(), "%4d-%2u-%2u", &year, &month, &day) != 3
3539 ) {
3540 throw std::runtime_error("invalid date field: " + std::string(key));
3541 }
3542 Date date{year, month, day};
3543 if (!is_valid_date(date)) {
3544 throw std::runtime_error("invalid date field: " + std::string(key));
3545 }
3546 return date;
3547 }
3548
3549 // Formats a calendar date as Toss's `YYYY-MM-DD` filter bound.
3550 static std::string iso_date(const Date& date) {
3551 char buffer[11];
3552 std::snprintf(buffer, sizeof(buffer), "%04d-%02u-%02u", date.year_, date.month_, date.day_);
3553 return std::string(buffer);
3554 }
3555
3556 // Sends a request that carries the access token, and forgets that token if Toss refuses it.
3557 //
3558 // Toss answers 401 to a token that has expired or been revoked, and issuing a token revokes the
3559 // one issued before it with the same key ("새로 발급된 토큰으로 대체되어 더 이상 유효하지 않은
3560 // 토큰입니다"), so another program using the key ends this one's token. Kept, it would be sent
3561 // until its stated expiry and every request would fail; forgotten, the next request asks for a new
3562 // one. The refused request is not sent again. Only the token the request carried is forgotten: a
3563 // late refusal of an older token leaves a newer one alone, so a token one program takes refuses the
3564 // other's requests that carry the old token and starts no chain of refreshes.
3565 template <typename Handler>
3566 void send(network::HttpRequest request, Handler handler) {
3567 std::string authorization;
3568 for (const auto& [name, value] : request.headers_) {
3569 if (name == "Authorization") {
3570 authorization = value;
3571 }
3572 }
3573 http_->async_request(
3574 std::move(request),
3575 [self = shared_from_this(), authorization = std::move(authorization),
3576 handler = std::move(handler)](Result<network::HttpResponse> result) mutable {
3577 if (result && result.value().result_int() == 401) {
3578 // Queued before the handler runs; every operation starts with a post to the strand, so
3579 // the next one finds the token gone.
3580 net::post(self->strand_, [self, authorization = std::move(authorization)] {
3581 self->forget_refused_token(authorization);
3582 });
3583 }
3584 std::move(handler)(std::move(result));
3585 }
3586 );
3587 }
3588
3589 // Forgets the held token if it is the one a refused request carried (its `Authorization` value).
3590 void forget_refused_token(const std::string& authorization) {
3591 if (!token_.access_token_.empty() && authorization == "Bearer " + token_.access_token_) {
3592 token_ = TossRest{};
3593 }
3594 }
3595
3596 // Dispatches one result through its associated executor, exactly once.
3597 //
3598 // Every operation's result passes through here, which makes it the one place a
3599 // broker's own rate-limit refusal can be fed back into this connection's pacer
3600 // without each operation having to remember to do it.
3601 template <typename Handler, typename T>
3602 void deliver(Handler handler, Result<T> result) {
3603 if (!result) {
3604 note_rate_limit(result.error());
3605 }
3606 auto executor = net::get_associated_executor(handler, strand_);
3607 net::dispatch(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
3608 std::move(handler)(std::move(result));
3609 });
3610 }
3611
3612 // Corrects this connection's pacing from a Toss rate-limit refusal.
3613 //
3614 // Toss documents a token bucket and reports `X-RateLimit-Limit` with its
3615 // refusal, so the allowance it is enforcing is known and is applied directly.
3616 // The headers are documented on the refusal rather than promised on every
3617 // response, so an absent one only holds admission rather than guessing an allowance.
3618 void note_rate_limit(const BrokerError& error) {
3619 if (!error_category_is_rate_limit(error.category_)) {
3620 return;
3621 }
3622 auto* limiter = http_->rate_limits();
3623 if (!limiter) {
3624 return;
3625 }
3626 const auto retry = error.retry_after_ ?
3627 std::chrono::duration_cast<network::RateLimitController::Duration>(*error.retry_after_) :
3628 std::chrono::duration_cast<network::RateLimitController::Duration>(std::chrono::seconds(1));
3629 if (error.rate_limit_) {
3630 limiter->shrink(*error.rate_limit_, *error.rate_limit_, retry);
3631 return;
3632 }
3633
3634 // The headers are documented on the refusal rather than promised on it, so an
3635 // absent allowance means waiting rather than guessing a smaller one.
3636 limiter->hold(retry);
3637 }
3638
3639 void complete_order_ack(OrderAckHandler handler, Result<OrderAck> result) {
3640 deliver(std::move(handler), std::move(result));
3641 }
3642
3643 // Dispatches an order-list result through its associated executor.
3644 void complete_order_page(OrderPageHandler handler, Result<OrderPage> result) {
3645 deliver(std::move(handler), std::move(result));
3646 }
3647
3648 // Dispatches a single-order result through its associated executor.
3649 void complete_order(OrderHandler handler, Result<OrderSnapshot> result) {
3650 deliver(std::move(handler), std::move(result));
3651 }
3652
3653 void complete(QuoteHandler handler, Result<QuoteSnapshot> result) {
3654 deliver(std::move(handler), std::move(result));
3655 }
3656
3657 void complete_accounts(AccountsHandler handler, Result<std::vector<TossAccount>> result) {
3658 deliver(std::move(handler), std::move(result));
3659 }
3660
3661 void complete_holdings(HoldingsHandler handler, Result<HoldingsSnapshot> result) {
3662 deliver(std::move(handler), std::move(result));
3663 }
3664
3665 void complete_buying_power(BuyingPowerHandler handler, Result<BuyingPower> result) {
3666 deliver(std::move(handler), std::move(result));
3667 }
3668
3669 void complete_sellable_quantity(SellableQuantityHandler handler, Result<Decimal64> result) {
3670 deliver(std::move(handler), std::move(result));
3671 }
3672
3673 void complete_commissions(CommissionScheduleHandler handler, Result<CommissionSchedule> result) {
3674 deliver(std::move(handler), std::move(result));
3675 }
3676};
3677
3690public:
3699 ssl::context& context, TossConfig config, network::HttpClientOptions options = {},
3700 std::shared_ptr<network::TokenStore> store = nullptr
3701 )
3702 : store_(std::move(store)),
3703 identity_(store_ ? config.token_identity() : std::string()),
3704 client_(std::make_shared<TossClient>(ioc_.get_executor(), context, std::move(config), options)) {
3705 client_->store_managed_ = store_ != nullptr;
3706 }
3707
3714 return run<QuoteSnapshot>(
3715 [&](auto&& sink) {
3716 client_->async_quote(std::move(instrument), std::move(sink));
3717 },
3718 "quote"
3719 );
3720 }
3721
3727 return run<std::vector<TossAccount>>(
3728 [&](auto&& sink) {
3729 client_->async_accounts(std::move(sink));
3730 },
3731 "accounts"
3732 );
3733 }
3734
3741 return run<Instrument>(
3742 [&](auto&& sink) {
3743 client_->async_instrument(std::move(subject), std::move(sink));
3744 },
3745 "instrument"
3746 );
3747 }
3748
3755 Result<TradingCalendar> calendar(Country country, std::optional<Date> from = std::nullopt) {
3756 return run<TradingCalendar>(
3757 [&](auto&& sink) {
3758 client_->async_calendar(country, from, std::move(sink));
3759 },
3760 "calendar"
3761 );
3762 }
3763
3770 return run<PriceLimits>(
3771 [&](auto&& sink) {
3772 client_->async_price_limits(std::move(instrument), std::move(sink));
3773 },
3774 "price_limits"
3775 );
3776 }
3777
3785 return run<std::vector<TradePrint>>(
3786 [&](auto&& sink) {
3787 client_->async_trades(std::move(instrument), count, std::move(sink));
3788 },
3789 "trades"
3790 );
3791 }
3792
3798 Result<std::vector<QuoteSnapshot>> prices(std::vector<InstrumentId> instruments) {
3799 return run<std::vector<QuoteSnapshot>>(
3800 [&](auto&& sink) {
3801 client_->async_prices(std::move(instruments), std::move(sink));
3802 },
3803 "prices"
3804 );
3805 }
3806
3813 return run<DepthSnapshot>(
3814 [&](auto&& sink) {
3815 client_->async_depth(std::move(instrument), std::move(sink));
3816 },
3817 "depth"
3818 );
3819 }
3820
3827 return run<BarSeries>(
3828 [&](auto&& sink) {
3829 client_->async_bars(std::move(query), std::move(sink));
3830 },
3831 "bars"
3832 );
3833 }
3834
3840 Result<HoldingsSnapshot> holdings(std::int64_t account_sequence) {
3841 return run<HoldingsSnapshot>(
3842 [&](auto&& sink) {
3843 client_->async_holdings(account_sequence, std::move(sink));
3844 },
3845 "holdings"
3846 );
3847 }
3848
3855 Result<BuyingPower> buying_power(Currency currency, std::int64_t account_sequence) {
3856 return run<BuyingPower>(
3857 [&](auto&& sink) {
3858 client_->async_buying_power(currency, account_sequence, std::move(sink));
3859 },
3860 "buying_power"
3861 );
3862 }
3863
3871 return run<Decimal64>(
3872 [&](auto&& sink) {
3873 client_->async_sellable_quantity(std::move(instrument), account_sequence, std::move(sink));
3874 },
3875 "sellable_quantity"
3876 );
3877 }
3878
3884 Result<CommissionSchedule> commissions(std::int64_t account_sequence) {
3885 return run<CommissionSchedule>(
3886 [&](auto&& sink) {
3887 client_->async_commissions(account_sequence, std::move(sink));
3888 },
3889 "commissions"
3890 );
3891 }
3892
3904 Result<OrderAck> place_order(std::int64_t account_sequence, OrderRequest order) {
3905 return run<OrderAck>(
3906 [&](auto&& sink) {
3907 client_->async_place_order(account_sequence, std::move(order), std::move(sink));
3908 },
3909 "order placement"
3910 );
3911 }
3912
3920 Result<OrderAck> replace_order(std::int64_t account_sequence, TossAmendment amendment) {
3921 return run<OrderAck>(
3922 [&](auto&& sink) {
3923 client_->async_replace_order(account_sequence, std::move(amendment), std::move(sink));
3924 },
3925 "order modification"
3926 );
3927 }
3928
3936 Result<OrderAck> cancel_order(std::int64_t account_sequence, std::string order_id) {
3937 return run<OrderAck>(
3938 [&](auto&& sink) {
3939 client_->async_cancel_order(account_sequence, std::move(order_id), std::move(sink));
3940 },
3941 "order cancellation"
3942 );
3943 }
3944
3951 return run<OrderPage>(
3952 [&](auto&& sink) {
3953 client_->async_orders(std::move(query), std::move(sink));
3954 },
3955 "order listing"
3956 );
3957 }
3958
3965 Result<OrderSnapshot> order(std::int64_t account_sequence, std::string order_id) {
3966 return run<OrderSnapshot>(
3967 [&](auto&& sink) {
3968 client_->async_order(account_sequence, std::move(order_id), std::move(sink));
3969 },
3970 "order inquiry"
3971 );
3972 }
3973
3979 return client_->rate_limit_stats();
3980 }
3981
3986 TossRest token() const {
3987 return client_->token();
3988 }
3989
3996 return client_->adopt_token(std::move(token));
3997 }
3998
3999private:
4000 friend struct TossClientTestAccess;
4001
4002 // Runs one call: with a store, prepares the token first and discards one Toss refused during the call.
4003 template <typename T, typename Start>
4004 Result<T> run(Start start, std::string_view operation) {
4005 if (!store_) {
4006 return drive<T>(std::move(start), operation);
4007 }
4008 const auto request = [this] {
4009 return drive<TossRest>(
4010 [this](auto&& sink) {
4011 client_->async_ensure_token(std::move(sink));
4012 },
4013 "token request"
4014 );
4015 };
4016 if (auto error = network::token_store_detail::prepare(*store_, identity_, *client_, request)) {
4017 return Result<T>(std::move(*error));
4018 }
4019 const auto carried = client_->token();
4020 auto result = drive<T>(std::move(start), operation);
4021 network::token_store_detail::discard_refused(*store_, identity_, carried, client_->token());
4022 return result;
4023 }
4024
4025 // Drives one asynchronous operation to completion on the private loop.
4026 template <typename T, typename Start>
4027 Result<T> drive(Start start, std::string_view operation) {
4028 std::optional<Result<T>> result;
4029 ioc_.restart();
4030 start([&result](Result<T> value) {
4031 result.emplace(std::move(value));
4032 });
4033 ioc_.run();
4034 if (!result) {
4035 BrokerError error;
4036 error.category_ = ErrorCategory::TRANSPORT;
4037 error.broker_code_ = "event_loop_stopped";
4038 error.message_ = "event loop stopped before " + std::string(operation) + " completion";
4039 return Result<T>(std::move(error));
4040 }
4041 return std::move(*result);
4042 }
4043
4044 std::shared_ptr<network::TokenStore> store_;
4045 std::string identity_;
4046 net::io_context ioc_;
4047 std::shared_ptr<TossClient> client_;
4048};
4049
4050} // namespace algotradelib::tossinvest
static std::optional< Code > try_make(std::string_view text)
Makes a code without throwing.
Definition types.hpp:291
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
static Currency usd()
Returns United States dollars.
Definition types.hpp:410
Currency()
Constructs Korean won.
Definition types.hpp:377
static Currency krw()
Returns Korean won.
Definition types.hpp:402
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
static StatedDate unreadable()
Makes an unreadable date.
static StatedDate stated(Date date)
Makes a stated date.
std::string to_form_urlencoded_body() const
Builds a form-encoded token-request body (grant_type, client_id, client_secret).
Definition oauth.hpp:107
Blocking facade that drives TossClient on a private event loop.
Definition client.hpp:3689
Result< OrderAck > replace_order(std::int64_t account_sequence, TossAmendment amendment)
Amends an open order; the outcome can be unknown after an error. The acknowledgement carries a new id...
Definition client.hpp:3920
Result< BuyingPower > buying_power(Currency currency, std::int64_t account_sequence)
Returns what the account may spend in currency.
Definition client.hpp:3855
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics (safe to read between calls).
Definition client.hpp:3978
Result< Decimal64 > sellable_quantity(InstrumentId instrument, std::int64_t account_sequence)
Returns how much of instrument the account may sell.
Definition client.hpp:3870
Result< OrderPage > orders(TossOrderQuery query)
Returns one page of orders; see TossClient::async_orders for which orders are listed.
Definition client.hpp:3950
TossBlockingClient(ssl::context &context, TossConfig config, network::HttpClientOptions options={}, std::shared_ptr< network::TokenStore > store=nullptr)
Constructs a blocking Toss Securities client.
Definition client.hpp:3698
Result< Instrument > instrument(InstrumentId subject)
Returns static reference data for one instrument.
Definition client.hpp:3740
Result< OrderAck > place_order(std::int64_t account_sequence, OrderRequest order)
Places an order; see TossClient::async_place_order.
Definition client.hpp:3904
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns the resting orders on both sides of the book.
Definition client.hpp:3812
Result< HoldingsSnapshot > holdings(std::int64_t account_sequence)
Returns normalized positions and per-currency totals for one account.
Definition client.hpp:3840
Result< std::vector< QuoteSnapshot > > prices(std::vector< InstrumentId > instruments)
Returns a quote for every instrument in one request.
Definition client.hpp:3798
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns a quote for a Korean instrument (a US instrument is refused; use prices).
Definition client.hpp:3713
bool adopt_token(TossRest token)
Uses a token issued earlier; see TossClient::adopt_token.
Definition client.hpp:3995
Result< CommissionSchedule > commissions(std::int64_t account_sequence)
Returns the commission rates in force for the account.
Definition client.hpp:3884
Result< OrderAck > cancel_order(std::int64_t account_sequence, std::string order_id)
Cancels an open order; the outcome can be unknown after an error. The acknowledgement carries a new i...
Definition client.hpp:3936
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns today's upper and lower price bound.
Definition client.hpp:3769
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns recent executions for one instrument.
Definition client.hpp:3784
Result< std::vector< TossAccount > > accounts()
Discovers the brokerage accounts available to the current credentials.
Definition client.hpp:3726
Result< OrderSnapshot > order(std::int64_t account_sequence, std::string order_id)
Returns one order by id; see TossClient::async_order for which orders can be read.
Definition client.hpp:3965
Result< BarSeries > bars(BarQuery query)
Returns up to count_ bars; see TossClient::async_bars.
Definition client.hpp:3826
Result< TradingCalendar > calendar(Country country, std::optional< Date > from=std::nullopt)
Returns the trading calendar around from for one market.
Definition client.hpp:3755
TossRest token() const
Returns the access token; see TossClient::token.
Definition client.hpp:3986
The asynchronous Toss Securities REST client: market data, accounts and orders.
Definition client.hpp:149
auto async_commissions(std::int64_t account_sequence, CompletionToken &&token)
Requests the commission rates in force for the account.
Definition client.hpp:480
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests static reference data for one instrument.
Definition client.hpp:270
auto async_orders(TossOrderQuery query, CompletionToken &&token)
Requests a page of orders.
Definition client.hpp:629
net::any_completion_handler< void(std::optional< BrokerError >)> TokenHandler
Internal completion handler for a shared access-token refresh.
Definition client.hpp:196
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests recent executions for one instrument, newest first.
Definition client.hpp:319
net::any_completion_handler< void(Result< HoldingsSnapshot >)> HoldingsHandler
Completion handler for one normalized holdings snapshot.
Definition client.hpp:178
net::any_completion_handler< void(Result< BarSeries >)> BarsHandler
Completion handler for one normalized bar series.
Definition client.hpp:155
TossClient(net::any_io_executor executor, ssl::context &context, TossConfig config, network::HttpClientOptions options={})
Constructs a client; nothing is sent until the first request.
Definition client.hpp:208
net::any_completion_handler< void(Result< std::vector< QuoteSnapshot > >)> PricesHandler
Completion handler for several instruments quoted at once.
Definition client.hpp:167
net::any_completion_handler< void(Result< TossRest >)> TokenResultHandler
The completion handler type of async_ensure_token.
Definition client.hpp:199
net::any_completion_handler< void(Result< CommissionSchedule >)> CommissionScheduleHandler
Completion handler for the account's commission schedule.
Definition client.hpp:184
bool adopt_token(TossRest token)
Uses a token issued earlier for the same key instead of requesting one.
Definition client.hpp:714
net::any_completion_handler< void(Result< DepthSnapshot >)> DepthHandler
Completion handler for one normalized order book.
Definition client.hpp:158
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests a quote for a Korean instrument (a US instrument is refused before sending; use async_prices...
Definition client.hpp:394
net::any_completion_handler< void(Result< std::vector< TossAccount > >)> AccountsHandler
Completion handler for Toss account discovery.
Definition client.hpp:175
net::any_completion_handler< void(Result< BuyingPower >)> BuyingPowerHandler
Completion handler for one normalized buying-power reading.
Definition client.hpp:180
auto async_bars(BarQuery query, CompletionToken &&token)
Requests up to count_ bars, oldest first.
Definition client.hpp:227
auto async_holdings(std::int64_t account_sequence, CompletionToken &&token)
Requests and normalizes holdings for one discovered account sequence.
Definition client.hpp:500
net::any_completion_handler< void(Result< QuoteSnapshot >)> QuoteHandler
Completion handler for one normalized quote.
Definition client.hpp:152
net::any_completion_handler< void(Result< OrderPage >)> OrderPageHandler
Completion handler for one normalized page of orders.
Definition client.hpp:190
net::any_completion_handler< void(Result< TradingCalendar >)> CalendarHandler
Completion handler for one trading calendar.
Definition client.hpp:170
auto async_accounts(CompletionToken &&token)
Discovers the brokerage accounts available to the current credentials.
Definition client.hpp:415
net::any_completion_handler< void(Result< PriceLimits >)> PriceLimitsHandler
Completion handler for one instrument's price bounds.
Definition client.hpp:161
net::any_completion_handler< void(Result< OrderAck >)> OrderAckHandler
Completion handler for one accepted Toss order instruction.
Definition client.hpp:187
net::any_completion_handler< void(Result< OrderSnapshot >)> OrderHandler
Completion handler for one normalized order.
Definition client.hpp:193
void close()
Cancels transport work and queued HTTP operations.
Definition client.hpp:758
auto async_cancel_order(std::int64_t account_sequence, std::string order_id, CompletionToken &&token)
Cancels an open order.
Definition client.hpp:598
TossRest token() const
Returns the access token the client holds, to reuse in another client or a later process (adopt_token...
Definition client.hpp:695
auto async_place_order(std::int64_t account_sequence, OrderRequest order, CompletionToken &&token)
Places an order.
Definition client.hpp:536
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests and normalizes the resting orders on both sides of the book.
Definition client.hpp:371
auto async_buying_power(Currency currency, std::int64_t account_sequence, CompletionToken &&token)
Requests the account's buying power in a currency.
Definition client.hpp:436
net::any_completion_handler< void(Result< Instrument >)> InstrumentHandler
Completion handler for one instrument's reference data.
Definition client.hpp:173
net::any_completion_handler< void(Result< Decimal64 >)> SellableQuantityHandler
Completion handler for one instrument's sellable quantity.
Definition client.hpp:182
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:678
auto async_calendar(Country country, std::optional< Date > from, CompletionToken &&token)
Requests the trading calendar around a date: that date and the business days either side of it (three...
Definition client.hpp:250
auto async_prices(std::vector< InstrumentId > instruments, CompletionToken &&token)
Quotes up to 200 instruments in one request.
Definition client.hpp:349
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests today's upper and lower price bound for one instrument.
Definition client.hpp:294
void forget_token()
Drops the held token: the next request asks for one.
Definition client.hpp:753
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:730
auto async_order(std::int64_t account_sequence, std::string order_id, CompletionToken &&token)
Requests one order by id, in any state.
Definition client.hpp:655
auto async_sellable_quantity(InstrumentId instrument, std::int64_t account_sequence, CompletionToken &&token)
Requests how much of one instrument the account may sell.
Definition client.hpp:457
net::any_completion_handler< void(Result< std::vector< TradePrint > >)> TradesHandler
Completion handler for recent executions.
Definition client.hpp:164
auto async_replace_order(std::int64_t account_sequence, TossAmendment amendment, CompletionToken &&token)
Amends an open order's price, and for a Korean order its quantity.
Definition client.hpp:568
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
PriceRule price_rule_for(SecurityType type)
Returns the KRX price grid for a kind of security listed on KRX.
Definition krx.hpp:52
HTTP and WebSocket transport, OAuth tokens, and request pacing.
@ MARKET_DATA
Quotes, bars, order book and trades.
@ ACCOUNT
Holdings, working orders, order history and buying power.
@ TRADING
Order placement, amendment and cancellation. HttpClientOptions::fresh_connection_for_orders_ applies ...
@ REFERENCE
Instrument reference data and trading calendars.
@ AUTH
Access-token issue and refresh.
BrokerError token_unusable_error()
Returns the error of a call whose token stopped being usable while it ran on a client with a store: A...
http::response< http::string_body > HttpResponse
The HTTP response type the transport clients return.
void quote(S &strategy, Ctx &context, const QuoteEvent &event)
Calls strategy.on_quote(context, event) if the strategy declares on_quote; otherwise does nothing.
Definition concept.hpp:331
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
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
The Toss Securities Open API client.
Definition auth.hpp:9
std::optional< BrokerError > unsupported_bar_interval(BarInterval interval)
Refuses a bar interval Toss does not publish (it publishes one-minute and one-day bars only; nothing ...
Definition client.hpp:124
TossOrderScope
Which orders a Toss order listing returns.
Definition client.hpp:42
@ CLOSED
Ended orders (including a partly filled order that ended).
Definition client.hpp:46
@ OPEN
Open orders: pending, partly filled, or with an amendment or cancellation pending.
Definition client.hpp:44
std::optional< std::chrono::seconds > retry_after(const network::HttpResponse &response)
Reads the Retry-After header of a Toss rate-limit refusal.
Definition client.hpp:97
std::optional< int > reported_rate_limit(const network::HttpResponse &response)
Reads the X-RateLimit-Limit header of a Toss rate-limit refusal (requests per second).
Definition client.hpp:110
@ CLOSE
The timestamp is the instant the period ended.
@ OPEN
The timestamp is the first instant of the period.
MarketSegment market_segment(std::string_view code)
Maps a broker's segment code to a MarketSegment.
SecurityType
What kind of security an instrument is.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
@ BROKER_PUBLISHED
The broker published them, through an inquiry the library made.
Definition types.hpp:1669
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
@ RATE_LIMIT
The broker refused the request for its rate limit.
Definition types.hpp:958
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
@ AUTHENTICATION
The credentials or token were refused.
Definition types.hpp:956
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
InstrumentStatus
Whether an instrument is listed, awaiting listing, or delisted.
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
Country
A country (market) the library supports.
Definition types.hpp:32
OrderSession
The trading session an order is submitted into.
Definition types.hpp:2130
@ OPENING_AUCTION
The opening single-price auction (시가단일가; Toss OPG).
Definition types.hpp:2135
@ AFTER_HOURS
After the close, at that session's close (장후 시간외).
Definition types.hpp:2141
@ CLOSING_AUCTION
The closing auction (Toss CLS, a US limit-on-close).
Definition types.hpp:2137
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
@ AFTER_MARKET
KRX's after-market session (애프터마켓).
Definition types.hpp:2145
@ AFTER_HOURS_AUCTION
The after-hours single-price auction (시간외 단일가).
Definition types.hpp:2143
@ PRE_MARKET
Before the open, at the previous session's close (장전 시간외).
Definition types.hpp:2139
@ GTP
NXT's GTP session.
Definition types.hpp:2147
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
BarInterval
The period one bar covers.
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
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
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An order to place, in broker-neutral form.
Definition types.hpp:2216
static PriceRule unconstrained()
Returns a rule with no grid, for a market quoted in free decimals.
static PriceRule unknown(std::string reason)
Returns a rule that knows no grid and refuses to round.
bool valid(std::chrono::seconds margin=std::chrono::minutes(5)) const noexcept
Tests whether the token is set and stays valid for at least a margin.
Definition oauth.hpp:201
void from_json(const json::object &document)
Reads a token response.
Definition oauth.hpp:166
std::string access_token_
The bearer token; do not log it.
Definition oauth.hpp:152
Deadlines, size limits and pacing for an HTTP client.
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...
A Toss account, as account discovery (async_accounts) returns it.
Definition client.hpp:30
std::int64_t sequence_
Toss's account sequence, which every account request names.
Definition client.hpp:34
std::string account_type_
The account type as Toss reports it, for display.
Definition client.hpp:36
std::string account_number_
The account number as Toss reports it (accountNo): the full number, not masked.
Definition client.hpp:32
An amendment of a Toss order: a new price, and for a Korean order a new quantity.
Definition client.hpp:79
std::string order_id_
Toss's order id.
Definition client.hpp:81
bool confirm_high_value_
Confirms a high-value order, which Toss otherwise refuses.
Definition client.hpp:89
std::optional< Decimal64 > price_
The new price.
Definition client.hpp:87
std::optional< Decimal64 > quantity_
The new quantity: required for a Korean order, empty for a US one.
Definition client.hpp:85
OrderType type_
The order type it should have.
Definition client.hpp:83
Toss Securities credentials (client id and secret). Toss has no demo environment.
Definition config.hpp:27
A Toss order-listing query.
Definition client.hpp:56
std::optional< Date > to_
The last order date to include; before from_ is refused.
Definition client.hpp:66
std::optional< Date > from_
The first order date to include (Korean date; any scope).
Definition client.hpp:64
std::optional< std::string > symbol_
Only this symbol, if set.
Definition client.hpp:62
std::int64_t account_sequence_
The account (TossAccount::sequence_).
Definition client.hpp:58
std::optional< std::string > cursor_
The cursor from a previous page (OrderPage::next_cursor_); ignored for OPEN.
Definition client.hpp:68
TossOrderScope scope_
Open or closed orders.
Definition client.hpp:60
std::optional< int > limit_
The most rows to return, 1 to 100 (outside that range is refused, even for OPEN); not sent for OPEN.
Definition client.hpp:70
A Toss REST access token and its expiry.
Definition config.hpp:120