36#include <algotradelib/kis>
37#include <algotradelib/krx>
38#include <algotradelib/live>
39#include <algotradelib/tossinvest>
41#include <boost/asio/ssl/context.hpp>
54namespace ssl = boost::asio::ssl;
58namespace strategy = algotradelib::strategy;
59namespace runner = algotradelib::runner;
60namespace live = algotradelib::live;
63using algotradelib::BarQuery;
64using algotradelib::BlockingSession;
66using algotradelib::Decimal64;
67using algotradelib::InstrumentId;
91 InstrumentId instrument_;
96 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
97 if (!(
bar.instrument_ == instrument_)) {
100 strategy::TargetPosition target;
103 target.
tag_ =
"hold";
109HoldsShares strategy_for(
const InstrumentId& instrument) {
110 return HoldsShares{instrument, Decimal64::parse(
"1")};
114strategy::RiskLimits example_limits() {
115 strategy::RiskLimits limits;
133 algotradelib::Instrument reference_;
134 algotradelib::BarSeries bars_;
135 algotradelib::HoldingsSnapshot holdings_;
145template <
typename Tag,
typename R>
147 const InstrumentId& instrument,
const MarketState& state,
const algotradelib::WorkingOrders<Tag>& open_orders,
150 live_runner.context().set_instrument(state.reference_);
156 strategy::Portfolio<Tag> portfolio;
173 live_runner.context().set_portfolio(std::move(portfolio));
175 const auto& last = state.bars_.
bars_.back();
176 live_runner.context().set_last_price(instrument, last.close_);
182 for (
const auto& order : report.would_place_) {
184 <<
"order: " << (order.side_ == OrderSide::BUY ?
"BUY " :
"SELL") <<
' ' << order.quantity_.str() <<
" at "
185 << (order.price_ ? order.price_->str() : std::string(
"market")) <<
'\n';
187 for (
const auto& refusal : report.refused_) {
190 for (
const auto& rejection : report.rejected_) {
195 for (
const auto& held : report.withheld_) {
196 std::cout <<
"withheld pending reconciliation: " << held.detail_ <<
'\n';
198 for (
const auto& order : report.indeterminate_) {
200 <<
"UNKNOWN OUTCOME for " << order.instrument_.symbol_
201 <<
": read the broker's order list before trading it again\n";
203 if (report.quiet()) {
204 std::cout <<
"the strategy asked for nothing: the target is already met\n";
206 if (!live_runner.ledger().empty()) {
207 std::cout <<
"\nreconciliation required before this instrument may be traded again\n";
214void note_interruption_hazard() {
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";
235template <
typename Session>
236int trade(Session& session,
const InstrumentId& instrument, Mode mode) {
237 using Caps =
typename Session::Caps;
238 using Tag =
typename Session::BrokerTag;
241 <<
"broker: " << Tag::name <<
" instrument: " << instrument.symbol_
242 <<
" mode: " << (mode == Mode::TRADE ?
"TRADE" :
"observe") <<
"\n\n";
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";
247 std::cout <<
"this broker accepts no idempotency key, so no order is ever replayed\n";
254 auto reference = session.instrument(instrument);
256 std::cerr <<
"could not read reference data: " << reference.error().message_ <<
'\n';
259 state.reference_ = std::move(reference.value());
262 query.instrument_ = instrument;
263 query.interval_ = BarInterval::ONE_DAY;
265 auto bars = session.bars(query);
267 std::cerr <<
"could not read bars: " <<
bars.error().message_ <<
'\n';
270 if (
bars.value().bars_.empty()) {
271 std::cerr <<
"the broker returned no bars\n";
274 state.bars_ = std::move(
bars.value());
278 algotradelib::WorkingOrders<Tag> open_orders;
279 if constexpr (Caps::has_working_orders) {
280 auto listed = session.working_orders();
282 std::cerr <<
"could not read open orders: " << listed.error().message_ <<
'\n';
285 open_orders = std::move(listed.value());
287 if (mode == Mode::TRADE) {
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";
294 auto holdings = session.holdings();
296 std::cerr <<
"could not read holdings: " << holdings.error().message_ <<
'\n';
299 state.holdings_ = std::move(holdings.value());
303 if (mode == Mode::TRADE) {
305 drive<Tag>(instrument, state, open_orders, live::bind(session, strategy_for(instrument), example_limits()));
306 note_interruption_hazard();
310 instrument, state, open_orders, live::bind_observer(session, strategy_for(instrument), example_limits())
314int trade_kis(ssl::context& tls,
const std::string& symbol, Mode mode) {
315 namespace kis = algotradelib::kis;
317 kis::KisConfig config;
318 kis::KisAccount account;
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);
326int trade_tossinvest(ssl::context& tls,
const std::string& symbol,
const char* sequence, Mode mode) {
327 namespace toss = algotradelib::tossinvest;
329 toss::TossConfig config;
331 auto client = std::make_shared<toss::TossBlockingClient>(tls, std::move(config));
336 std::int64_t selected = 0;
337 if (sequence !=
nullptr) {
338 selected = std::strtoll(sequence,
nullptr, 10);
342 std::cerr <<
"account discovery failed: " << accounts.error().message_ <<
'\n';
345 if (accounts.value().empty()) {
346 std::cerr <<
"no Toss accounts are available for these credentials\n";
349 selected = accounts.value().front().selector_;
352 BlockingSession<toss::TossBlockingClient> session(std::move(client), selected);
353 return trade(session, InstrumentId{Country::KR, Venue::COMBINED, symbol}, mode);
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";
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);
370 dry.context().set_last_price(instrument, Decimal64::parse(
"70000"));
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");
382 for (
const auto& order : report.would_place_) {
384 <<
"would send: " << (order.side_ == OrderSide::BUY ?
"BUY " :
"SELL") <<
' ' << order.quantity_.str()
392int main(
int argc,
char** argv) {
393 std::vector<std::string> arguments(argv + 1, argv + argc);
394 Mode mode = Mode::OBSERVE;
396 std::vector<std::string> positional;
397 for (
const auto& argument : arguments) {
398 if (argument ==
"--live") {
400 }
else if (argument ==
"--dry-run") {
402 }
else if (argument.rfind(
"--", 0) == 0) {
406 <<
"example-strategy-live: unknown option " << argument
407 <<
" (credentials come from the environment or ATL_CREDENTIALS_DIR)\n";
410 positional.push_back(argument);
414 const std::string symbol = positional.size() > 1 ? positional[1] :
"005930";
416 return trade_dry(symbol);
419 const std::string broker = positional.empty() ?
"" : positional[0];
420 if (broker !=
"kis" && broker !=
"tossinvest") {
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";
430 ssl::context tls(ssl::context::tls_client);
431 tls.set_default_verify_paths();
432 tls.set_verify_mode(ssl::verify_peer);
434 if (broker ==
"kis") {
435 return trade_kis(tls, symbol, mode);
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';
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).
Runner< Strategy, CapsType, DryTag, RecordingExecutor< DryTag > > DryRunner
A runner that sends nothing: handlers fire and instructions are recorded by a RecordingExecutor.
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
@ OPEN
Inside the session.
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.
@ 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.
Venue
A trading venue: an exchange, or the combined view across exchanges.
BarInterval
The period one bar covers.
OrderSide
The side of an order: its economic direction, buy or sell.
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).
SellableBasis sellable_basis_
What the rows' sellable_quantity_ figures cover (unless a row carries its own).
std::vector< HoldingPosition > positions_
Every position row; one instrument may appear in more than one.
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.
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
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.
std::optional< Decimal64 > max_position_quantity_
The largest absolute position, in shares, any instrument may reach.
std::optional< std::size_t > max_orders_per_window_
The most orders that may be sent within rate_window_.
std::optional< Decimal64 > max_order_notional_
The largest value one order may have, in its own currency.
InstrumentId instrument_
The instrument.
std::string tag_
A label carried to the orders and their fills.
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.