algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
traits.hpp
1#pragma once
2
8#define ATL_BROKER_ADAPTER_PRESENT 1
9
10#include "./client.hpp"
11
12#include "../../core/broker_session.hpp"
13#include "../../core/broker_traits.hpp"
14
15#include <boost/asio/associated_executor.hpp>
16#include <boost/asio/dispatch.hpp>
17#include <boost/asio/execution/outstanding_work.hpp>
18#include <boost/asio/post.hpp>
19#include <boost/asio/prefer.hpp>
20
21#include <optional>
22#include <string>
23#include <utility>
24
25namespace algotradelib {
26
27namespace kiwoom {
28
33struct Broker {
35 static constexpr std::string_view name = "kiwoom";
36};
37
38namespace traits_detail {
39
41using Ref = OrderRef<kiwoom::Broker>;
42
44struct Normalizers {
46 static constexpr bool has_depth = true;
47
49 static constexpr bool has_price_limits = true;
50
52 static constexpr bool has_trade_prints = true;
53
58 static constexpr bool has_batch_prices = false;
59
61 static constexpr bool has_buying_power = true;
62
67 static constexpr bool has_buying_power_quantity = true;
68
73 static constexpr SellableSource sellable_source = SellableSource::NONE;
74
79 static constexpr bool has_commission_schedule = false;
80
82 static constexpr bool has_reference_data = true;
83
85 static constexpr bool has_batch_reference_data = false;
86
91 static constexpr bool has_calendar = false;
92
94 static constexpr bool has_calendar_range = false;
95
97 static constexpr bool has_calendar_sessions = false;
98
105 static std::optional<BrokerError> validate_calendar(Country country, std::optional<Date> from) {
106 static_cast<void>(country);
107 static_cast<void>(from);
108 BrokerError error;
110 error.reached_broker_ = false;
111 error.broker_code_ = "calendar_unsupported";
112 error.message_ = "Kiwoom publishes no trading calendar";
113 return error;
114 }
115
122 static constexpr bool supports_interval(BarInterval interval) {
123 return kiwoom::chart_api_id(interval) != nullptr && kiwoom::chart_rows_field(interval) != nullptr;
124 }
125
131 static std::optional<BrokerError> validate_bars(const BarQuery& query) {
133 }
134
146 static Result<HoldingsSnapshot> refuse_holdings() {
147 BrokerError error;
149 error.reached_broker_ = false;
150 error.broker_code_ = "holdings_scope_unestablished";
151 error.message_ =
152 "Kiwoom's balance inquiry names one venue (kt00018 dmst_stex_tp: KRX or NXT) and publishes no "
153 "all-venue value, and whether that filters the positions or only values them is not stated. "
154 "This library will not present one venue's answer as the account's holdings unless you say "
155 "that is what it is: set KiwoomConfig::holdings_position_scope_ to "
156 "KiwoomPositionScope::VALUATION_ONLY to assert it, and "
157 "KiwoomConfig::holdings_sellable_scope_ separately for trde_able_qty. Until then read the rows "
158 "through session.client().holdings(). Both assertions are unverified; see KiwoomConfig's "
159 "documentation";
160 return Result<HoldingsSnapshot>(std::move(error));
161 }
162
169 static Ref make_ref(const KiwoomOrderRef& order) {
170 Ref ref;
171 ref.primary_ = order.order_number_;
172 ref.secondary_ = order.symbol_;
173 return ref;
174 }
175
181 static KiwoomOrderRef from_ref(const Ref& ref) {
182 KiwoomOrderRef order;
183 order.order_number_ = ref.primary_;
184 order.symbol_ = ref.secondary_;
185 return order;
186 }
187
194 static std::optional<BrokerError> validate_place(const OrderRequest& order) {
195 // **The holdings refusal is deliberately not repeated here**, although this is the port's
196 // pre-flight. It lives in `KiwoomClient::validate_order`, which every placement reaches --
197 // including this port's, because `place` calls the client immediately after this returns and
198 // the client refuses before any I/O. Checking it here as well would only change *which* message
199 // a caller gets: this function does not validate the order's venue, price or shape, so it would
200 // report the holdings gap for an order that is also malformed, burying the mistake the caller
201 // can actually fix. See `kiwoom::unestablished_holdings_scope`.
203 }
204
211 if (!raw) {
212 return Result<PlacedOrder<kiwoom::Broker>>(std::move(raw.error()));
213 }
215 placed.ack_ = std::move(raw.value().ack_);
216 placed.ref_ = make_ref(raw.value().order_);
217 return Result<PlacedOrder<kiwoom::Broker>>(std::move(placed));
218 }
219
229 static Result<WorkingOrders<kiwoom::Broker>> normalize_working_orders(
231 ) {
232 if (!raw) {
233 return Result<WorkingOrders<kiwoom::Broker>>(std::move(raw.error()));
234 }
236 orders.received_at_ = raw.value().received_at_;
237 orders.orders_.reserve(raw.value().orders_.size());
238 for (auto& open_order : raw.value().orders_) {
240 working.order_ = std::move(open_order.order_);
241 working.ref_ = make_ref(open_order.order_ref_);
242 working.amendable_quantity_ = open_order.amendable_quantity_;
243 orders.orders_.push_back(std::move(working));
244 }
245 return Result<WorkingOrders<kiwoom::Broker>>(std::move(orders));
246 }
247
263 static Result<KiwoomAmendment> to_amendment(
264 const Ref& ref,
265 const AmendInstruction& instruction,
266 bool cancel
267 ) {
268 BrokerError error;
270 error.reached_broker_ = false;
271
272 if (!instruction.all_remaining_ && !instruction.quantity_) {
273 error.broker_code_ = "quantity_required";
274 error.message_ =
275 "a Kiwoom modification or cancellation affects a stated quantity; set all_remaining_ to "
276 "act on everything still resting, or build the instruction with cancel_all()";
277 return Result<KiwoomAmendment>(std::move(error));
278 }
279 if (auto refusal = refuse_shape_change(instruction, cancel)) {
280 return Result<KiwoomAmendment>(std::move(*refusal));
281 }
282
283 KiwoomAmendment amendment;
284 amendment.order_ = from_ref(ref);
285 amendment.venue_ = instruction.venue_;
286 // Kiwoom's own "everything still resting", which it evaluates when it processes the
287 // instruction rather than when the caller read the listing.
288 amendment.quantity_ =
289 instruction.all_remaining_ ? Decimal64() : *instruction.quantity_;
290 if (!cancel) {
291 // The basis is known here and nowhere after: `kt10002` carries no `trde_tp`, so this is the
292 // last point that can tell a trigger the order wants from one it would silently lose.
293 const auto trigger = amended_trigger_price(instruction);
294 if (auto invalid = kiwoom::invalid_trigger(instruction.shape_.type_, trigger)) {
295 return Result<KiwoomAmendment>(std::move(*invalid));
296 }
297 amendment.price_ = instruction.shape_.price_;
298 amendment.condition_price_ = trigger;
299 }
300 // **Never on a cancellation.** `kt10003` has no trigger field and the client refuses a
301 // cancellation carrying one; `cancel_all` restates the resting trigger, so copying it here would
302 // make every stop order impossible to withdraw through the port.
303 return Result<KiwoomAmendment>(std::move(amendment));
304 }
305
318 static std::optional<BrokerError> refuse_shape_change(
319 const AmendInstruction& instruction,
320 bool cancel
321 ) {
322 BrokerError error;
324 error.reached_broker_ = false;
325 error.broker_code_ = "shape_change_unsupported";
326
327 const auto refuse = [&error, cancel](const char* what) {
328 error.message_ = cancel ?
329 std::string("Kiwoom's cancellation carries a quantity and nothing else, so it cannot "
330 "change an order's ") + what + " on the way out" :
331 std::string("Kiwoom's amendment endpoints carry a quantity and a price only, so they "
332 "cannot change an order's ") + what +
333 "; cancel the order and place a new one instead";
334 return error;
335 };
336
337 // An unset field means "leave it as it is", so it is never a change. A set field is a change
338 // only when it differs from what the order already is -- and a set field with no resting shape
339 // to compare against cannot be shown to be a restatement, so it is refused rather than assumed
340 // harmless.
341 const auto differs = [](auto stated, auto current) {
342 return stated.has_value() && (!current.has_value() || *stated != *current);
343 };
344
345 if (cancel) {
346 // **A cancellation transmits a quantity and nothing else**, so every other stated field is
347 // one Kiwoom cannot act on. The price and the trigger are refused because acting on them is
348 // what a caller would expect; these three are refused for the same reason and it is not a
349 // lesser one -- reporting acceptance for a stated change that never reached the broker is
350 // the defect, whatever the field.
351 //
352 // `cancel_all()` and `cancel_quantity()` copy the resting order's whole shape into both
353 // `shape_` and `resting_`, so every comparison below sees a restatement and the ordinary
354 // withdrawal path is unaffected.
355 const bool restates_price = instruction.resting_ &&
356 instruction.resting_->price_ == instruction.shape_.price_;
357 if (instruction.shape_.price_ && !restates_price) {
358 error.broker_code_ = "price_on_cancellation";
359 error.message_ =
360 "Kiwoom's cancellation carries a quantity and no price, so it cannot reprice an order on "
361 "the way out; cancel it and place a new one instead";
362 return error;
363 }
364 // The same rule as the price: a restatement of the resting trigger -- which is what
365 // `cancel_all` writes -- is the ordinary withdrawal, and only a stated *change* is refused.
366 const bool restates_trigger = instruction.resting_ &&
367 instruction.resting_->trigger_price_ == instruction.shape_.trigger_price_;
368 if (instruction.shape_.trigger_price_ && !restates_trigger) {
369 error.broker_code_ = "trigger_on_cancellation";
370 error.message_ =
371 "Kiwoom's cancellation carries a quantity and no trigger price, so it cannot move an "
372 "order's stop on the way out; cancel it and place a new one instead";
373 return error;
374 }
375 } else if (!instruction.resting_) {
376 // **A modification with no resting shape is refused, and that is the conservative
377 // direction.** `OrderShape::type_` is a plain value defaulting to `LIMIT`, so this adapter
378 // cannot tell a caller who *means* `LIMIT` from one who left it alone -- and if the resting
379 // order is a best-limit order, accepting the instruction would send a price and leave the
380 // basis where it was, reporting success for a change that did not happen. KIS refuses the
381 // same case for the same reason, as `incomplete_shape`.
382 error.broker_code_ = "incomplete_shape";
383 error.message_ =
384 "Kiwoom's modification cannot change an order's price basis, validity condition or session, "
385 "and without the order's current shape this adapter cannot tell a restatement from a "
386 "change; build the instruction with reprice() or replace_with(), which take it from the "
387 "resting order";
388 return error;
389 }
390
391 const auto resting_condition = instruction.resting_ ?
392 instruction.resting_->time_in_force_ :
393 std::optional<TimeInForce>();
394 const auto resting_session = instruction.resting_ ?
395 instruction.resting_->session_ :
396 std::optional<OrderSession>();
397 if (differs(instruction.shape_.time_in_force_, resting_condition)) {
398 return refuse("validity condition");
399 }
400 if (differs(instruction.shape_.session_, resting_session)) {
401 return refuse("session");
402 }
403 // `OrderShape::type_` is a plain value rather than an optional, so "left alone" and "stated
404 // `LIMIT`" are the same bytes and the comparison has to be made in two steps.
405 if (instruction.resting_) {
406 if (instruction.shape_.type_ != instruction.resting_->type_) {
407 return refuse("price basis");
408 }
409 } else if (instruction.shape_.type_ != OrderShape().type_) {
410 // **With no resting shape, a value that differs from the default is still a stated change.**
411 // Only the default is ambiguous; `MARKET` on a cancellation is a caller saying something, and
412 // `kt10003` transmits no basis, so accepting it would report acceptance for a change the
413 // broker never saw. Compared against `OrderShape`'s own default rather than a literal, so the
414 // two cannot drift apart.
415 return refuse("price basis");
416 }
417 return std::nullopt;
418 }
419
426 static Result<KiwoomAmendment> to_replacement(
427 const Ref& ref,
428 const AmendInstruction& instruction
429 ) {
430 return to_amendment(ref, instruction, false);
431 }
432
439 static Result<KiwoomAmendment> to_cancellation(
440 const Ref& ref,
441 const AmendInstruction& instruction
442 ) {
443 return to_amendment(ref, instruction, true);
444 }
445
456 static Result<KiwoomHistoryQuery> to_history_query(
457 const KiwoomAccount&,
458 const OrderHistoryQuery& query
459 ) {
460 BrokerError error;
462 error.reached_broker_ = false;
463 if (!query.from_) {
464 error.broker_code_ = "date_required";
465 error.message_ = "Kiwoom's order-history inquiry lists one calendar date, which must be given";
466 return Result<KiwoomHistoryQuery>(std::move(error));
467 }
468 if (query.to_ && !(query.to_->year_ == query.from_->year_ &&
469 query.to_->month_ == query.from_->month_ &&
470 query.to_->day_ == query.from_->day_)) {
471 error.broker_code_ = "single_date_only";
472 error.message_ =
473 "Kiwoom's order-history inquiry lists one calendar date; ask for each date separately "
474 "rather than for a range";
475 return Result<KiwoomHistoryQuery>(std::move(error));
476 }
477 if (query.cursor_) {
478 error.broker_code_ = "cursor_unsupported";
479 error.message_ = "Kiwoom order history pages internally and exposes no cursor";
480 return Result<KiwoomHistoryQuery>(std::move(error));
481 }
482 if (query.limit_) {
483 error.broker_code_ = "limit_unsupported";
484 error.message_ = "Kiwoom order history documents no row limit and cannot honor one";
485 return Result<KiwoomHistoryQuery>(std::move(error));
486 }
487 KiwoomHistoryQuery converted;
488 converted.date_ = *query.from_;
489 converted.symbol_ = query.symbol_ ? *query.symbol_ : std::string();
490 return Result<KiwoomHistoryQuery>(std::move(converted));
491 }
492
498 static KiwoomAccount selector_of(const KiwoomAccountInfo&) { return KiwoomAccount{}; }
499
505 static std::string display_of(const KiwoomAccountInfo& account) {
506 return account.account_number_;
507 }
508
513 static std::string type_of(const KiwoomAccountInfo&) { return {}; }
514};
515
517struct Capabilities {
519 static constexpr bool has_account_discovery = true;
520
522 static constexpr bool has_client_order_id = false;
523
528 static constexpr bool has_trigger_price = true;
529
531 static constexpr bool data_only = false;
532
534 static constexpr bool has_working_orders = true;
535
537 static constexpr bool has_amendable_quantity = true;
538
543 static constexpr bool working_orders_state_terminal = false;
544
546 static constexpr bool has_order_by_id = false;
547
549 static constexpr bool has_partial_cancel = true;
550
552 static constexpr bool history_requires_range = false;
553
555 static constexpr bool has_history_cursor = false;
556
558 static constexpr bool has_history_limit = false;
559
561 static constexpr bool has_history_symbol_filter = true;
562};
563
564} // namespace traits_detail
565} // namespace kiwoom
566
573inline constexpr Venue kiwoom_route(Venue asked) noexcept { return kiwoom::kiwoom_effective_route(asked); }
574
576template <>
577struct BrokerTraits<kiwoom::KiwoomClient>
578: kiwoom::traits_detail::Normalizers, kiwoom::traits_detail::Capabilities {
584 static constexpr Venue effective_route(Venue asked) noexcept { return kiwoom_route(asked); }
585
588
591
594
597
600
603
606
609
612
614 static constexpr std::string_view name = kiwoom::Broker::name;
615
617 static constexpr bool blocking = false;
618
624 static const network::RateLimitStats* rate_limit_stats(const Client& client) {
625 return client.rate_limit_stats();
626 }
627
636 template <typename Token>
637 static auto quote(Client& client, InstrumentId instrument, Token&& token) {
638 return client.async_quote(std::move(instrument), std::forward<Token>(token));
639 }
640
649 template <typename Token>
650 static auto price_limits(Client& client, InstrumentId instrument, Token&& token) {
651 return client.async_price_limits(std::move(instrument), std::forward<Token>(token));
652 }
653
663 template <typename Token>
664 static auto trades(Client& client, InstrumentId instrument, int count, Token&& token) {
665 return client.async_trades(std::move(instrument), count, std::forward<Token>(token));
666 }
667
676 template <typename Token>
677 static auto depth(Client& client, InstrumentId instrument, Token&& token) {
678 return client.async_depth(std::move(instrument), std::forward<Token>(token));
679 }
680
689 template <typename Token>
690 static auto bars(Client& client, BarQuery query, Token&& token) {
691 return client.async_bars(std::move(query), std::forward<Token>(token));
692 }
693
702 template <typename Token>
703 static auto instrument(Client& client, InstrumentId subject, Token&& token) {
704 return client.async_instrument(std::move(subject), std::forward<Token>(token));
705 }
706
714 template <typename Token>
715 static auto accounts(Client& client, Token&& token) {
716 return client.async_accounts(std::forward<Token>(token));
717 }
718
728 template <typename Token>
729 static auto buying_power(
730 Client& client,
731 const Account& account,
732 Currency currency,
733 Token&& token
734 ) {
735 return client.async_buying_power(currency, account, std::forward<Token>(token));
736 }
737
750 template <typename Token>
751 static auto holdings(Client& client, const Account& account, Token&& token) {
753 static_cast<void>(account);
754 return net::async_initiate<Token, void(Result<HoldingsSnapshot>)>(
755 [strand = client.get_executor()](auto&& handler) mutable {
756 auto work = net::prefer(
757 net::get_associated_executor(handler), net::execution::outstanding_work.tracked
758 );
759 net::post(
760 strand,
761 [handler = std::forward<decltype(handler)>(handler), work = std::move(work)]() mutable {
762 net::dispatch(work, [handler = std::move(handler)]() mutable {
763 std::move(handler)(refuse_holdings());
764 });
765 }
766 );
767 },
768 token
769 );
770 }
771 return client.async_holdings(account, std::forward<Token>(token));
772 }
773
783 template <typename Token>
784 static auto place_order(
785 Client& client,
786 const Account& account,
787 OrderRequest order,
788 Token&& token
789 ) {
790 return client.async_place_order(account, std::move(order), std::forward<Token>(token));
791 }
792
802 template <typename Token>
803 static auto replace_order(
804 Client& client,
805 const Account& account,
806 Amendment amendment,
807 Token&& token
808 ) {
809 return client.async_replace_order(account, std::move(amendment), std::forward<Token>(token));
810 }
811
821 template <typename Token>
822 static auto cancel_order(
823 Client& client,
824 const Account& account,
825 Amendment amendment,
826 Token&& token
827 ) {
828 return client.async_cancel_order(account, std::move(amendment), std::forward<Token>(token));
829 }
830
839 template <typename Token>
840 static auto working_orders(Client& client, const Account& account, Token&& token) {
841 return client.async_open_orders(account, std::forward<Token>(token));
842 }
843
853 template <typename Token>
854 static auto order_history(
855 Client& client,
856 const Account& account,
857 HistoryQuery query,
858 Token&& token
859 ) {
860 return client.async_order_history(account, std::move(query), std::forward<Token>(token));
861 }
862};
863
865template <>
866struct BrokerTraits<kiwoom::KiwoomBlockingClient>
867: kiwoom::traits_detail::Normalizers, kiwoom::traits_detail::Capabilities {
873 static constexpr Venue effective_route(Venue asked) noexcept { return kiwoom_route(asked); }
874
877
880
883
886
889
892
895
898
901
903 static constexpr std::string_view name = kiwoom::Broker::name;
904
906 static constexpr bool blocking = true;
907
913 static const network::RateLimitStats* rate_limit_stats(const Client& client) {
914 return client.rate_limit_stats();
915 }
916
924 return client.quote(std::move(instrument));
925 }
926
934 return client.price_limits(std::move(instrument));
935 }
936
945 Client& client,
947 int count
948 ) {
949 return client.trades(std::move(instrument), count);
950 }
951
959 return client.depth(std::move(instrument));
960 }
961
968 static Result<BarSeries> bars(Client& client, BarQuery query) {
969 return client.bars(std::move(query));
970 }
971
979 return client.instrument(std::move(subject));
980 }
981
988 return client.accounts();
989 }
990
997 static Result<HoldingsSnapshot> holdings(Client& client, const Account& account) {
999 static_cast<void>(account);
1000 return refuse_holdings();
1001 }
1002 return client.holdings(account);
1003 }
1004
1013 Client& client,
1014 const Account& account,
1015 Currency currency
1016 ) {
1017 return client.buying_power(currency, account);
1018 }
1019
1027 static Result<PlaceAck> place_order(Client& client, const Account& account, OrderRequest order) {
1028 return client.place_order(account, std::move(order));
1029 }
1030
1039 Client& client,
1040 const Account& account,
1041 Amendment amendment
1042 ) {
1043 return client.replace_order(account, std::move(amendment));
1044 }
1045
1054 Client& client,
1055 const Account& account,
1056 Amendment amendment
1057 ) {
1058 return client.cancel_order(account, std::move(amendment));
1059 }
1060
1068 return client.open_orders(account);
1069 }
1070
1079 Client& client,
1080 const Account& account,
1081 HistoryQuery query
1082 ) {
1083 return client.order_history(account, std::move(query));
1084 }
1085};
1086
1087} // namespace algotradelib
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:234
Decimal64()=default
Constructs zero.
Either a value or a BrokerError.
Definition types.hpp:797
Result(T value)
Constructs a successful result.
Definition types.hpp:803
BrokerError & error()
Returns the error.
Definition types.hpp:842
T & value()
Returns the value.
Definition types.hpp:828
A blocking Kiwoom client: each call runs a KiwoomClient request on a private event loop and returns i...
Definition client.hpp:3795
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns today's upper and lower price bound.
Definition client.hpp:3829
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns recent executions, newest first.
Definition client.hpp:3854
const KiwoomConfig & config() const noexcept
Returns the configuration; see KiwoomClient::config.
Definition client.hpp:3889
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:4046
Result< BuyingPower > buying_power(Currency currency, KiwoomAccount account)
Returns what the bound credential's account may spend.
Definition client.hpp:3909
Result< KiwoomOrderAck > replace_order(KiwoomAccount account, KiwoomAmendment amendment)
Modifies an existing order. The outcome can be unknown after an error; see KiwoomClient::async_replac...
Definition client.hpp:3983
Result< OrderPage > order_history(KiwoomAccount account, KiwoomHistoryQuery query)
Returns one day of order history.
Definition client.hpp:4026
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns the resting orders on both sides of the book.
Definition client.hpp:3841
Result< KiwoomOrderAck > cancel_order(KiwoomAccount account, KiwoomAmendment amendment)
Cancels an existing order. The outcome can be unknown after an error; see KiwoomClient::async_cancel_...
Definition client.hpp:3999
Result< BarSeries > bars(BarQuery query)
Returns bars; see KiwoomClient::async_bars.
Definition client.hpp:3878
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the current normalized quote or a structured error.
Definition client.hpp:3817
Result< std::vector< KiwoomAccountInfo > > accounts()
Returns the one account the bound credential drives.
Definition client.hpp:3953
Result< KiwoomOpenOrderPage > open_orders(KiwoomAccount account)
Returns every order still open to amendment.
Definition client.hpp:4013
Result< KiwoomOrderAck > place_order(KiwoomAccount account, OrderRequest order)
Submits a new order. The outcome can be unknown after an error; see KiwoomClient::async_place_order.
Definition client.hpp:3967
Result< Instrument > instrument(InstrumentId subject)
Returns static reference data for one instrument.
Definition client.hpp:3866
Result< HoldingsSnapshot > holdings(KiwoomAccount account)
Returns the holdings for KiwoomConfig::holdings_venue_; see KiwoomClient::async_holdings.
Definition client.hpp:3896
The asynchronous Kiwoom REST client: market data, account inquiries and orders for domestic stocks.
Definition client.hpp:885
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests static reference data for one instrument, from ka10100 종목정보 조회.
Definition client.hpp:1049
auto async_buying_power(Currency currency, KiwoomAccount account, CompletionToken &&token)
Requests what the account may spend, from kt00001 예수금상세현황요청.
Definition client.hpp:1145
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests the resting orders on both sides of the book, from ka10004 주식호가요청.
Definition client.hpp:998
auto async_open_orders(KiwoomAccount account, CompletionToken &&token)
Requests every order still open to amendment, paging ka10075 미체결요청.
Definition client.hpp:1375
auto async_order_history(KiwoomAccount account, KiwoomHistoryQuery query, CompletionToken &&token)
Requests one day of order history, paging kt00007 계좌별주문체결내역상세요청.
Definition client.hpp:1399
auto async_cancel_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Cancels an order, all or part of it (kt10003).
Definition client.hpp:1347
auto async_replace_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Amends an order's quantity, price or trigger price (kt10002).
Definition client.hpp:1305
const KiwoomConfig & config() const noexcept
Returns the configuration (the session reads its holdings assertions from it).
Definition client.hpp:1099
auto async_bars(BarQuery query, CompletionToken &&token)
Requests bars, following Kiwoom's continuation pages from before_'s Korean date (or today).
Definition client.hpp:1080
auto async_place_order(KiwoomAccount account, OrderRequest order, CompletionToken &&token)
Places an order (kt10000 buy, kt10001 sell).
Definition client.hpp:1274
net::strand< net::any_io_executor > get_executor() const noexcept
Returns the client's strand.
Definition client.hpp:1105
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests today's upper and lower price bound, from the same ka10007 response.
Definition client.hpp:972
auto async_accounts(CompletionToken &&token)
Requests the one account the bound credential drives, from ka00001 계좌번호조회.
Definition client.hpp:1228
auto async_holdings(KiwoomAccount account, CompletionToken &&token)
Requests the holdings kt00018 lists for KiwoomConfig::holdings_venue_ (refused before sending until i...
Definition client.hpp:1121
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:1427
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests recent executions, newest first, from ka10003 체결정보요청.
Definition client.hpp:1025
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests and normalizes a current quote, from ka10007 시세표성정보요청.
Definition client.hpp:946
Placeholder types and the refusal used by DataOnlyTraits.
The Kiwoom Securities REST API client.
Definition auth.hpp:12
std::optional< BrokerError > unsupported_bar_interval(BarInterval interval)
Refuses a bar interval this client requests no chart for (chart_api_id).
Definition client.hpp:797
constexpr const char * chart_rows_field(BarInterval interval) noexcept
Returns the array field a bar interval's chart endpoint returns its rows in.
Definition client.hpp:771
std::optional< BrokerError > invalid_trigger(OrderType type, const std::optional< Decimal64 > &trigger)
Checks that a trigger price is present exactly when the order type takes one (only STOP_LIMIT,...
Definition client.hpp:241
std::optional< BrokerError > unsupported_client_order_id(const OrderRequest &order)
Refuses an idempotency key, which Kiwoom does not offer (an order carrying client_order_id_ is refuse...
Definition client.hpp:208
constexpr bool kiwoom_position_scope_asserted(KiwoomPositionScope scope) noexcept
Tests whether a holdings scope states what Kiwoom's holdings figure covers, so holdings may be read a...
Definition config.hpp:124
constexpr const char * chart_api_id(BarInterval interval) noexcept
Returns the api-id of the chart endpoint for a bar interval.
Definition client.hpp:745
constexpr Venue kiwoom_effective_route(Venue asked) noexcept
Returns the venue a Kiwoom order reaches: the one it names (Kiwoom requires one, so an order naming n...
Definition client.hpp:663
The library: broker-neutral types (core), and the modules below.
SellableSource
Where the library gets a broker's sellable quantity.
Definition types.hpp:1092
@ NONE
No per-instrument inquiry: any figure comes on the holdings rows (Kiwoom), or there is none.
Definition types.hpp:1098
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:713
Country
A country (market) the library supports.
Definition types.hpp:30
constexpr Venue kiwoom_route(Venue asked) noexcept
Returns the venue a Kiwoom order reaches: the one it names. Kiwoom has no default venue,...
Definition traits.hpp:573
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:43
BarInterval
The period one bar covers.
std::optional< Decimal64 > amended_trigger_price(const AmendInstruction &instruction)
Returns the trigger price an amendment leaves the order with.
Definition types.hpp:2271
A modification or cancellation of a working order.
Definition types.hpp:2240
Venue venue_
The venue the order rests at, for a broker whose amendment needs it (KIS).
Definition types.hpp:2248
std::optional< OrderShape > resting_
The shape the order has now, or unset if unknown.
Definition types.hpp:2261
std::optional< Decimal64 > quantity_
The quantity affected; never substituted if a broker needs one and it is missing.
Definition types.hpp:2250
OrderShape shape_
The shape the order should have afterwards.
Definition types.hpp:2242
bool all_remaining_
Whether the whole remaining quantity is affected, rather than quantity_.
Definition types.hpp:2252
What bars to fetch.
BarInterval interval_
The period of each bar; an interval the broker does not publish is refused.
The error a broker or transport operation returns.
Definition types.hpp:742
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:772
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:744
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:761
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:753
static Result< Instrument > instrument(Client &client, InstrumentId subject)
Returns static reference data for one instrument.
Definition traits.hpp:978
kiwoom::KiwoomAccount Account
Kiwoom account selector, which carries nothing because Kiwoom takes nothing.
Definition traits.hpp:882
static Result< OrderPage > order_history(Client &client, const Account &account, HistoryQuery query)
Returns order history for the bound account.
Definition traits.hpp:1078
static Result< HoldingsSnapshot > holdings(Client &client, const Account &account)
Serves the normalized holdings verb once a scope is asserted; see the asynchronous thunk.
Definition traits.hpp:997
kiwoom::KiwoomBlockingClient Client
The client type.
Definition traits.hpp:876
static constexpr bool blocking
true: requests return their result directly.
Definition traits.hpp:906
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:903
static Result< BuyingPower > buying_power(Client &client, const Account &account, Currency currency)
Returns what the bound account may spend in currency.
Definition traits.hpp:1012
kiwoom::KiwoomOpenOrderPage WorkingOrdersResult
Kiwoom amendable-order result.
Definition traits.hpp:900
static Result< QuoteSnapshot > quote(Client &client, InstrumentId instrument)
Returns a quote.
Definition traits.hpp:923
kiwoom::KiwoomAccountInfo AccountListItem
Item type of the broker's own account listing.
Definition traits.hpp:885
kiwoom::KiwoomHistoryQuery HistoryQuery
Kiwoom order-history selector.
Definition traits.hpp:897
static Result< BarSeries > bars(Client &client, BarQuery query)
Returns bars, paging inside the client.
Definition traits.hpp:968
static Result< DepthSnapshot > depth(Client &client, InstrumentId instrument)
Returns the order book.
Definition traits.hpp:958
kiwoom::KiwoomOrderAck PlaceAck
Acknowledgement Kiwoom returns for an order instruction.
Definition traits.hpp:891
static Result< PlaceAck > place_order(Client &client, const Account &account, OrderRequest order)
Submits an order for the bound account.
Definition traits.hpp:1027
static Result< std::vector< TradePrint > > trades(Client &client, InstrumentId instrument, int count)
Returns recent executions.
Definition traits.hpp:944
kiwoom::KiwoomConfig Config
Kiwoom application credentials and environment selection.
Definition traits.hpp:879
static const network::RateLimitStats * rate_limit_stats(const Client &client)
Returns the rate limiter's statistics.
Definition traits.hpp:913
static Result< PlaceAck > replace_order(Client &client, const Account &account, Amendment amendment)
Modifies an order for the bound account.
Definition traits.hpp:1038
static Result< WorkingOrdersResult > working_orders(Client &client, const Account &account)
Returns the amendable orders for the bound account.
Definition traits.hpp:1067
kiwoom::KiwoomAmendment Amendment
Kiwoom modification and cancellation instruction.
Definition traits.hpp:894
static Result< PlaceAck > cancel_order(Client &client, const Account &account, Amendment amendment)
Cancels an order for the bound account.
Definition traits.hpp:1053
static Result< std::vector< AccountListItem > > accounts(Client &client)
Returns the one account the bound credential drives.
Definition traits.hpp:987
static constexpr Venue effective_route(Venue asked) noexcept
Returns the venue an order reaches; see kiwoom_route.
Definition traits.hpp:873
static Result< PriceLimits > price_limits(Client &client, InstrumentId instrument)
Returns today's price bounds.
Definition traits.hpp:933
static auto buying_power(Client &client, const Account &account, Currency currency, Token &&token)
Forwards a buying-power request for the bound account.
Definition traits.hpp:729
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:614
static auto bars(Client &client, BarQuery query, Token &&token)
Forwards a bar request.
Definition traits.hpp:690
static auto quote(Client &client, InstrumentId instrument, Token &&token)
Forwards a quote request.
Definition traits.hpp:637
static auto holdings(Client &client, const Account &account, Token &&token)
Forwards a holdings request, or completes it with refuse_holdings() (sending nothing) while KiwoomCon...
Definition traits.hpp:751
static constexpr bool blocking
false: requests complete through a completion token.
Definition traits.hpp:617
static auto price_limits(Client &client, InstrumentId instrument, Token &&token)
Forwards a price-bound request.
Definition traits.hpp:650
static auto trades(Client &client, InstrumentId instrument, int count, Token &&token)
Forwards a recent-execution request.
Definition traits.hpp:664
static auto order_history(Client &client, const Account &account, HistoryQuery query, Token &&token)
Forwards an order-history inquiry for the bound account.
Definition traits.hpp:854
static auto place_order(Client &client, const Account &account, OrderRequest order, Token &&token)
Forwards an order submission for the bound account.
Definition traits.hpp:784
kiwoom::Broker BrokerTag
The broker tag.
Definition traits.hpp:599
static auto accounts(Client &client, Token &&token)
Forwards an account listing request.
Definition traits.hpp:715
kiwoom::KiwoomConfig Config
Kiwoom application credentials and environment selection.
Definition traits.hpp:590
kiwoom::KiwoomOpenOrderPage WorkingOrdersResult
Kiwoom amendable-order result.
Definition traits.hpp:611
static auto depth(Client &client, InstrumentId instrument, Token &&token)
Forwards an order book request.
Definition traits.hpp:677
kiwoom::KiwoomAccount Account
Kiwoom account selector, which carries nothing because Kiwoom takes nothing.
Definition traits.hpp:593
static auto working_orders(Client &client, const Account &account, Token &&token)
Forwards an amendable-order inquiry for the bound account.
Definition traits.hpp:840
static const network::RateLimitStats * rate_limit_stats(const Client &client)
Returns the rate limiter's statistics.
Definition traits.hpp:624
kiwoom::KiwoomOrderAck PlaceAck
Acknowledgement Kiwoom returns for an order instruction.
Definition traits.hpp:602
kiwoom::KiwoomHistoryQuery HistoryQuery
Kiwoom order-history selector.
Definition traits.hpp:608
static auto replace_order(Client &client, const Account &account, Amendment amendment, Token &&token)
Forwards an order modification for the bound account.
Definition traits.hpp:803
static auto cancel_order(Client &client, const Account &account, Amendment amendment, Token &&token)
Forwards an order cancellation for the bound account.
Definition traits.hpp:822
static auto instrument(Client &client, InstrumentId subject, Token &&token)
Forwards a reference-data request.
Definition traits.hpp:703
kiwoom::KiwoomClient Client
The client type.
Definition traits.hpp:587
static constexpr Venue effective_route(Venue asked) noexcept
Returns the venue an order reaches; see kiwoom_route.
Definition traits.hpp:584
kiwoom::KiwoomAmendment Amendment
Kiwoom modification and cancellation instruction.
Definition traits.hpp:605
kiwoom::KiwoomAccountInfo AccountListItem
Item type of the broker's own account listing.
Definition traits.hpp:596
Describes one broker client to the library: its types, capabilities, call thunks and normalizers.
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:78
The filter for an order-history inquiry.
Definition types.hpp:2325
std::optional< std::string > symbol_
Only this symbol, where the broker supports the filter.
Definition types.hpp:2331
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2335
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
Definition types.hpp:2333
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
Definition types.hpp:2327
std::optional< Date > to_
The last date to include.
Definition types.hpp:2329
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2111
std::string primary_
The order number or id.
Definition types.hpp:2113
An order to place, in broker-neutral form.
Definition types.hpp:1925
An order's type, price, trigger, time in force and session, as an amendment states them.
Definition types.hpp:2179
std::optional< TimeInForce > time_in_force_
The time in force; unset means "keep the resting order's".
Definition types.hpp:2223
std::optional< Decimal64 > price_
The price, for a basis that takes one.
Definition types.hpp:2207
std::optional< OrderSession > session_
The session; unset means "keep the resting order's".
Definition types.hpp:2230
std::optional< Decimal64 > trigger_price_
The trigger price, for STOP_LIMIT.
Definition types.hpp:2216
OrderType type_
The price basis.
Definition types.hpp:2205
An accepted order: the acknowledgement and the reference to address it with.
Definition types.hpp:2165
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2169
OrderAck ack_
The acknowledgement.
Definition types.hpp:2167
An order still open to modification or cancellation.
Definition types.hpp:2290
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2294
std::optional< Decimal64 > amendable_quantity_
How much the broker says may still be amended. Empty means it stated none, not zero.
Definition types.hpp:2296
OrderSnapshot order_
The order's state.
Definition types.hpp:2292
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2312
std::vector< WorkingOrder< Broker > > orders_
The open orders.
Definition types.hpp:2314
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
Definition types.hpp:2316
The Kiwoom broker tag: order references are typed by it, so a Kiwoom reference works with both Kiwoom...
Definition traits.hpp:33
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:35
One account Kiwoom's ka00001 reports for the bound credential.
Definition client.hpp:45
std::string account_number_
The account number as Kiwoom reported it, for display.
Definition client.hpp:47
The Kiwoom account selector, which is empty: no Kiwoom endpoint takes an account number,...
Definition client.hpp:35
An amendment or cancellation of a Kiwoom order.
Definition client.hpp:70
Venue venue_
The venue the order rests on, as listed (Kiwoom's dmst_stex_tp): KRX, NXT or COMBINED (SOR)....
Definition client.hpp:77
KiwoomOrderRef order_
The order to amend, which carries the symbol Kiwoom requires beside the order number.
Definition client.hpp:72
Decimal64 quantity_
The quantity affected, or zero for everything still resting (Kiwoom evaluates 0 when it processes the...
Definition client.hpp:82
std::optional< Decimal64 > price_
The new price, on a modification; absent on an unpriced basis, and refused on a cancellation.
Definition client.hpp:84
std::optional< Decimal64 > condition_price_
The new trigger price (mdfy_cond_uv), for amending a stop-limit (28) order; must be empty on a cancel...
Definition client.hpp:89
Kiwoom credentials (app key and secret key), demo or real account, the market-data tape,...
Definition config.hpp:154
KiwoomPositionScope holdings_position_scope_
Your assertion of what holdings_venue_ means for the positions listed. No default: until it is set,...
Definition config.hpp:193
A Kiwoom order-history query: one date (kt00007 takes no range, so a multi-day query is refused).
Definition client.hpp:143
Date date_
The single 주문일자 to list.
Definition client.hpp:145
std::string symbol_
Restrict to one symbol, which Kiwoom expresses as stk_cd. Empty lists every symbol.
Definition client.hpp:147
One page of Kiwoom orders that remain modifiable or cancellable.
Definition client.hpp:132
Kiwoom's acknowledgement of an accepted order, amendment or cancellation.
Definition client.hpp:98
A Kiwoom order's address: order number and symbol, both of which amendments and cancellations require...
Definition client.hpp:56
std::string order_number_
Kiwoom's ord_no.
Definition client.hpp:58
std::string symbol_
Kiwoom's stk_cd, which its amendment endpoints require beside the order number.
Definition client.hpp:60
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...