algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-strategy-dryrun.cpp
1// A strategy run end to end with no broker, no credentials, and no network.
2//
3// Bars are built in code, so the output is identical every time and the binary contains no code
4// path that could place an order -- `<algotradelib/runner>` links no TLS, which a test asserts.
5// That is what makes this the right place to see what a strategy decides before letting it near
6// a market.
7//
8// Run it as:
9//
10// example-strategy-dryrun
11
12#include <algotradelib/krx>
13#include <algotradelib/runner>
14
15#include <chrono>
16#include <cstddef>
17#include <iomanip>
18#include <iostream>
19#include <map>
20#include <string>
21#include <utility>
22#include <vector>
23
24namespace {
25
28
41
42InstrumentId samsung() {
43 return InstrumentId{Country::KR, Venue::COMBINED, "005930"};
44}
45
47Instrument samsung_reference() {
48 Instrument reference;
49 reference.id_ = samsung();
50 reference.name_ = "Samsung Electronics";
51 reference.type_ = SecurityType::STOCK;
52 reference.currency_ = Currency{"KRW"};
53 reference.lot_size_ = Decimal64::parse("1");
54 reference.price_rule_ = algotradelib::krx::equity_price_rule();
55 return reference;
56}
57
64const std::vector<const char*>& closes() {
65 static const std::vector<const char*> series = {
66 "60000",
67 "60500",
68 "61200",
69 "61000",
70 "62000",
71 "63000",
72 "64500",
73 "65000",
74 "66200",
75 "67000",
76 "68500",
77 "69000",
78 "70200",
79 "71000",
80 "72500",
81 "73000",
82 "72800",
83 "72000",
84 "71000",
85 "69500",
86 "68000",
87 "66500",
88 "65000",
89 "63500",
90 "62000",
91 "61000",
92 "60000",
93 "59000",
94 "58500",
95 "58000",
96 };
97 return series;
98}
99
100// ---------------------------------------------------------------------------------------------
101// Two strategies, written here as you would write your own.
102// ---------------------------------------------------------------------------------------------
103
110struct HoldsShares {
112 Decimal64 quantity_;
113
114 template <class Ctx>
115 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
116 strategy::TargetPosition target;
117 target.instrument_ = bar.instrument_;
118 target.target_quantity_ = quantity_;
119 target.tag_ = "hold";
120 ctx.submit(target);
121 }
122};
123
136struct BreakoutThenFlatten {
138 Decimal64 quantity_;
140 std::vector<Decimal64> closes_;
142 bool flattened_{false};
143
144 static constexpr std::size_t lookback = 5;
145
146 template <class Ctx>
147 void on_bar(Ctx& ctx, const strategy::BarEvent& bar) {
148 closes_.push_back(bar.bar_.close_);
149 if (flattened_ || closes_.size() <= lookback) {
150 return;
151 }
152 // Exact decimals, so this needs no linear algebra backend.
153 Decimal64 highest = closes_[closes_.size() - 1 - lookback];
154 for (std::size_t at = closes_.size() - lookback; at + 1 < closes_.size(); ++at) {
155 if (algotradelib::decimal_less(highest, closes_[at])) {
156 highest = closes_[at];
157 }
158 }
159 if (!algotradelib::decimal_less(highest, closes_.back())) {
160 return;
161 }
162 strategy::TargetPosition target;
163 target.instrument_ = bar.instrument_;
164 target.target_quantity_ = quantity_;
165 target.tag_ = "breakout";
166 ctx.submit(target);
167 }
168
169 template <class Ctx>
170 void on_phase(Ctx& ctx, strategy::MarketPhase phase) {
172 return;
173 }
174 std::vector<InstrumentId> targeted;
175 for (const auto& position : ctx.portfolio().positions_) {
176 bool seen = false;
177 for (const auto& already : targeted) {
178 seen = seen || already == position.instrument_;
179 }
180 if (seen || position.quantity_.coefficient() == 0) {
181 continue;
182 }
183 targeted.push_back(position.instrument_);
184 strategy::TargetPosition target;
185 target.instrument_ = position.instrument_;
186 target.target_quantity_ = Decimal64::parse("0");
187 target.tag_ = "session-end";
188 ctx.submit(target);
189 }
190 flattened_ = true;
191 }
192};
193
196
198strategy::BarEvent bar(std::size_t index) {
199 Bar value;
200 value.timestamp_ =
201 std::chrono::system_clock::time_point{} + std::chrono::hours(24 * (20000 + static_cast<int>(index)));
202 value.open_ = Decimal64::parse(closes()[index]);
203 value.high_ = Decimal64::parse(closes()[index]);
204 value.low_ = Decimal64::parse(closes()[index]);
205 value.close_ = Decimal64::parse(closes()[index]);
206 value.volume_ = Decimal64::parse("1200000");
207 return strategy::make_bar_event(samsung(), BarInterval::ONE_DAY, BarStamp::CLOSE, value);
208}
209
211template <typename Report>
212void print(std::size_t day, const Report& report) {
213 for (const auto& order : report.would_place_) {
214 std::cout
215 << " day " << std::setw(2) << day << " " << (order.side_ == OrderSide::BUY ? "BUY " : "SELL") << ' '
216 << std::setw(4) << order.quantity_.str() << " shares";
217 if (order.price_) {
218 std::cout << " at " << order.price_->str();
219 } else {
220 std::cout << " at market";
221 }
222 std::cout << " [" << order.tag_ << "]\n";
223 }
224 for (const auto& rejection : report.rejected_) {
225 std::cout
226 << " day " << std::setw(2) << day << " rejected: " << strategy::reject_reason_name(rejection.reason_) << '\n';
227 }
228}
229
237using RefusalTally = std::map<std::string, std::pair<std::size_t, std::size_t>>;
238
239template <typename Report>
240void tally(std::size_t day, const Report& report, RefusalTally& counts) {
241 for (const auto& refusal : report.refused_) {
242 const std::string reason(strategy::guard_reason_name(refusal.reason_));
243 auto found = counts.find(reason);
244 if (found == counts.end()) {
245 counts.emplace(reason, std::pair<std::size_t, std::size_t>{day, 1});
246 } else {
247 ++found->second.second;
248 }
249 }
250}
251
253strategy::Portfolio<runner::DryTag> portfolio_of(const Decimal64& held) {
255 HoldingPosition position;
256 position.instrument_ = samsung();
257 position.quantity_ = held;
258 // What the account may sell, which a broker's holdings state and the guard checks a sell against by
259 // default: here the whole holding. Without it a dry run refuses every sell (`quantity_not_sellable`).
260 position.sellable_quantity_ = held;
261 portfolio.positions_.push_back(position);
265 false,
266 };
267 return portfolio;
268}
269
271template <typename Report>
272void apply(const Report& report, Decimal64& held) {
273 for (const auto& order : report.would_place_) {
274 const auto signed_quantity = order.side_ == OrderSide::BUY ?
275 algotradelib::decimal_add(held, order.quantity_) :
276 algotradelib::decimal_subtract(held, order.quantity_);
277 if (signed_quantity) {
278 held = *signed_quantity;
279 }
280 }
281}
282
290template <typename Strategy>
291void run(const char* title, Strategy instance, const strategy::RiskLimits& limits = {}, bool end_session = false) {
292 std::cout << title << '\n';
293
294 runner::DryRunner<Strategy> dry(std::move(instance), limits);
295 dry.context().set_instrument(samsung_reference());
296 dry.context().set_phase(strategy::MarketPhase::OPEN);
297 dry.set_portfolio_value(Decimal64::parse("100000000"));
298 // A runner driven by hand starts its strategy before the first feed.
299 dry.start();
300
301 Decimal64 held = Decimal64::parse("0");
302 RefusalTally refusals;
303 for (std::size_t day = 0; day < closes().size(); ++day) {
304 dry.context().set_last_price(samsung(), Decimal64::parse(closes()[day]));
305
306 dry.context().set_portfolio(portfolio_of(held));
307
308 const auto report = dry.feed(bar(day));
309 print(day, report);
310 tally(day, report, refusals);
311 apply(report, held);
312 }
313 if (end_session) {
314 // The session ends after the last bar. The runner sees the holding the last bar left, then the phase.
315 std::cout << " holding " << held.str() << " shares when the session closes\n";
316 dry.context().set_portfolio(portfolio_of(held));
317 const auto report = dry.feed(strategy::MarketPhase::POST_CLOSE);
318 print(closes().size(), report);
319 tally(closes().size(), report, refusals);
320 apply(report, held);
321 }
322 for (const auto& entry : refusals) {
323 std::cout
324 << " day " << std::setw(2) << entry.second.first << " refused: " << entry.first << " (and on "
325 << entry.second.second - 1 << " later bars)\n";
326 }
327 std::cout << " ending position: " << held.str() << " shares\n\n";
328}
329
330} // namespace
331
332int main() {
333 std::cout << "005930, " << closes().size() << " daily bars built in code -- no credentials, no network\n\n";
334
335 run("HoldsShares: one target, then nothing, and it remembers nothing to do it", HoldsShares{Decimal64::parse("100")});
336
337 run(
338 "BreakoutThenFlatten: in on a breakout, out when the session closes",
339 BreakoutThenFlatten{Decimal64::parse("100"), {}, false}, {}, true
340 );
341
342 // A guard refusing an order is part of the pipeline, not an error, so it belongs in the output.
344 tight.max_order_notional_ = Decimal64::parse("1000000");
345 run(
346 "HoldsShares with a 1,000,000 KRW per-order ceiling: refused, never resized", HoldsShares{Decimal64::parse("100")},
347 tight
348 );
349
350 return 0;
351}
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
#define ATL_ASSERT_STRATEGY(S, Ctx)
Asserts at compile time that S is a strategy a runner with context Ctx can drive.
Definition concept.hpp:866
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
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
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
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:33
@ PRE_OPEN
A trading day, before the session opens; under filled session hours, the day's earlier stated session...
Definition event.hpp:44
@ POST_CLOSE
A trading day, after the session closed; under filled session hours, until the next day's first sessi...
Definition event.hpp:51
@ OPEN
Inside the session.
Definition event.hpp:46
ProbeContextT< NoCaps > MinimalContext
A probe context whose broker implements nothing optional.
Definition concept.hpp:802
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
The library: broker-neutral types (core), and the modules below.
BarStamp
Which edge of its period a bar's timestamp marks.
SecurityType
What kind of security an instrument is.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
Country
A country (market) the library supports.
Definition types.hpp:32
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
BarInterval
The period one bar covers.
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
One bar: the prices and volume of one period, as exact decimals.
One position row in a holdings snapshot.
Definition types.hpp:1288
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Reference data for one instrument.
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
Definition types.hpp:1191
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
Definition types.hpp:1197
@ DEDUCT
Subtract every resting sell from the figure.
Definition types.hpp:1215
One bar, delivered to on_bar.
Definition event.hpp:313
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
Definition portfolio.hpp:88
The limits the operator sets for RiskGuard.
Definition risk.hpp:412
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