64#include <algotradelib/kis>
65#include <algotradelib/kiwoom>
66#include <algotradelib/network>
67#include <algotradelib/tossinvest>
69#include <boost/asio/ssl/context.hpp>
85namespace ssl = boost::asio::ssl;
95 std::optional<std::string> journal_;
96 std::optional<std::string> control_;
97 std::optional<std::int64_t> toss_account_;
98 std::optional<std::filesystem::path> credentials_;
99 bool credentials_from_flag_{
false};
100 std::optional<std::string> market_data_;
101 std::optional<std::string> kiwoom_account_;
102 std::optional<std::string> tokens_;
113 atl::InstrumentId instrument_;
115 atl::Decimal64 quantity_;
118 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
119 if (!(
bar.instrument_ == instrument_)) {
122 strategy::TargetPosition target;
125 target.
tag_ =
"hold";
170std::string file_safe(std::string text) {
171 for (
auto& ch : text) {
172 if (!std::isalnum(
static_cast<unsigned char>(ch)) && ch !=
'-') {
188 const std::string& account
190 settings.
journal_scope_ = broker +
':' + (demo ?
"demo" :
"live") +
':' + account;
191 const std::string stem =
"atl-" + broker +
'-' + (demo ?
"demo" :
"live") +
'-' + file_safe(account);
192 settings.
journal_path_ = arguments.journal_ ? *arguments.journal_ : stem +
".jsonl";
193 settings.
control_file_ = arguments.control_ ? *arguments.control_ : stem +
".stop";
204 std::cout <<
"broker : " << arguments.broker_ << (demo ?
" (demo)" :
" (LIVE ACCOUNT)") <<
'\n';
207 if (demo && demo_variable !=
nullptr && std::getenv(demo_variable) ==
nullptr) {
208 std::cout <<
" demo by default; set " << demo_variable <<
"=0 to trade live\n";
211 <<
"instrument : " << arguments.symbol_ <<
'\n'
212 <<
"mode : " << (arguments.live_ ?
"TRADE -- orders will be sent" :
"observe") <<
'\n'
218 if (arguments.live_) {
224std::shared_ptr<atl::network::TokenStore> token_store(
const Arguments& arguments) {
229 return std::make_shared<atl::network::FileTokenStore>(arguments.tokens_ ? *arguments.tokens_ :
"atl-tokens");
234std::shared_ptr<atl::network::CalendarCache> calendar_cache(
const Arguments& arguments) {
239 const std::filesystem::path tokens = arguments.tokens_ ? *arguments.tokens_ :
"atl-tokens";
240 return std::make_shared<atl::network::FileCalendarCache>((tokens.parent_path() /
"atl-calendars").string());
245template <
typename Session,
typename MarketData>
252 const auto exit = live ?
253 live_program::trade(session, market_data, strategy_for(instrument), settings, stop, std::cout) :
254 live_program::
observe(session, market_data, strategy_for(instrument), settings,
stop, std::cout);
256 return static_cast<int>(exit);
260template <
typename Session>
262 return run(session, session, instrument, settings, live);
265int run_kis(ssl::context& tls,
const Arguments& arguments) {
268 kis::KisConfig config;
269 kis::KisAccount account;
271 const bool demo = config.is_demo_;
273 const atl::InstrumentId instrument{atl::Country::KR, atl::Venue::COMBINED, arguments.symbol_};
274 auto settings = settings_for(instrument);
275 name_journal(settings, arguments,
"kis", demo, account.account_number_ +
'-' + account.product_code_);
276 announce(arguments, settings, demo,
"KIS_DEMO");
278 const auto tokens = token_store(arguments);
279 const auto calendars = calendar_cache(arguments);
281 std::make_shared<kis::KisBlockingClient>(
289 if (arguments.market_data_ ==
"toss") {
293 throw std::runtime_error(
"--market-data toss is for a KIS demo run only");
295 if (!arguments.credentials_) {
296 throw std::runtime_error(
"--market-data toss reads tossinvest/real.json; give --credentials DIR");
298 const auto path = *arguments.credentials_ /
"tossinvest" /
"real.json";
302 std::make_shared<algotradelib::tossinvest::TossBlockingClient>(
307 std::cout <<
"market data: toss " << path.string() <<
" (no account: cannot trade)\n";
308 return run(session, market_data, instrument, settings, arguments.live_);
310 if (!demo && arguments.market_data_ ==
"kis") {
311 throw std::runtime_error(
"--market-data kis is for a demo run; a live run reads its own market data");
317 std::make_shared<kis::KisBlockingClient>(
323 <<
"market data: kis " << (*arguments.credentials_ /
"kis" /
"real.json").
string()
324 <<
" (no account: cannot trade)\n";
325 return run(session, market_data, instrument, settings, arguments.live_);
327 if (arguments.market_data_ ==
"kis") {
328 throw std::runtime_error(
329 arguments.credentials_ ?
330 "--market-data kis reads kis/real.json, and there is none" :
331 "--market-data kis reads kis/real.json; give --credentials DIR"
335 <<
"market data: the demo account's own (no kis/real.json); a demo host refuses\n"
336 <<
" reference data, so this run stops there\n";
338 return run(session, instrument, settings, arguments.live_);
341int run_kiwoom(ssl::context& tls,
const Arguments& arguments) {
344 kiwoom::KiwoomConfig config;
352 config.holdings_venue_ = atl::Venue::KRX;
355 const bool demo = config.is_demo_;
358 std::make_shared<kiwoom::KiwoomBlockingClient>(
361 kiwoom::KiwoomAccount{}
365 const auto accounts = session.
accounts();
366 if (!accounts || accounts.value().empty()) {
368 <<
"could not read which account this Kiwoom key drives"
369 << (accounts ? std::string() :
": " + accounts.error().message_) <<
'\n';
373 const atl::InstrumentId instrument{atl::Country::KR, atl::Venue::COMBINED, arguments.symbol_};
374 auto settings = settings_for(instrument);
381 name_journal(settings, arguments,
"kiwoom", demo, accounts.value().front().display_number_);
382 announce(arguments, settings, demo,
"KIWOOM_DEMO");
389 <<
"note : on Kiwoom this program places nothing yet -- holdings need a stated\n"
390 <<
" scope, and the market phase is unknown without a calendar\n";
391 return run(session, instrument, settings, arguments.live_);
394int run_toss(ssl::context& tls,
const Arguments& arguments) {
397 toss::TossConfig config;
399 std::cout <<
"credentials: environment variables (Toss reads no credentials directory)\n";
400 auto client = std::make_shared<toss::TossBlockingClient>(
409 if (!accounts || accounts.value().empty()) {
411 <<
"could not list the accounts these Toss credentials reach"
412 << (accounts ? std::string() :
": " + accounts.error().message_) <<
'\n';
415 if (!arguments.toss_account_ && accounts.value().size() > 1) {
417 <<
"these Toss credentials reach " << accounts.value().size() <<
" accounts; choose one with --toss-account:\n";
418 for (
const auto& account : accounts.value()) {
419 std::cerr <<
" --toss-account " << account.selector_ <<
" (" << account.type_ <<
")\n";
423 auto chosen = accounts.value().front();
424 if (arguments.toss_account_) {
426 for (
const auto& account : accounts.value()) {
427 if (account.selector_ == *arguments.toss_account_) {
433 std::cerr <<
"no Toss account has sequence " << *arguments.toss_account_ <<
'\n';
437 if (chosen.display_number_.empty()) {
439 <<
"Toss reported no account number for sequence " << chosen.selector_
440 <<
", so the journal could not be named after the account\n";
444 const atl::InstrumentId instrument{atl::Country::KR, atl::Venue::COMBINED, arguments.symbol_};
445 auto settings = settings_for(instrument);
448 name_journal(settings, arguments,
"toss",
false, chosen.display_number_);
449 announce(arguments, settings,
false,
nullptr);
450 std::cout <<
"note : Toss has no paper-trading environment; --live trades real money\n";
453 return run(session, instrument, settings, arguments.live_);
457std::optional<Arguments> parse(
int argc,
char** argv) {
459 const int given = argc;
462 arguments.credentials_from_flag_ = argc != given;
464 }
catch (
const std::runtime_error& error) {
465 std::cerr <<
"example-live-program: " << error.what() <<
'\n';
468 std::vector<std::string> positional;
469 for (
int i = 1; i < argc; ++i) {
470 const std::string argument = argv[i];
471 const bool has_value = i + 1 < argc;
472 if (argument ==
"--live") {
473 arguments.live_ =
true;
474 }
else if (argument ==
"--journal" && has_value) {
475 arguments.journal_ = argv[++i];
476 }
else if (argument ==
"--control" && has_value) {
477 arguments.control_ = argv[++i];
478 }
else if (argument ==
"--tokens" && has_value) {
479 arguments.tokens_ = argv[++i];
480 }
else if (argument ==
"--toss-account" && has_value) {
481 arguments.toss_account_ = std::strtoll(argv[++i],
nullptr, 10);
482 }
else if (argument ==
"--market-data" && has_value) {
483 arguments.market_data_ = argv[++i];
484 if (*arguments.market_data_ !=
"kis" && *arguments.market_data_ !=
"toss") {
487 }
else if (argument.rfind(
"--", 0) == 0) {
490 positional.push_back(argument);
493 if (positional.size() != 2) {
496 arguments.broker_ = positional[0];
497 arguments.symbol_ = positional[1];
498 if (arguments.broker_ !=
"kis" && arguments.broker_ !=
"kiwoom" && arguments.broker_ !=
"toss") {
504 if (arguments.market_data_ && arguments.broker_ !=
"kis") {
507 if (arguments.credentials_from_flag_ && arguments.broker_ ==
"toss") {
510 if (arguments.kiwoom_account_ && arguments.broker_ !=
"kiwoom") {
525int main(
int argc,
char** argv) {
526 const auto arguments = parse(argc, argv);
529 <<
"usage: example-live-program <kis|kiwoom|toss> <symbol> [--live] [--journal PATH]\n"
530 <<
" [--control PATH] [--toss-account SEQUENCE]\n"
531 <<
" [--credentials DIR] [--market-data kis|toss]\n"
532 <<
" [--kiwoom-account LABEL] [--tokens DIR]\n\n"
533 <<
"Without --live it observes: nothing can be sent. KIS and Kiwoom are demo unless\n"
534 <<
"KIS_DEMO=0 / KIWOOM_DEMO=0; Toss has no demo, so toss --live trades real money.\n";
539 ssl::context tls(ssl::context::tls_client);
540 tls.set_default_verify_paths();
541 tls.set_verify_mode(ssl::verify_peer);
543 if (arguments->broker_ ==
"kis") {
544 return run_kis(tls, *arguments);
546 if (arguments->broker_ ==
"kiwoom") {
547 return run_kiwoom(tls, *arguments);
549 return run_toss(tls, *arguments);
550 }
catch (
const std::exception& exception) {
551 std::cerr <<
"example-live-program: " << exception.what() <<
'\n';
A blocking broker client bound to one account, with the same broker operations as BrokerSession,...
Result< std::vector< AccountInfo< Client > > > accounts()
Lists the broker's accounts; requires Caps::has_account_discovery.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
void from_json(const std::string &filename)
Loads the credentials from a JSON file, in the broker's format.
static void install(StopSource &source) noexcept
Installs the handlers: SIGINT and SIGTERM request a quiesce on source; SIGHUP, where it exists,...
static void uninstall() noexcept
Restores the default disposition of SIGINT, SIGTERM and (POSIX) SIGHUP, and forgets the source.
A stop request the loop polls; safe to set from a signal handler.
The examples' KIS credentials: one JSON file per account, or the environment.
algotradelib::network::HttpClientOptions paced_options()
Returns transport options that pace a KIS client at one request a second.
std::optional< algotradelib::kis::KisConfig > market_data_config(const std::optional< std::filesystem::path > &directory)
Returns a configuration for market data alone, from DIR/kis/real.json.
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...
std::optional< std::filesystem::path > take_directory(int &argc, char **argv)
Removes --credentials DIR from the command line and returns the directory, else ATL_CREDENTIALS_DIR.
The examples' Kiwoom credentials: one JSON file per key, or the environment.
algotradelib::network::HttpClientOptions paced_options()
Returns transport options that pace a Kiwoom client at one request a second.
std::optional< std::string > take_label(int &argc, char **argv)
Removes --kiwoom-account LABEL from the command line and returns the label.
void load(const std::optional< std::filesystem::path > &directory, const std::optional< std::string > &label, algotradelib::kiwoom::KiwoomConfig &config, std::ostream &out)
Loads the credentials from DIR/kiwoom/{demo,real}-LABEL.json (as KIWOOM_DEMO chooses; label kr by def...
The production wiring of a live run, with no broker named: the part of example-live-program a consume...
Exit observe(Session &session, MarketData &market_data, Strategy strategy_instance, const Settings &settings, runner::StopSource &stop, std::ostream &out, Clock clock={})
Runs a strategy against a session's account and another's market data, with nothing to send through.
@ ACCOUNT_UNRESOLVED
The program could not settle which account to trade (used by example-live-program).
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.
The Korea Investment & Securities (KIS) Open API client.
The Kiwoom Securities REST API client.
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
void stop(S &strategy, Ctx &context)
Calls strategy.on_stop(context) if the strategy declares on_stop; otherwise does nothing.
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
The Toss Securities Open API client.
The library: broker-neutral types (core), and the modules below.
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 venue_name(Venue venue) noexcept
Returns a display name for a venue, such as "KRX".
Identifies an instrument: its country, venue and symbol.
Deadlines, size limits and pacing for an HTTP client.
std::optional< std::chrono::nanoseconds > holdings_
How often to read holdings; without it the portfolio is never refreshed.
std::optional< std::chrono::nanoseconds > price_limits_
How often to read today's price bands.
std::optional< std::chrono::nanoseconds > bars_
How often to fetch bars.
std::optional< std::chrono::nanoseconds > working_orders_
How often to read the working orders.
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.
Toss Securities credentials (client id and secret). Toss has no demo environment.
What a run is told, gathered so main states it once and a test can state it differently.
std::vector< atl::InstrumentId > universe_
The instruments the source polls.
std::string journal_path_
Where the order journal lives.
std::chrono::nanoseconds maximum_portfolio_age_
How old a holdings snapshot – and the order listing – may be before the loop stops sizing against it.
std::chrono::nanoseconds maximum_price_limits_age_
How old a price band may be before the loop stops clamping to it.
std::string control_file_
The file an operator writes quiesce, withdraw or flatten into to stop the run.
runner::PollSchedule schedule_
How often each kind is polled. trade needs working_orders_ set, shorter than maximum_portfolio_age_: ...
atl::Venue default_route_
The venue an order is sent to, since a strategy's orders name none; UNSPECIFIED takes the broker's ow...
std::string journal_scope_
Which account the journal belongs to; a journal naming another refuses to open.
strategy::RiskLimits limits_
The limits the guard enforces.