algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
instrument.hpp
1#pragma once
2
3#include "./types.hpp"
4
5#include <optional>
6#include <stdexcept>
7#include <string>
8#include <string_view>
9#include <vector>
10
11namespace algotradelib {
12
20 enum class Known {
21 UNKNOWN,
22 KOSPI,
23 KOSDAQ,
24 NYSE,
25 NASDAQ,
26 AMEX,
27 };
28
30 Known known_{Known::UNKNOWN};
38
43 std::string str() const {
44 switch (known_) {
45 case Known::KOSPI:
46 return "KOSPI";
47 case Known::KOSDAQ:
48 return "KOSDAQ";
49 case Known::NYSE:
50 return "NYSE";
51 case Known::NASDAQ:
52 return "NASDAQ";
53 case Known::AMEX:
54 return "AMEX";
55 case Known::UNKNOWN:
56 break;
57 }
58 return other_.empty() ? std::string("UNKNOWN") : other_.str();
59 }
60
67 friend bool operator==(const MarketSegment& lhs, const MarketSegment& rhs) {
68 return lhs.known_ == rhs.known_ && lhs.other_ == rhs.other_;
69 }
70
77 friend bool operator!=(const MarketSegment& lhs, const MarketSegment& rhs) {
78 return !(lhs == rhs);
79 }
80};
81
88inline MarketSegment market_segment(std::string_view code) {
89 MarketSegment segment;
90 if (code == "KOSPI") {
91 segment.known_ = MarketSegment::Known::KOSPI;
92 } else if (code == "KOSDAQ") {
93 segment.known_ = MarketSegment::Known::KOSDAQ;
94 } else if (code == "NYSE") {
95 segment.known_ = MarketSegment::Known::NYSE;
96 } else if (code == "NASDAQ") {
97 segment.known_ = MarketSegment::Known::NASDAQ;
98 } else if (code == "AMEX") {
99 segment.known_ = MarketSegment::Known::AMEX;
100 } else if (const auto preserved = Code<12>::try_make(code)) {
101 segment.other_ = *preserved;
102 }
103 return segment;
104}
105
111enum class SecurityType {
112 UNKNOWN,
113 STOCK,
114 FOREIGN_STOCK,
115 DEPOSITARY_RECEIPT,
116 INFRASTRUCTURE_FUND,
117 REIT,
118 ETF,
119 FOREIGN_ETF,
120 ETN,
121 STOCK_WARRANT,
122};
123
126 UNKNOWN,
127 SCHEDULED,
128 ACTIVE,
129 DELISTED,
130};
131
141
150struct PriceRule {
152 enum class Kind {
154 STATED,
156 UNCONSTRAINED,
160 UNKNOWN,
161 };
162
166 std::vector<TickBand> bands_;
168 std::string source_;
169
174 constexpr bool grid_known() const noexcept {
175 switch (kind_) {
176 case Kind::STATED:
178 return true;
179 case Kind::UNKNOWN:
180 return false;
181 }
182 return false;
183 }
184
191 std::optional<Decimal64> tick_at(const Decimal64& price) const {
192 std::optional<Decimal64> tick;
193 for (const auto& band : bands_) {
194 if (decimal_less(price, band.from_)) {
195 break;
196 }
197 tick = band.tick_;
198 }
199 return tick;
200 }
201
209 std::optional<bool> on_tick(const Decimal64& price) const {
210 if (!grid_known()) {
211 return std::nullopt;
212 }
213 const auto tick = tick_at(price);
214 if (!tick) {
215 return true;
216 }
217 const auto rest = remainder(price, *tick);
218 if (!rest) {
219 return std::nullopt;
220 }
221 return rest->coefficient() == 0;
222 }
223
235 std::optional<Decimal64> round_to_tick(const Decimal64& price, OrderSide side) const {
236 if (!grid_known()) {
237 return std::nullopt;
238 }
239 const auto tick = tick_at(price);
240 if (!tick) {
241 return price;
242 }
243 const auto rest = remainder(price, *tick);
244 if (!rest) {
245 return std::nullopt;
246 }
247 if (rest->coefficient() == 0) {
248 return decimal_normalized(price);
249 }
250 const auto floor_price = decimal_subtract(price, *rest);
251 if (!floor_price) {
252 return std::nullopt;
253 }
254 if (side == OrderSide::BUY) {
255 return floor_price;
256 }
257 return decimal_add(*floor_price, *tick);
258 }
259
265 PriceRule rule;
267 rule.source_ = "no exchange price grid";
268 return rule;
269 }
270
276 static PriceRule unknown(std::string reason) {
277 PriceRule rule;
278 rule.kind_ = Kind::UNKNOWN;
279 rule.source_ = std::move(reason);
280 return rule;
281 }
282
283private:
284 // `price` modulo `tick`, exactly.
285 static std::optional<Decimal64> remainder(const Decimal64& price, const Decimal64& tick) {
286 std::int64_t left = 0;
287 std::int64_t right = 0;
288 std::uint8_t scale = 0;
289 if (!decimal_detail::align(price, tick, left, right, scale) || right == 0) {
290 return std::nullopt;
291 }
292 auto rest = left % right;
293 if (rest < 0) {
294 rest += right < 0 ? -right : right;
295 }
296 return Decimal64(rest, scale);
297 }
298};
299
323public:
325 enum class State {
327 NOT_STATED,
329 STATED,
332 };
333
335 StatedDate() = default;
336
343 StatedDate result;
344 result.state_ = State::STATED;
345 result.date_ = date;
346 return result;
347 }
348
354 StatedDate result;
355 result.state_ = State::UNREADABLE;
356 return result;
357 }
358
363 State state() const noexcept {
364 return state_;
365 }
366
372 const Date& date() const {
373 if (state_ != State::STATED) {
374 throw std::logic_error("StatedDate::date() read a date that was not stated");
375 }
376 return date_;
377 }
378
385 friend bool operator==(const StatedDate& lhs, const StatedDate& rhs) {
386 return lhs.state_ == rhs.state_ && (lhs.state_ != State::STATED || lhs.date_ == rhs.date_);
387 }
388
395 friend bool operator!=(const StatedDate& lhs, const StatedDate& rhs) {
396 return !(lhs == rhs);
397 }
398
399private:
400 State state_{State::NOT_STATED};
401 Date date_{};
402};
403
413
424 std::string name_;
426 std::string english_name_;
428 std::string isin_;
432 SecurityType type_{SecurityType::UNKNOWN};
434 InstrumentStatus status_{InstrumentStatus::UNKNOWN};
438 bool common_share_{true};
448 std::optional<Decimal64> shares_outstanding_;
450 std::optional<Decimal64> lot_size_;
453
463 using State = StatedDate::State;
464 if (listed_on_.state() == State::STATED && day < listed_on_.date()) {
466 }
467 if (delisted_on_.state() == State::STATED && !(day < delisted_on_.date())) {
469 }
470 if (leaves_exclusion_unknown(listed_on_.state()) || leaves_exclusion_unknown(delisted_on_.state())) {
472 }
474 }
475
476private:
477 // Whether a date in this state could rule a day out without saying so: only an unreadable one.
478 static constexpr bool leaves_exclusion_unknown(StatedDate::State state) noexcept {
479 switch (state) {
481 return true;
484 return false;
485 }
486 return true;
487 }
488};
489
490} // namespace algotradelib
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
static std::optional< Code > try_make(std::string_view text)
Makes a code without throwing.
Definition types.hpp:291
std::string str() const
Returns the code as a string.
Definition types.hpp:320
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Decimal64()=default
Constructs zero.
A date a broker stated, did not state, or stated in a form that could not be read.
State
What the broker's field said.
@ STATED
A date that was read.
@ UNREADABLE
Something that is not a readable calendar date.
@ NOT_STATED
No date: absent, null, or the broker's empty spelling.
friend bool operator==(const StatedDate &lhs, const StatedDate &rhs)
Compares two values: the same state, and the same date when stated.
const Date & date() const
Returns the date.
State state() const noexcept
Returns what the broker's field said.
friend bool operator!=(const StatedDate &lhs, const StatedDate &rhs)
Compares two values for inequality.
StatedDate()=default
Constructs a date the broker did not state.
static StatedDate unreadable()
Makes an unreadable date.
static StatedDate stated(Date date)
Makes a stated date.
The library: broker-neutral types (core), and the modules below.
MarketSegment market_segment(std::string_view code)
Maps a broker's segment code to a MarketSegment.
SecurityType
What kind of security an instrument is.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
InstrumentStatus
Whether an instrument is listed, awaiting listing, or delisted.
DateExclusion
What an instrument's listing and delisting dates say about one day.
@ EXCLUDED
A readable date rules the day out: listed after it, or delisted on or before it.
@ UNREADABLE
No readable date rules it out, but an unreadable date might.
@ NOT_EXCLUDED
No date rules it out and neither is unreadable. This does not mean "listed".
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
Definition types.hpp:600
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
A calendar date with no time of day or time zone.
Definition types.hpp:1412
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Reference data for one instrument.
std::optional< Decimal64 > shares_outstanding_
Shares outstanding, if published; KIS's blank or zero is empty, never zero shares.
InstrumentStatus status_
Listed, awaiting listing, or delisted.
Currency currency_
The currency it trades in.
InstrumentId id_
The instrument.
std::string isin_
The ISIN, or empty.
StatedDate delisted_on_
The delisting date; always NOT_STATED from Kiwoom, which publishes none.
DateExclusion dates_exclude(Date day) const
Tests whether the listing and delisting dates rule a day out.
StatedDate listed_on_
The listing date.
bool common_share_
Whether this is the common share, not a preferred or derived line.
PriceRule price_rule_
The price grid, set by the adapter or the caller; kind UNKNOWN where it has no table.
MarketSegment segment_
The market segment.
std::optional< Decimal64 > lot_size_
The order quantity increment, if the broker publishes one.
std::string english_name_
The English name, or empty.
SecurityType type_
The kind of security.
std::string name_
The local-language name, as the broker spells it.
The market segment an instrument is listed on, such as KOSPI or NASDAQ.
Code< 12 > other_
The broker's code, when known_ is UNKNOWN and the code fits Code<12>.
friend bool operator!=(const MarketSegment &lhs, const MarketSegment &rhs)
Compares two segments for inequality.
Known known_
The segment, or UNKNOWN if the broker's code was not recognized.
Known
The segments the library recognizes.
std::string str() const
Returns the segment's name for display.
friend bool operator==(const MarketSegment &lhs, const MarketSegment &rhs)
Compares the normalized segment and the preserved code.
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::string source_
Where the table came from and its revision, or why there is none.
static PriceRule unconstrained()
Returns a rule with no grid, for a market quoted in free decimals.
std::optional< bool > on_tick(const Decimal64 &price) const
Tests whether a price is on the grid.
std::optional< Decimal64 > round_to_tick(const Decimal64 &price, OrderSide side) const
Rounds a price to its band's tick in the order's favour: a buy rounds down, a sell up.
std::vector< TickBand > bands_
The bands, ascending by from_; empty unless kind_ is STATED.
Kind
Whether the rule states a grid, imposes none, or does not know it.
@ STATED
bands_ describe the market's grid.
@ UNCONSTRAINED
The market imposes no grid (free decimals).
@ UNKNOWN
The library has no grid for this instrument and will not guess one.
constexpr bool grid_known() const noexcept
Tests whether the rule says anything about the grid: a stated one, or none at all.
static PriceRule unknown(std::string reason)
Returns a rule that knows no grid and refuses to round.
Kind kind_
The kind of rule; UNKNOWN by default, so an unset rule refuses to round.
One band of a price grid: the tick size from a price upward, until the next band.
Decimal64 from_
The price the band starts at, inclusive.
Decimal64 tick_
The tick size within the band.