algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-live-loop.cpp
Go to the documentation of this file.
1
18
19#include <algotradelib/krx>
20#include <algotradelib/runner>
21
22#include <chrono>
23#include <iostream>
24#include <string>
25#include <vector>
26
27using namespace algotradelib;
28
31
32namespace {
33
34using Clock = std::chrono::system_clock;
35
36InstrumentId samsung() {
37 return InstrumentId{Country::KR, Venue::COMBINED, "005930"};
38}
39
41Instrument samsung_reference() {
42 Instrument reference;
43 reference.id_ = samsung();
44 reference.type_ = SecurityType::STOCK;
45 reference.currency_ = Currency{"KRW"};
46 reference.lot_size_ = Decimal64::parse("1");
48 return reference;
49}
50
52struct CountBars {
53 std::size_t bars_{0};
54
55 template <class Ctx>
56 void on_bar(Ctx& ctx, const strategy::BarEvent&) {
57 ++bars_;
58 ctx.log().note("saw bar " + std::to_string(bars_));
59 }
60};
61
62using LoopRunner = runner::DryRunner<CountBars>;
63
86class ScriptedSource {
87public:
89 static constexpr bool reports_buying_power = true;
90
91 explicit ScriptedSource(int bars) : remaining_(bars) {}
92
93 runner::PollOutcome poll(runner::PollKind kind, LoopRunner& live_runner) {
95 // Today's permitted band, which reconciliation clamps a limit price into. A real source calls
96 // `session.price_limits(instrument)` per instrument here; what matters is that it lands on the
97 // runner rather than being fed as an event, and that it arrives **on a cadence** -- the band
98 // is a per-trading-day value, so one read at startup describes the day the process started on.
99 PriceLimits band;
100 band.currency_ = Currency{"KRW"};
101 band.upper_ = Decimal64::parse("91000");
102 band.lower_ = Decimal64::parse("49000");
103 live_runner.set_price_limits(samsung(), band);
105 }
106 if (kind != runner::PollKind::BARS) {
108 }
109 if (remaining_ <= 0) {
110 // Nothing new is the normal case between closes, and is not a failure.
112 }
113 --remaining_;
114
115 Bar bar;
116 bar.timestamp_ = Clock::time_point{} + std::chrono::hours(24 * (200 + fed_));
117 bar.close_ = Decimal64::parse(std::to_string(70000 + fed_ * 500));
118 bar.high_ = bar.close_;
119 bar.low_ = bar.close_;
120 bar.volume_ = Decimal64::parse("1000000");
121 ++fed_;
122
123 live_runner.context().set_last_price(samsung(), bar.close_);
124 live_runner.feed(strategy::make_bar_event(samsung(), BarInterval::ONE_DAY, BarStamp::CLOSE, bar));
126 }
127
128 runner::PollOutcome read_order_list(LoopRunner&) {
129 ++reads_;
130 // A real source calls working_orders() or order_history() here. Returning a failure until the
131 // second attempt shows the gate doing its job.
133 }
134
135 int reads() const noexcept {
136 return reads_;
137 }
138
139private:
140 int remaining_;
141 int fed_{0};
142 int reads_{0};
143};
144
146void describe(const runner::LoopReport& report) {
147 std::cout
148 << "iterations : " << report.iterations_ << '\n'
149 << "bar polls : " << report.attempted(runner::PollKind::BARS) << " (" << report.failed(runner::PollKind::BARS)
150 << " failed)\n"
151 << "blocked : " << report.blocked_ << " iteration(s)\n"
152 << "order list read : " << (report.order_list_read_ ? "yes" : "no") << '\n'
153 << "stopped by : "
154 << (report.stopped_by_ ? runner::stop_intent_name(*report.stopped_by_) : std::string_view("nothing")) << '\n'
155 << "final gate : "
156 << (report.final_gate_ ? strategy::halt_reason_name(*report.final_gate_) : std::string_view("none"))
157 << '\n'
158 // The phase the loop derived for itself, and how many changes it announced. Reported
159 // because it decides most of what could be sent: `unknown` beside a default
160 // `permitted_phases_` means every placement that would open a position was refused, and
161 // an empty placement count on its own does not say that.
162 << "market phase : " << strategy::market_phase_name(report.final_phase_) << " (" << report.phase_transitions_
163 << " transition(s))\n"
164 // And how many orders went out under a phase the limits do not permit. An order closing
165 // a held position is permitted in any phase -- which is what lets a flatten after the
166 // close reach the broker instead of being refused by the operator's own limit -- so this
167 // is the line that says it happened. Non-zero is not a fault; a nightly flatten is one.
168 << "sent off-phase : " << report.sends_outside_permitted_phase_
169 << '\n'
170 // And what the price-band policy decided. A band is a per-trading-day value, so a run
171 // that outlives the day it read one has to decide what to do with it: this library does
172 // not apply a band whose age nobody has bounded, and says so here rather than repricing
173 // an order against yesterday's ceiling in silence. Both stay zero in this example
174 // because `CountBars` places nothing -- the first counts plans, the second counts sent
175 // orders a broker refused after a band was withheld.
176 << "bands withheld : " << report.price_bands_withheld_ << '\n'
177 << "refused unclamped: " << report.unclamped_orders_rejected_ << '\n';
178 for (const auto& note : report.notes_) {
179 std::cout << "note : " << note << '\n';
180 }
181}
182
189Clock::time_point start_time() {
190 return Clock::time_point{} + std::chrono::hours(24 * 200);
191}
192
193} // namespace
194
199int main() {
200 std::cout << "a live loop with no broker attached\n\n";
201
202 LoopRunner live_runner;
203 live_runner.context().set_instrument(samsung_reference());
204
205 // **The phase is the loop's, not this program's.** The loop derives it from its session window and
206 // the trading calendar, and overwrites anything set here; a fixed `set_phase(MarketPhase::OPEN)`
207 // would trade as though the market never closed, and `on_phase` would never fire.
208 //
209 // A real program gets that calendar from `PollKind::CALENDAR`, which is on by default. This example
210 // has no broker, so its source answers no calendar; the date is therefore uncovered, the phase is
211 // `UNKNOWN`, and the report says so in as many words. Seeding one here is what a run with a broker
212 // gets from its first calendar poll.
214 calendar.country_ = algotradelib::Country::KR;
215 calendar.received_at_ = start_time();
216 calendar.days_.push_back(algotradelib::TradingDay{strategy::SessionWindow::krx().local_date(start_time()), true});
217 live_runner.context().set_calendar(calendar);
218
219 ScriptedSource source(4);
220
221 runner::PollSchedule schedule;
222 schedule.bars_ = std::chrono::minutes(1);
223 schedule.tick_ = std::chrono::minutes(1);
224 // No broker here, so nothing could answer a calendar request; a real program leaves this at its
225 // six-hour default.
226 schedule.calendar_.reset();
227 // **The band, on a cadence rather than once.** A band registered once at startup would clamp every
228 // limit order for as long as the process ran. Ten minutes here is arbitrary; the real constraint is
229 // that it be shorter than the session, because the value changes with the previous close.
230 schedule.price_limits_ = std::chrono::minutes(10);
231
233 live_runner, source, schedule, runner::ManualClock{start_time()}
234 );
235 // **Two statements every placement-enabled run owes, and this source cannot satisfy either.**
236 //
237 // A run states how old a holdings snapshot may be before it stops sizing against it, and a run
238 // that has never read one holds rather than treating an empty account as a current one -- an
239 // empty portfolio is the *permissive* answer to every ceiling and to every target subtraction, so a
240 // run that never thought about holdings would trade as though it held nothing.
241 //
242 // This example has no broker, so it reads no holdings ever. Saying so explicitly is what an
243 // operator in the same position does; leaving them out would hold this loop for the whole run.
245 loop.allow_absent_portfolio();
246 // **The third statement, and the same shape as the first.** A run states how old a band may be, or
247 // that it accepts any age; with neither, no band is applied. Twenty
248 // minutes against a ten-minute cadence, so one failed poll is tolerated and a run of failures is
249 // not -- which is what the policy is actually bounding, since a failed poll deliberately leaves
250 // the last good band in place.
251 loop.set_maximum_price_limits_age(std::chrono::minutes(20));
252
254 const auto report = loop.run(stop, 6);
255
256 describe(report);
257
258 std::cout << "\nthe strategy saw " << live_runner.strategy().bars_ << " bar(s)\n";
259
260 // The gate refused the first iteration because the order list had not been read. That is the
261 // cheapest half of reconciliation and it needs no persistence: a process that has just started
262 // cannot know whether a predecessor died mid-POST, and an empty ledger does not mean nothing is
263 // owed -- it means nothing is remembered.
264 std::cout << "the order list was read " << source.reads() << " time(s) before the gate opened\n";
265
266 std::cout
267 << "\nhow a real operator would stop this:\n"
268 << " runner::SignalStop::install(stop); // SIGINT and SIGTERM quiesce; SIGHUP ignored\n"
269 << " loop.set_control_file(runner::FileStopChannel(\"/var/run/atl/stop\"));\n"
270 << " echo withdraw > /var/run/atl/stop // or quiesce, or flatten\n\n"
271 << "and the trap worth knowing: a supervisor's grace period must exceed one loop\n"
272 << "iteration plus one request timeout, or its SIGKILL turns the cleanest stop into\n"
273 << "the worst one -- a process killed mid-request, with an order whose fate is unknown.\n";
274
275 return 0;
276}
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
A clock for tests: wait_for advances it instead of sleeping.
Definition clock.hpp:102
Runs a runner for a live session: polls a source on a schedule, gates placements, derives the market ...
Definition loop.hpp:1057
void allow_unbounded_portfolio_age()
Accepts holdings of any age, instead of stating a maximum.
Definition loop.hpp:1274
A stop request the loop polls; safe to set from a signal handler.
Definition stop.hpp:163
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
Definition krx.hpp:12
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
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
PollKind
What a PollingLoop polls for; each has a cadence in PollSchedule.
Definition loop.hpp:31
@ BARS
Completed bars.
Definition loop.hpp:33
@ PRICE_LIMITS
Today's price bands, which an aggressive limit price is clamped to; polled second,...
Definition loop.hpp:59
PollOutcome
What became of one poll.
Definition loop.hpp:134
@ UNCHANGED
The poll succeeded and there was nothing new.
Definition loop.hpp:138
@ FAILED
The poll failed; counted toward the failure budget.
Definition loop.hpp:140
@ UPDATED
New data arrived and was fed to the runner, or installed in it (a calendar, price bands).
Definition loop.hpp:136
constexpr std::string_view stop_intent_name(StopIntent intent) noexcept
Returns a lowercase name for an intent, as written in the control file ("withdraw").
Definition stop.hpp:61
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
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
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
constexpr std::string_view market_phase_name(MarketPhase phase) noexcept
Returns a lowercase name for a phase, such as "pre_open", for logs and display.
Definition event.hpp:68
constexpr std::string_view halt_reason_name(HaltReason reason) noexcept
Returns a lowercase name for a hold, such as "portfolio_stale", for logs.
Definition risk.hpp:149
The library: broker-neutral types (core), and the modules below.
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::optional< Decimal64 > lower_
The lowest price allowed today; empty means the same as for upper_.
std::optional< Decimal64 > upper_
The highest price allowed today.
Currency currency_
The currency of the bounds.
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
std::chrono::system_clock::time_point received_at_
When the calendar was received, on this machine's clock.
Definition calendar.hpp:78
std::vector< TradingDay > days_
The days the broker reported, ascending. A date outside them is uncovered, not closed.
Definition calendar.hpp:76
Country country_
The market this calendar is for.
Definition calendar.hpp:74
One calendar date and whether the market opens on it.
Definition calendar.hpp:31
std::size_t iterations_
How many iterations ran.
Definition loop.hpp:643
std::size_t blocked_
How many iterations were blocked from placing (a named cancellation may still have gone).
Definition loop.hpp:651
std::size_t failed(PollKind kind) const noexcept
Returns how many polls of a kind failed.
Definition loop.hpp:850
std::optional< strategy::HaltReason > final_gate_
The most fundamental hold in force when the run ended, whoever took it.
Definition loop.hpp:655
bool order_list_read_
Whether the broker's order list was read at least once.
Definition loop.hpp:728
std::optional< StopIntent > stopped_by_
The stop intent that ended the run, if one did.
Definition loop.hpp:653
std::size_t attempted(PollKind kind) const noexcept
Returns how many polls of a kind were attempted.
Definition loop.hpp:841
std::vector< std::string > notes_
Notes for the operator, such as an unrecognized control-file word or a missing policy.
Definition loop.hpp:834
How often a PollingLoop polls each kind; an unset interval disables that poll.
Definition loop.hpp:191
std::optional< std::chrono::nanoseconds > calendar_
How often to read the trading calendar; six hours by default.
Definition loop.hpp:226
std::chrono::nanoseconds tick_
The loop's step, which bounds how quickly a stop is noticed; not a poll.
Definition loop.hpp:217
std::optional< std::chrono::nanoseconds > price_limits_
How often to read today's price bands.
Definition loop.hpp:233
std::optional< std::chrono::nanoseconds > bars_
How often to fetch bars.
Definition loop.hpp:193
Date local_date(std::chrono::system_clock::time_point now) const
Returns the market's local date at an instant.
Definition event.hpp:176
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
Definition event.hpp:136