algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-portable-market-data.cpp
1// One market-data report written once and compiled for two brokers, KIS and Toss.
2//
3// `report()` names no vendor type. Everything that differs between KIS and Toss
4// appears as an `if constexpr` on a capability, which is what the port is for: the
5// common questions are asked the same way, and each broker's own strengths are
6// reached deliberately rather than faked for the other.
7//
8// Run it as:
9//
10// example-portable-market-data kis 005930
11// example-portable-market-data tossinvest 005930 [account-sequence]
12//
13// Credentials come from the same environment variables the other examples document.
14// It reads market data only and can place no order.
15
16#include "kis_credentials.hpp"
17
18#include <algotradelib/kis>
19#include <algotradelib/tossinvest>
20
21#include <boost/asio/ssl/context.hpp>
22
23#include <cstdlib>
24#include <exception>
25#include <iostream>
26#include <memory>
27#include <string>
28#include <string_view>
29#include <utility>
30#include <vector>
31
32namespace ssl = boost::asio::ssl;
33
34namespace {
35
38using algotradelib::BarQuery;
39using algotradelib::BarSeries;
40using algotradelib::BlockingSession;
41using algotradelib::BrokerCaps;
42using algotradelib::BrokerError;
44using algotradelib::DepthSnapshot;
45using algotradelib::Instrument;
46using algotradelib::InstrumentId;
48using algotradelib::PriceLimits;
49using algotradelib::StatedDate;
50using algotradelib::TradingCalendar;
52
54void print_error(std::string_view operation, const BrokerError& error) {
55 std::cerr << " " << operation << " failed";
56 if (!error.broker_code_.empty()) {
57 std::cerr << " [" << error.broker_code_ << ']';
58 }
59 if (!error.message_.empty()) {
60 std::cerr << ": " << error.message_;
61 }
62 std::cerr << '\n';
63}
64
66void print_bars(const BarSeries& series) {
67 std::cout
68 << "bars: " << series.bars_.size() << ' ' << bar_interval_name(series.interval_)
69 << (series.adjusted_ ? " adjusted" : " raw") << ' ' << series.currency_.str() << ", stamped at each period's "
70 << (series.stamp_ == algotradelib::BarStamp::OPEN ? "open" : "close") << '\n';
71 if (series.bars_.empty()) {
72 return;
73 }
74 std::cout << " ascending: " << (series.ascending() ? "yes" : "no") << '\n';
75 for (const auto* bar : {&series.bars_.front(), &series.bars_.back()}) {
76 std::cout
77 << " " << (bar == &series.bars_.front() ? "oldest" : "newest") << " close=" << bar->close_.str() << " volume="
78 << bar->volume_.str() << " open=" << (bar->open_ ? bar->open_->str() : std::string("not reported")) << '\n';
79 }
80 if (series.next_cursor_) {
81 std::cout << " may continue from " << *series.next_cursor_ << '\n';
82 }
83}
84
86void print_depth(const DepthSnapshot& book) {
87 std::cout << "book: " << book.bids_.size() << " bids, " << book.asks_.size() << " asks\n";
88 const auto bid = book.best_bid();
89 const auto ask = book.best_ask();
90 std::cout
91 << " best bid: " << (bid ? bid->price_.str() : std::string("none"))
92 << " best ask: " << (ask ? ask->price_.str() : std::string("none")) << '\n';
93 const auto spread = book.spread();
94 const auto mid = book.mid();
95 std::cout
96 << " spread: " << (spread ? spread->str() : std::string("not both sides"))
97 << " mid: " << (mid ? mid->str() : std::string("not both sides")) << '\n';
98}
99
101void print_price_limits(const PriceLimits& limits) {
102 std::cout
103 << "price bounds: " << (limits.lower_ ? limits.lower_->str() : std::string("no lower limit")) << " .. "
104 << (limits.upper_ ? limits.upper_->str() : std::string("no upper limit")) << ' ' << limits.currency_.str() << '\n';
105}
106
108void print_instrument(const Instrument& instrument) {
109 std::cout << "instrument: " << instrument.name_;
110 if (!instrument.english_name_.empty()) {
111 std::cout << " (" << instrument.english_name_ << ')';
112 }
113 std::cout << "\n market: " << instrument.segment_.str();
114 if (!instrument.isin_.empty()) {
115 std::cout << " isin: " << instrument.isin_;
116 }
117 switch (instrument.listed_on_.state()) {
118 case StatedDate::State::STATED: {
119 const auto& listed = instrument.listed_on_.date();
120 std::cout << " listed: " << listed.year_ << '-' << listed.month_ << '-' << listed.day_;
121 break;
122 }
123 case StatedDate::State::UNREADABLE:
124 // The broker stated a date nobody can read, which is not the same as stating none.
125 std::cout << " listed: (unreadable)";
126 break;
127 case StatedDate::State::NOT_STATED:
128 break;
129 }
130 std::cout << '\n';
131 std::cout << " price grid: " << instrument.price_rule_.source_ << '\n';
132}
133
135void print_calendar(const TradingCalendar& calendar) {
136 std::cout << "calendar: " << calendar.days_.size() << " date(s) covered\n";
137 for (const auto& day : calendar.days_) {
138 std::cout
139 << " " << day.date_.year_ << '-' << day.date_.month_ << '-' << day.date_.day_
140 << (day.open_ ? " market opens" : " market closed") << '\n';
141 }
142}
143
150template <typename Client>
151int report(BlockingSession<Client>& session, const InstrumentId& subject) {
152 using Caps = BrokerCaps<Client>;
153
154 std::cout << "broker: " << session.broker_name() << "\n\n";
155
156 algotradelib::PriceRule reference_rule;
157 if (auto reference = session.instrument(subject)) {
158 print_instrument(reference.value());
159 reference_rule = reference.value().price_rule_;
160 } else {
161 print_error("reference data", reference.error());
162 }
163
164 BarQuery daily;
165 daily.instrument_ = subject;
166 daily.interval_ = BarInterval::ONE_DAY;
167 daily.count_ = 120;
168 if (auto bars = session.bars(daily)) {
169 print_bars(bars.value());
170 } else {
171 print_error("daily bars", bars.error());
172 }
173
174 if constexpr (Caps::supports_interval(BarInterval::ONE_WEEK)) {
175 // Only one broker publishes bars longer than a day. They are not aggregated for
176 // the other, because resampling answers a different question from the one asked.
177 BarQuery weekly = daily;
178 weekly.interval_ = BarInterval::ONE_WEEK;
179 weekly.count_ = 12;
180 if (auto bars = session.bars(weekly)) {
181 print_bars(bars.value());
182 } else {
183 print_error("weekly bars", bars.error());
184 }
185 } else {
186 std::cout << "bars: this broker publishes no period longer than a day\n";
187 }
188
189 if constexpr (Caps::has_depth) {
190 if (auto book = session.depth(subject)) {
191 print_depth(book.value());
192
193 // A computed price has to sit on the exchange's grid, and the grid is the
194 // library's own because no broker publishes one.
195 if (const auto mid = book.value().mid()) {
196 // The grid comes from the instrument: the adapter chose it from what the instrument is.
197 // An instrument whose ladder the library does not know refuses to round rather than guessing one.
198 const auto rule = reference_rule;
199 const auto buy = rule.round_to_tick(*mid, OrderSide::BUY);
200 std::cout
201 << " a buy at the midpoint would rest at "
202 << (buy ? buy->str() : std::string("no grid known for this instrument")) << '\n';
203 }
204 } else {
205 print_error("order book", book.error());
206 }
207 }
208
209 if constexpr (Caps::has_price_limits) {
210 if (auto limits = session.price_limits(subject)) {
211 print_price_limits(limits.value());
212 } else {
213 print_error("price bounds", limits.error());
214 }
215 }
216
217 if constexpr (Caps::has_trade_prints) {
218 if (auto prints = session.trades(subject, 5)) {
219 std::cout << "recent executions: " << prints.value().size() << '\n';
220 for (const auto& print : prints.value()) {
221 std::cout << " " << print.price_.str() << " x " << print.quantity_.str() << '\n';
222 }
223 } else {
224 print_error("recent executions", prints.error());
225 }
226 }
227
228 if constexpr (Caps::has_batch_prices) {
229 // One request for several instruments, where the broker offers it. Looping
230 // single quotes instead would spend several times the request budget.
231 if (auto quotes = session.prices({subject})) {
232 std::cout << "batch quotes: " << quotes.value().size() << '\n';
233 } else {
234 print_error("batch quotes", quotes.error());
235 }
236 } else {
237 std::cout << "batch quotes: this broker quotes one instrument per request\n";
238 }
239
240 if constexpr (Caps::has_calendar) {
241 if (auto calendar = session.calendar(subject.country_)) {
242 print_calendar(calendar.value());
243 if constexpr (!Caps::has_calendar_range) {
244 std::cout << " one request covers the requested day and the ones either side\n";
245 }
246 } else {
247 print_error("calendar", calendar.error());
248 }
249 }
250
251 if constexpr (Caps::has_calendar_sessions) {
252 std::cout
253 << "sessions: this adapter fills each open day's session hours, and a live loop takes the market "
254 << "phase from them\n";
255 }
256
257 return 0;
258}
259
261int report_kis(ssl::context& tls, const std::string& symbol) {
262 namespace kis = algotradelib::kis;
263
264 kis::KisConfig config;
265 kis::KisAccount account;
266 kis_credentials::load(kis_credentials::environment_directory(), config, &account, std::cout);
267
268 auto client = std::make_shared<kis::KisBlockingClient>(tls, std::move(config), kis_credentials::paced_options());
269 BlockingSession<kis::KisBlockingClient> session(std::move(client), std::move(account));
270 return report(session, InstrumentId{Country::KR, Venue::COMBINED, symbol});
271}
272
274int report_tossinvest(ssl::context& tls, const std::string& symbol, const char* sequence) {
275 namespace toss = algotradelib::tossinvest;
276
277 toss::TossConfig config;
278 config.from_env();
279 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
280
281 std::int64_t selected = 0;
282 if (sequence) {
283 selected = std::strtoll(sequence, nullptr, 10);
284 } else {
285 auto accounts = algotradelib::list_accounts(*client);
286 if (!accounts) {
287 print_error("account discovery", accounts.error());
288 return 1;
289 }
290 if (accounts.value().empty()) {
291 std::cerr << "no Toss accounts are available for these credentials\n";
292 return 1;
293 }
294 selected = accounts.value().front().selector_;
295 }
296
297 BlockingSession<toss::TossBlockingClient> session(std::move(client), selected);
298 return report(session, InstrumentId{Country::KR, Venue::COMBINED, symbol});
299}
300
301} // namespace
302
303int main(int argc, char** argv) {
304 const std::string broker = argc > 1 ? argv[1] : "";
305 if (broker != "kis" && broker != "tossinvest") {
306 std::cerr << "usage: example-portable-market-data <kis|tossinvest> [symbol] [account-sequence]\n";
307 return 2;
308 }
309 const std::string symbol = argc > 2 ? argv[2] : "005930";
310
311 try {
312 ssl::context tls(ssl::context::tls_client);
313 tls.set_default_verify_paths();
314 tls.set_verify_mode(ssl::verify_peer);
315
316 if (broker == "kis") {
317 return report_kis(tls, symbol);
318 }
319 return report_tossinvest(tls, symbol, argc > 3 ? argv[3] : nullptr);
320 } catch (const std::exception& exception) {
321 std::cerr << "example failed: " << exception.what() << '\n';
322 return 1;
323 }
324}
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...
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
Definition concept.hpp:309
@ OPEN
The timestamp is the first instant of the period.
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...
constexpr std::string_view bar_interval_name(BarInterval interval) noexcept
Returns a short name for an interval, such as "1m", "5m", "1h" or "1d".
Country
A country (market) the library supports.
Definition types.hpp:32
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
BarInterval
The period one bar covers.
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
std::optional< Decimal64 > round_to_tick(const Decimal64 &price, OrderSide side) const
Rounds a price to its band's tick in the order's favour: a buy rounds down, a sell up.