algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
types.hpp
1#pragma once
2
3#include <boost/config.hpp>
4
5#include <array>
6#include <chrono>
7#include <cstddef>
8#include <cstdint>
9#include <cstdio>
10#include <cstdlib>
11#include <ctime>
12#include <functional>
13#include <limits>
14#include <optional>
15#include <stdexcept>
16#include <string>
17#include <string_view>
18#include <utility>
19#include <variant>
20#include <vector>
21
22#include "./enum_values.hpp"
23
24namespace algotradelib {
25
32enum class Country {
33 KR,
34 US,
35};
36
38inline constexpr std::array<Country, 2> all_countries{Country::KR, Country::US};
39
45enum class Venue {
46 UNSPECIFIED,
47 KRX,
48 NXT,
49 COMBINED,
50};
51
53inline constexpr std::array<Venue, 4> all_venues{Venue::UNSPECIFIED, Venue::KRX, Venue::NXT, Venue::COMBINED};
54
60inline constexpr std::string_view venue_name(Venue venue) noexcept {
61 switch (venue) {
62 case Venue::UNSPECIFIED:
63 return "unspecified";
64 case Venue::KRX:
65 return "KRX";
66 case Venue::NXT:
67 return "NXT";
68 case Venue::COMBINED:
69 return "COMBINED";
70 }
71 return "";
72}
73
74static_assert(
77 [](Venue venue) {
78 return !venue_name(venue).empty();
79 }
80 ),
81 "all_venues must list every Venue"
82);
83
87 Country country_{Country::KR};
93 Venue venue_{Venue::COMBINED};
95 std::string symbol_;
96
103 friend bool operator==(const InstrumentId& lhs, const InstrumentId& rhs) {
104 // The length and the first character settle most mismatches without a call to compare the strings.
105 return lhs.country_ == rhs.country_ && lhs.venue_ == rhs.venue_ && lhs.symbol_.size() == rhs.symbol_.size() &&
106 (lhs.symbol_.empty() || lhs.symbol_.front() == rhs.symbol_.front()) && lhs.symbol_ == rhs.symbol_;
107 }
108
118 friend bool operator<(const InstrumentId& lhs, const InstrumentId& rhs) {
119 if (lhs.country_ != rhs.country_) {
120 return lhs.country_ < rhs.country_;
121 }
122 if (lhs.venue_ != rhs.venue_) {
123 return lhs.venue_ < rhs.venue_;
124 }
125 return lhs.symbol_ < rhs.symbol_;
126 }
127};
128
130namespace id_detail {
131
133struct InstrumentIdHash {
134 std::size_t operator()(const InstrumentId& id) const noexcept {
135 std::size_t seed = std::hash<std::string>{}(id.symbol_);
136 seed ^= static_cast<std::size_t>(id.country_) + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
137 seed ^= static_cast<std::size_t>(id.venue_) + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
138 return seed;
139 }
140};
141
146inline constexpr std::size_t scan_limit = 16;
147
154class PositionTable {
155public:
156 PositionTable() = default;
157 PositionTable(const PositionTable&) = default;
158 PositionTable& operator=(const PositionTable&) = default;
159
161 PositionTable(PositionTable&& other) noexcept
162 : slots_(std::move(other.slots_)), count_(std::exchange(other.count_, 0)) {
163 other.slots_.clear();
164 }
165
167 PositionTable& operator=(PositionTable&& other) noexcept {
168 if (this != &other) {
169 slots_ = std::move(other.slots_);
170 other.slots_.clear();
171 count_ = std::exchange(other.count_, 0);
172 }
173 return *this;
174 }
175
177 bool empty() const noexcept {
178 return count_ == 0;
179 }
180
182 void reset() noexcept {
183 for (auto& slot : slots_) {
184 slot = 0;
185 }
186 count_ = 0;
187 }
188
190 template <typename IdOf>
191 std::optional<std::size_t> find(const InstrumentId& id, const IdOf& id_of) const noexcept {
192 if (count_ == 0) {
193 return std::nullopt;
194 }
195 const std::size_t mask = slots_.size() - 1;
196 for (std::size_t at = InstrumentIdHash{}(id)&mask;; at = (at + 1) & mask) {
197 const std::size_t slot = slots_[at];
198 if (slot == 0) {
199 return std::nullopt;
200 }
201 if (id_of(slot - 1) == id) {
202 return slot - 1;
203 }
204 }
205 }
206
211 template <typename IdOf>
212 void insert(const InstrumentId& id, std::size_t position, const IdOf& id_of) {
213 if (2 * (count_ + 1) > slots_.size()) {
214 std::size_t size = slots_.empty() ? 32 : 2 * slots_.size();
215 while (2 * (count_ + 1) > size) {
216 size *= 2;
217 }
218 std::vector<std::size_t> grown(size, 0);
219 for (const auto slot : slots_) {
220 if (slot != 0) {
221 place(grown, InstrumentIdHash{}(id_of(slot - 1)), slot);
222 }
223 }
224 slots_.swap(grown);
225 }
226 place(slots_, InstrumentIdHash{}(id), position + 1);
227 ++count_;
228 }
229
230private:
231 static void place(std::vector<std::size_t>& slots, std::size_t hash, std::size_t slot) noexcept {
232 const std::size_t mask = slots.size() - 1;
233 std::size_t at = hash & mask;
234 while (slots[at] != 0) {
235 at = (at + 1) & mask;
236 }
237 slots[at] = slot;
238 }
239
240 // A position plus one; zero is an empty slot.
241 std::vector<std::size_t> slots_;
242 std::size_t count_{0};
243};
244
245} // namespace id_detail
247
258template <std::size_t N>
259class Code {
260public:
262 Code() = default;
263
270 explicit Code(std::string_view text) {
271 if (text.size() > N) {
272 throw std::invalid_argument("code is longer than its capacity");
273 }
274 for (std::size_t i = 0; i < text.size(); ++i) {
275 const char ch = text[i];
276 const bool valid = (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_';
277 if (!valid) {
278 throw std::invalid_argument("code must use uppercase ASCII, digits, or underscore");
279 }
280 characters_[i] = ch;
281 }
282 size_ = static_cast<std::uint8_t>(text.size());
283 }
284
291 static std::optional<Code> try_make(std::string_view text) {
292 if (text.size() > N) {
293 return std::nullopt;
294 }
295 Code code;
296 for (std::size_t i = 0; i < text.size(); ++i) {
297 const char ch = text[i];
298 const bool valid = (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_';
299 if (!valid) {
300 return std::nullopt;
301 }
302 code.characters_[i] = ch;
303 }
304 code.size_ = static_cast<std::uint8_t>(text.size());
305 return code;
306 }
307
312 std::string_view view() const noexcept {
313 return std::string_view(characters_.data(), size_);
314 }
315
320 std::string str() const {
321 return std::string(view());
322 }
323
328 bool empty() const noexcept {
329 return size_ == 0;
330 }
331
336 std::size_t size() const noexcept {
337 return size_;
338 }
339
344 static constexpr std::size_t capacity() noexcept {
345 return N;
346 }
347
354 friend bool operator==(const Code& lhs, const Code& rhs) {
355 return lhs.view() == rhs.view();
356 }
357
364 friend bool operator!=(const Code& lhs, const Code& rhs) {
365 return !(lhs == rhs);
366 }
367
368private:
369 std::array<char, N> characters_{};
370 std::uint8_t size_{0};
371};
372
374class Currency {
375public:
377 Currency() : code_{'K', 'R', 'W'} {}
378
385 explicit Currency(std::string_view code) {
386 if (code.size() != code_.size()) {
387 throw std::invalid_argument("currency code must contain three characters");
388 }
389 for (std::size_t i = 0; i < code_.size(); ++i) {
390 const char ch = code[i];
391 if (ch < 'A' || ch > 'Z') {
392 throw std::invalid_argument("currency code must use uppercase ASCII characters");
393 }
394 code_[i] = ch;
395 }
396 }
397
402 static Currency krw() {
403 return Currency("KRW");
404 }
405
410 static Currency usd() {
411 return Currency("USD");
412 }
413
418 std::string str() const {
419 return std::string(code_.begin(), code_.end());
420 }
421
428 friend bool operator==(const Currency& lhs, const Currency& rhs) {
429 return lhs.code_ == rhs.code_;
430 }
431
432private:
433 std::array<char, 3> code_{};
434};
435
444public:
446 Decimal64() = default;
447
453 Decimal64(std::int64_t coefficient, std::uint8_t scale) : coefficient_(coefficient), scale_(scale) {}
454
468 static Decimal64 parse(std::string_view input) {
469 if (input.empty()) {
470 throw std::invalid_argument("decimal value is empty");
471 }
472
473 bool negative = false;
474 std::size_t index = 0;
475 if (input.front() == '+' || input.front() == '-') {
476 negative = input.front() == '-';
477 index = 1;
478 }
479 if (index == input.size()) {
480 throw std::invalid_argument("decimal value has no digits");
481 }
482
483 std::uint64_t magnitude = 0;
484 std::uint8_t scale = 0;
485 bool decimal_point = false;
486 bool has_digit = false;
487 const std::uint64_t limit = negative ?
488 static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + 1ULL :
489 static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max());
490
491 for (; index < input.size(); ++index) {
492 const char ch = input[index];
493 if (ch == '.') {
494 if (decimal_point) {
495 throw std::invalid_argument("decimal value contains multiple points");
496 }
497 decimal_point = true;
498 continue;
499 }
500 if (ch < '0' || ch > '9') {
501 throw std::invalid_argument("decimal value contains an invalid character");
502 }
503 has_digit = true;
504 const auto digit = static_cast<std::uint64_t>(ch - '0');
505 if (magnitude > (limit - digit) / 10ULL) {
506 throw std::out_of_range("decimal value exceeds Decimal64 range");
507 }
508 magnitude = magnitude * 10ULL + digit;
509 if (decimal_point) {
510 if (scale == std::numeric_limits<std::uint8_t>::max()) {
511 throw std::out_of_range("decimal scale exceeds Decimal64 range");
512 }
513 ++scale;
514 }
515 }
516 if (!has_digit) {
517 throw std::invalid_argument("decimal value has no digits");
518 }
519
520 while (scale > 0 && magnitude % 10ULL == 0) {
521 magnitude /= 10ULL;
522 --scale;
523 }
524
525 std::int64_t coefficient;
526 if (negative && magnitude == static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + 1ULL) {
527 coefficient = std::numeric_limits<std::int64_t>::min();
528 } else {
529 coefficient = static_cast<std::int64_t>(magnitude);
530 if (negative) {
532 }
533 }
534 return Decimal64(coefficient, scale);
535 }
536
541 std::int64_t coefficient() const noexcept {
542 return coefficient_;
543 }
544
549 std::uint8_t scale() const noexcept {
550 return scale_;
551 }
552
557 std::string str() const {
558 const bool negative = coefficient_ < 0;
559 std::uint64_t magnitude =
560 negative ? static_cast<std::uint64_t>(-(coefficient_ + 1)) + 1ULL : static_cast<std::uint64_t>(coefficient_);
561 std::string digits = std::to_string(magnitude);
562 if (scale_ > 0) {
563 if (digits.size() <= scale_) {
564 digits.insert(0, static_cast<std::size_t>(scale_) - digits.size() + 1, '0');
565 }
566 digits.insert(digits.size() - scale_, 1, '.');
567 }
568 if (negative) {
569 digits.insert(digits.begin(), '-');
570 }
571 return digits;
572 }
573
586 friend bool operator==(const Decimal64& lhs, const Decimal64& rhs) {
587 return lhs.coefficient_ == rhs.coefficient_ && lhs.scale_ == rhs.scale_;
588 }
589
590private:
591 std::int64_t coefficient_{0};
592 std::uint8_t scale_{0};
593};
594
601 auto coefficient = value.coefficient();
602 auto scale = value.scale();
603 while (scale > 0 && coefficient % 10 == 0) {
604 coefficient /= 10;
605 --scale;
606 }
607 return Decimal64(coefficient, scale);
608}
609
610namespace decimal_detail {
611
618inline bool align(
619 const Decimal64& lhs, const Decimal64& rhs, std::int64_t& left, std::int64_t& right, std::uint8_t& scale
620) {
621 scale = lhs.scale() > rhs.scale() ? lhs.scale() : rhs.scale();
622 left = lhs.coefficient();
623 right = rhs.coefficient();
624 for (std::uint8_t step = lhs.scale(); step < scale; ++step) {
625 if (left > std::numeric_limits<std::int64_t>::max() / 10 || left < std::numeric_limits<std::int64_t>::min() / 10) {
626 return false;
627 }
628 left *= 10;
629 }
630 for (std::uint8_t step = rhs.scale(); step < scale; ++step) {
631 if (
632 right > std::numeric_limits<std::int64_t>::max() / 10 || right < std::numeric_limits<std::int64_t>::min() / 10
633 ) {
634 return false;
635 }
636 right *= 10;
637 }
638 return true;
639}
640
645struct PowersOfTen {
646 std::uint64_t power_[20]{};
647 std::uint64_t limit_[20]{};
648
649 constexpr PowersOfTen() {
650 std::uint64_t value = 1;
651 for (int k = 0; k < 20; ++k) {
652 power_[k] = value;
653 limit_[k] = std::numeric_limits<std::uint64_t>::max() / value;
654 if (k < 19) {
655 value *= 10;
656 }
657 }
658 }
659};
660
661inline constexpr PowersOfTen powers_of_ten{};
662
667inline std::optional<Decimal64> signed_quotient(std::uint64_t quotient, int places, bool negative) {
668 if (quotient == 0) {
669 return Decimal64(0, 0);
670 }
671 while (places > 0 && quotient % 10 == 0) {
672 quotient /= 10;
673 --places;
674 }
675 const std::uint64_t limit = static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + (negative ? 1 : 0);
676 if (quotient > limit) {
677 return std::nullopt;
678 }
679 const auto coefficient =
680 negative ? -static_cast<std::int64_t>(quotient - 1) - 1 : static_cast<std::int64_t>(quotient);
681 return Decimal64(coefficient, static_cast<std::uint8_t>(places));
682}
683
689BOOST_NOINLINE inline std::optional<Decimal64> divide_by_digits(
690 std::uint64_t dividend, std::uint64_t divisor, int shift, int places, bool negative
691) {
692 const std::uint64_t limit = static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + (negative ? 1 : 0);
693 std::uint64_t quotient = dividend / divisor;
694 std::uint64_t remainder = dividend % divisor;
695 // Zero digits owed to the end of `quotient`, kept as a count until a nonzero digit follows them,
696 // because normalization may remove them again.
697 int zeros = 0;
698 for (; shift > 0 && remainder != 0; --shift) {
699 // The next digit is `10 x remainder / divisor`. When ten times the remainder would not fit, it
700 // is formed by ten additions reduced modulo the divisor; two residues sum to at most 2^64 - 2.
701 std::uint64_t digit = 0;
702 if (remainder <= std::numeric_limits<std::uint64_t>::max() / 10) {
703 const std::uint64_t tenfold = remainder * 10;
704 digit = tenfold / divisor;
705 remainder = tenfold % divisor;
706 } else {
707 std::uint64_t next = 0;
708 for (int step = 0; step < 10; ++step) {
709 next += remainder;
710 if (next >= divisor) {
711 next -= divisor;
712 ++digit;
713 }
714 }
715 remainder = next;
716 }
717 if (digit == 0) {
718 ++zeros;
719 continue;
720 }
721 // Each step is checked before it is taken: past the limit, the result cannot fit.
722 for (; zeros > 0; --zeros) {
723 if (quotient > limit / 10) {
724 return std::nullopt;
725 }
726 quotient *= 10;
727 }
728 if (quotient > (limit - digit) / 10) {
729 return std::nullopt;
730 }
731 quotient = quotient * 10 + digit;
732 }
733 // A zero remainder leaves only zero digits.
734 zeros += shift;
735 if (quotient == 0) {
736 return Decimal64(0, 0);
737 }
738 // A pending zero within the scale lowers the scale; one beyond it is a digit of the integer part.
739 const int dropped = zeros < places ? zeros : places;
740 places -= dropped;
741 zeros -= dropped;
742 for (; zeros > 0; --zeros) {
743 if (quotient > limit / 10) {
744 return std::nullopt;
745 }
746 quotient *= 10;
747 }
748 return signed_quotient(quotient, places, negative);
749}
750
751} // namespace decimal_detail
752
760inline std::optional<Decimal64> decimal_add(const Decimal64& lhs, const Decimal64& rhs) {
761 std::int64_t left = 0;
762 std::int64_t right = 0;
763 std::uint8_t scale = 0;
764 if (!decimal_detail::align(lhs, rhs, left, right, scale)) {
765 return std::nullopt;
766 }
767 if (
768 (right > 0 && left > std::numeric_limits<std::int64_t>::max() - right) ||
769 (right < 0 && left < std::numeric_limits<std::int64_t>::min() - right)
770 ) {
771 return std::nullopt;
772 }
773 return decimal_normalized(Decimal64(left + right, scale));
774}
775
783inline std::optional<Decimal64> decimal_subtract(const Decimal64& lhs, const Decimal64& rhs) {
784 std::int64_t left = 0;
785 std::int64_t right = 0;
786 std::uint8_t scale = 0;
787 if (!decimal_detail::align(lhs, rhs, left, right, scale)) {
788 return std::nullopt;
789 }
790 if (
791 (right < 0 && left > std::numeric_limits<std::int64_t>::max() + right) ||
792 (right > 0 && left < std::numeric_limits<std::int64_t>::min() + right)
793 ) {
794 return std::nullopt;
795 }
796 return decimal_normalized(Decimal64(left - right, scale));
797}
798
804inline std::optional<Decimal64> decimal_halve(const Decimal64& value) {
805 const auto coefficient = value.coefficient();
806 if (coefficient % 2 == 0) {
807 return decimal_normalized(Decimal64(coefficient / 2, value.scale()));
808 }
809 if (
810 value.scale() == std::numeric_limits<std::uint8_t>::max() ||
811 coefficient > std::numeric_limits<std::int64_t>::max() / 5 ||
812 coefficient < std::numeric_limits<std::int64_t>::min() / 5
813 ) {
814 return std::nullopt;
815 }
816 return decimal_normalized(Decimal64(coefficient * 5, static_cast<std::uint8_t>(value.scale() + 1)));
817}
818
826inline std::optional<Decimal64> decimal_multiply(const Decimal64& lhs, const Decimal64& rhs) {
827 const auto left = lhs.coefficient();
828 const auto right = rhs.coefficient();
829 const int scale = static_cast<int>(lhs.scale()) + static_cast<int>(rhs.scale());
830 if (scale > std::numeric_limits<std::uint8_t>::max()) {
831 return std::nullopt;
832 }
833 if (left != 0 && right != 0) {
834 // Checked before multiplying rather than after, because signed overflow is undefined and a
835 // wrapped price is exactly the failure this type exists to prevent.
836 constexpr auto largest = std::numeric_limits<std::int64_t>::max();
837 constexpr auto smallest = std::numeric_limits<std::int64_t>::min();
838 if (
839 left > 0 ?
840 (right > 0 ? left > largest / right : right < smallest / left) :
841 (right > 0 ? left < smallest / right : left < largest / right)
842 ) {
843 return std::nullopt;
844 }
845 }
846 return decimal_normalized(Decimal64(left * right, static_cast<std::uint8_t>(scale)));
847}
848
860inline std::optional<Decimal64> decimal_divide(const Decimal64& lhs, const Decimal64& rhs, std::uint8_t scale) {
861 // Magnitudes, so the smallest coefficient is 2^63 and the sign is applied once, at the end.
862 const auto magnitude = [](std::int64_t value) {
863 return value < 0 ? static_cast<std::uint64_t>(-(value + 1)) + 1 : static_cast<std::uint64_t>(value);
864 };
865 const std::uint64_t dividend = magnitude(lhs.coefficient());
866 const std::uint64_t divisor = magnitude(rhs.coefficient());
867 if (divisor == 0) {
868 return std::nullopt;
869 }
870 const bool negative = (lhs.coefficient() < 0) != (rhs.coefficient() < 0);
871
872 // The coefficient is `dividend x 10^shift / divisor`, truncated, at `scale` places. When the
873 // dividend times 10^shift fits 64 bits, one division gives it; otherwise the digits come from
874 // `divide_by_digits`, so no intermediate leaves 64 bits.
875 const int shift = static_cast<int>(scale) + static_cast<int>(rhs.scale()) - static_cast<int>(lhs.scale());
876 constexpr const auto& powers = decimal_detail::powers_of_ten;
877 std::uint64_t quotient = 0;
878 if (shift <= 0) {
879 // A divisor times 10^-shift that leaves 64 bits exceeds every dividend.
880 const int places_dropped = -shift;
881 quotient = places_dropped < 20 && divisor <= powers.limit_[places_dropped] ?
882 dividend / (divisor * powers.power_[places_dropped]) :
883 0;
884 } else if (shift < 20 && dividend <= powers.limit_[shift]) {
885 quotient = dividend * powers.power_[shift] / divisor;
886 } else {
887 return decimal_detail::divide_by_digits(dividend, divisor, shift, scale, negative);
888 }
889 return decimal_detail::signed_quotient(quotient, scale, negative);
890}
891
903inline std::optional<Decimal64> decimal_floor_to_multiple(const Decimal64& value, const Decimal64& step) {
904 std::int64_t left = 0;
905 std::int64_t right = 0;
906 std::uint8_t scale = 0;
907 if (!decimal_detail::align(value, step, left, right, scale) || right <= 0) {
908 return std::nullopt;
909 }
910 auto rest = left % right;
911 if (rest < 0) {
912 rest += right;
913 }
914 if (left < std::numeric_limits<std::int64_t>::min() + rest) {
915 return std::nullopt;
916 }
917 return decimal_normalized(Decimal64(left - rest, scale));
918}
919
926inline bool decimal_less(const Decimal64& lhs, const Decimal64& rhs) {
927 std::int64_t left = 0;
928 std::int64_t right = 0;
929 std::uint8_t scale = 0;
930 if (decimal_detail::align(lhs, rhs, left, right, scale)) {
931 return left < right;
932 }
933 // Rescaling overflowed, so the values differ by more than any shared scale can
934 // express: the one with the smaller scale has the larger magnitude. Between two
935 // negatives the larger magnitude is the smaller value.
936 const bool left_negative = lhs.coefficient() < 0;
937 if (left_negative != (rhs.coefficient() < 0)) {
938 return left_negative;
939 }
940 return left_negative ? lhs.scale() < rhs.scale() : lhs.scale() > rhs.scale();
941}
942
976
983inline constexpr bool error_category_is_rate_limit(ErrorCategory category) noexcept {
984 switch (category) {
986 return true;
993 return false;
994 }
995 return false;
996}
997
1022 std::string broker_code_;
1024 std::string request_id_;
1033 std::string message_;
1040 std::optional<std::chrono::seconds> retry_after_;
1046 std::optional<int> rate_limit_;
1047};
1048
1057template <typename T>
1058class Result {
1059public:
1064 Result(T value) : value_(std::move(value)) {}
1065
1070 Result(BrokerError error) : value_(std::move(error)) {}
1071
1076 bool has_value() const noexcept {
1077 return std::holds_alternative<T>(value_);
1078 }
1079
1084 explicit operator bool() const noexcept {
1085 return has_value();
1086 }
1087
1093 T& value() {
1094 return std::get<T>(value_);
1095 }
1096
1102 const T& value() const {
1103 return std::get<T>(value_);
1104 }
1105
1112 return std::get<BrokerError>(value_);
1113 }
1114
1120 const BrokerError& error() const {
1121 return std::get<BrokerError>(value_);
1122 }
1123
1124private:
1125 std::variant<T, BrokerError> value_;
1126};
1127
1133 std::optional<Decimal64> bid_price_;
1135 std::optional<Decimal64> bid_quantity_;
1137 std::optional<Decimal64> ask_price_;
1139 std::optional<Decimal64> ask_quantity_;
1140};
1141
1151 std::optional<std::chrono::system_clock::time_point> exchange_time_;
1153 std::chrono::system_clock::time_point received_at_;
1154
1162 std::optional<TopOfBook> top_of_book_;
1164 std::optional<Decimal64> volume_;
1165};
1166
1168struct Money {
1173
1180 friend bool operator==(const Money& lhs, const Money& rhs) {
1181 return lhs.amount_ == rhs.amount_ && lhs.currency_ == rhs.currency_;
1182 }
1183};
1184
1193 enum class Coverage {
1195 UNESTABLISHED,
1197 WHOLE_HOLDING,
1202 PARTIAL,
1203 };
1204
1206 enum class RestingTreatment {
1208 UNESTABLISHED,
1215 DEDUCT,
1216 };
1217
1227 bool verified_ = false;
1228
1233 constexpr bool is_enforceable() const noexcept {
1234 bool covers = false;
1235 switch (coverage_) {
1237 covers = true;
1238 break;
1240 case Coverage::PARTIAL:
1241 break;
1242 }
1243 bool treated = false;
1244 switch (resting_) {
1246 treated = true;
1247 break;
1249 break;
1250 }
1251 return covers && treated;
1252 }
1253};
1254
1260inline constexpr std::string_view sellable_coverage_name(SellableBasis::Coverage coverage) noexcept {
1261 switch (coverage) {
1263 return "unestablished";
1265 return "whole_holding";
1267 return "partial";
1268 }
1269 return "unestablished";
1270}
1271
1277inline constexpr std::string_view sellable_resting_name(SellableBasis::RestingTreatment treatment) noexcept {
1278 switch (treatment) {
1280 return "unestablished";
1282 return "deduct";
1283 }
1284 return "unestablished";
1285}
1286
1326
1343
1347 std::vector<HoldingPosition> positions_;
1349 std::vector<HoldingsTotals> totals_;
1351 std::chrono::system_clock::time_point received_at_;
1359};
1360
1362enum class SellableSource {
1364 HOLDINGS,
1368 NONE,
1369};
1370
1376inline constexpr std::string_view sellable_source_name(SellableSource source) noexcept {
1377 switch (source) {
1379 return "holdings";
1381 return "inquiry";
1383 return "none";
1384 }
1385 return "none";
1386}
1387
1404 std::chrono::system_clock::time_point received_at_{};
1405};
1406
1412struct Date {
1414 int year_{0};
1416 unsigned month_{0};
1418 unsigned day_{0};
1419
1426 friend bool operator==(const Date& lhs, const Date& rhs) {
1427 return lhs.year_ == rhs.year_ && lhs.month_ == rhs.month_ && lhs.day_ == rhs.day_;
1428 }
1429
1436 friend bool operator<(const Date& lhs, const Date& rhs) {
1437 if (lhs.year_ != rhs.year_) {
1438 return lhs.year_ < rhs.year_;
1439 }
1440 if (lhs.month_ != rhs.month_) {
1441 return lhs.month_ < rhs.month_;
1442 }
1443 return lhs.day_ < rhs.day_;
1444 }
1445};
1446
1456inline Date date_from_epoch_days(std::int64_t days) {
1457 // Shifts the era so that the year starts in March, which is what removes the leap-day special
1458 // case from everything below: 1970-01-01 is 719468 days after 0000-03-01.
1459 const std::int64_t shifted = days + 719468;
1460 const std::int64_t era = (shifted >= 0 ? shifted : shifted - 146096) / 146097;
1461 const std::int64_t day_of_era = shifted - era * 146097;
1462 const std::int64_t year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / 365;
1463 const std::int64_t year = year_of_era + era * 400;
1464 const std::int64_t day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1465 const std::int64_t shifted_month = (5 * day_of_year + 2) / 153;
1466 const std::int64_t day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
1467 const std::int64_t month = shifted_month + (shifted_month < 10 ? 3 : -9);
1468 return Date{
1469 static_cast<int>(year + (month <= 2 ? 1 : 0)),
1470 static_cast<unsigned>(month),
1471 static_cast<unsigned>(day),
1472 };
1473}
1474
1480inline bool is_valid_date(const Date& date) {
1481 if (date.year_ < 1 || date.year_ > 9999 || date.month_ < 1 || date.month_ > 12) {
1482 return false;
1483 }
1484 static constexpr unsigned days_per_month[] = {
1485 31,
1486 28,
1487 31,
1488 30,
1489 31,
1490 30,
1491 31,
1492 31,
1493 30,
1494 31,
1495 30,
1496 31,
1497 };
1498 unsigned days = days_per_month[date.month_ - 1];
1499 const bool leap = date.year_ % 4 == 0 && (date.year_ % 100 != 0 || date.year_ % 400 == 0);
1500 if (date.month_ == 2 && leap) {
1501 ++days;
1502 }
1503 return date.day_ >= 1 && date.day_ <= days;
1504}
1505
1515
1524public:
1526 VenueKey() = default;
1527
1532 static VenueKey any() noexcept {
1533 return VenueKey();
1534 }
1535
1541 static std::optional<VenueKey> normalized(Venue venue) {
1542 if (venue == Venue::UNSPECIFIED) {
1543 return std::nullopt;
1544 }
1545 VenueKey key;
1546 key.kind_ = VenueKeyKind::NORMALIZED;
1547 key.venue_ = venue;
1548 return key;
1549 }
1550
1556 static std::optional<VenueKey> raw(std::string_view code) {
1557 auto stored = Code<8>::try_make(code);
1558 if (!stored || stored->empty()) {
1559 return std::nullopt;
1560 }
1561 VenueKey key;
1562 key.kind_ = VenueKeyKind::RAW;
1563 key.raw_ = *stored;
1564 return key;
1565 }
1566
1571 VenueKeyKind kind() const noexcept {
1572 return kind_;
1573 }
1574
1579 bool is_any() const noexcept {
1580 return kind_ == VenueKeyKind::ANY;
1581 }
1582
1587 Venue venue() const noexcept {
1588 return venue_;
1589 }
1590
1595 const Code<8>& raw_code() const noexcept {
1596 return raw_;
1597 }
1598
1608 bool matches(const VenueKey& asserted) const noexcept {
1609 if (kind_ != asserted.kind_) {
1610 return false;
1611 }
1612 switch (kind_) {
1613 case VenueKeyKind::ANY:
1614 return true;
1616 return venue_ == asserted.venue_;
1617 case VenueKeyKind::RAW:
1618 return raw_ == asserted.raw_;
1619 }
1620 return false;
1621 }
1622
1629 friend bool operator==(const VenueKey& lhs, const VenueKey& rhs) noexcept {
1630 return lhs.matches(rhs);
1631 }
1632
1639 friend bool operator!=(const VenueKey& lhs, const VenueKey& rhs) noexcept {
1640 return !(lhs == rhs);
1641 }
1642
1643private:
1645 Venue venue_{Venue::UNSPECIFIED};
1646 Code<8> raw_;
1647};
1648
1654inline constexpr std::string_view venue_key_kind_name(VenueKeyKind kind) noexcept {
1655 switch (kind) {
1656 case VenueKeyKind::ANY:
1657 return "any";
1659 return "normalized";
1660 case VenueKeyKind::RAW:
1661 return "raw";
1662 }
1663 return "unknown";
1664}
1665
1673
1679inline constexpr bool commission_origin_is_broker(CommissionOrigin origin) noexcept {
1680 switch (origin) {
1682 return true;
1684 return false;
1685 }
1686 return false;
1687}
1688
1694inline constexpr bool commission_origin_names_tariff(CommissionOrigin origin) noexcept {
1695 switch (origin) {
1697 return true;
1699 return false;
1700 }
1701 return true;
1702}
1703
1709inline constexpr std::string_view commission_origin_name(CommissionOrigin origin) noexcept {
1710 switch (origin) {
1712 return "broker_published";
1714 return "caller_stated";
1715 }
1716 return "unknown";
1717}
1718
1732
1744 Country country_{Country::KR};
1768 std::optional<Decimal64> institution_rate_;
1772 std::optional<Date> from_;
1774 std::optional<Date> until_;
1781 bool from_unreadable_{false};
1789
1794 bool normalized() const noexcept {
1795 return other_.empty();
1796 }
1797
1805 RateApplicability applies_on(const Date& date) const {
1806 if (excluded_on(date)) {
1807 return RateApplicability::NO;
1808 }
1811 }
1813 }
1814
1820 bool excluded_on(const Date& date) const {
1821 return (from_ && date < *from_) || (until_ && *until_ < date);
1822 }
1823};
1824
1832 std::vector<CommissionRate> rates_;
1834 std::chrono::system_clock::time_point received_at_{};
1844 std::string tariff_;
1845
1851 std::size_t dropped_{0};
1852
1859 std::size_t unreadable_bounds_{0};
1860
1864 std::optional<CommissionRate> rate_;
1872 };
1873
1887 RateSelection rate_for(Country country, const VenueKey& asserted, const Date& date) const {
1888 // A row for a market this library does not normalize can never be the answer to a question asked
1889 // in terms of `Country`, and it is kept so a caller can see that the broker sent it.
1890 const auto in_market = [&](const CommissionRate& rate) {
1891 return rate.normalized() && rate.country_ == country;
1892 };
1893 // **Each pass stops at the first row that decides it, and an unreadable row decides it too.**
1894 // Within a pass the first match has always won, so a damaged row *after* a definite match could
1895 // never have been the answer and is not a reason to refuse -- scanning the whole pass first would
1896 // throw away an answer this library knows. A damaged row reached *before* any match is the
1897 // opposite case: it may have been the match, so nothing later in the pass can be trusted to be
1898 // the winner.
1899 const auto pass = [&](bool venue_specific) -> std::optional<RateSelection> {
1900 for (const auto& rate : rates_) {
1901 if (!in_market(rate)) {
1902 continue;
1903 }
1904 if (!(venue_specific ? rate.venue_.matches(asserted) : rate.venue_.is_any())) {
1905 continue;
1906 }
1907 switch (rate.applies_on(date)) {
1909 continue;
1911 RateSelection found;
1912 found.rate_ = rate;
1913 return found;
1914 }
1916 RateSelection refused;
1917 refused.bounds_unreadable_ = true;
1918 return refused;
1919 }
1920 }
1921 }
1922 return std::nullopt;
1923 };
1924 // An undecided pass one falls through; a *refused* pass one does not. Pass two's precondition is
1925 // "no row for the asserted venue applies", and that is precisely what stopped being known.
1926 if (const auto venue_row = pass(true)) {
1927 return *venue_row;
1928 }
1929 if (const auto neutral_row = pass(false)) {
1930 return *neutral_row;
1931 }
1932 return RateSelection{};
1933 }
1934
1940 bool any_dated_rate_for(Country country) const {
1941 for (const auto& rate : rates_) {
1942 // A bound that could not be read is still a bound the source stated. Asking only whether the
1943 // optionals are filled would read a row dated *solely* by damage as undated, and hand the
1944 // caller the very "every candidate is the same whichever calendar named the day" assurance
1945 // that the damage makes impossible.
1946 const bool dated = rate.from_ || rate.until_ || rate.from_unreadable_ || rate.until_unreadable_;
1947 if (rate.normalized() && rate.country_ == country && dated) {
1948 return true;
1949 }
1950 }
1951 return false;
1952 }
1953
1963 RateSelection rate_for(Country country, const Date& date) const {
1964 return rate_for(country, VenueKey::any(), date);
1965 }
1966};
1967
1974enum class OrderSide {
1975 BUY,
1976 SELL,
1977};
1978
1980inline constexpr std::array<OrderSide, 2> all_order_sides{OrderSide::BUY, OrderSide::SELL};
1981
1982// The direction is closed: about forty sites in the ledger, fills, costs, risk and reconciliation read
1983// "not BUY" as SELL. A short-sale or short-exempt mark, or a cover-only constraint, is a separate fact that
1984// would travel in its own field through the intent, the request, the journal and recovery.
1985static_assert(
1986 all_order_sides.size() == 2,
1987 "OrderSide is buy or sell: a short-sale mark or a cover belongs in its own field, not in OrderSide"
1988);
1989
2017
2019inline constexpr std::array<OrderType, 9> all_order_types{
2020 OrderType::UNKNOWN,
2029};
2030
2039inline constexpr bool carries_caller_price(OrderType type) noexcept {
2040 switch (type) {
2041 case OrderType::LIMIT:
2044 return true;
2045 case OrderType::UNKNOWN:
2046 case OrderType::MARKET:
2051 return false;
2052 }
2053 return false;
2054}
2055
2065inline constexpr bool carries_trigger_price(OrderType type) noexcept {
2066 switch (type) {
2068 return true;
2069 case OrderType::UNKNOWN:
2070 case OrderType::LIMIT:
2071 case OrderType::MARKET:
2077 return false;
2078 }
2079 return false;
2080}
2081
2097
2099inline constexpr std::array<TimeInForce, 4> all_times_in_force{
2100 TimeInForce::UNKNOWN,
2104};
2105
2113inline constexpr bool time_in_force_expires_at_close(TimeInForce condition) noexcept {
2114 switch (condition) {
2115 case TimeInForce::DAY:
2116 return true;
2117 case TimeInForce::UNKNOWN:
2120 return false;
2121 }
2122 return false;
2123}
2124
2149
2162
2170enum class OrderStatus {
2171 UNKNOWN,
2172 PENDING,
2173 PENDING_CANCEL,
2174 PENDING_REPLACE,
2175 PARTIAL_FILLED,
2176 FILLED,
2177 CANCELED,
2178 REJECTED,
2179 CANCEL_REJECTED,
2180 REPLACE_REJECTED,
2181 REPLACED,
2182};
2183
2190inline constexpr bool order_status_cancel_pending(OrderStatus status) noexcept {
2191 switch (status) {
2192 case OrderStatus::PENDING_CANCEL:
2193 return true;
2194 case OrderStatus::UNKNOWN:
2195 case OrderStatus::PENDING:
2196 case OrderStatus::PENDING_REPLACE:
2197 case OrderStatus::PARTIAL_FILLED:
2198 case OrderStatus::FILLED:
2199 case OrderStatus::CANCELED:
2200 case OrderStatus::REJECTED:
2201 case OrderStatus::CANCEL_REJECTED:
2202 case OrderStatus::REPLACE_REJECTED:
2203 case OrderStatus::REPLACED:
2204 return false;
2205 }
2206 return false;
2207}
2208
2261
2281 std::optional<Decimal64> average_filled_price_;
2287 std::optional<Money> filled_amount_;
2289 std::optional<Money> commission_;
2291 std::optional<Money> tax_;
2293 std::optional<std::chrono::system_clock::time_point> filled_at_;
2295 std::optional<Date> settlement_date_;
2296};
2297
2301 std::string order_id_;
2305 std::string name_;
2307 OrderSide side_{OrderSide::BUY};
2309 OrderType type_{OrderType::UNKNOWN};
2311 TimeInForce time_in_force_{TimeInForce::UNKNOWN};
2313 OrderSession session_{OrderSession::UNKNOWN};
2320 Venue venue_{Venue::UNSPECIFIED};
2329 OrderStatus status_{OrderStatus::UNKNOWN};
2331 std::optional<Decimal64> price_;
2339 std::optional<Decimal64> trigger_price_;
2349 std::optional<Decimal64> order_amount_;
2356 std::optional<std::chrono::system_clock::time_point> ordered_at_;
2363 std::optional<std::chrono::system_clock::time_point> canceled_at_;
2366};
2367
2371 std::vector<OrderSnapshot> orders_;
2373 std::optional<std::string> next_cursor_;
2375 std::chrono::system_clock::time_point received_at_;
2376};
2377
2383struct OrderAck {
2385 std::string order_id_;
2387 std::optional<std::string> client_order_id_;
2389 std::chrono::system_clock::time_point accepted_at_;
2390};
2391
2401template <typename Broker>
2402struct OrderRef {
2404 std::string primary_;
2406 std::string secondary_;
2407
2412 static constexpr std::string_view broker() noexcept {
2413 return Broker::name;
2414 }
2415
2420 std::string str() const {
2421 std::string text(broker());
2422 text += ':';
2423 text += primary_;
2424 if (!secondary_.empty()) {
2425 text += ':';
2426 text += secondary_;
2427 }
2428 return text;
2429 }
2430
2437 friend bool operator==(const OrderRef& lhs, const OrderRef& rhs) {
2438 return lhs.primary_ == rhs.primary_ && lhs.secondary_ == rhs.secondary_;
2439 }
2440
2447 friend bool operator!=(const OrderRef& lhs, const OrderRef& rhs) {
2448 return !(lhs == rhs);
2449 }
2450};
2451
2459template <typename Broker>
2466
2476 OrderShape() = default;
2487 OrderType type, std::optional<Decimal64> price, std::optional<TimeInForce> time_in_force = std::nullopt,
2488 std::optional<OrderSession> session = std::nullopt, std::optional<Decimal64> trigger_price = std::nullopt
2489 )
2490 : type_(type),
2491 price_(std::move(price)),
2492 trigger_price_(std::move(trigger_price)),
2493 time_in_force_(time_in_force),
2494 session_(session) {}
2495
2499 std::optional<Decimal64> price_;
2508 std::optional<Decimal64> trigger_price_;
2515 std::optional<TimeInForce> time_in_force_;
2522 std::optional<OrderSession> session_;
2523};
2524
2540 Venue venue_{Venue::UNSPECIFIED};
2542 std::optional<Decimal64> quantity_;
2544 bool all_remaining_{false};
2553 std::optional<OrderShape> resting_;
2554};
2555
2563inline std::optional<Decimal64> amended_trigger_price(const AmendInstruction& instruction) {
2564 if (instruction.shape_.trigger_price_) {
2565 return instruction.shape_.trigger_price_;
2566 }
2567 if (
2568 carries_trigger_price(instruction.shape_.type_) && instruction.resting_ &&
2569 carries_trigger_price(instruction.resting_->type_)
2570 ) {
2571 return instruction.resting_->trigger_price_;
2572 }
2573 return std::nullopt;
2574}
2575
2581template <typename Broker>
2598
2603template <typename Broker>
2606 std::vector<WorkingOrder<Broker>> orders_;
2608 std::chrono::system_clock::time_point received_at_;
2609};
2610
2619 std::optional<Date> from_;
2621 std::optional<Date> to_;
2623 std::optional<std::string> symbol_;
2625 std::optional<std::string> cursor_;
2627 std::optional<int> limit_;
2628};
2629
2636template <typename Broker>
2638 OrderShape shape;
2639 shape.type_ = order.order_.type_;
2640 shape.price_ = order.order_.price_;
2641 shape.trigger_price_ = order.order_.trigger_price_;
2642 shape.time_in_force_ = order.order_.time_in_force_;
2643 shape.session_ = order.order_.session_;
2644 return shape;
2645}
2646
2653template <typename Broker>
2655 AmendInstruction instruction;
2656 // A cancellation copies the whole shape, so a broker that re-reads it sees the same order.
2657 instruction.shape_.type_ = order.order_.type_;
2658 instruction.shape_.time_in_force_ = order.order_.time_in_force_;
2659 instruction.shape_.session_ = order.order_.session_;
2660 instruction.shape_.price_ = order.order_.price_;
2661 instruction.shape_.trigger_price_ = order.order_.trigger_price_;
2662 instruction.resting_ = instruction.shape_;
2663 instruction.venue_ = order.order_.venue_;
2664 instruction.quantity_ = order.amendable_quantity_;
2665 instruction.all_remaining_ = true;
2666 return instruction;
2667}
2668
2676template <typename Broker>
2678 AmendInstruction instruction;
2679 instruction.shape_.type_ = order.order_.type_;
2680 instruction.shape_.time_in_force_ = order.order_.time_in_force_;
2681 instruction.shape_.session_ = order.order_.session_;
2682 instruction.shape_.price_ = order.order_.price_;
2683 instruction.shape_.trigger_price_ = order.order_.trigger_price_;
2684 instruction.resting_ = instruction.shape_;
2685 instruction.venue_ = order.order_.venue_;
2686 instruction.quantity_ = quantity;
2687 instruction.all_remaining_ = false;
2688 return instruction;
2689}
2690
2705template <typename Broker>
2707 const WorkingOrder<Broker>& order, OrderShape shape, std::optional<Decimal64> quantity = std::nullopt
2708) {
2709 AmendInstruction instruction;
2710 instruction.shape_ = std::move(shape);
2711 instruction.resting_ = resting_shape(order);
2712 // The caller's shape is kept as written; `resting_` lets each adapter tell a change from a keep.
2713 instruction.venue_ = order.order_.venue_;
2714 instruction.all_remaining_ = !quantity.has_value();
2715 instruction.quantity_ = quantity ? quantity : order.amendable_quantity_;
2716 return instruction;
2717}
2718
2727template <typename Broker>
2729 const WorkingOrder<Broker>& order, Decimal64 price, std::optional<Decimal64> quantity = std::nullopt
2730) {
2731 auto shape = resting_shape(order);
2732 shape.price_ = std::move(price);
2733 return replace_with(order, std::move(shape), std::move(quantity));
2734}
2735
2741inline std::string format_iso8601_utc(std::chrono::system_clock::time_point value) {
2742 const auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(value);
2743 const std::time_t raw = std::chrono::system_clock::to_time_t(seconds);
2744 std::tm utc{};
2745#ifdef _WIN32
2746 gmtime_s(&utc, &raw);
2747#else
2748 gmtime_r(&raw, &utc);
2749#endif
2750 char buffer[32];
2751 const auto written = std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &utc);
2752 return std::string(buffer, written);
2753}
2754
2766inline std::optional<std::chrono::system_clock::time_point> parse_iso8601_timestamp(std::string_view value) {
2767 // The fixed layout first: `sscanf`'s `%d` would accept signs, spaces and short fields.
2768 const auto digits = [value](std::size_t from, std::size_t count) {
2769 for (std::size_t index = from; index < from + count; ++index) {
2770 if (value[index] < '0' || value[index] > '9') {
2771 return false;
2772 }
2773 }
2774 return true;
2775 };
2776 if (
2777 value.size() < 20 || !digits(0, 4) || value[4] != '-' || !digits(5, 2) || value[7] != '-' || !digits(8, 2) ||
2778 value[10] != 'T' || !digits(11, 2) || value[13] != ':' || !digits(14, 2) || value[16] != ':' || !digits(17, 2)
2779 ) {
2780 return std::nullopt;
2781 }
2782 int year, month, day, hour, minute, second;
2783 if (std::sscanf(std::string(value).c_str(), "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute, &second) != 6) {
2784 return std::nullopt;
2785 }
2786 if (
2787 !is_valid_date(Date{year, static_cast<unsigned>(month), static_cast<unsigned>(day)}) || hour < 0 || hour > 23 ||
2788 minute < 0 || minute > 59 || second < 0 || second > 60
2789 ) {
2790 return std::nullopt;
2791 }
2792
2793 // An optional fraction of digits only, then the zone, then nothing.
2794 std::size_t timezone_position = 19;
2795 if (value[19] == '.') {
2796 timezone_position = 20;
2797 while (timezone_position < value.size() && value[timezone_position] >= '0' && value[timezone_position] <= '9') {
2798 ++timezone_position;
2799 }
2800 if (timezone_position == 20) {
2801 return std::nullopt;
2802 }
2803 }
2804 if (timezone_position >= value.size()) {
2805 return std::nullopt;
2806 }
2807 const char zone = value[timezone_position];
2808 if (zone == 'Z') {
2809 if (timezone_position + 1 != value.size()) {
2810 return std::nullopt;
2811 }
2812 } else if (zone == '+' || zone == '-') {
2813 if (
2814 value.size() != timezone_position + 6 || !digits(timezone_position + 1, 2) ||
2815 value[timezone_position + 3] != ':' || !digits(timezone_position + 4, 2)
2816 ) {
2817 return std::nullopt;
2818 }
2819 } else {
2820 return std::nullopt;
2821 }
2822
2823 std::tm time{};
2824 time.tm_year = year - 1900;
2825 time.tm_mon = month - 1;
2826 time.tm_mday = day;
2827 time.tm_hour = hour;
2828 time.tm_min = minute;
2829 time.tm_sec = second;
2830 time.tm_isdst = 0;
2831#ifdef _WIN32
2832 std::time_t utc = _mkgmtime(&time);
2833#else
2834 std::time_t utc = timegm(&time);
2835#endif
2836 if (utc == static_cast<std::time_t>(-1)) {
2837 return std::nullopt;
2838 }
2839
2840 if (value[timezone_position] != 'Z') {
2841 int offset_hour, offset_minute;
2842 if (
2843 std::sscanf(std::string(value.substr(timezone_position + 1)).c_str(), "%d:%d", &offset_hour, &offset_minute) != 2
2844 ) {
2845 return std::nullopt;
2846 }
2847 if (offset_hour > 23 || offset_minute > 59) {
2848 return std::nullopt;
2849 }
2850 const int offset = offset_hour * 3600 + offset_minute * 60;
2851 utc += value[timezone_position] == '+' ? -offset : offset;
2852 }
2853
2854 auto result = std::chrono::system_clock::from_time_t(utc);
2855 const auto dot = value.find('.', 19);
2856 if (dot != std::string_view::npos && dot < timezone_position) {
2857 std::uint32_t milliseconds = 0;
2858 std::uint32_t factor = 100;
2859 for (std::size_t index = dot + 1; index < timezone_position && factor > 0; ++index) {
2860 if (value[index] < '0' || value[index] > '9') {
2861 return std::nullopt;
2862 }
2863 milliseconds += static_cast<std::uint32_t>(value[index] - '0') * factor;
2864 factor /= 10;
2865 }
2866 result += std::chrono::milliseconds(milliseconds);
2867 }
2868 return result;
2869}
2870
2871} // namespace algotradelib
2872
2873namespace std {
2874
2879template <typename Broker>
2880struct hash<algotradelib::OrderRef<Broker>> {
2886 std::size_t operator()(const algotradelib::OrderRef<Broker>& ref) const noexcept {
2887 std::size_t seed = hash<std::string>{}(ref.primary_);
2888 seed ^= hash<std::string>{}(ref.secondary_) + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
2889 return seed;
2890 }
2891};
2892
2893} // namespace std
A short uppercase code (letters, digits, _), stored inline without allocation.
Definition types.hpp:259
bool empty() const noexcept
Tests whether the code is empty.
Definition types.hpp:328
friend bool operator!=(const Code &lhs, const Code &rhs)
Compares two codes for inequality.
Definition types.hpp:364
Code()=default
Constructs an empty code.
static std::optional< Code > try_make(std::string_view text)
Makes a code without throwing.
Definition types.hpp:291
friend bool operator==(const Code &lhs, const Code &rhs)
Compares two codes' characters.
Definition types.hpp:354
std::size_t size() const noexcept
Returns the number of characters.
Definition types.hpp:336
static constexpr std::size_t capacity() noexcept
Returns the maximum number of characters.
Definition types.hpp:344
std::string str() const
Returns the code as a string.
Definition types.hpp:320
Code(std::string_view text)
Constructs a code.
Definition types.hpp:270
std::string_view view() const noexcept
Returns the code's characters.
Definition types.hpp:312
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
static Currency usd()
Returns United States dollars.
Definition types.hpp:410
Currency()
Constructs Korean won.
Definition types.hpp:377
static Currency krw()
Returns Korean won.
Definition types.hpp:402
friend bool operator==(const Currency &lhs, const Currency &rhs)
Compares two currencies.
Definition types.hpp:428
Currency(std::string_view code)
Constructs a currency from its code.
Definition types.hpp:385
std::string str() const
Returns the code.
Definition types.hpp:418
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::uint8_t scale() const noexcept
Returns the scale.
Definition types.hpp:549
friend bool operator==(const Decimal64 &lhs, const Decimal64 &rhs)
Compares the coefficient and the scale.
Definition types.hpp:586
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
Decimal64(std::int64_t coefficient, std::uint8_t scale)
Constructs coefficient * 10^-scale, keeping the scale as given.
Definition types.hpp:453
std::string str() const
Formats the value as a decimal string.
Definition types.hpp:557
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
const BrokerError & error() const
Returns the error.
Definition types.hpp:1120
BrokerError & error()
Returns the error.
Definition types.hpp:1111
const T & value() const
Returns the value.
Definition types.hpp:1102
bool has_value() const noexcept
Tests whether the result holds a value.
Definition types.hpp:1076
T & value()
Returns the value.
Definition types.hpp:1093
Result(BrokerError error)
Constructs a failed result.
Definition types.hpp:1070
Which venue a commission rate applies to: any venue, a normalized Venue, or a raw code.
Definition types.hpp:1523
friend bool operator!=(const VenueKey &lhs, const VenueKey &rhs) noexcept
Compares two keys for inequality.
Definition types.hpp:1639
static VenueKey any() noexcept
Returns the key for any venue.
Definition types.hpp:1532
bool matches(const VenueKey &asserted) const noexcept
Tests whether two keys name the same venue, exactly in kind and value.
Definition types.hpp:1608
static std::optional< VenueKey > raw(std::string_view code)
Makes a key for a venue code the library does not normalize.
Definition types.hpp:1556
friend bool operator==(const VenueKey &lhs, const VenueKey &rhs) noexcept
Compares kind and value; same as matches.
Definition types.hpp:1629
static std::optional< VenueKey > normalized(Venue venue)
Makes a key for a normalized venue.
Definition types.hpp:1541
bool is_any() const noexcept
Tests whether the key is for any venue.
Definition types.hpp:1579
const Code< 8 > & raw_code() const noexcept
Returns the raw venue code.
Definition types.hpp:1595
VenueKey()=default
Constructs the key for any venue.
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
A compile-time check that a list names every value of an enum, and a parser over the list.
The library: broker-neutral types (core), and the modules below.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
std::optional< Decimal64 > decimal_floor_to_multiple(const Decimal64 &value, const Decimal64 &step)
Rounds down to a multiple of a step (toward negative infinity).
Definition types.hpp:903
SellableSource
Where the library gets a broker's sellable quantity.
Definition types.hpp:1362
@ HOLDINGS
On the holdings snapshot, at no extra request.
Definition types.hpp:1364
@ INQUIRY
From a per-instrument inquiry, made only where the snapshot has no figure.
Definition types.hpp:1366
@ NONE
No per-instrument inquiry: any figure comes on the holdings rows (Kiwoom), or there is none.
Definition types.hpp:1368
AmendInstruction reprice(const WorkingOrder< Broker > &order, Decimal64 price, std::optional< Decimal64 > quantity=std::nullopt)
Makes an instruction changing only a working order's price.
Definition types.hpp:2728
VenueKeyKind
Which kind of venue a VenueKey names.
Definition types.hpp:1507
@ 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
constexpr std::array< Venue, 4 > all_venues
Every Venue, in declaration order.
Definition types.hpp:53
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
std::optional< std::chrono::system_clock::time_point > parse_iso8601_timestamp(std::string_view value)
Parses an ISO 8601 timestamp, YYYY-MM-DDTHH:MM:SS[.fraction] followed by Z or a +hh:mm/-hh:mm offset.
Definition types.hpp:2766
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
constexpr bool lists_every_value(const std::array< Enum, N > &values, IsEnumerator is_enumerator) noexcept
Tests whether a list holds every value of an enum exactly once, in any order.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
constexpr std::string_view commission_origin_name(CommissionOrigin origin) noexcept
Returns a lowercase name for an origin, such as "caller_stated", for reports.
Definition types.hpp:1709
ErrorCategory
The kind of failure a BrokerError reports.
Definition types.hpp:948
@ RATE_LIMIT
The broker refused the request for its rate limit.
Definition types.hpp:958
@ HTTP
The broker answered with an HTTP error status (http_status_).
Definition types.hpp:954
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
@ CANCELLED
The operation was cancelled, such as by closing the client or a local deadline.
Definition types.hpp:950
@ AUTHENTICATION
The credentials or token were refused.
Definition types.hpp:956
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
Definition types.hpp:2007
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
Definition types.hpp:2009
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
Definition types.hpp:2005
@ MID_PRICE
중간가: priced at the midpoint of the spread.
Definition types.hpp:2011
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
Definition types.hpp:2015
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
constexpr bool carries_trigger_price(OrderType type) noexcept
Tests whether an order type takes a trigger price.
Definition types.hpp:2065
RateApplicability
Whether a commission rate applies on a date.
Definition types.hpp:1720
@ UNREADABLE
Unknown: no readable bound excludes the date, but a bound could not be read.
Definition types.hpp:1730
@ YES
Every bound was readable, and they cover the date.
Definition types.hpp:1724
@ NO
A readable date bound puts the date outside the rate's window.
Definition types.hpp:1722
constexpr bool carries_caller_price(OrderType type) noexcept
Tests whether an order type takes a price from the caller.
Definition types.hpp:2039
std::optional< Decimal64 > decimal_halve(const Decimal64 &value)
Halves a decimal exactly, adding a decimal place when needed.
Definition types.hpp:804
AmendInstruction cancel_all(const WorkingOrder< Broker > &order)
Makes an instruction cancelling all that remains of an order.
Definition types.hpp:2654
constexpr std::array< OrderType, 9 > all_order_types
Every OrderType, in declaration order.
Definition types.hpp:2019
constexpr std::string_view sellable_coverage_name(SellableBasis::Coverage coverage) noexcept
Returns a lowercase name for a coverage, such as "whole_holding", for logs.
Definition types.hpp:1260
constexpr bool order_status_cancel_pending(OrderStatus status) noexcept
Tests whether a cancellation of an order in this status is already on its way, so asking again can on...
Definition types.hpp:2190
AmendInstruction cancel_quantity(const WorkingOrder< Broker > &order, Decimal64 quantity)
Makes an instruction cancelling part of an order.
Definition types.hpp:2677
constexpr bool error_category_is_rate_limit(ErrorCategory category) noexcept
Tests whether an error of this category is a broker asking the caller to slow down,...
Definition types.hpp:983
@ UNREADABLE
No readable date rules it out, but an unreadable date might.
constexpr std::string_view sellable_resting_name(SellableBasis::RestingTreatment treatment) noexcept
Returns a lowercase name for a treatment, such as "deduct", for logs.
Definition types.hpp:1277
Country
A country (market) the library supports.
Definition types.hpp:32
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
Definition types.hpp:600
OrderSession
The trading session an order is submitted into.
Definition types.hpp:2130
@ OPENING_AUCTION
The opening single-price auction (시가단일가; Toss OPG).
Definition types.hpp:2135
@ AFTER_HOURS
After the close, at that session's close (장후 시간외).
Definition types.hpp:2141
@ CLOSING_AUCTION
The closing auction (Toss CLS, a US limit-on-close).
Definition types.hpp:2137
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
@ AFTER_MARKET
KRX's after-market session (애프터마켓).
Definition types.hpp:2145
@ AFTER_HOURS_AUCTION
The after-hours single-price auction (시간외 단일가).
Definition types.hpp:2143
@ PRE_MARKET
Before the open, at the previous session's close (장전 시간외).
Definition types.hpp:2139
@ GTP
NXT's GTP session.
Definition types.hpp:2147
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
constexpr std::array< OrderSide, 2 > all_order_sides
Every OrderSide, in declaration order.
Definition types.hpp:1980
AmendInstruction replace_with(const WorkingOrder< Broker > &order, OrderShape shape, std::optional< Decimal64 > quantity=std::nullopt)
Makes an instruction changing a working order to a new shape.
Definition types.hpp:2706
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
constexpr std::array< OrderSession, 9 > all_order_sessions
Every OrderSession, in declaration order.
Definition types.hpp:2151
constexpr bool time_in_force_expires_at_close(TimeInForce condition) noexcept
Tests whether an order with this condition expires at the session's close, so its filled quantity is ...
Definition types.hpp:2113
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
constexpr std::array< TimeInForce, 4 > all_times_in_force
Every TimeInForce, in declaration order.
Definition types.hpp:2099
constexpr std::string_view venue_key_kind_name(VenueKeyKind kind) noexcept
Returns a lowercase name for a key kind, such as "raw", for reports.
Definition types.hpp:1654
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
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
Definition types.hpp:1456
constexpr std::string_view sellable_source_name(SellableSource source) noexcept
Returns a lowercase name for a source, such as "inquiry", for logs.
Definition types.hpp:1376
bool is_valid_date(const Date &date)
Tests whether a date exists in the Gregorian calendar, in years 1 to 9999.
Definition types.hpp:1480
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
Definition types.hpp:2088
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
std::optional< Decimal64 > amended_trigger_price(const AmendInstruction &instruction)
Returns the trigger price an amendment leaves the order with.
Definition types.hpp:2563
std::string format_iso8601_utc(std::chrono::system_clock::time_point value)
Formats an instant as an ISO 8601 timestamp in UTC, such as 2026-10-06T00:30:00Z.
Definition types.hpp:2741
constexpr std::array< Country, 2 > all_countries
Every Country, in declaration order.
Definition types.hpp:38
OrderShape resting_shape(const WorkingOrder< Broker > &order)
Returns a working order's current shape.
Definition types.hpp:2637
A modification or cancellation of a working order.
Definition types.hpp:2532
Venue venue_
The venue the order rests at, for a broker whose amendment needs it (KIS).
Definition types.hpp:2540
bool confirm_high_value_
Confirms a high-value amendment, where the broker asks for that confirmation.
Definition types.hpp:2546
std::optional< OrderShape > resting_
The shape the order has now, or unset if unknown.
Definition types.hpp:2553
std::optional< Decimal64 > quantity_
The quantity affected; never substituted if a broker needs one and it is missing.
Definition types.hpp:2542
OrderShape shape_
The shape the order should have afterwards.
Definition types.hpp:2534
bool all_remaining_
Whether the whole remaining quantity is affected, rather than quantity_.
Definition types.hpp:2544
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string request_id_
The broker's request id for this call, if it gave one.
Definition types.hpp:1024
int http_status_
The HTTP status of the reply: set for an HTTP error and for a reply whose body is not a JSON object....
Definition types.hpp:1020
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
std::optional< int > rate_limit_
The rate limit the broker says it enforces, in requests per second, for a rate-limit error.
Definition types.hpp:1046
std::optional< std::chrono::seconds > retry_after_
How long the broker asked the caller to wait (Retry-After), for a rate-limit error.
Definition types.hpp:1040
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
What the broker says may be spent, in one currency.
Definition types.hpp:1396
Money cash_
The amount that may be spent.
Definition types.hpp:1398
std::chrono::system_clock::time_point received_at_
When the figure was received, on this machine's clock (brokers do not timestamp it).
Definition types.hpp:1404
One commission rate, the market and venue it applies to, and the dates it applies on.
Definition types.hpp:1742
bool until_unreadable_
Whether the source stated an end date that could not be read (so until_ is empty).
Definition types.hpp:1788
bool normalized() const noexcept
Tests whether the rate's market is a normalized Country.
Definition types.hpp:1794
Country country_
The market the rate applies to; meaningless when other_ is set.
Definition types.hpp:1744
RateApplicability applies_on(const Date &date) const
Tests whether the rate applies on a date.
Definition types.hpp:1805
std::optional< Date > from_
The first date the rate applies on; empty is open-ended unless from_unreadable_ is set.
Definition types.hpp:1772
VenueKey venue_
The venue the rate applies to.
Definition types.hpp:1758
std::optional< Date > until_
The last date the rate applies on; empty is open-ended unless until_unreadable_ is set.
Definition types.hpp:1774
bool excluded_on(const Date &date) const
Tests whether a readable bound puts a date outside the rate's window.
Definition types.hpp:1820
Decimal64 rate_
The broker's commission, as a fraction of traded value (0.00015, not 0.015).
Definition types.hpp:1760
std::optional< Decimal64 > institution_rate_
The institution fee (유관기관제비용), as a fraction of traded value, if stated separately.
Definition types.hpp:1768
bool from_unreadable_
Whether the source stated a start date that could not be read (so from_ is empty).
Definition types.hpp:1781
Code< 16 > other_
The broker's market code, when the library does not normalize that market.
Definition types.hpp:1751
The result of rate_for: a rate, or why there is none.
Definition types.hpp:1862
bool bounds_unreadable_
Whether an unreadable date window is why no rate was returned.
Definition types.hpp:1871
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
RateSelection rate_for(Country country, const Date &date) const
Finds the venue-neutral rate in force for a market on a date.
Definition types.hpp:1963
std::vector< CommissionRate > rates_
The rate rows.
Definition types.hpp:1832
CommissionOrigin origin_
Whether a broker published the rates or a caller stated them.
Definition types.hpp:1836
std::chrono::system_clock::time_point received_at_
When the schedule was received, on this machine's clock.
Definition types.hpp:1834
std::size_t unreadable_bounds_
How many rows have a date bound that could not be read.
Definition types.hpp:1859
std::size_t dropped_
How many broker rows were skipped because their market code could not be stored.
Definition types.hpp:1851
bool any_dated_rate_for(Country country) const
Tests whether any rate for a market has a date bound, readable or not.
Definition types.hpp:1940
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
friend bool operator==(const Date &lhs, const Date &rhs)
Compares two dates.
Definition types.hpp:1426
friend bool operator<(const Date &lhs, const Date &rhs)
Orders dates chronologically.
Definition types.hpp:1436
unsigned month_
The month, 1-12; zero means unset.
Definition types.hpp:1416
int year_
The year.
Definition types.hpp:1414
unsigned day_
The day of the month, 1-31; zero means unset.
Definition types.hpp:1418
One position row in a holdings snapshot.
Definition types.hpp:1288
std::string name_
The instrument's name as the broker spells it.
Definition types.hpp:1292
Money unrealized_profit_loss_
The unrealized profit or loss, as the broker reported it.
Definition types.hpp:1322
Money purchase_value_
The cost basis, as the broker computed it.
Definition types.hpp:1318
Decimal64 average_purchase_price_
The broker's average purchase price.
Definition types.hpp:1314
std::optional< Decimal64 > sellable_quantity_
How much the broker says may be sold now.
Definition types.hpp:1305
Decimal64 unrealized_return_
The broker's return figure, as a fraction (0.05 is 5%).
Definition types.hpp:1324
Decimal64 quantity_
The quantity in this row.
Definition types.hpp:1298
InstrumentId instrument_
The instrument held (brokers report holdings without a trading venue).
Definition types.hpp:1290
Money market_value_
The market value, as the broker computed it.
Definition types.hpp:1320
Decimal64 last_price_
The price the broker valued the position at.
Definition types.hpp:1316
std::optional< SellableBasis > sellable_basis_
What this row's sellable_quantity_ covers, when the figure came from a per-instrument inquiry rather ...
Definition types.hpp:1312
An account's positions and per-currency totals at one point in time.
Definition types.hpp:1345
std::chrono::system_clock::time_point received_at_
When this process received the snapshot (brokers do not timestamp holdings).
Definition types.hpp:1351
std::vector< HoldingsTotals > totals_
One totals row per currency held.
Definition types.hpp:1349
SellableBasis sellable_basis_
What the rows' sellable_quantity_ figures cover (unless a row carries its own).
Definition types.hpp:1358
std::vector< HoldingPosition > positions_
Every position row; one instrument may appear in more than one.
Definition types.hpp:1347
The broker's holdings totals for one currency.
Definition types.hpp:1328
Decimal64 unrealized_profit_loss_
The broker's total unrealized profit or loss in currency_, from its summary.
Definition types.hpp:1341
Decimal64 market_value_
The broker's total market value in currency_, from its summary.
Definition types.hpp:1339
Decimal64 purchase_value_
The broker's total cost basis in currency_.
Definition types.hpp:1337
Currency currency_
The currency; there is one totals row per currency, never converted.
Definition types.hpp:1330
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Country country_
The listing country, which selects the symbol convention and the price grid.
Definition types.hpp:87
friend bool operator==(const InstrumentId &lhs, const InstrumentId &rhs)
Compares country, venue and symbol.
Definition types.hpp:103
Venue venue_
The venue that is part of the identity (two venues are two instruments).
Definition types.hpp:93
std::string symbol_
The symbol as the venue spells it, such as "005930".
Definition types.hpp:95
friend bool operator<(const InstrumentId &lhs, const InstrumentId &rhs)
Orders identities by country, venue, then symbol, so they can key a map.
Definition types.hpp:118
An exact amount of money in one currency.
Definition types.hpp:1168
Currency currency_
The currency; the library never adds amounts in different currencies.
Definition types.hpp:1172
friend bool operator==(const Money &lhs, const Money &rhs)
Compares amount (with Decimal64::operator==) and currency.
Definition types.hpp:1180
Decimal64 amount_
The amount.
Definition types.hpp:1170
The broker's acknowledgement that it accepted an instruction.
Definition types.hpp:2383
std::optional< std::string > client_order_id_
The idempotency key, if the broker echoed one.
Definition types.hpp:2387
std::chrono::system_clock::time_point accepted_at_
When the acknowledgement was received.
Definition types.hpp:2389
std::string order_id_
The order number the broker assigned.
Definition types.hpp:2385
What has filled on one order, and what it cost.
Definition types.hpp:2272
std::optional< Money > commission_
Commission charged so far, if the broker reports it per order.
Definition types.hpp:2289
Decimal64 filled_quantity_
The quantity filled so far; zero if nothing has filled. Always present.
Definition types.hpp:2274
std::optional< Decimal64 > average_filled_price_
The average fill price, only where the broker supplies it.
Definition types.hpp:2281
std::optional< std::chrono::system_clock::time_point > filled_at_
When the most recent fill happened, if the broker timestamps it.
Definition types.hpp:2293
std::optional< Money > filled_amount_
The value of the fills, as the broker computed it.
Definition types.hpp:2287
std::optional< Money > tax_
Transaction tax charged so far, if the broker reports it per order.
Definition types.hpp:2291
std::optional< Date > settlement_date_
The settlement date the broker stated.
Definition types.hpp:2295
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< std::string > symbol_
Only this symbol, where the broker supports the filter.
Definition types.hpp:2623
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2627
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
Definition types.hpp:2625
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
Definition types.hpp:2619
std::optional< Date > to_
The last date to include.
Definition types.hpp:2621
One page of an order listing.
Definition types.hpp:2369
std::vector< OrderSnapshot > orders_
The rows, in the broker's order.
Definition types.hpp:2371
std::optional< std::string > next_cursor_
The cursor for the next page, to pass back unchanged; empty if there is none.
Definition types.hpp:2373
std::chrono::system_clock::time_point received_at_
When the page was received, on this machine's clock.
Definition types.hpp:2375
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
friend bool operator==(const OrderRef &lhs, const OrderRef &rhs)
Compares two references.
Definition types.hpp:2437
friend bool operator!=(const OrderRef &lhs, const OrderRef &rhs)
Compares two references for inequality.
Definition types.hpp:2447
std::string str() const
Formats the reference for logs, as broker:primary[:secondary].
Definition types.hpp:2420
static constexpr std::string_view broker() noexcept
Returns the issuing broker's name.
Definition types.hpp:2412
An order to place, in broker-neutral form.
Definition types.hpp:2216
std::optional< std::string > client_order_id_
An idempotency key, if the broker offers one; never generated by the library.
Definition types.hpp:2257
Decimal64 quantity_
The quantity, in the instrument's units (shares).
Definition types.hpp:2241
OrderType type_
The price basis: limit, market, best-limit, and so on.
Definition types.hpp:2222
InstrumentId instrument_
The instrument; its venue_ is identity, and routing is this struct's venue_.
Definition types.hpp:2218
Venue venue_
Where to route the order, if the broker offers a choice.
Definition types.hpp:2239
std::optional< Decimal64 > price_
The price; required when carries_caller_price(type_), refused otherwise.
Definition types.hpp:2243
OrderSide side_
Buy or sell.
Definition types.hpp:2220
OrderSession session_
The trading session.
Definition types.hpp:2226
TimeInForce time_in_force_
How long the order stays valid.
Definition types.hpp:2224
bool confirm_high_value_
Confirms a high-value order, where the broker asks for that confirmation.
Definition types.hpp:2259
std::optional< Decimal64 > trigger_price_
The trigger price; required for STOP_LIMIT, refused otherwise.
Definition types.hpp:2250
An order's type, price, trigger, time in force and session, as an amendment states them.
Definition types.hpp:2474
std::optional< TimeInForce > time_in_force_
The time in force; unset means "keep the resting order's".
Definition types.hpp:2515
std::optional< Decimal64 > price_
The price, for a basis that takes one.
Definition types.hpp:2499
std::optional< OrderSession > session_
The session; unset means "keep the resting order's".
Definition types.hpp:2522
OrderShape()=default
Constructs a limit shape with nothing else stated.
OrderShape(OrderType type, std::optional< Decimal64 > price, std::optional< TimeInForce > time_in_force=std::nullopt, std::optional< OrderSession > session=std::nullopt, std::optional< Decimal64 > trigger_price=std::nullopt)
Constructs a shape, stating only what the caller means to set.
Definition types.hpp:2486
std::optional< Decimal64 > trigger_price_
The trigger price, for STOP_LIMIT.
Definition types.hpp:2508
OrderType type_
The price basis.
Definition types.hpp:2497
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
Venue venue_
Where the broker says the order was routed; UNSPECIFIED if it does not say.
Definition types.hpp:2320
OrderSide side_
Buy or sell.
Definition types.hpp:2307
OrderStatus status_
The status; UNKNOWN where the broker publishes none.
Definition types.hpp:2329
OrderSession session_
The session; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2313
std::optional< std::chrono::system_clock::time_point > canceled_at_
When the order was cancelled, if the broker reports it.
Definition types.hpp:2363
OrderType type_
The price basis; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2309
OrderExecution execution_
What has filled and what it cost; see OrderExecution before testing a fill.
Definition types.hpp:2365
std::string name_
The instrument's name as the broker spells it.
Definition types.hpp:2305
std::optional< Decimal64 > trigger_price_
The trigger price, whenever the broker reports a positive one.
Definition types.hpp:2339
bool ordered_date_assumed_
Whether the broker stated only the time of day, and the date in ordered_at_ is the day the adapter re...
Definition types.hpp:2361
Currency currency_
The currency of the row's prices and amounts.
Definition types.hpp:2351
Decimal64 quantity_
The quantity ordered; the remainder is this minus execution_.filled_quantity_.
Definition types.hpp:2341
std::string order_id_
The broker's order number.
Definition types.hpp:2301
std::optional< std::chrono::system_clock::time_point > ordered_at_
When the broker recorded the order, if it gives a time. KIS's real-server working orders have none; o...
Definition types.hpp:2356
std::optional< Decimal64 > order_amount_
The money an amount-based order committed (Toss US market orders), if any.
Definition types.hpp:2349
InstrumentId instrument_
The instrument (identity venue; the routing venue is venue_).
Definition types.hpp:2303
TimeInForce time_in_force_
The time in force; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2311
Code< 8 > shape_code_
The broker's own order-type code, verbatim (KIS two digits, Toss three letters).
Definition types.hpp:2327
std::optional< Decimal64 > price_
The limit price, if the order has one.
Definition types.hpp:2331
An accepted order: the acknowledgement and the reference to address it with.
Definition types.hpp:2460
A quote: the last traded price of an instrument at a point in time.
Definition types.hpp:1143
Currency currency_
The currency of last_price_.
Definition types.hpp:1149
Decimal64 last_price_
The last traded price, as the broker reported it.
Definition types.hpp:1147
std::chrono::system_clock::time_point received_at_
When this process received the quote, on this machine's clock.
Definition types.hpp:1153
std::optional< TopOfBook > top_of_book_
The best bid and offer.
Definition types.hpp:1162
std::optional< std::chrono::system_clock::time_point > exchange_time_
When the exchange says the quote was true, if the broker gave a timestamp.
Definition types.hpp:1151
InstrumentId instrument_
The instrument.
Definition types.hpp:1145
std::optional< Decimal64 > volume_
The session's cumulative traded volume, if the broker gave it.
Definition types.hpp:1164
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
Definition types.hpp:1191
bool verified_
Whether the basis was confirmed from a real broker response, rather than stated as a policy.
Definition types.hpp:1227
constexpr bool is_enforceable() const noexcept
Tests whether RiskGuard may check a sell against a figure with this basis.
Definition types.hpp:1233
RestingTreatment resting_
How resting sells are treated; unestablished by default.
Definition types.hpp:1221
Coverage
Whether the figure covers the whole holding.
Definition types.hpp:1193
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
Definition types.hpp:1197
@ UNESTABLISHED
Not established; RiskGuard refuses.
Definition types.hpp:1195
@ PARTIAL
Only part of the holding, such as one venue's shares; RiskGuard refuses, reporting SELLABLE_BASIS_UNE...
Definition types.hpp:1202
Coverage coverage_
What the figure covers; unestablished by default.
Definition types.hpp:1219
RestingTreatment
How RiskGuard treats resting sell orders against the figure.
Definition types.hpp:1206
@ DEDUCT
Subtract every resting sell from the figure.
Definition types.hpp:1215
@ UNESTABLISHED
Not stated; RiskGuard refuses.
Definition types.hpp:1208
The best bid and offer, with the size at each. An absent field was not stated, never zero.
Definition types.hpp:1131
std::optional< Decimal64 > bid_price_
The best bid price.
Definition types.hpp:1133
std::optional< Decimal64 > ask_price_
The best offer price.
Definition types.hpp:1137
std::optional< Decimal64 > bid_quantity_
The size at the best bid.
Definition types.hpp:1135
std::optional< Decimal64 > ask_quantity_
The size at the best offer.
Definition types.hpp:1139
An order still open to modification or cancellation.
Definition types.hpp:2582
std::optional< Decimal64 > amendable_quantity_
Definition types.hpp:2588
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2604
std::vector< WorkingOrder< Broker > > orders_
Definition types.hpp:2606
std::chrono::system_clock::time_point received_at_
Definition types.hpp:2608
std::size_t operator()(const algotradelib::OrderRef< Broker > &ref) const noexcept
Hashes both parts of the reference.
Definition types.hpp:2886