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
48struct Normalizers {
50 static constexpr bool has_depth = true;
51
53 static constexpr bool has_price_limits = true;
54
56 static constexpr bool has_trade_prints = true;
57
62 static constexpr bool has_batch_prices = false;
63
65 static constexpr bool has_buying_power = true;
66
71 static constexpr bool has_buying_power_quantity = true;
72
77 static constexpr SellableSource sellable_source = SellableSource::NONE;
78
83 static constexpr bool has_commission_schedule = false;
84
86 static constexpr bool has_reference_data = true;
87
89 static constexpr bool has_batch_reference_data = false;
90
95 static constexpr bool has_calendar = false;
96
98 static constexpr bool has_calendar_range = false;
99
101 static constexpr bool has_calendar_sessions = false;
102
109 static std::optional<BrokerError> validate_calendar(Country country, std::optional<Date> from) {
110 static_cast<void>(country);
111 static_cast<void>(from);
112 BrokerError error;
114 error.reached_broker_ = false;
115 error.broker_code_ = "calendar_unsupported";
116 error.message_ = "Kiwoom publishes no trading calendar";
117 return error;
118 }
119
126 static constexpr bool supports_interval(BarInterval interval) {
127 return kiwoom::chart_api_id(interval) != nullptr && kiwoom::chart_rows_field(interval) != nullptr;
128 }
129
135 static std::optional<BrokerError> validate_bars(const BarQuery& query) {
137 }
138
150 static Result<HoldingsSnapshot> refuse_holdings() {
151 BrokerError error;
153 error.reached_broker_ = false;
154 error.broker_code_ = "holdings_scope_unestablished";
155 error.message_ =
156 "Kiwoom's balance inquiry names one venue (kt00018 dmst_stex_tp: KRX or NXT) and publishes no "
157 "all-venue value, and whether that filters the positions or only values them is not stated. "
158 "This library will not present one venue's answer as the account's holdings unless you say "
159 "that is what it is: set KiwoomConfig::holdings_position_scope_ to "
160 "KiwoomPositionScope::VALUATION_ONLY to assert it, and "
161 "KiwoomConfig::holdings_sellable_scope_ separately for trde_able_qty. Until then read the rows "
162 "through session.client().holdings(). Both assertions are unverified; see KiwoomConfig's "
163 "documentation";
164 return Result<HoldingsSnapshot>(std::move(error));
165 }
166
173 static Ref make_ref(const KiwoomOrderRef& order) {
174 Ref ref;
175 ref.primary_ = order.order_number_;
176 ref.secondary_ = order.symbol_;
177 return ref;
178 }
179
185 static KiwoomOrderRef from_ref(const Ref& ref) {
186 KiwoomOrderRef order;
187 order.order_number_ = ref.primary_;
188 order.symbol_ = ref.secondary_;
189 return order;
190 }
191
198 static std::optional<BrokerError> validate_place(const OrderRequest& order) {
199 // **The holdings refusal is deliberately not repeated here**, although this is the port's
200 // pre-flight. It lives in `KiwoomClient::validate_order`, which every placement reaches --
201 // including this port's, because `place` calls the client immediately after this returns and
202 // the client refuses before any I/O. Checking it here as well would only change *which* message
203 // a caller gets: this function does not validate the order's venue, price or shape, so it would
204 // report the holdings gap for an order that is also malformed, burying the mistake the caller
205 // can actually fix. See `kiwoom::unestablished_holdings_scope`.
207 }
208
215 if (!raw) {
216 return Result<PlacedOrder<kiwoom::Broker>>(std::move(raw.error()));
217 }
219 placed.ack_ = std::move(raw.value().ack_);
220 placed.ref_ = make_ref(raw.value().order_);
221 return Result<PlacedOrder<kiwoom::Broker>>(std::move(placed));
222 }
223
233 static Result<WorkingOrders<kiwoom::Broker>> normalize_working_orders(Result<KiwoomOpenOrderPage> raw) {
234 if (!raw) {
235 return Result<WorkingOrders<kiwoom::Broker>>(std::move(raw.error()));
236 }
238 orders.received_at_ = raw.value().received_at_;
239 orders.orders_.reserve(raw.value().orders_.size());
240 for (auto& open_order : raw.value().orders_) {
242 working.order_ = std::move(open_order.order_);
243 working.ref_ = make_ref(open_order.order_ref_);
244 working.amendable_quantity_ = open_order.amendable_quantity_;
245 orders.orders_.push_back(std::move(working));
246 }
247 return Result<WorkingOrders<kiwoom::Broker>>(std::move(orders));
248 }
249
265 static Result<KiwoomAmendment> to_amendment(const Ref& ref, const AmendInstruction& instruction, bool cancel) {
266 BrokerError error;
268 error.reached_broker_ = false;
269
270 if (!instruction.all_remaining_ && !instruction.quantity_) {
271 error.broker_code_ = "quantity_required";
272 error.message_ =
273 "a Kiwoom modification or cancellation affects a stated quantity; set all_remaining_ to "
274 "act on everything still resting, or build the instruction with cancel_all()";
275 return Result<KiwoomAmendment>(std::move(error));
276 }
277 if (auto refusal = refuse_shape_change(instruction, cancel)) {
278 return Result<KiwoomAmendment>(std::move(*refusal));
279 }
280
281 KiwoomAmendment amendment;
282 amendment.order_ = from_ref(ref);
283 amendment.venue_ = instruction.venue_;
284 // Kiwoom's own "everything still resting", which it evaluates when it processes the
285 // instruction rather than when the caller read the listing.
286 amendment.quantity_ = instruction.all_remaining_ ? Decimal64() : *instruction.quantity_;
287 if (!cancel) {
288 // The basis is known here and nowhere after: `kt10002` carries no `trde_tp`, so this is the
289 // last point that can tell a trigger the order wants from one it would silently lose.
290 const auto trigger = amended_trigger_price(instruction);
291 if (auto invalid = kiwoom::invalid_trigger(instruction.shape_.type_, trigger)) {
292 return Result<KiwoomAmendment>(std::move(*invalid));
293 }
294 amendment.price_ = instruction.shape_.price_;
295 amendment.condition_price_ = trigger;
296 }
297 // **Never on a cancellation.** `kt10003` has no trigger field and the client refuses a
298 // cancellation carrying one; `cancel_all` restates the resting trigger, so copying it here would
299 // make every stop order impossible to withdraw through the port.
300 return Result<KiwoomAmendment>(std::move(amendment));
301 }
302
315 static std::optional<BrokerError> refuse_shape_change(const AmendInstruction& instruction, bool cancel) {
316 BrokerError error;
318 error.reached_broker_ = false;
319 error.broker_code_ = "shape_change_unsupported";
320
321 const auto refuse = [&error, cancel](const char* what) {
322 error.message_ = cancel ?
323 std::string(
324 "Kiwoom's cancellation carries a quantity and nothing else, so it cannot "
325 "change an order's "
326 ) +
327 what + " on the way out" :
328 std::string(
329 "Kiwoom's amendment endpoints carry a quantity and a price only, so they "
330 "cannot change an order's "
331 ) +
332 what + "; cancel the order and place a new one instead";
333 return error;
334 };
335
336 // An unset field means "leave it as it is", so it is never a change. A set field is a change
337 // only when it differs from what the order already is -- and a set field with no resting shape
338 // to compare against cannot be shown to be a restatement, so it is refused rather than assumed
339 // harmless.
340 const auto differs = [](auto stated, auto current) {
341 return stated.has_value() && (!current.has_value() || *stated != *current);
342 };
343
344 if (cancel) {
345 // **A cancellation transmits a quantity and nothing else**, so every other stated field is
346 // one Kiwoom cannot act on. The price and the trigger are refused because acting on them is
347 // what a caller would expect; these three are refused for the same reason and it is not a
348 // lesser one -- reporting acceptance for a stated change that never reached the broker is
349 // the defect, whatever the field.
350 //
351 // `cancel_all()` and `cancel_quantity()` copy the resting order's whole shape into both
352 // `shape_` and `resting_`, so every comparison below sees a restatement and the ordinary
353 // withdrawal path is unaffected.
354 const bool restates_price = instruction.resting_ && instruction.resting_->price_ == instruction.shape_.price_;
355 if (instruction.shape_.price_ && !restates_price) {
356 error.broker_code_ = "price_on_cancellation";
357 error.message_ =
358 "Kiwoom's cancellation carries a quantity and no price, so it cannot reprice an order on "
359 "the way out; cancel it and place a new one instead";
360 return error;
361 }
362 // The same rule as the price: a restatement of the resting trigger -- which is what
363 // `cancel_all` writes -- is the ordinary withdrawal, and only a stated *change* is refused.
364 const bool restates_trigger =
365 instruction.resting_ && instruction.resting_->trigger_price_ == instruction.shape_.trigger_price_;
366 if (instruction.shape_.trigger_price_ && !restates_trigger) {
367 error.broker_code_ = "trigger_on_cancellation";
368 error.message_ =
369 "Kiwoom's cancellation carries a quantity and no trigger price, so it cannot move an "
370 "order's stop on the way out; cancel it and place a new one instead";
371 return error;
372 }
373 } else if (!instruction.resting_) {
374 // **A modification with no resting shape is refused, and that is the conservative
375 // direction.** `OrderShape::type_` is a plain value defaulting to `LIMIT`, so this adapter
376 // cannot tell a caller who *means* `LIMIT` from one who left it alone -- and if the resting
377 // order is a best-limit order, accepting the instruction would send a price and leave the
378 // basis where it was, reporting success for a change that did not happen. KIS refuses the
379 // same case for the same reason, as `incomplete_shape`.
380 error.broker_code_ = "incomplete_shape";
381 error.message_ =
382 "Kiwoom's modification cannot change an order's price basis, validity condition or session, "
383 "and without the order's current shape this adapter cannot tell a restatement from a "
384 "change; build the instruction with reprice() or replace_with(), which take it from the "
385 "resting order";
386 return error;
387 }
388
389 const auto resting_condition =
390 instruction.resting_ ? instruction.resting_->time_in_force_ : std::optional<TimeInForce>();
391 const auto resting_session = instruction.resting_ ? instruction.resting_->session_ : std::optional<OrderSession>();
392 if (differs(instruction.shape_.time_in_force_, resting_condition)) {
393 return refuse("validity condition");
394 }
395 if (differs(instruction.shape_.session_, resting_session)) {
396 return refuse("session");
397 }
398 // `OrderShape::type_` is a plain value rather than an optional, so "left alone" and "stated
399 // `LIMIT`" are the same bytes and the comparison has to be made in two steps.
400 if (instruction.resting_) {
401 if (instruction.shape_.type_ != instruction.resting_->type_) {
402 return refuse("price basis");
403 }
404 } else if (instruction.shape_.type_ != OrderShape().type_) {
405 // **With no resting shape, a value that differs from the default is still a stated change.**
406 // Only the default is ambiguous; `MARKET` on a cancellation is a caller saying something, and
407 // `kt10003` transmits no basis, so accepting it would report acceptance for a change the
408 // broker never saw. Compared against `OrderShape`'s own default rather than a literal, so the
409 // two cannot drift apart.
410 return refuse("price basis");
411 }
412 return std::nullopt;
413 }
414
421 static Result<KiwoomAmendment> to_replacement(const Ref& ref, const AmendInstruction& instruction) {
422 return to_amendment(ref, instruction, false);
423 }
424
431 static Result<KiwoomAmendment> to_cancellation(const Ref& ref, const AmendInstruction& instruction) {
432 return to_amendment(ref, instruction, true);
433 }
434
445 static Result<KiwoomHistoryQuery> to_history_query(const KiwoomAccount&, const OrderHistoryQuery& query) {
446 BrokerError error;
448 error.reached_broker_ = false;
449 if (!query.from_) {
450 error.broker_code_ = "date_required";
451 error.message_ = "Kiwoom's order-history inquiry lists one calendar date, which must be given";
452 return Result<KiwoomHistoryQuery>(std::move(error));
453 }
454 if (
455 query.to_ &&
456 !(query.to_->year_ == query.from_->year_ && query.to_->month_ == query.from_->month_ &&
457 query.to_->day_ == query.from_->day_)
458 ) {
459 error.broker_code_ = "single_date_only";
460 error.message_ =
461 "Kiwoom's order-history inquiry lists one calendar date; ask for each date separately "
462 "rather than for a range";
463 return Result<KiwoomHistoryQuery>(std::move(error));
464 }
465 if (query.cursor_) {
466 error.broker_code_ = "cursor_unsupported";
467 error.message_ = "Kiwoom order history pages internally and exposes no cursor";
468 return Result<KiwoomHistoryQuery>(std::move(error));
469 }
470 if (query.limit_) {
471 error.broker_code_ = "limit_unsupported";
472 error.message_ = "Kiwoom order history documents no row limit and cannot honor one";
473 return Result<KiwoomHistoryQuery>(std::move(error));
474 }
475 KiwoomHistoryQuery converted;
476 converted.date_ = *query.from_;
477 converted.symbol_ = query.symbol_ ? *query.symbol_ : std::string();
478 return Result<KiwoomHistoryQuery>(std::move(converted));
479 }
480
486 static KiwoomAccount selector_of(const KiwoomAccountInfo&) {
487 return KiwoomAccount{};
488 }
489
495 static std::string display_of(const KiwoomAccountInfo& account) {
496 return account.account_number_;
497 }
498
503 static std::string type_of(const KiwoomAccountInfo&) {
504 return {};
505 }
506};
507
509struct Capabilities {
511 static constexpr bool has_account_discovery = true;
512
514 static constexpr bool has_client_order_id = false;
515
520 static constexpr bool has_trigger_price = true;
521
523 static constexpr bool data_only = false;
524
526 static constexpr bool has_working_orders = true;
527
529 static constexpr bool has_amendable_quantity = true;
530
535 static constexpr bool working_orders_state_terminal = false;
536
538 static constexpr bool has_order_by_id = false;
539
541 static constexpr bool has_partial_cancel = true;
542
544 static constexpr bool history_requires_range = false;
545
547 static constexpr bool has_history_cursor = false;
548
550 static constexpr bool has_history_limit = false;
551
553 static constexpr bool has_history_symbol_filter = true;
554};
555
556} // namespace traits_detail
557} // namespace kiwoom
558
565inline constexpr Venue kiwoom_route(Venue asked) noexcept {
566 return kiwoom::kiwoom_effective_route(asked);
567}
568
570template <>
571struct BrokerTraits<kiwoom::KiwoomClient> : kiwoom::traits_detail::Normalizers, kiwoom::traits_detail::Capabilities {
577 static constexpr Venue effective_route(Venue asked) noexcept {
578 return kiwoom_route(asked);
579 }
580
583
586
589
592
595
598
601
604
607
609 static constexpr std::string_view name = kiwoom::Broker::name;
610
612 static constexpr bool blocking = false;
613
619 static const network::RateLimitStats* rate_limit_stats(const Client& client) {
620 return client.rate_limit_stats();
621 }
622
631 template <typename Token>
632 static auto quote(Client& client, InstrumentId instrument, Token&& token) {
633 return client.async_quote(std::move(instrument), std::forward<Token>(token));
634 }
635
644 template <typename Token>
645 static auto price_limits(Client& client, InstrumentId instrument, Token&& token) {
646 return client.async_price_limits(std::move(instrument), std::forward<Token>(token));
647 }
648
658 template <typename Token>
659 static auto trades(Client& client, InstrumentId instrument, int count, Token&& token) {
660 return client.async_trades(std::move(instrument), count, std::forward<Token>(token));
661 }
662
671 template <typename Token>
672 static auto depth(Client& client, InstrumentId instrument, Token&& token) {
673 return client.async_depth(std::move(instrument), std::forward<Token>(token));
674 }
675
684 template <typename Token>
685 static auto bars(Client& client, BarQuery query, Token&& token) {
686 return client.async_bars(std::move(query), std::forward<Token>(token));
687 }
688
697 template <typename Token>
698 static auto instrument(Client& client, InstrumentId subject, Token&& token) {
699 return client.async_instrument(std::move(subject), std::forward<Token>(token));
700 }
701
709 template <typename Token>
710 static auto accounts(Client& client, Token&& token) {
711 return client.async_accounts(std::forward<Token>(token));
712 }
713
723 template <typename Token>
724 static auto buying_power(Client& client, const Account& account, Currency currency, Token&& token) {
725 return client.async_buying_power(currency, account, std::forward<Token>(token));
726 }
727
740 template <typename Token>
741 static auto holdings(Client& client, const Account& account, Token&& token) {
743 static_cast<void>(account);
744 return net::async_initiate<Token, void(Result<HoldingsSnapshot>)>(
745 [strand = client.get_executor()](auto&& handler) mutable {
746 auto work = net::prefer(net::get_associated_executor(handler), net::execution::outstanding_work.tracked);
747 net::post(strand, [handler = std::forward<decltype(handler)>(handler), work = std::move(work)]() mutable {
748 net::dispatch(work, [handler = std::move(handler)]() mutable {
749 std::move(handler)(refuse_holdings());
750 });
751 });
752 },
753 token
754 );
755 }
756 return client.async_holdings(account, std::forward<Token>(token));
757 }
758
768 template <typename Token>
769 static auto place_order(Client& client, const Account& account, OrderRequest order, Token&& token) {
770 return client.async_place_order(account, std::move(order), std::forward<Token>(token));
771 }
772
782 template <typename Token>
783 static auto replace_order(Client& client, const Account& account, Amendment amendment, Token&& token) {
784 return client.async_replace_order(account, std::move(amendment), std::forward<Token>(token));
785 }
786
796 template <typename Token>
797 static auto cancel_order(Client& client, const Account& account, Amendment amendment, Token&& token) {
798 return client.async_cancel_order(account, std::move(amendment), std::forward<Token>(token));
799 }
800
809 template <typename Token>
810 static auto working_orders(Client& client, const Account& account, Token&& token) {
811 return client.async_open_orders(account, std::forward<Token>(token));
812 }
813
823 template <typename Token>
824 static auto order_history(Client& client, const Account& account, HistoryQuery query, Token&& token) {
825 return client.async_order_history(account, std::move(query), std::forward<Token>(token));
826 }
827};
828
830template <>
831struct BrokerTraits<kiwoom::KiwoomBlockingClient>
832: kiwoom::traits_detail::Normalizers, kiwoom::traits_detail::Capabilities {
838 static constexpr Venue effective_route(Venue asked) noexcept {
839 return kiwoom_route(asked);
840 }
841
844
847
850
853
856
859
862
865
868
870 static constexpr std::string_view name = kiwoom::Broker::name;
871
873 static constexpr bool blocking = true;
874
880 static const network::RateLimitStats* rate_limit_stats(const Client& client) {
881 return client.rate_limit_stats();
882 }
883
891 return client.quote(std::move(instrument));
892 }
893
901 return client.price_limits(std::move(instrument));
902 }
903
912 return client.trades(std::move(instrument), count);
913 }
914
922 return client.depth(std::move(instrument));
923 }
924
931 static Result<BarSeries> bars(Client& client, BarQuery query) {
932 return client.bars(std::move(query));
933 }
934
942 return client.instrument(std::move(subject));
943 }
944
951 return client.accounts();
952 }
953
960 static Result<HoldingsSnapshot> holdings(Client& client, const Account& account) {
962 static_cast<void>(account);
963 return refuse_holdings();
964 }
965 return client.holdings(account);
966 }
967
975 static Result<BuyingPower> buying_power(Client& client, const Account& account, Currency currency) {
976 return client.buying_power(currency, account);
977 }
978
986 static Result<PlaceAck> place_order(Client& client, const Account& account, OrderRequest order) {
987 return client.place_order(account, std::move(order));
988 }
989
997 static Result<PlaceAck> replace_order(Client& client, const Account& account, Amendment amendment) {
998 return client.replace_order(account, std::move(amendment));
999 }
1000
1008 static Result<PlaceAck> cancel_order(Client& client, const Account& account, Amendment amendment) {
1009 return client.cancel_order(account, std::move(amendment));
1010 }
1011
1019 return client.open_orders(account);
1020 }
1021
1029 static Result<OrderPage> order_history(Client& client, const Account& account, HistoryQuery query) {
1030 return client.order_history(account, std::move(query));
1031 }
1032};
1033
1034} // namespace algotradelib
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
Decimal64()=default
Constructs zero.
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
BrokerError & error()
Returns the error.
Definition types.hpp:1111
T & value()
Returns the value.
Definition types.hpp:1093
A blocking Kiwoom client: each call runs a KiwoomClient request on a private event loop and returns i...
Definition client.hpp:3644
Result< PriceLimits > price_limits(InstrumentId instrument)
Returns today's upper and lower price bound.
Definition client.hpp:3682
Result< std::vector< TradePrint > > trades(InstrumentId instrument, int count)
Returns recent executions, newest first.
Definition client.hpp:3711
const KiwoomConfig & config() const noexcept
Returns the configuration; see KiwoomClient::config.
Definition client.hpp:3752
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:3919
Result< BuyingPower > buying_power(Currency currency, KiwoomAccount account)
Returns what the bound credential's account may spend.
Definition client.hpp:3776
Result< KiwoomOrderAck > replace_order(KiwoomAccount account, KiwoomAmendment amendment)
Modifies an existing order. The outcome can be unknown after an error; see KiwoomClient::async_replac...
Definition client.hpp:3852
Result< OrderPage > order_history(KiwoomAccount account, KiwoomHistoryQuery query)
Returns one day of order history.
Definition client.hpp:3897
Result< DepthSnapshot > depth(InstrumentId instrument)
Returns the resting orders on both sides of the book.
Definition client.hpp:3696
Result< KiwoomOrderAck > cancel_order(KiwoomAccount account, KiwoomAmendment amendment)
Cancels an existing order. The outcome can be unknown after an error; see KiwoomClient::async_cancel_...
Definition client.hpp:3868
Result< BarSeries > bars(BarQuery query)
Returns bars; see KiwoomClient::async_bars.
Definition client.hpp:3739
Result< QuoteSnapshot > quote(InstrumentId instrument)
Returns the current normalized quote or a structured error.
Definition client.hpp:3668
Result< std::vector< KiwoomAccountInfo > > accounts()
Returns the one account the bound credential drives.
Definition client.hpp:3820
Result< KiwoomOpenOrderPage > open_orders(KiwoomAccount account)
Returns every order still open to amendment.
Definition client.hpp:3882
Result< KiwoomOrderAck > place_order(KiwoomAccount account, OrderRequest order)
Submits a new order. The outcome can be unknown after an error; see KiwoomClient::async_place_order.
Definition client.hpp:3836
Result< Instrument > instrument(InstrumentId subject)
Returns static reference data for one instrument.
Definition client.hpp:3725
Result< HoldingsSnapshot > holdings(KiwoomAccount account)
Returns the holdings for KiwoomConfig::holdings_venue_; see KiwoomClient::async_holdings.
Definition client.hpp:3761
The asynchronous Kiwoom REST client: market data, account inquiries and orders for domestic stocks.
Definition client.hpp:882
auto async_instrument(InstrumentId instrument, CompletionToken &&token)
Requests static reference data for one instrument, from ka10100 종목정보 조회.
Definition client.hpp:1028
auto async_buying_power(Currency currency, KiwoomAccount account, CompletionToken &&token)
Requests what the account may spend, from kt00001 예수금상세현황요청.
Definition client.hpp:1116
auto async_depth(InstrumentId instrument, CompletionToken &&token)
Requests the resting orders on both sides of the book, from ka10004 주식호가요청.
Definition client.hpp:986
auto async_open_orders(KiwoomAccount account, CompletionToken &&token)
Requests every order still open to amendment, paging ka10075 미체결요청.
Definition client.hpp:1302
auto async_order_history(KiwoomAccount account, KiwoomHistoryQuery query, CompletionToken &&token)
Requests one day of order history, paging kt00007 계좌별주문체결내역상세요청.
Definition client.hpp:1322
auto async_cancel_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Cancels an order, all or part of it (kt10003).
Definition client.hpp:1283
auto async_replace_order(KiwoomAccount account, KiwoomAmendment amendment, CompletionToken &&token)
Amends an order's quantity, price or trigger price (kt10002).
Definition client.hpp:1252
const KiwoomConfig & config() const noexcept
Returns the configuration (the session reads its holdings assertions from it).
Definition client.hpp:1070
auto async_bars(BarQuery query, CompletionToken &&token)
Requests bars, following Kiwoom's continuation pages from before_'s Korean date (or today).
Definition client.hpp:1055
auto async_place_order(KiwoomAccount account, OrderRequest order, CompletionToken &&token)
Places an order (kt10000 buy, kt10001 sell).
Definition client.hpp:1226
net::strand< net::any_io_executor > get_executor() const noexcept
Returns the client's strand.
Definition client.hpp:1078
auto async_price_limits(InstrumentId instrument, CompletionToken &&token)
Requests today's upper and lower price bound, from the same ka10007 response.
Definition client.hpp:964
auto async_accounts(CompletionToken &&token)
Requests the one account the bound credential drives, from ka00001 계좌번호조회.
Definition client.hpp:1183
auto async_holdings(KiwoomAccount account, CompletionToken &&token)
Requests the holdings kt00018 lists for KiwoomConfig::holdings_venue_ (refused before sending until i...
Definition client.hpp:1096
const network::RateLimitStats * rate_limit_stats() const
Returns the rate limiter's statistics.
Definition client.hpp:1341
auto async_trades(InstrumentId instrument, int count, CompletionToken &&token)
Requests recent executions, newest first, from ka10003 체결정보요청.
Definition client.hpp:1009
auto async_quote(InstrumentId instrument, CompletionToken &&token)
Requests and normalizes a current quote, from ka10007 시세표성정보요청.
Definition client.hpp:942
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:792
constexpr const char * chart_rows_field(BarInterval interval) noexcept
Returns the array field a bar interval's chart endpoint returns its rows in.
Definition client.hpp:766
std::optional< BrokerError > invalid_trigger(OrderType type, const std::optional< Decimal64 > &trigger)
Checks that a trigger price is present exactly when the order type takes one (only STOP_LIMIT,...
Definition client.hpp:243
std::optional< BrokerError > unsupported_client_order_id(const OrderRequest &order)
Refuses an idempotency key, which Kiwoom does not offer (an order carrying client_order_id_ is refuse...
Definition client.hpp:210
constexpr bool kiwoom_position_scope_asserted(KiwoomPositionScope scope) noexcept
Tests whether a holdings scope states what Kiwoom's holdings figure covers, so holdings may be read a...
Definition config.hpp:125
constexpr const char * chart_api_id(BarInterval interval) noexcept
Returns the api-id of the chart endpoint for a bar interval.
Definition client.hpp:740
constexpr Venue kiwoom_effective_route(Venue asked) noexcept
Returns the venue a Kiwoom order reaches: the one it names (Kiwoom requires one, so an order naming n...
Definition client.hpp:656
The library: broker-neutral types (core), and the modules below.
SellableSource
Where the library gets a broker's sellable quantity.
Definition types.hpp:1362
@ NONE
No per-instrument inquiry: any figure comes on the holdings rows (Kiwoom), or there is none.
Definition types.hpp:1368
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
Country
A country (market) the library supports.
Definition types.hpp:32
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:565
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
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:2563
A modification or cancellation of a working order.
Definition types.hpp:2532
Venue venue_
The venue the order rests at, for a broker whose amendment needs it (KIS).
Definition types.hpp:2540
std::optional< OrderShape > resting_
The shape the order has now, or unset if unknown.
Definition types.hpp:2553
std::optional< Decimal64 > quantity_
The quantity affected; never substituted if a broker needs one and it is missing.
Definition types.hpp:2542
OrderShape shape_
The shape the order should have afterwards.
Definition types.hpp:2534
bool all_remaining_
Whether the whole remaining quantity is affected, rather than quantity_.
Definition types.hpp:2544
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: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
static Result< Instrument > instrument(Client &client, InstrumentId subject)
Returns static reference data for one instrument.
Definition traits.hpp:941
kiwoom::KiwoomAccount Account
Kiwoom account selector, which carries nothing because Kiwoom takes nothing.
Definition traits.hpp:849
static Result< OrderPage > order_history(Client &client, const Account &account, HistoryQuery query)
Returns order history for the bound account.
Definition traits.hpp:1029
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:960
kiwoom::KiwoomBlockingClient Client
The client type.
Definition traits.hpp:843
static constexpr bool blocking
true: requests return their result directly.
Definition traits.hpp:873
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:870
static Result< BuyingPower > buying_power(Client &client, const Account &account, Currency currency)
Returns what the bound account may spend in currency.
Definition traits.hpp:975
kiwoom::KiwoomOpenOrderPage WorkingOrdersResult
Kiwoom amendable-order result.
Definition traits.hpp:867
static Result< QuoteSnapshot > quote(Client &client, InstrumentId instrument)
Returns a quote.
Definition traits.hpp:890
kiwoom::KiwoomAccountInfo AccountListItem
Item type of the broker's own account listing.
Definition traits.hpp:852
kiwoom::KiwoomHistoryQuery HistoryQuery
Kiwoom order-history selector.
Definition traits.hpp:864
static Result< BarSeries > bars(Client &client, BarQuery query)
Returns bars, paging inside the client.
Definition traits.hpp:931
static Result< DepthSnapshot > depth(Client &client, InstrumentId instrument)
Returns the order book.
Definition traits.hpp:921
kiwoom::KiwoomOrderAck PlaceAck
Acknowledgement Kiwoom returns for an order instruction.
Definition traits.hpp:858
static Result< PlaceAck > place_order(Client &client, const Account &account, OrderRequest order)
Submits an order for the bound account.
Definition traits.hpp:986
static Result< std::vector< TradePrint > > trades(Client &client, InstrumentId instrument, int count)
Returns recent executions.
Definition traits.hpp:911
kiwoom::KiwoomConfig Config
Kiwoom application credentials and environment selection.
Definition traits.hpp:846
static const network::RateLimitStats * rate_limit_stats(const Client &client)
Returns the rate limiter's statistics.
Definition traits.hpp:880
static Result< PlaceAck > replace_order(Client &client, const Account &account, Amendment amendment)
Modifies an order for the bound account.
Definition traits.hpp:997
static Result< WorkingOrdersResult > working_orders(Client &client, const Account &account)
Returns the amendable orders for the bound account.
Definition traits.hpp:1018
kiwoom::KiwoomAmendment Amendment
Kiwoom modification and cancellation instruction.
Definition traits.hpp:861
static Result< PlaceAck > cancel_order(Client &client, const Account &account, Amendment amendment)
Cancels an order for the bound account.
Definition traits.hpp:1008
static Result< std::vector< AccountListItem > > accounts(Client &client)
Returns the one account the bound credential drives.
Definition traits.hpp:950
static constexpr Venue effective_route(Venue asked) noexcept
Returns the venue an order reaches; see kiwoom_route.
Definition traits.hpp:838
static Result< PriceLimits > price_limits(Client &client, InstrumentId instrument)
Returns today's price bounds.
Definition traits.hpp:900
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:724
static constexpr std::string_view name
The broker's name.
Definition traits.hpp:609
static auto bars(Client &client, BarQuery query, Token &&token)
Forwards a bar request.
Definition traits.hpp:685
static auto quote(Client &client, InstrumentId instrument, Token &&token)
Forwards a quote request.
Definition traits.hpp:632
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:741
static constexpr bool blocking
false: requests complete through a completion token.
Definition traits.hpp:612
static auto price_limits(Client &client, InstrumentId instrument, Token &&token)
Forwards a price-bound request.
Definition traits.hpp:645
static auto trades(Client &client, InstrumentId instrument, int count, Token &&token)
Forwards a recent-execution request.
Definition traits.hpp:659
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:824
static auto place_order(Client &client, const Account &account, OrderRequest order, Token &&token)
Forwards an order submission for the bound account.
Definition traits.hpp:769
kiwoom::Broker BrokerTag
The broker tag.
Definition traits.hpp:594
static auto accounts(Client &client, Token &&token)
Forwards an account listing request.
Definition traits.hpp:710
kiwoom::KiwoomConfig Config
Kiwoom application credentials and environment selection.
Definition traits.hpp:585
kiwoom::KiwoomOpenOrderPage WorkingOrdersResult
Kiwoom amendable-order result.
Definition traits.hpp:606
static auto depth(Client &client, InstrumentId instrument, Token &&token)
Forwards an order book request.
Definition traits.hpp:672
kiwoom::KiwoomAccount Account
Kiwoom account selector, which carries nothing because Kiwoom takes nothing.
Definition traits.hpp:588
static auto working_orders(Client &client, const Account &account, Token &&token)
Forwards an amendable-order inquiry for the bound account.
Definition traits.hpp:810
static const network::RateLimitStats * rate_limit_stats(const Client &client)
Returns the rate limiter's statistics.
Definition traits.hpp:619
kiwoom::KiwoomOrderAck PlaceAck
Acknowledgement Kiwoom returns for an order instruction.
Definition traits.hpp:597
kiwoom::KiwoomHistoryQuery HistoryQuery
Kiwoom order-history selector.
Definition traits.hpp:603
static auto replace_order(Client &client, const Account &account, Amendment amendment, Token &&token)
Forwards an order modification for the bound account.
Definition traits.hpp:783
static auto cancel_order(Client &client, const Account &account, Amendment amendment, Token &&token)
Forwards an order cancellation for the bound account.
Definition traits.hpp:797
static auto instrument(Client &client, InstrumentId subject, Token &&token)
Forwards a reference-data request.
Definition traits.hpp:698
kiwoom::KiwoomClient Client
The client type.
Definition traits.hpp:582
static constexpr Venue effective_route(Venue asked) noexcept
Returns the venue an order reaches; see kiwoom_route.
Definition traits.hpp:577
kiwoom::KiwoomAmendment Amendment
Kiwoom modification and cancellation instruction.
Definition traits.hpp:600
kiwoom::KiwoomAccountInfo AccountListItem
Item type of the broker's own account listing.
Definition traits.hpp:591
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:85
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< std::string > symbol_
Only this symbol, where the broker supports the filter.
Definition types.hpp:2623
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2627
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
Definition types.hpp:2625
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
Definition types.hpp:2619
std::optional< Date > to_
The last date to include.
Definition types.hpp:2621
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
std::string primary_
The order number or id.
Definition types.hpp:2404
An order to place, in broker-neutral form.
Definition types.hpp:2216
An order's type, price, trigger, time in force and session, as an amendment states them.
Definition types.hpp:2474
std::optional< TimeInForce > time_in_force_
The time in force; unset means "keep the resting order's".
Definition types.hpp:2515
std::optional< Decimal64 > price_
The price, for a basis that takes one.
Definition types.hpp:2499
std::optional< OrderSession > session_
The session; unset means "keep the resting order's".
Definition types.hpp:2522
std::optional< Decimal64 > trigger_price_
The trigger price, for STOP_LIMIT.
Definition types.hpp:2508
OrderType type_
The price basis.
Definition types.hpp:2497
An accepted order: the acknowledgement and the reference to address it with.
Definition types.hpp:2460
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2464
OrderAck ack_
The acknowledgement.
Definition types.hpp:2462
An order still open to modification or cancellation.
Definition types.hpp:2582
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2586
std::optional< Decimal64 > amendable_quantity_
How much the broker says may still be amended. Empty means it stated none, not zero.
Definition types.hpp:2588
OrderSnapshot order_
The order's state.
Definition types.hpp:2584
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2604
std::vector< WorkingOrder< Broker > > orders_
The open orders.
Definition types.hpp:2606
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
Definition types.hpp:2608
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:48
std::string account_number_
The account number as Kiwoom reported it, for display.
Definition client.hpp:50
The Kiwoom account selector, which is empty: no Kiwoom endpoint takes an account number,...
Definition client.hpp:36
An amendment or cancellation of a Kiwoom order.
Definition client.hpp:73
Venue venue_
The venue the order rests on, as listed (Kiwoom's dmst_stex_tp): KRX, NXT or COMBINED (SOR)....
Definition client.hpp:80
KiwoomOrderRef order_
The order to amend, which carries the symbol Kiwoom requires beside the order number.
Definition client.hpp:75
Decimal64 quantity_
The quantity affected, or zero for everything still resting (Kiwoom evaluates 0 when it processes the...
Definition client.hpp:85
std::optional< Decimal64 > price_
The new price, on a modification; absent on an unpriced basis, and refused on a cancellation.
Definition client.hpp:87
std::optional< Decimal64 > condition_price_
The new trigger price (mdfy_cond_uv), for amending a stop-limit (28) order; must be empty on a cancel...
Definition client.hpp:92
Kiwoom credentials (app key and secret key), demo or real account, the market-data tape,...
Definition config.hpp:155
KiwoomPositionScope holdings_position_scope_
Your assertion of what holdings_venue_ means for the positions listed. No default: until it is set,...
Definition config.hpp:194
A Kiwoom order-history query: one date (kt00007 takes no range, so a multi-day query is refused).
Definition client.hpp:146
Date date_
The single 주문일자 to list.
Definition client.hpp:148
std::string symbol_
Restrict to one symbol, which Kiwoom expresses as stk_cd. Empty lists every symbol.
Definition client.hpp:150
One page of Kiwoom orders that remain modifiable or cancellable.
Definition client.hpp:135
Kiwoom's acknowledgement of an accepted order, amendment or cancellation.
Definition client.hpp:101
A Kiwoom order's address: order number and symbol, both of which amendments and cancellations require...
Definition client.hpp:59
std::string order_number_
Kiwoom's ord_no.
Definition client.hpp:61
std::string symbol_
Kiwoom's stk_cd, which its amendment endpoints require beside the order number.
Definition client.hpp:63
A rate limiter's counters per traffic class, its current budget, and the broker's refusals (from Rate...