algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-portable-holdings.cpp
1// One account report written once and compiled for two brokers, KIS and Toss.
2//
3// `report()` below is the point of this example: it names no vendor type, no
4// account selector, and no broker-specific acknowledgement. It is instantiated
5// twice — once for KIS and once for Toss Securities — and the only thing that
6// differs between the two runs is the type parameter chosen in `main()`.
7//
8// Run it as:
9//
10// example-portable-holdings kis
11// example-portable-holdings tossinvest [account-sequence]
12//
13// KIS reads its account from `DIR/kis/demo.json` (or `real.json` with `KIS_DEMO=0`) when
14// `ATL_CREDENTIALS_DIR` names a directory, and otherwise from `KIS_CANO` and the optional
15// `KIS_ACNT_PRDT_CD`; Toss discovers its accounts over the network and uses the
16// first one unless a sequence is supplied. Credentials come from the same
17// environment variables the other examples document, and no order is ever placed.
18
19#include "kis_credentials.hpp"
20
21#include <algotradelib/kis>
22#include <algotradelib/tossinvest>
23
24#include <boost/asio/ssl/context.hpp>
25
26#include <cstdlib>
27#include <exception>
28#include <iostream>
29#include <memory>
30#include <string>
31#include <string_view>
32#include <utility>
33
34namespace ssl = boost::asio::ssl;
35
36namespace {
37
38using algotradelib::BlockingSession;
39using algotradelib::BrokerCaps;
40using algotradelib::BrokerError;
41using algotradelib::HoldingsSnapshot;
42
44std::string mask_account_number(std::string_view account_number) {
45 if (account_number.size() <= 4) {
46 return std::string(account_number.size(), '*');
47 }
48 return std::string(account_number.size() - 4, '*') + std::string(account_number.substr(account_number.size() - 4));
49}
50
52void print_error(std::string_view operation, const BrokerError& error) {
53 std::cerr << operation << " failed";
54 if (!error.broker_code_.empty()) {
55 std::cerr << " [" << error.broker_code_ << ']';
56 }
57 if (error.http_status_ != 0) {
58 std::cerr << " HTTP " << error.http_status_;
59 }
60 if (!error.message_.empty()) {
61 std::cerr << ": " << error.message_;
62 }
63 if (error.retry_after_) {
64 std::cerr << " (retry after " << error.retry_after_->count() << "s)";
65 }
66 std::cerr << '\n';
67}
68
70void print_holdings(const HoldingsSnapshot& snapshot) {
71 std::cout << "positions: " << snapshot.positions_.size() << '\n';
72 for (const auto& position : snapshot.positions_) {
73 std::cout
74 << " " << position.instrument_.symbol_ << " " << position.name_ << " quantity=" << position.quantity_.str()
75 << " market=" << position.market_value_.amount_.str() << ' ' << position.market_value_.currency_.str() << '\n';
76 }
77 for (const auto& total : snapshot.totals_) {
78 std::cout
79 << " total " << total.currency_.str() << " purchase=" << total.purchase_value_.str()
80 << " market=" << total.market_value_.str() << " unrealized=" << total.unrealized_profit_loss_.str() << '\n';
81 }
82}
83
85template <typename Broker>
86void print_working_orders(const algotradelib::WorkingOrders<Broker>& orders) {
87 std::cout << "working orders: " << orders.orders_.size() << '\n';
88 for (const auto& working : orders.orders_) {
89 std::cout
90 << " " << working.order_.instrument_.symbol_ << " reference=" << working.ref_.str() << " ordered="
91 << working.order_.quantity_.str() << " filled=" << working.order_.execution_.filled_quantity_.str();
92 if (working.amendable_quantity_) {
93 std::cout << " amendable=" << working.amendable_quantity_->str();
94 } else {
95 std::cout << " amendable=not reported";
96 }
97 std::cout << '\n';
98 }
99}
100
108template <typename Client>
109int report(BlockingSession<Client>& session) {
110 using Caps = BrokerCaps<Client>;
111
112 std::cout << "broker: " << session.broker_name() << '\n';
113 std::cout << "reports an amendable quantity: " << (Caps::has_amendable_quantity ? "yes" : "no") << '\n';
114 std::cout << "accepts an idempotency key: " << (Caps::has_client_order_id ? "yes" : "no") << '\n';
115
116 auto holdings = session.holdings();
117 if (!holdings) {
118 print_error("holdings request", holdings.error());
119 return 1;
120 }
121 print_holdings(holdings.value());
122
123 if constexpr (Caps::has_working_orders) {
124 auto working = session.working_orders();
125 if (!working) {
126 // A failed inquiry is a run-time condition (a refused key, a closed host), not a missing
127 // feature, so the report continues instead of failing. On a KIS demo account the inquiry is
128 // answered from the day's order history.
129 print_error("working-order inquiry", working.error());
130 } else {
131 print_working_orders(working.value());
132 }
133 }
134
135 return 0;
136}
137
139int report_kis(ssl::context& tls) {
140 namespace kis = algotradelib::kis;
141
142 kis::KisConfig config;
143 kis::KisAccount account;
144 kis_credentials::load(kis_credentials::environment_directory(), config, &account, std::cout);
145
146 std::cout << "environment: " << (config.is_demo_ ? "demo" : "live") << '\n';
147
148 auto client = std::make_shared<kis::KisBlockingClient>(tls, std::move(config), kis_credentials::paced_options());
149 BlockingSession<kis::KisBlockingClient> session(std::move(client), std::move(account));
150 return report(session);
151}
152
154int report_tossinvest(ssl::context& tls, const char* requested_sequence) {
155 namespace toss = algotradelib::tossinvest;
156
157 toss::TossConfig config;
158 config.from_env();
159
160 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
161
162 std::int64_t sequence = 0;
163 if (requested_sequence) {
164 sequence = std::strtoll(requested_sequence, nullptr, 10);
165 } else {
166 auto accounts = algotradelib::list_accounts(*client);
167 if (!accounts) {
168 print_error("account discovery", accounts.error());
169 return 1;
170 }
171 if (accounts.value().empty()) {
172 std::cerr << "no Toss accounts are available for these credentials\n";
173 return 1;
174 }
175 for (const auto& account : accounts.value()) {
176 std::cout
177 << "account " << mask_account_number(account.display_number_) << " type=" << account.type_
178 << " sequence=" << account.selector_ << '\n';
179 }
180 sequence = accounts.value().front().selector_;
181 }
182
183 BlockingSession<toss::TossBlockingClient> session(std::move(client), sequence);
184 return report(session);
185}
186
187} // namespace
188
189int main(int argc, char** argv) {
190 const std::string broker = argc > 1 ? argv[1] : "";
191 if (broker != "kis" && broker != "tossinvest") {
192 std::cerr << "usage: example-portable-holdings <kis|tossinvest> [account-sequence]\n";
193 return 2;
194 }
195
196 try {
197 ssl::context tls(ssl::context::tls_client);
198 tls.set_default_verify_paths();
199 tls.set_verify_mode(ssl::verify_peer);
200
201 if (broker == "kis") {
202 return report_kis(tls);
203 }
204 return report_tossinvest(tls, argc > 2 ? argv[2] : nullptr);
205 } catch (const std::exception& exception) {
206 std::cerr << "example failed: " << exception.what() << '\n';
207 return 1;
208 }
209}
The examples' KIS credentials: one JSON file per account, or the environment.
void load(const std::optional< std::filesystem::path > &directory, algotradelib::kis::KisConfig &config, algotradelib::kis::KisAccount *account, std::ostream &out)
Loads the credentials (and account) KIS_DEMO chooses, and prints where from (a path or "environment v...
Result< std::vector< AccountInfo< Client > > > list_accounts(Client &client)
Lists a broker's accounts with a blocking client, before a session exists; requires BrokerCaps<Client...
std::vector< WorkingOrder< Broker > > orders_
The open orders.
Definition types.hpp:2606