algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
algotradelib::kis::KisClient Class Reference

The asynchronous KIS REST client: market data, account inquiries and orders for domestic stocks. More...

#include <algotradelib/src/brokers/kis/client.hpp>

Inheritance diagram for algotradelib::kis::KisClient:
Collaboration diagram for algotradelib::kis::KisClient:

Public Types

using QuoteHandler = net::any_completion_handler<void(Result<QuoteSnapshot>)>
 The completion handler type of async_quote.
using BarsHandler = net::any_completion_handler<void(Result<BarSeries>)>
 The completion handler type of async_bars.
using DepthHandler = net::any_completion_handler<void(Result<DepthSnapshot>)>
 The completion handler type of async_depth.
using PriceLimitsHandler = net::any_completion_handler<void(Result<PriceLimits>)>
 The completion handler type of async_price_limits.
using TradesHandler = net::any_completion_handler<void(Result<std::vector<TradePrint>>)>
 The completion handler type of async_trades.
using CalendarHandler = net::any_completion_handler<void(Result<TradingCalendar>)>
 The completion handler type of async_calendar.
using InstrumentHandler = net::any_completion_handler<void(Result<Instrument>)>
 The completion handler type of async_instrument.
using HoldingsHandler = net::any_completion_handler<void(Result<HoldingsSnapshot>)>
 The completion handler type of async_holdings.
using BuyingPowerHandler = net::any_completion_handler<void(Result<BuyingPower>)>
 The completion handler type of async_buying_power.
using OrderAckHandler = net::any_completion_handler<void(Result<KisOrderAck>)>
 The completion handler type of the order requests.
using OpenOrderHandler = net::any_completion_handler<void(Result<KisOpenOrderPage>)>
 The completion handler type of async_open_orders.
using OrderPageHandler = net::any_completion_handler<void(Result<OrderPage>)>
 The completion handler type of async_order_history.
using TokenHandler = net::any_completion_handler<void(std::optional<BrokerError>)>
 The completion handler type of a token refresh (internal).
using TokenResultHandler = net::any_completion_handler<void(Result<KisRest>)>
 The completion handler type of async_ensure_token.

Public Member Functions

 KisClient (net::any_io_executor executor, ssl::context &context, KisConfig config, network::HttpClientOptions options={})
 Constructs a client; nothing is sent until the first request.
template<typename CompletionToken>
auto async_bars (BarQuery query, CompletionToken &&token)
 Requests bars, reading KIS pages until count_ bars are collected.
template<typename CompletionToken>
auto async_instrument (InstrumentId instrument, CompletionToken &&token)
 Requests an instrument's reference data.
template<typename CompletionToken>
auto async_calendar (Date from, bool refresh, CompletionToken &&token)
 Requests the trading calendar from a date on, and caches it for the client's life.
template<typename CompletionToken>
auto async_price_limits (InstrumentId instrument, CompletionToken &&token)
 Requests an instrument's price band for today (from its current-price inquiry).
template<typename CompletionToken>
auto async_trades (InstrumentId instrument, int count, CompletionToken &&token)
 Requests an instrument's recent trades.
template<typename CompletionToken>
auto async_depth (InstrumentId instrument, CompletionToken &&token)
 Requests the order book (ten levels a side).
template<typename CompletionToken>
auto async_quote (InstrumentId instrument, CompletionToken &&token)
 Requests a quote.
template<typename CompletionToken>
auto async_buying_power (Currency currency, KisAccount account, CompletionToken &&token)
 Requests the account's buying power (the account-level amount, in won).
template<typename CompletionToken>
auto async_holdings (KisAccount account, CompletionToken &&token)
 Requests the account's holdings.
template<typename CompletionToken>
auto async_place_order (KisAccount account, OrderRequest order, CompletionToken &&token)
 Places a cash order.
template<typename CompletionToken>
auto async_replace_order (KisAccount account, KisAmendment amendment, CompletionToken &&token)
 Amends an order's price or quantity.
template<typename CompletionToken>
auto async_cancel_order (KisAccount account, KisAmendment amendment, CompletionToken &&token)
 Cancels an order (all or part of it, as amendment says).
template<typename CompletionToken>
auto async_open_orders (KisAccount account, CompletionToken &&token)
 Requests every order that can still be amended or cancelled.
template<typename CompletionToken>
auto async_order_history (KisAccount account, KisHistoryRange range, CompletionToken &&token)
 Requests the orders placed over a date range, with their fills.
const network::RateLimitStats * rate_limit_stats () const
 Returns the rate limiter's statistics.
KisRest token () const
 Returns the access token the client holds, to reuse in a later process (adopt_token).
bool adopt_token (KisRest token)
 Uses a token issued earlier for the same app key and environment instead of requesting one.
bool adopt_calendar (TradingCalendar calendar)
 Uses a calendar obtained earlier, such as from a network::CalendarCache, instead of requesting one while it covers the date asked (async_calendar).
template<typename CompletionToken>
auto async_ensure_token (CompletionToken &&token)
 Requests an access token unless the held one stays valid for five more minutes, as any request does first, and reports the token held afterwards.
void forget_token ()
 Drops the held token: the next request asks for one.
void close ()
 Closes the client for good: pending requests, and later ones that would send, complete with CANCELLED. A request already being sent has reached_broker_ set and an unknown outcome. A later calendar request the cache covers is still answered, and a request refused before sending is still refused.

Friends

struct KisClientTestAccess
class KisBlockingClient

Detailed Description

The asynchronous KIS REST client: market data, account inquiries and orders for domestic stocks.

It requests an access token when first needed, and again after KIS refuses the one it holds; one refresh is shared among concurrent requests, and a refused request is not sent again. Sends custtype P. KIS's field reference reads B : 법인 / P : 개인, and its token guide (접근토큰발급) groups 일반개인고객 and 일반법인고객 under the one-day client-credentials token, apart from 제휴법인 (a three-month token by authorization code, and personalseckey, 제휴사 회원 관리를 위한 고객식별키). The partner-corporation flow (custtype B) is not supported. Create it with std::make_shared. Each completion runs on the handler's associated executor, or on the client's strand if it has none. A blocking wrapper is KisBlockingClient.

Definition at line 339 of file client.hpp.

Member Typedef Documentation

◆ BarsHandler

using algotradelib::kis::KisClient::BarsHandler = net::any_completion_handler<void(Result<BarSeries>)>

The completion handler type of async_bars.

Definition at line 345 of file client.hpp.

◆ BuyingPowerHandler

using algotradelib::kis::KisClient::BuyingPowerHandler = net::any_completion_handler<void(Result<BuyingPower>)>

The completion handler type of async_buying_power.

Definition at line 365 of file client.hpp.

◆ CalendarHandler

using algotradelib::kis::KisClient::CalendarHandler = net::any_completion_handler<void(Result<TradingCalendar>)>

The completion handler type of async_calendar.

Definition at line 357 of file client.hpp.

◆ DepthHandler

using algotradelib::kis::KisClient::DepthHandler = net::any_completion_handler<void(Result<DepthSnapshot>)>

The completion handler type of async_depth.

Definition at line 348 of file client.hpp.

◆ HoldingsHandler

using algotradelib::kis::KisClient::HoldingsHandler = net::any_completion_handler<void(Result<HoldingsSnapshot>)>

The completion handler type of async_holdings.

Definition at line 363 of file client.hpp.

◆ InstrumentHandler

using algotradelib::kis::KisClient::InstrumentHandler = net::any_completion_handler<void(Result<Instrument>)>

The completion handler type of async_instrument.

Definition at line 360 of file client.hpp.

◆ OpenOrderHandler

using algotradelib::kis::KisClient::OpenOrderHandler = net::any_completion_handler<void(Result<KisOpenOrderPage>)>

The completion handler type of async_open_orders.

Definition at line 371 of file client.hpp.

◆ OrderAckHandler

using algotradelib::kis::KisClient::OrderAckHandler = net::any_completion_handler<void(Result<KisOrderAck>)>

The completion handler type of the order requests.

Definition at line 368 of file client.hpp.

◆ OrderPageHandler

using algotradelib::kis::KisClient::OrderPageHandler = net::any_completion_handler<void(Result<OrderPage>)>

The completion handler type of async_order_history.

Definition at line 374 of file client.hpp.

◆ PriceLimitsHandler

using algotradelib::kis::KisClient::PriceLimitsHandler = net::any_completion_handler<void(Result<PriceLimits>)>

The completion handler type of async_price_limits.

Definition at line 351 of file client.hpp.

◆ QuoteHandler

using algotradelib::kis::KisClient::QuoteHandler = net::any_completion_handler<void(Result<QuoteSnapshot>)>

The completion handler type of async_quote.

Definition at line 342 of file client.hpp.

◆ TokenHandler

using algotradelib::kis::KisClient::TokenHandler = net::any_completion_handler<void(std::optional<BrokerError>)>

The completion handler type of a token refresh (internal).

Definition at line 377 of file client.hpp.

◆ TokenResultHandler

using algotradelib::kis::KisClient::TokenResultHandler = net::any_completion_handler<void(Result<KisRest>)>

The completion handler type of async_ensure_token.

Definition at line 380 of file client.hpp.

◆ TradesHandler

using algotradelib::kis::KisClient::TradesHandler = net::any_completion_handler<void(Result<std::vector<TradePrint>>)>

The completion handler type of async_trades.

Definition at line 354 of file client.hpp.

Constructor & Destructor Documentation

◆ KisClient()

algotradelib::kis::KisClient::KisClient ( net::any_io_executor executor,
ssl::context & context,
KisConfig config,
network::HttpClientOptions options = {} )
inline

Constructs a client; nothing is sent until the first request.

Parameters
executorThe executor its strand runs on.
contextThe TLS context; borrowed, and must outlive the client.
configThe credentials and environment (real or demo).
optionsHTTP options (set rate_limit_ to pace requests). An empty fresh_connection_for_orders_ is taken as on for a demo configuration and off for a real one.

Definition at line 390 of file client.hpp.

Member Function Documentation

◆ adopt_calendar()

bool algotradelib::kis::KisClient::adopt_calendar ( TradingCalendar calendar)
inline

Uses a calendar obtained earlier, such as from a network::CalendarCache, instead of requesting one while it covers the date asked (async_calendar).

Call it on the client's strand or before any request, with no calendar request in progress; on the blocking client, between calls.

Parameters
calendarThe calendar; its received_at_ is kept as it is.
Returns
false (nothing adopted, the held calendar kept) if its country is not KR, it has no days, or a day's date is invalid.

Definition at line 838 of file client.hpp.

◆ adopt_token()

bool algotradelib::kis::KisClient::adopt_token ( KisRest token)
inline

Uses a token issued earlier for the same app key and environment instead of requesting one.

When KIS refuses the token a request carried (EGW00121 invalid, EGW00123 expired), that request fails with KIS's code and is not sent again, and the client drops the token: the next request asks for a new one, which token() then returns. The token does not identify its key, so key stored tokens by environment and app key, and discard one KIS refused. The token is a bearer credential: store it as carefully as the key and secret.

Call it on the client's strand or before any request; on the blocking client, between calls. A blocking client given a network::TokenStore shares its token with other clients and programs without this call.

Parameters
tokenThe token.
Returns
false (nothing adopted) if the token is empty or expires within five minutes.

Definition at line 822 of file client.hpp.

◆ async_bars()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_bars ( BarQuery query,
CompletionToken && token )
inline

Requests bars, reading KIS pages until count_ bars are collected.

Every bar is stamped at its open: a minute bar at the start of its minute. Paging stops early after 50 pages, when a page returns no bars, or (for minutes) at the start of the trading day. A period page asks for a date window of 100 bars' worth of calendar days, so an empty one means KIS has no older bars or none in that window (a halt longer than the window). A series may therefore be shorter than count_ for any interval; then, unless it is empty, next_cursor_ is set to continue from, since an empty page does not prove the history exhausted.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
queryThe query.
tokenThe completion token, called with Result<BarSeries>.
Returns
Whatever the completion token returns.

Definition at line 417 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::bars().

◆ async_buying_power()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_buying_power ( Currency currency,
KisAccount account,
CompletionToken && token )
inline

Requests the account's buying power (the account-level amount, in won).

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
currencyThe currency; anything but KRW is refused before sending.
accountThe account.
tokenThe completion token, called with Result<BuyingPower>.
Returns
Whatever the completion token returns.

Definition at line 584 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::buying_power().

◆ async_calendar()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_calendar ( Date from,
bool refresh,
CompletionToken && token )
inline

Requests the trading calendar from a date on, and caches it for the client's life.

KIS asks that its holiday endpoint be called at most once a day, so a request the cache covers is answered without a request.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
fromThe first date; an invalid date is refused (invalid_date) before sending.
refreshtrue to request again even if the cache covers from.
tokenThe completion token, called with Result<TradingCalendar>.
Returns
Whatever the completion token returns.

Definition at line 464 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::calendar().

◆ async_cancel_order()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_cancel_order ( KisAccount account,
KisAmendment amendment,
CompletionToken && token )
inline

Cancels an order (all or part of it, as amendment says).

After an error of unknown outcome (see async_place_order) the order may still rest.

One refusal is recognized as one, on a demo account only: the demo server's 40330000 (nothing left to amend or cancel), in an HTTP 200 reply that carries no new acknowledgement, is INVALID_ARGUMENT with reached_broker_ set. It says the cancellation did nothing, not what became of the order: it may have filled. The same reply from the real server stays PROTOCOL, as does every other refusal of a cancellation this client does not classify further (a rate-limit code is RATE_LIMIT).

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
amendmentThe order and quantity.
tokenThe completion token, called with Result<KisOrderAck>.
Returns
Whatever the completion token returns.

Definition at line 708 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::cancel_order().

◆ async_depth()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_depth ( InstrumentId instrument,
CompletionToken && token )
inline

Requests the order book (ten levels a side).

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
instrumentThe instrument.
tokenThe completion token, called with Result<DepthSnapshot>.
Returns
Whatever the completion token returns.

Definition at line 539 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::depth().

◆ async_ensure_token()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_ensure_token ( CompletionToken && token)
inline

Requests an access token unless the held one stays valid for five more minutes, as any request does first, and reports the token held afterwards.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
tokenThe completion token, called with Result<KisRest>: a bearer credential, never to be logged.
Returns
Whatever the completion token returns.

Definition at line 859 of file client.hpp.

◆ async_holdings()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_holdings ( KisAccount account,
CompletionToken && token )
inline

Requests the account's holdings.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
tokenThe completion token, called with Result<HoldingsSnapshot>.
Returns
Whatever the completion token returns.

Definition at line 606 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::holdings().

◆ async_instrument()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_instrument ( InstrumentId instrument,
CompletionToken && token )
inline

Requests an instrument's reference data.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
instrumentThe instrument.
tokenThe completion token, called with Result<Instrument>.
Returns
Whatever the completion token returns.

Definition at line 437 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::instrument().

◆ async_open_orders()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_open_orders ( KisAccount account,
CompletionToken && token )
inline

Requests every order that can still be amended or cancelled.

Demo accounts lack this inquiry, so on demo it is answered from today's unfilled orders in the daily order inquiry: each with a remaining quantity is listed with that as its amendable quantity. It then lags as that history lags, stop_released_ stays empty, and it may list an order that can no longer be cancelled.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
tokenThe completion token, called with Result<KisOpenOrderPage>.
Returns
Whatever the completion token returns.

Definition at line 739 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::working_orders().

◆ async_order_history()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_order_history ( KisAccount account,
KisHistoryRange range,
CompletionToken && token )
inline

Requests the orders placed over a date range, with their fills.

KIS reports no status here; each order's status is derived from its quantity, filled, remaining, rejected and cancelled figures.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
rangeThe dates (an invalid range, or to_ before from_, is refused before sending).
tokenThe completion token, called with Result<OrderPage>.
Returns
Whatever the completion token returns.

Definition at line 764 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::order_history().

◆ async_place_order()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_place_order ( KisAccount account,
OrderRequest order,
CompletionToken && token )
inline

Places a cash order.

The request is never resent. After an error for which runner::outcome_of returns INDETERMINATE (BrokerError::reached_broker_ set and a category of TRANSPORT, CANCELLED or PROTOCOL, or HTTP with a status of 500 or more), the outcome is unknown. That includes a 200 reply KIS marks as failed (rt_cd not 0, such as insufficient balance) and this client does not recognize, which it reports as PROTOCOL; a rate-limit code there is RATE_LIMIT, which runner::Runner keeps for a later pass. Read async_open_orders or async_order_history before placing again, since KIS has no idempotency key.

Some refusals are recognized as refusals, each from its own server only: the demo server's 40240000 (nothing held to sell), 40570000 (the market has not opened) and 40580000 (the market has closed), and the real server's APBK3061 (during the after-market session, only after-market order types are accepted). In an HTTP 200 reply that carries no acknowledgement, each is INVALID_ARGUMENT with reached_broker_ set, which runner::outcome_of reads as REJECTED. A demo code from the real server, or the real code from the demo server, stays PROTOCOL, as does every other refusal this client does not classify further (a rate-limit code is RATE_LIMIT, as above).

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
orderThe order (without client_order_id_; see unsupported_client_order_id).
tokenThe completion token, called with Result<KisOrderAck>.
Returns
Whatever the completion token returns.

Definition at line 645 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::place_order().

◆ async_price_limits()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_price_limits ( InstrumentId instrument,
CompletionToken && token )
inline

Requests an instrument's price band for today (from its current-price inquiry).

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
instrumentThe instrument.
tokenThe completion token, called with Result<PriceLimits>.
Returns
Whatever the completion token returns.

Definition at line 484 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::price_limits().

◆ async_quote()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_quote ( InstrumentId instrument,
CompletionToken && token )
inline

Requests a quote.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
instrumentThe instrument.
tokenThe completion token, called with Result<QuoteSnapshot>.
Returns
Whatever the completion token returns.

Definition at line 561 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::quote().

◆ async_replace_order()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_replace_order ( KisAccount account,
KisAmendment amendment,
CompletionToken && token )
inline

Amends an order's price or quantity.

After an error of unknown outcome (see async_place_order) the amendment may have been made.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
accountThe account.
amendmentThe amendment.
tokenThe completion token, called with Result<KisOrderAck>.
Returns
Whatever the completion token returns.

Definition at line 672 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::replace_order().

◆ async_trades()

template<typename CompletionToken>
auto algotradelib::kis::KisClient::async_trades ( InstrumentId instrument,
int count,
CompletionToken && token )
inline

Requests an instrument's recent trades.

Template Parameters
CompletionTokenAn Asio completion token.
Parameters
instrumentThe instrument.
countThe most trades to return (KIS returns a fixed window, trimmed to this; zero or less returns the whole window).
tokenThe completion token, called with Result<std::vector<TradePrint>>.
Returns
Whatever the completion token returns.

Definition at line 511 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::trades().

◆ close()

void algotradelib::kis::KisClient::close ( )
inline

Closes the client for good: pending requests, and later ones that would send, complete with CANCELLED. A request already being sent has reached_broker_ set and an unknown outcome. A later calendar request the cache covers is still answered, and a request refused before sending is still refused.

Definition at line 892 of file client.hpp.

◆ forget_token()

void algotradelib::kis::KisClient::forget_token ( )
inline

Drops the held token: the next request asks for one.

Call it on the client's strand or before any request; on the blocking client, between calls.

Definition at line 882 of file client.hpp.

◆ rate_limit_stats()

const network::RateLimitStats * algotradelib::kis::KisClient::rate_limit_stats ( ) const
inline

Returns the rate limiter's statistics.

Read them on the client's strand or while no request is in progress (between calls on the blocking client).

Returns
The statistics, or null if the client has no rate-limit budget.

Definition at line 786 of file client.hpp.

Referenced by algotradelib::BrokerTraits< kis::KisClient >::rate_limit_stats().

◆ token()

KisRest algotradelib::kis::KisClient::token ( ) const
inline

Returns the access token the client holds, to reuse in a later process (adopt_token).

KIS issues one token per app key per minute (EGW00133), so a program that runs once per action can act only once a minute unless it keeps the token. The token is a bearer credential: store it as carefully as the key and secret.

Read it on the client's strand or before any request; on the blocking client, between calls.

Returns
The token, empty until a request has obtained one.

Definition at line 802 of file client.hpp.

Referenced by adopt_token(), async_bars(), async_buying_power(), async_calendar(), async_cancel_order(), async_depth(), async_ensure_token(), async_holdings(), async_instrument(), async_open_orders(), async_order_history(), async_place_order(), async_price_limits(), async_quote(), async_replace_order(), and async_trades().

◆ KisBlockingClient

friend class KisBlockingClient
friend

Definition at line 898 of file client.hpp.

◆ KisClientTestAccess

friend struct KisClientTestAccess
friend

Definition at line 897 of file client.hpp.


The documentation for this class was generated from the following file: