algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-strategy-live.cpp
1// One strategy, compiled for KIS and Toss from this one source, bound at a single line in `main`.
2//
3// The point, demonstrated: `trade()` below names no broker. It takes a session
4// by template parameter, and everything broker-specific is either behind a capability gate or
5// inside the adapter. Swapping KIS for Toss changes which overload `main` calls, nothing else.
6//
7// **It can place real orders.** Three modes, and only the last one trades:
8//
9// --dry-run no session at all, bars built in code, no credentials needed
10// (default) a real session for market data, but the send step goes to an executor that holds
11// no session, so there is nothing for an order to be sent through
12// --live the send step goes to the bound session
13//
14// Run it as:
15//
16// example-strategy-live --dry-run
17// example-strategy-live kis 005930 [--live]
18// example-strategy-live tossinvest 005930 [account-sequence] [--live]
19//
20// Credentials come from the same environment variables the other examples document. Without
21// `--live` a bound session still only *reads*: it fetches bars and prints what it would do.
22//
23// **On interrupting it.** A `Ctrl+C` stops this program, and that is all it does. An order the broker
24// already accepted stays live on the exchange, which knows nothing about a process that died -- and an
25// order *in flight* at that moment never reaches the classification that would have recorded its
26// outcome as unknown, because the default signal handler terminates immediately. So after
27// interrupting a `--live` run, read the broker's order list before running it again. This example
28// places at most one order per run, which bounds what can be in doubt to that one.
29//
30// **On running it again.** Each run reads the open orders before the holdings, so a buy still waiting
31// to fill counts toward the one-share limit. A buy that has filled but does not show in the holdings
32// yet is in neither, and is bought again: wait until the holdings show it. Never run two at once.
33
34#include "kis_credentials.hpp"
35
36#include <algotradelib/kis>
37#include <algotradelib/krx>
38#include <algotradelib/live>
39#include <algotradelib/tossinvest>
40
41#include <boost/asio/ssl/context.hpp>
42
43#include <chrono>
44#include <cstddef>
45#include <cstdlib>
46#include <exception>
47#include <iostream>
48#include <memory>
49#include <string>
50#include <string_view>
51#include <utility>
52#include <vector>
53
54namespace ssl = boost::asio::ssl;
55
56namespace {
57
58namespace strategy = algotradelib::strategy;
59namespace runner = algotradelib::runner;
60namespace live = algotradelib::live;
61
63using algotradelib::BarQuery;
64using algotradelib::BlockingSession;
66using algotradelib::Decimal64;
67using algotradelib::InstrumentId;
70
72enum class Mode {
78 OBSERVE,
80 TRADE,
81};
82
89struct HoldsShares {
91 InstrumentId instrument_;
93 Decimal64 quantity_;
94
95 template <class Ctx>
96 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
97 if (!(bar.instrument_ == instrument_)) {
98 return;
99 }
100 strategy::TargetPosition target;
101 target.instrument_ = instrument_;
102 target.target_quantity_ = quantity_;
103 target.tag_ = "hold";
104 ctx.submit(target);
105 }
106};
107
109HoldsShares strategy_for(const InstrumentId& instrument) {
110 return HoldsShares{instrument, Decimal64::parse("1")};
111}
112
114strategy::RiskLimits example_limits() {
115 strategy::RiskLimits limits;
116 // One share of a Korean blue chip is well under this, so a configuration mistake that asked for
117 // a hundred is refused rather than filled.
118 limits.max_order_notional_ = Decimal64::parse("500000");
119 limits.max_position_quantity_ = Decimal64::parse("1");
120 limits.max_orders_per_window_ = 2;
121 return limits;
122}
123
132struct MarketState {
133 algotradelib::Instrument reference_;
134 algotradelib::BarSeries bars_;
135 algotradelib::HoldingsSnapshot holdings_;
136};
137
145template <typename Tag, typename R>
146int drive(
147 const InstrumentId& instrument, const MarketState& state, const algotradelib::WorkingOrders<Tag>& open_orders,
148 R live_runner
149) {
150 live_runner.context().set_instrument(state.reference_);
151 // A single pass driven by hand, so the phase is this program's to state: only
152 // `runner::PollingLoop` computes one, from a session window and a polled calendar. A program that
153 // runs continuously uses the loop and does not set this at all -- see `example-live-loop.cpp`.
154 live_runner.context().set_phase(strategy::MarketPhase::OPEN);
155
156 strategy::Portfolio<Tag> portfolio;
157 portfolio.positions_ = state.holdings_.positions_;
158 // **Stamped with when the broker's answer arrived, and that is not optional.** A runner bound to a
159 // session refuses to size an order against a portfolio it cannot date: an unstamped one reads as
160 // an account nobody has read, and an empty account is the permissive answer to every ceiling.
161 // Copying the rows without the timestamp is the mistake this line exists to prevent.
162 portfolio.as_of_ = state.holdings_.received_at_;
163 // **And the orders still open, with when they were listed.** Without them a buy that is still
164 // waiting to fill is invisible, and the runner buys again past `max_position_quantity_`.
165 portfolio.working_ = open_orders.orders_;
166 portfolio.working_as_of_ = open_orders.received_at_;
167 // **And with what the broker's sellable figures are evidence of, for the same reason.** A guard
168 // enforcing `enforce_sellable_quantity_` refuses a figure whose coverage nobody stated, so a hand-
169 // built portfolio that copies the rows without this refuses every sell -- and one that invented an
170 // enforceable basis would measure a sale against a number it had not characterized. Copy it; do not
171 // construct it. The limit is on by default, so without this line every sell here would be refused.
172 portfolio.sellable_basis_ = state.holdings_.sellable_basis_;
173 live_runner.context().set_portfolio(std::move(portfolio));
174
175 const auto& last = state.bars_.bars_.back();
176 live_runner.context().set_last_price(instrument, last.close_);
177 // A runner driven by hand starts its strategy before the first feed.
178 live_runner.start();
179 const auto report =
180 live_runner.feed(strategy::make_bar_event(instrument, state.bars_.interval_, state.bars_.stamp_, last));
181
182 for (const auto& order : report.would_place_) {
183 std::cout
184 << "order: " << (order.side_ == OrderSide::BUY ? "BUY " : "SELL") << ' ' << order.quantity_.str() << " at "
185 << (order.price_ ? order.price_->str() : std::string("market")) << '\n';
186 }
187 for (const auto& refusal : report.refused_) {
188 std::cout << "refused by a guard: " << strategy::guard_reason_name(refusal.reason_) << '\n';
189 }
190 for (const auto& rejection : report.rejected_) {
191 // Not always "could not build": the bucket also holds a broker's refusal and one this binding
192 // made without asking a broker, and the reason on the entry is what says which.
193 std::cout << "not placed: " << strategy::reject_reason_name(rejection.reason_) << '\n';
194 }
195 for (const auto& held : report.withheld_) {
196 std::cout << "withheld pending reconciliation: " << held.detail_ << '\n';
197 }
198 for (const auto& order : report.indeterminate_) {
199 std::cout
200 << "UNKNOWN OUTCOME for " << order.instrument_.symbol_
201 << ": read the broker's order list before trading it again\n";
202 }
203 if (report.quiet()) {
204 std::cout << "the strategy asked for nothing: the target is already met\n";
205 }
206 if (!live_runner.ledger().empty()) {
207 std::cout << "\nreconciliation required before this instrument may be traded again\n";
208 return 1;
209 }
210 return 0;
211}
212
214void note_interruption_hazard() {
215 std::cout
216 << "\nnote: interrupting a live run does not withdraw an accepted order, and an order in\n"
217 << " flight at that moment leaves no record that its outcome is unknown. Read the\n"
218 << " broker's order list before running again, and wait until the holdings show any\n"
219 << " fill: a filled buy they do not show yet is bought again.\n";
220}
221
235template <typename Session>
236int trade(Session& session, const InstrumentId& instrument, Mode mode) {
237 using Caps = typename Session::Caps;
238 using Tag = typename Session::BrokerTag;
239
240 std::cout
241 << "broker: " << Tag::name << " instrument: " << instrument.symbol_
242 << " mode: " << (mode == Mode::TRADE ? "TRADE" : "observe") << "\n\n";
243
244 if constexpr (Caps::has_client_order_id) {
245 std::cout << "this broker accepts an idempotency key, so a retry could be made safe\n";
246 } else {
247 std::cout << "this broker accepts no idempotency key, so no order is ever replayed\n";
248 }
249
250 MarketState state;
251
252 // Reference data first: without a tick grid and a lot size there is nothing reconciliation can
253 // build, and it would refuse every order by name.
254 auto reference = session.instrument(instrument);
255 if (!reference) {
256 std::cerr << "could not read reference data: " << reference.error().message_ << '\n';
257 return 1;
258 }
259 state.reference_ = std::move(reference.value());
260
261 BarQuery query;
262 query.instrument_ = instrument;
263 query.interval_ = BarInterval::ONE_DAY;
264 query.count_ = 30;
265 auto bars = session.bars(query);
266 if (!bars) {
267 std::cerr << "could not read bars: " << bars.error().message_ << '\n';
268 return 1;
269 }
270 if (bars.value().bars_.empty()) {
271 std::cerr << "the broker returned no bars\n";
272 return 1;
273 }
274 state.bars_ = std::move(bars.value());
275
276 // **Open orders before holdings.** An order that fills between the two reads then shows in the
277 // holdings. Read the other way round, it would be in neither.
278 algotradelib::WorkingOrders<Tag> open_orders;
279 if constexpr (Caps::has_working_orders) {
280 auto listed = session.working_orders();
281 if (!listed) {
282 std::cerr << "could not read open orders: " << listed.error().message_ << '\n';
283 return 1;
284 }
285 open_orders = std::move(listed.value());
286 } else {
287 if (mode == Mode::TRADE) {
288 std::cerr
289 << "this broker lists no open orders, so a live run could not see an earlier order still waiting to fill; use example-live-program\n";
290 return 1;
291 }
292 }
293
294 auto holdings = session.holdings();
295 if (!holdings) {
296 std::cerr << "could not read holdings: " << holdings.error().message_ << '\n';
297 return 1;
298 }
299 state.holdings_ = std::move(holdings.value());
300
301 // One line per mode. The factories read the capabilities and the tag off the session, so the two
302 // runners differ in exactly one thing -- where the send goes -- and cannot differ in any other.
303 if (mode == Mode::TRADE) {
304 const auto status =
305 drive<Tag>(instrument, state, open_orders, live::bind(session, strategy_for(instrument), example_limits()));
306 note_interruption_hazard();
307 return status;
308 }
309 return drive<Tag>(
310 instrument, state, open_orders, live::bind_observer(session, strategy_for(instrument), example_limits())
311 );
312}
313
314int trade_kis(ssl::context& tls, const std::string& symbol, Mode mode) {
315 namespace kis = algotradelib::kis;
316
317 kis::KisConfig config;
318 kis::KisAccount account;
319 kis_credentials::load(kis_credentials::environment_directory(), config, &account, std::cout);
320
321 auto client = std::make_shared<kis::KisBlockingClient>(tls, std::move(config), kis_credentials::paced_options());
322 BlockingSession<kis::KisBlockingClient> session(std::move(client), std::move(account));
323 return trade(session, InstrumentId{Country::KR, Venue::COMBINED, symbol}, mode);
324}
325
326int trade_tossinvest(ssl::context& tls, const std::string& symbol, const char* sequence, Mode mode) {
327 namespace toss = algotradelib::tossinvest;
328
329 toss::TossConfig config;
330 config.from_env();
331 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
332
333 // Toss selects an account by sequence number and publishes the list, so an unstated one is
334 // discovered rather than guessed. KIS takes the account from the environment instead, which is
335 // exactly the kind of difference the port leaves to the adapter.
336 std::int64_t selected = 0;
337 if (sequence != nullptr) {
338 selected = std::strtoll(sequence, nullptr, 10);
339 } else {
340 auto accounts = algotradelib::list_accounts(*client);
341 if (!accounts) {
342 std::cerr << "account discovery failed: " << accounts.error().message_ << '\n';
343 return 1;
344 }
345 if (accounts.value().empty()) {
346 std::cerr << "no Toss accounts are available for these credentials\n";
347 return 1;
348 }
349 selected = accounts.value().front().selector_;
350 }
351
352 BlockingSession<toss::TossBlockingClient> session(std::move(client), selected);
353 return trade(session, InstrumentId{Country::KR, Venue::COMBINED, symbol}, mode);
354}
355
357int trade_dry(const std::string& symbol) {
358 const InstrumentId instrument{Country::KR, Venue::COMBINED, symbol};
359 std::cout << "no broker bound: nothing in this path can reach a market\n\n";
360
361 runner::DryRunner<HoldsShares> dry(strategy_for(instrument), example_limits());
362 algotradelib::Instrument reference;
363 reference.id_ = instrument;
364 reference.type_ = algotradelib::SecurityType::STOCK;
365 reference.currency_ = algotradelib::Currency{"KRW"};
366 reference.lot_size_ = Decimal64::parse("1");
368 dry.context().set_instrument(reference);
369 dry.context().set_phase(strategy::MarketPhase::OPEN);
370 dry.context().set_last_price(instrument, Decimal64::parse("70000"));
371
372 algotradelib::Bar bar;
373 bar.timestamp_ = std::chrono::system_clock::now();
374 bar.high_ = Decimal64::parse("70500");
375 bar.low_ = Decimal64::parse("69400");
376 bar.close_ = Decimal64::parse("70000");
377 bar.volume_ = Decimal64::parse("1200000");
378
379 dry.start();
380 const auto report =
381 dry.feed(strategy::make_bar_event(instrument, BarInterval::ONE_DAY, algotradelib::BarStamp::CLOSE, bar));
382 for (const auto& order : report.would_place_) {
383 std::cout
384 << "would send: " << (order.side_ == OrderSide::BUY ? "BUY " : "SELL") << ' ' << order.quantity_.str()
385 << " at market\n";
386 }
387 return 0;
388}
389
390} // namespace
391
392int main(int argc, char** argv) {
393 std::vector<std::string> arguments(argv + 1, argv + argc);
394 Mode mode = Mode::OBSERVE;
395 bool dry = false;
396 std::vector<std::string> positional;
397 for (const auto& argument : arguments) {
398 if (argument == "--live") {
399 mode = Mode::TRADE;
400 } else if (argument == "--dry-run") {
401 dry = true;
402 } else if (argument.rfind("--", 0) == 0) {
403 // An option this program does not know is refused, never read as a positional argument: a
404 // mistyped or unsupported flag beside `--live` must not leave the run trading as if it were absent.
405 std::cerr
406 << "example-strategy-live: unknown option " << argument
407 << " (credentials come from the environment or ATL_CREDENTIALS_DIR)\n";
408 return 2;
409 } else {
410 positional.push_back(argument);
411 }
412 }
413
414 const std::string symbol = positional.size() > 1 ? positional[1] : "005930";
415 if (dry) {
416 return trade_dry(symbol);
417 }
418
419 const std::string broker = positional.empty() ? "" : positional[0];
420 if (broker != "kis" && broker != "tossinvest") {
421 std::cerr
422 << "usage: example-strategy-live --dry-run\n"
423 << " example-strategy-live <kis|tossinvest> [symbol] [account-sequence] [--live]\n\n"
424 << "Without --live the session is used for market data only: the send step goes to an\n"
425 << "executor that holds no session, so there is nothing for an order to be sent through.\n";
426 return 2;
427 }
428
429 try {
430 ssl::context tls(ssl::context::tls_client);
431 tls.set_default_verify_paths();
432 tls.set_verify_mode(ssl::verify_peer);
433
434 if (broker == "kis") {
435 return trade_kis(tls, symbol, mode);
436 }
437 return trade_tossinvest(tls, symbol, positional.size() > 2 ? positional[2].c_str() : nullptr, mode);
438 } catch (const std::exception& exception) {
439 std::cerr << "example failed: " << exception.what() << '\n';
440 return 1;
441 }
442}
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...
Exit trade(Session &session, MarketData &market_data, Strategy strategy_instance, const Settings &settings, runner::StopSource &stop, std::ostream &out, Clock clock={})
Trades a strategy through a session, reading market data and reference data from another.
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
Definition krx.hpp:12
Runner< Strategy, CapsType, DryTag, RecordingExecutor< DryTag > > DryRunner
A runner that sends nothing: handlers fire and instructions are recorded by a RecordingExecutor.
Definition runner.hpp:5791
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
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
Definition event.hpp:380
@ OPEN
Inside the session.
Definition event.hpp:46
constexpr std::string_view reject_reason_name(RejectReason reason) noexcept
Returns a lowercase name for a reason, such as "no_reference_data", for logs.
constexpr std::string_view guard_reason_name(GuardReason reason) noexcept
Returns a lowercase name for a refusal reason, such as "order_rate_exceeded", for logs.
Definition risk.hpp:258
@ CLOSE
The timestamp is the instant the period ended.
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...
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
BarInterval interval_
The period each bar covers.
BarStamp stamp_
Which edge of its period each bar's timestamp marks.
std::vector< Bar > bars_
The bars, oldest first.
std::chrono::system_clock::time_point received_at_
When this process received the snapshot (brokers do not timestamp holdings).
Definition types.hpp:1351
SellableBasis sellable_basis_
What the rows' sellable_quantity_ figures cover (unless a row carries its own).
Definition types.hpp:1358
std::vector< HoldingPosition > positions_
Every position row; one instrument may appear in more than one.
Definition types.hpp:1347
Currency currency_
The currency it trades in.
InstrumentId id_
The instrument.
PriceRule price_rule_
The price grid, set by the adapter or the caller; kind UNKNOWN where it has no table.
std::optional< Decimal64 > lot_size_
The order quantity increment, if the broker publishes one.
SecurityType type_
The kind of security.
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
std::vector< WorkingOrder< Broker > > working_
Orders still outstanding at the broker.
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::chrono::system_clock::time_point working_as_of_
When the working-order listing was received, on the same clock as as_of_.
std::chrono::system_clock::time_point as_of_
When the holdings were received, on this machine's clock.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
Definition portfolio.hpp:88
std::optional< Decimal64 > max_position_quantity_
The largest absolute position, in shares, any instrument may reach.
Definition risk.hpp:421
std::optional< std::size_t > max_orders_per_window_
The most orders that may be sent within rate_window_.
Definition risk.hpp:437
std::optional< Decimal64 > max_order_notional_
The largest value one order may have, in its own currency.
Definition risk.hpp:414
InstrumentId instrument_
The instrument.
Definition intent.hpp:453
std::string tag_
A label carried to the orders and their fills.
Definition intent.hpp:459
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.
Definition intent.hpp:455