algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
cost.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algotradelib/core>
4
5#include <cstdint>
6#include <optional>
7#include <string>
8#include <string_view>
9#include <utility>
10
11namespace algotradelib {
12namespace backtest {
13
22
37 bool from_broker_{false};
38
46 std::optional<Decimal64> on(const Decimal64& quantity, const Decimal64& price) const {
47 const auto value = decimal_multiply(quantity, price);
48 if (!value) {
49 return std::nullopt;
50 }
51 auto charged = decimal_multiply(*value, rate_);
52 if (!charged) {
53 return std::nullopt;
54 }
55 // Truncated to whole currency units, as a broker charges.
56 const auto whole = decimal_divide(*charged, Decimal64::parse("1"), 0);
57 if (!whole) {
58 return std::nullopt;
59 }
60 return decimal_less(*whole, minimum_) ? minimum_ : *whole;
61 }
62
68 return CommissionModel{};
69 }
70
77 static CommissionModel of(Decimal64 rate, Decimal64 minimum = Decimal64::parse("0")) {
78 return CommissionModel{std::move(rate), std::move(minimum)};
79 }
80};
81
97 const CommissionSchedule& schedule, Country country, const Date& date
98) {
99 const auto selection = schedule.rate_for(country, date);
100 if (!selection.rate_) {
101 BrokerError error;
103 // Nothing was asked of anybody: this reads a schedule already in hand.
104 error.reached_broker_ = false;
105 // Distinct codes: a missing row wants a rate stated; an unreadable window wants a refetch.
106 if (selection.bounds_unreadable_) {
107 error.broker_code_ = "rate_bounds_unreadable";
108 error.message_ =
109 "the published schedule holds a commission rate for that market whose date "
110 "bounds could not be read, so whether it applies on that date is unknown";
111 return Result<CommissionModel>(std::move(error));
112 }
113 error.broker_code_ = "no_rate_for_date";
114 error.message_ = "the published schedule states no commission rate for that market and date";
115 return Result<CommissionModel>(std::move(error));
116 }
117 const auto& rate = selection.rate_;
118 auto model = CommissionModel::of(rate->rate_);
119 // A caller's stated schedule stays the caller's: the report says where the rate it charged came from.
120 model.from_broker_ = commission_origin_is_broker(schedule.origin_);
121 return Result<CommissionModel>(std::move(model));
122}
123
127 Country country_{Country::KR};
133 std::optional<Decimal64> institution_rate_;
137 std::optional<Date> from_;
139 std::optional<Date> until_;
147 std::size_t executions_{0};
148
155 friend bool operator==(const AppliedRate& lhs, const AppliedRate& rhs) {
156 return lhs.country_ == rhs.country_ && lhs.venue_ == rhs.venue_ && lhs.rate_ == rhs.rate_ &&
157 lhs.institution_rate_ == rhs.institution_rate_ && lhs.minimum_ == rhs.minimum_ && lhs.from_ == rhs.from_ &&
158 lhs.until_ == rhs.until_ && lhs.origin_ == rhs.origin_;
159 }
160};
161
176
186public:
188 CommissionPolicy() = default;
189
196 CommissionPolicy policy;
197 policy.flat_ = std::move(model);
198 return policy;
199 }
200
214 return Result<CommissionPolicy>(refusal(
215 "commission_tariff_unnamed",
216 "a caller-stated commission schedule must name the tariff it was read from, because the "
217 "published table is channel by venue and nothing here can select the channel"
218 ));
219 }
220 if (asserted.kind() == VenueKeyKind::NORMALIZED && asserted.venue() == Venue::COMBINED) {
221 return Result<CommissionPolicy>(refusal(
222 "commission_venue_not_an_execution",
223 "COMBINED is consolidated routing rather than a venue an order matched on, so it cannot be "
224 "asserted as the venue a fill happened at"
225 ));
226 }
227 CommissionPolicy policy;
228 policy.schedule_ = std::move(schedule);
229 policy.asserted_ = std::move(asserted);
230 policy.dating_market_ = dating_market;
231 return Result<CommissionPolicy>(std::move(policy));
232 }
233
238 bool is_scheduled() const noexcept {
239 return schedule_.has_value();
240 }
241
246 const VenueKey& asserted_venue() const noexcept {
247 return asserted_;
248 }
249
254 std::string_view tariff() const noexcept {
255 return schedule_ ? std::string_view(schedule_->tariff_) : std::string_view();
256 }
257
262 const CommissionModel& stated_model() const noexcept {
263 return flat_;
264 }
265
270 const std::optional<CommissionSchedule>& schedule() const noexcept {
271 return schedule_;
272 }
273
278 Country dating_market() const noexcept {
279 return dating_market_;
280 }
281
296 const Decimal64& quantity, const Decimal64& price, const Date& date, Country country
297 ) const {
298 if (!schedule_) {
299 const auto charged = flat_.on(quantity, price);
300 if (!charged) {
302 refusal("commission_not_representable", "the commission on that execution does not fit an exact decimal")
303 );
304 }
305 CommissionCharge result;
306 result.broker_ = *charged;
307 // A flat model is one inclusive figure: no institution split.
308 result.applied_.country_ = country;
309 result.applied_.rate_ = flat_.rate_;
310 result.applied_.minimum_ = flat_.minimum_;
311 result.applied_.origin_ =
313 return Result<CommissionCharge>(std::move(result));
314 }
315
316 // A market other than the dating market is refused if any of its rates is dated: the replay's
317 // date is another market's day, so which dated rate applies cannot be decided.
318 if (country != dating_market_ && schedule_->any_dated_rate_for(country)) {
319 BrokerError error;
321 error.reached_broker_ = false;
322 error.broker_code_ = "commission_date_not_market_local";
323 error.message_ = "this market's rates have dated bounds, and the replay's date " + named(date) +
324 " is that of another market's trading day, so which rate applies cannot be "
325 "decided here; price it in a replay whose session is that market's, or state rates with "
326 "no dated bounds";
327 return Result<CommissionCharge>(std::move(error));
328 }
329
330 const auto selection = schedule_->rate_for(country, asserted_, date);
331 const auto& rate = selection.rate_;
332 if (!rate) {
333 BrokerError error;
335 error.reached_broker_ = false;
336 // Name the date, and distinguish an unreadable window (refetch) from a missing rate (state one).
337 if (selection.bounds_unreadable_) {
338 error.broker_code_ = "rate_bounds_unreadable";
339 error.message_ = "the schedule holds a commission rate for " + described(asserted_) +
340 " in this instrument's market whose date bounds could not be read, so whether it applies "
341 "on " +
342 named(date) + " is unknown; refetch the schedule or state the rates";
343 return Result<CommissionCharge>(std::move(error));
344 }
345 error.broker_code_ = "no_rate_for_date";
346 error.message_ = "the schedule states no commission rate for " + named(date) + " at venue " +
347 described(asserted_) + " in the market this instrument is listed in";
348 return Result<CommissionCharge>(std::move(error));
349 }
350
351 // No minimum on a scheduled rate: no schedule states one. A caller with a minimum uses `stated`.
352 const auto broker = component(quantity, price, rate->rate_, Decimal64::parse("0"));
353 if (!broker) {
355 refusal("commission_not_representable", "the commission on that execution does not fit an exact decimal")
356 );
357 }
358 CommissionCharge result;
359 result.broker_ = *broker;
360 if (rate->institution_rate_) {
361 // Its own component, with no minimum (the minimum is the broker's).
362 const auto institution = component(quantity, price, *rate->institution_rate_, Decimal64::parse("0"));
363 if (!institution) {
365 refusal("commission_not_representable", "the institution fee on that execution does not fit an exact decimal")
366 );
367 }
368 result.institution_ = *institution;
369 }
370 result.applied_.country_ = country;
371 result.applied_.venue_ = rate->venue_;
372 result.applied_.rate_ = rate->rate_;
373 result.applied_.institution_rate_ = rate->institution_rate_;
374 result.applied_.from_ = rate->from_;
375 result.applied_.until_ = rate->until_;
376 result.applied_.origin_ = schedule_->origin_;
377 return Result<CommissionCharge>(std::move(result));
378 }
379
380private:
381 // The venue a refusal was asked about, as the asker spelled it.
382 static std::string described(const VenueKey& venue) {
383 switch (venue.kind()) {
385 return "(none asserted)";
387 return std::string(venue_name(venue.venue()));
389 return "'" + venue.raw_code().str() + "'";
390 }
391 return "(unknown)";
392 }
393
394 // `date` as `YYYY-MM-DD`.
395 static std::string named(const Date& date) {
396 const auto pad = [](unsigned value) {
397 return value < 10 ? "0" + std::to_string(value) : std::to_string(value);
398 };
399 return std::to_string(date.year_) + "-" + pad(date.month_) + "-" + pad(date.day_);
400 }
401
402 static BrokerError refusal(std::string code, std::string message) {
403 BrokerError error;
404 error.category_ = ErrorCategory::INVALID_ARGUMENT;
405 // Nothing was asked of anybody: this reads a schedule already in hand.
406 error.reached_broker_ = false;
407 error.broker_code_ = std::move(code);
408 error.message_ = std::move(message);
409 return error;
410 }
411
412 // One component's charge, truncated to whole units and floored at `minimum`.
413 static std::optional<Decimal64> component(
414 const Decimal64& quantity, const Decimal64& price, const Decimal64& rate, const Decimal64& minimum
415 ) {
416 CommissionModel model;
417 model.rate_ = rate;
418 model.minimum_ = minimum;
419 return model.on(quantity, price);
420 }
421
422 // The stated model; unused by a scheduled policy.
423 CommissionModel flat_{};
424 // Present exactly when this policy resolves a schedule.
425 std::optional<CommissionSchedule> schedule_;
426 // The venue a caller asserted its fills happened at.
427 VenueKey asserted_;
428 // The market whose local trading day `charge`'s date is; dated rates of other markets refuse.
429 Country dating_market_{Country::KR};
430};
431
444 int ticks_{0};
445
459 std::optional<std::pair<Decimal64, Decimal64>> apply(
460 const Decimal64& price, OrderSide side, const PriceRule& rule
461 ) const {
462 auto moved = price;
463
464 if (basis_points_.coefficient() != 0) {
465 const auto fraction = decimal_divide(basis_points_, Decimal64::parse("10000"), 8);
466 if (!fraction) {
467 return std::nullopt;
468 }
469 const auto amount = decimal_multiply(price, *fraction);
470 if (!amount) {
471 return std::nullopt;
472 }
473 const auto shifted = side == OrderSide::BUY ? decimal_add(moved, *amount) : decimal_subtract(moved, *amount);
474 if (!shifted) {
475 return std::nullopt;
476 }
477 moved = *shifted;
478 }
479
480 if (ticks_ > 0) {
481 // One step at a time, each with the tick where it starts: the first tick of a band is not the
482 // last tick of the band below.
483 const auto zero = Decimal64::parse("0");
484 auto walked = price;
485 for (int step = 0; step < ticks_; ++step) {
486 const auto tick = side == OrderSide::BUY ? rule.tick_at(walked) : tick_below(rule, walked);
487 if (!tick) {
488 // An unknown grid, or the bottom of a known one, contributes nothing rather than a guessed step.
489 break;
490 }
491 const auto next = side == OrderSide::BUY ? decimal_add(walked, *tick) : decimal_subtract(walked, *tick);
492 if (!next) {
493 return std::nullopt;
494 }
495 if (!decimal_less(zero, *next)) {
496 // No price at or below zero.
497 break;
498 }
499 walked = *next;
500 }
501 const auto steps = side == OrderSide::BUY ? decimal_subtract(walked, price) : decimal_subtract(price, walked);
502 if (!steps) {
503 return std::nullopt;
504 }
505 const auto shifted = side == OrderSide::BUY ? decimal_add(moved, *steps) : decimal_subtract(moved, *steps);
506 if (!shifted) {
507 return std::nullopt;
508 }
509 moved = *shifted;
510 }
511
512 const auto given_up = side == OrderSide::BUY ? decimal_subtract(moved, price) : decimal_subtract(price, moved);
513 if (!given_up) {
514 return std::nullopt;
515 }
516 return std::pair<Decimal64, Decimal64>{moved, *given_up};
517 }
518
524 return SlippageModel{};
525 }
526
533 SlippageModel model;
534 model.basis_points_ = std::move(points);
535 return model;
536 }
537
543 static SlippageModel of_ticks(int count) {
544 SlippageModel model;
545 model.ticks_ = count;
546 return model;
547 }
548
549private:
550 // The tick of the band below a price: the step down to the next lower grid price, for a price on a
551 // grid like KRX's. None at or below the first band's start, or without bands.
552 static std::optional<Decimal64> tick_below(const PriceRule& rule, const Decimal64& price) {
553 std::optional<Decimal64> tick;
554 for (const auto& band : rule.bands_) {
555 if (!decimal_less(band.from_, price)) {
556 break;
557 }
558 tick = band.tick_;
559 }
560 return tick;
561 }
562};
563
581
587inline constexpr std::string_view limit_fill_price_name(LimitFillPrice choice) noexcept {
588 switch (choice) {
590 return "at_limit";
592 return "at_open_if_better";
593 }
594 return "unknown";
595}
596
597} // namespace backtest
598} // namespace algotradelib
std::string str() const
Returns the code as a string.
Definition types.hpp:320
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
Which venue a commission rate applies to: any venue, a normalized Venue, or a raw code.
Definition types.hpp:1523
const Code< 8 > & raw_code() const noexcept
Returns the raw venue code.
Definition types.hpp:1595
VenueKeyKind kind() const noexcept
Returns the key's kind.
Definition types.hpp:1571
Venue venue() const noexcept
Returns the normalized venue.
Definition types.hpp:1587
CommissionPolicy()=default
Constructs a policy that charges nothing (the report says so).
static Result< CommissionPolicy > scheduled(CommissionSchedule schedule, VenueKey asserted, Country dating_market)
Makes a policy that picks a rate from a schedule for each execution.
Definition cost.hpp:212
const VenueKey & asserted_venue() const noexcept
Returns the asserted venue.
Definition cost.hpp:246
std::string_view tariff() const noexcept
Returns the schedule's tariff name.
Definition cost.hpp:254
static CommissionPolicy stated(CommissionModel model)
Makes a policy that charges one model on every execution.
Definition cost.hpp:195
const std::optional< CommissionSchedule > & schedule() const noexcept
Returns the schedule.
Definition cost.hpp:270
Result< CommissionCharge > charge(const Decimal64 &quantity, const Decimal64 &price, const Date &date, Country country) const
Computes the commission on one execution.
Definition cost.hpp:295
Country dating_market() const noexcept
Returns the market whose local trading day a scheduled policy's dates are.
Definition cost.hpp:278
const CommissionModel & stated_model() const noexcept
Returns the stated model.
Definition cost.hpp:262
bool is_scheduled() const noexcept
Tests whether the policy resolves a schedule.
Definition cost.hpp:238
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Definition bootstrap.hpp:16
Result< CommissionModel > commission_model_from(const CommissionSchedule &schedule, Country country, const Date &date)
Builds a flat commission model from a schedule's rate for a market on a date.
Definition cost.hpp:96
LimitFillPrice
Which price a backtest credits a limit order that fills.
Definition cost.hpp:565
@ AT_OPEN_IF_BETTER
Fill at the bar's open when it opened through the limit (assumes the order was resting before the ope...
Definition cost.hpp:579
@ AT_LIMIT
The default: fill at the limit, or at the bar's worst traded price when the whole bar was better than...
Definition cost.hpp:574
constexpr std::string_view limit_fill_price_name(LimitFillPrice choice) noexcept
Returns a lowercase name for a choice, such as "at_limit", for reports.
Definition cost.hpp:587
The library: broker-neutral types (core), and the modules below.
@ NORMALIZED
A Venue the library normalizes.
Definition types.hpp:1511
@ RAW
A broker venue code the library does not normalize, kept verbatim.
Definition types.hpp:1513
@ ANY
Any venue (a venue-neutral rate).
Definition types.hpp:1509
CommissionOrigin
Where a commission schedule's numbers came from.
Definition types.hpp:1667
@ CALLER_STATED
The caller stated them, from a fee page or their own agreement.
Definition types.hpp:1671
@ BROKER_PUBLISHED
The broker published them, through an inquiry the library made.
Definition types.hpp:1669
constexpr bool commission_origin_names_tariff(CommissionOrigin origin) noexcept
Tests whether a schedule of this origin must name the tariff it was read from.
Definition types.hpp:1694
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
Country
A country (market) the library supports.
Definition types.hpp:32
constexpr bool commission_origin_is_broker(CommissionOrigin origin) noexcept
Tests whether commission rates of this origin came from the broker.
Definition types.hpp:1679
constexpr std::string_view venue_name(Venue venue) noexcept
Returns a display name for a venue, such as "KRX".
Definition types.hpp:60
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
Definition types.hpp:860
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
std::optional< CommissionRate > rate_
The rate in force, if one definitely is.
Definition types.hpp:1864
The commission rates a broker published for an account, or a caller stated.
Definition types.hpp:1830
RateSelection rate_for(Country country, const VenueKey &asserted, const Date &date) const
Finds the rate in force for a market and venue on a date.
Definition types.hpp:1887
CommissionOrigin origin_
Whether a broker published the rates or a caller stated them.
Definition types.hpp:1836
std::string tariff_
Which tariff the rates are, in the source's own words.
Definition types.hpp:1844
A calendar date with no time of day or time zone.
Definition types.hpp:1412
The price grid (tick sizes) an instrument's order prices must sit on.
std::optional< Decimal64 > tick_at(const Decimal64 &price) const
Returns the tick size at a price.
std::vector< TickBand > bands_
The bands, ascending by from_; empty unless kind_ is STATED.
The commission rate that charged an execution, as the backtest report lists it.
Definition cost.hpp:125
VenueKey venue_
The venue the rate was keyed to.
Definition cost.hpp:129
std::optional< Decimal64 > institution_rate_
The institution fee rate; empty if the source gave one combined rate.
Definition cost.hpp:133
std::optional< Date > until_
The last date of the rate's window; empty if open-ended.
Definition cost.hpp:139
friend bool operator==(const AppliedRate &lhs, const AppliedRate &rhs)
Compares every field except executions_.
Definition cost.hpp:155
std::optional< Date > from_
The first date of the rate's window; empty if open-ended.
Definition cost.hpp:137
Decimal64 minimum_
The per-execution minimum on the broker's commission; zero if none.
Definition cost.hpp:135
CommissionOrigin origin_
Whether a broker published the rate or a caller stated it.
Definition cost.hpp:141
Decimal64 rate_
The broker's commission, as a fraction of traded value.
Definition cost.hpp:131
std::size_t executions_
How many executions the rate charged, counted in the report's table.
Definition cost.hpp:147
Country country_
The market the rate was selected for.
Definition cost.hpp:127
What one execution was charged: the broker's commission and the institution fee.
Definition cost.hpp:168
std::optional< Decimal64 > institution_
The institution fee (유관기관제비용), if the rate is split.
Definition cost.hpp:172
Decimal64 broker_
The broker's commission, after its minimum.
Definition cost.hpp:170
AppliedRate applied_
The rate that charged it.
Definition cost.hpp:174
A flat commission: a rate on traded value, with an optional per-execution minimum.
Definition cost.hpp:28
std::optional< Decimal64 > on(const Decimal64 &quantity, const Decimal64 &price) const
Computes the commission on one execution.
Definition cost.hpp:46
Decimal64 rate_
The fraction of traded value charged per execution (0.00015, not 0.015).
Definition cost.hpp:30
static CommissionModel of(Decimal64 rate, Decimal64 minimum=Decimal64::parse("0"))
Returns a rate-based model.
Definition cost.hpp:77
Decimal64 minimum_
The smallest commission on any execution.
Definition cost.hpp:32
bool from_broker_
Whether the rate came from a broker's published schedule; commission_model_from sets it from the sche...
Definition cost.hpp:37
static CommissionModel none()
Returns a model that charges nothing (the report says so).
Definition cost.hpp:67
Slippage: how far a fill price moves against the order (a buy pays more, a sell gets less).
Definition cost.hpp:440
Decimal64 basis_points_
The price given up per execution, in ten-thousandths of the price.
Definition cost.hpp:442
static SlippageModel of_basis_points(Decimal64 points)
Returns a basis-point slippage model.
Definition cost.hpp:532
static SlippageModel of_ticks(int count)
Returns a tick slippage model.
Definition cost.hpp:543
static SlippageModel none()
Returns a model with no slippage (the report says so).
Definition cost.hpp:523
int ticks_
Grid steps given up per execution, each a step to the next grid price against the order.
Definition cost.hpp:444
std::optional< std::pair< Decimal64, Decimal64 > > apply(const Decimal64 &price, OrderSide side, const PriceRule &rule) const
Moves a price against the order.
Definition cost.hpp:459