FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
instrument.hpp
Go to the documentation of this file.
1#pragma once
2// Instrument: the single definition of a tradable contract (5.3 / 5.15). 128 bytes: the
3// first cache line holds everything the hot path reads (tick, lot, limits, multiplier),
4// the second holds cold reference data (symbol, expiry, strike).
5//
6// All asset-class differences live here (contract_multiplier, option fields) so strategies
7// never branch on asset class; they call inst.notional()/pnl_per_tick().
8#include "fastmm/core/config_macros.hpp"
9#include "fastmm/core/containers/flat_map.hpp"
10#include "fastmm/core/containers/static_vector.hpp"
11#include "fastmm/core/enums.hpp"
13#include "fastmm/core/fixed_string.hpp"
16
17#include <cstddef>
18#include <cstdint>
19#include <string_view>
20#include <type_traits>
21
22namespace fastmm {
23
24inline constexpr std::size_t kMaxInstruments = 256;
25using Symbol = FixedString<20>;
27struct alignas(kCacheLine) Instrument {
28 enum Flags : std::uint8_t {
29 kEnabled = 1U << 0,
30 // Priced in one currency and settled in another (Deribit's BTC perpetual: USD against BTC):
31 // notional is qty * multiplier / price and PnL moves with 1 / price, in the base coin.
32 kInverse = 1U << 1,
33 kReduceOnlySupported = 1U << 2,
34 // An option whose premium is in its underlying coin (Deribit's BTC options, 0.0065 BTC): its
35 // model value is the USD price divided by the forward. Valued linearly in that premium; not
36 // kInverse.
37 kCoinQuoted = 1U << 3,
38 };
40 // ---- hot line (64 bytes) -------------------------------------------------------------
41 InstrumentId id{}; // 4
42 VenueId venue{}; // 1
43 AssetClass asset_class{}; // 1
44 std::uint8_t flags = 0; // 1
45 std::uint8_t price_decimals = 8; // 1 venue formatting hint
46 Price tick{}; // 8
47 Qty lot{}; // 8
48 Qty min_qty{}; // 8
49 Qty max_qty{}; // 8
50 Notional min_notional{}; // 8
51 Qty contract_multiplier = Qty::from_int(1); // 8 units of underlying per contract
52 Notional max_notional{}; // 8 -> 64
53 // ---- cold line (64 bytes) ------------------------------------------------------------
54 std::int64_t expiry_ns = 0; // 8 (0 = perpetual / spot)
55 Price strike{}; // 8 -> 16
56 Symbol symbol{}; // 21
57 FixedString<8> base{}; // 9
58 FixedString<8> quote{}; // 9 -> 55
59 // Byte 119 (the cold line's 55): option_type in the low nibble and, from journal format 6, the
60 // trading status in the high one (zero, Trading, in older journals: their byte 119 is
61 // option_type, at most 2).
62 OptionType option_type : 4 = OptionType::None; // 119, low nibble
63 // Whether the venue takes orders on it: the venue's at start-up, then each InstrumentRulesMsg's.
64 TradingStatus status : 4 = TradingStatus::Trading; // 119, high nibble -> 56
65 std::uint8_t cold_pad_[8] = {}; // -> 64
66
67 [[nodiscard]] constexpr bool enabled() const noexcept { return (flags & kEnabled) != 0; }
68 [[nodiscard]] constexpr bool inverse() const noexcept { return (flags & kInverse) != 0; }
69 [[nodiscard]] constexpr bool coin_quoted() const noexcept { return (flags & kCoinQuoted) != 0; }
70 [[nodiscard]] constexpr bool trading() const noexcept { return status == TradingStatus::Trading; }
71
72 // Passive rounding: bids down, asks up.
73 [[nodiscard]] constexpr Price round_price(Price p, Side side) const noexcept {
74 return round_to_tick(p, tick, side);
75 }
76 [[nodiscard]] constexpr Qty round_qty(Qty q) const noexcept { return round_to_lot(q, lot); }
77 // n ticks as a price distance (tick * n).
78 [[nodiscard]] constexpr Price ticks(std::int64_t n) const noexcept { return tick * n; }
79 [[nodiscard]] constexpr bool valid_price(Price p) const noexcept {
80 return p.is_positive() && on_tick(p, tick);
81 }
82 [[nodiscard]] constexpr bool valid_qty(Qty q) const noexcept {
83 return q.is_positive() && on_lot(q, lot) && q >= min_qty && (max_qty.is_zero() || q <= max_qty);
84 }
85 // Notional in the settlement currency: price * qty * multiplier for a linear contract, and
86 // qty * multiplier / price (base coin) for an inverse one, whose contract size is quoted in the
87 // quote currency. Zero for an inverse contract at a non-positive price.
88 [[nodiscard]] constexpr Notional notional(Price p, Qty q) const noexcept {
89 if (inverse()) {
90 if (!p.is_positive()) return Notional{};
91 return Notional::from_raw(
92 static_cast<std::int64_t>(static_cast<Int128>(q.raw) * contract_multiplier.raw / p.raw));
93 }
94 const Notional n = mul(p, q);
95 if (contract_multiplier == Qty::from_int(1)) return n;
96 return Notional::from_raw(mul_raw(n, contract_multiplier));
97 }
98 // PnL change (settlement ccy) for one tick move on one contract. An inverse contract's tick
99 // value depends on the price (multiplier * tick / price^2), so this is zero for one: use
100 // inverse_pnl() instead.
101 [[nodiscard]] constexpr Notional pnl_per_tick() const noexcept {
102 if (inverse()) return Notional{};
103 return Notional::from_raw(mul_raw(tick, contract_multiplier));
104 }
105 // PnL in the base coin of moving `qty` contracts from `from` to `to`:
106 // qty * multiplier * (1/from - 1/to). Zero unless both prices are positive.
107 [[nodiscard]] constexpr Notional inverse_pnl(Price from, Price to, Qty qty) const noexcept {
108 if (!from.is_positive() || !to.is_positive()) return Notional{};
109 const Int128 num = static_cast<Int128>(qty.raw) * contract_multiplier.raw * (to.raw - from.raw);
110 const Int128 den = static_cast<Int128>(from.raw) * to.raw;
111 return Notional::from_raw(static_cast<std::int64_t>(num / den));
112 }
113 // The currency PnL, fees and notional are denominated in: the base coin for an inverse
114 // contract, the quote currency otherwise. Empty when the instrument does not name it.
115 [[nodiscard]] constexpr std::string_view settlement_ccy() const noexcept {
116 return inverse() ? base.view() : quote.view();
117 }
118 [[nodiscard]] constexpr bool is_derivative() const noexcept {
119 return asset_class == AssetClass::Perpetual || asset_class == AssetClass::Future ||
120 asset_class == AssetClass::Option;
121 }
122};
123static_assert(sizeof(Instrument) == 128 && offsetof(Instrument, cold_pad_) == 120);
124static_assert(alignof(Instrument) == 64);
125static_assert(std::is_trivially_copyable_v<Instrument>);
126
127// Instruments do not all settle in the same currency: an inverse contract settles in its base
128// coin, a linear one in its quote currency. PnL totals and [risk] max_loss are one currency-less
129// Notional, so a table that mixes them adds unrelated numbers; callers refuse such a table (see
130// docs/explanation/risk-model.md).
132 const Instrument* first = nullptr; // first enabled instrument
133 const Instrument* other = nullptr; // first enabled instrument that settles in another currency
134 [[nodiscard]] bool mixed() const noexcept { return other != nullptr; }
135};
136
137enum class InstrumentError : std::uint8_t {
138 TableFull,
143};
144
145// Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by
146// (venue, symbol). Ids are the insertion index.
148 public:
149 struct Key {
152 constexpr auto operator<=>(const Key&) const noexcept = default;
153 };
154
156 if (inst.symbol.empty()) return fail(InstrumentError::EmptySymbol);
157 if (!inst.tick.is_positive()) return fail(InstrumentError::InvalidTick);
158 if (!inst.lot.is_positive()) return fail(InstrumentError::InvalidLot);
159 if (by_id_.full()) return fail(InstrumentError::TableFull);
160 const InstrumentId id{static_cast<std::uint32_t>(by_id_.size())};
161 auto [p, inserted] = by_symbol_.insert(Key{inst.venue, inst.symbol}, id);
162 if (!inserted) return fail(InstrumentError::DuplicateSymbol);
163 by_id_.push_back(inst);
164 by_id_[id.value].id = id;
165 return id;
166 }
167
168 [[nodiscard]] std::size_t size() const noexcept { return by_id_.size(); }
169 [[nodiscard]] bool contains(InstrumentId id) const noexcept { return id.value < by_id_.size(); }
170 [[nodiscard]] const Instrument& get(InstrumentId id) const noexcept {
171 FASTMM_ASSERT(contains(id));
172 return by_id_[id.value];
173 }
174 [[nodiscard]] Instrument& get(InstrumentId id) noexcept {
175 FASTMM_ASSERT(contains(id));
176 return by_id_[id.value];
177 }
178 [[nodiscard]] const Instrument& operator[](InstrumentId id) const noexcept { return get(id); }
179 [[nodiscard]] const Instrument* find(VenueId venue, std::string_view symbol) const noexcept {
180 const InstrumentId* id = by_symbol_.find(Key{venue, Symbol(symbol)});
181 return id == nullptr ? nullptr : &by_id_[id->value];
182 }
183 [[nodiscard]] const Instrument* begin() const noexcept { return by_id_.begin(); }
184 [[nodiscard]] const Instrument* end() const noexcept { return by_id_.end(); }
185 [[nodiscard]] const Instrument* data() const noexcept { return by_id_.data(); }
186 // Two instruments settle alike when they name the same settlement currency, linear or inverse
187 // (Deribit's inverse BTC-PERPETUAL and its BTC-quoted options both settle in BTC); an unnamed
188 // currency only matches another unnamed one of the same kind.
189 [[nodiscard]] SettlementMix settlement_mix() const noexcept {
191 for (const Instrument& inst : *this) {
192 if (!inst.enabled()) continue;
193 if (m.first == nullptr) {
194 m.first = &inst;
195 } else if (inst.settlement_ccy() != m.first->settlement_ccy() ||
196 (inst.settlement_ccy().empty() && inst.inverse() != m.first->inverse())) {
197 m.other = &inst;
198 break;
199 }
200 }
201 return m;
202 }
203 void clear() noexcept {
204 by_id_.clear();
205 by_symbol_.clear();
206 }
207
208 private:
209 StaticVector<Instrument, kMaxInstruments> by_id_;
210 FlatMap<Key, InstrumentId, kMaxInstruments> by_symbol_;
211};
212
213} // namespace fastmm
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
bool contains(InstrumentId id) const noexcept
Definition instrument.hpp:169
SettlementMix settlement_mix() const noexcept
Two instruments settle alike when they name the same settlement currency, linear or inverse (Deribit'...
Definition instrument.hpp:189
const Instrument * find(VenueId venue, std::string_view symbol) const noexcept
Definition instrument.hpp:179
std::size_t size() const noexcept
Definition instrument.hpp:168
const Instrument & operator[](InstrumentId id) const noexcept
Definition instrument.hpp:178
Instrument & get(InstrumentId id) noexcept
Definition instrument.hpp:174
const Instrument & get(InstrumentId id) const noexcept
Definition instrument.hpp:170
void clear() noexcept
Definition instrument.hpp:203
Result< InstrumentId, InstrumentError > add(const Instrument &inst) noexcept
Definition instrument.hpp:155
const Instrument * begin() const noexcept
Definition instrument.hpp:183
const Instrument * end() const noexcept
Definition instrument.hpp:184
const Instrument * data() const noexcept
Definition instrument.hpp:185
Definition result.hpp:30
Minimal expected<T, E>: the hot path never throws, it returns Result.
All engine enumerations.
Fixed<Tag>: int64 fixed point with a global 1e-8 scale (ADR-0001).
Definition strategy.hpp:23
constexpr Qty round_to_lot(Qty q, Qty lot) noexcept
Quantities always round down (never send more than intended).
Definition fixed_point.hpp:405
TradingStatus
Whether a venue takes orders on an instrument (Instrument::status, InstrumentRulesMsg).
Definition enums.hpp:436
AssetClass
Definition enums.hpp:51
Side
Definition enums.hpp:12
constexpr Unexpected< std::decay_t< E > > fail(E &&e) noexcept
Definition result.hpp:25
constexpr std::size_t kMaxInstruments
Definition instrument.hpp:26
constexpr std::int64_t mul_raw(Fixed< A > a, Fixed< B > b) noexcept
Generic scaled multiply for fixed*fixed in one domain (e.g. qty * multiplier).
Definition fixed_point.hpp:367
constexpr bool on_lot(Qty q, Qty lot) noexcept
Definition fixed_point.hpp:409
InstrumentError
Definition instrument.hpp:137
OptionType
Definition enums.hpp:77
FixedString< 20 > Symbol
Definition instrument.hpp:27
constexpr Notional mul(Price p, Qty q) noexcept
price * qty with a 128-bit intermediate, truncated toward zero to 1e-8.
Definition fixed_point.hpp:362
constexpr Price round_to_tick(Price p, Price tick, Side side) noexcept
Round to the tick grid in the passive direction: bids down, asks up. tick > 0.
Definition fixed_point.hpp:388
constexpr bool on_tick(Price p, Price tick) noexcept
Definition fixed_point.hpp:401
Strongly typed identifiers.
std::int64_t raw
Definition fixed_point.hpp:152
Definition instrument.hpp:149
Symbol symbol
Definition instrument.hpp:151
VenueId venue
Definition instrument.hpp:150
constexpr auto operator<=>(const Key &) const noexcept=default
Definition instrument.hpp:29
constexpr bool inverse() const noexcept
Definition instrument.hpp:68
constexpr bool trading() const noexcept
Definition instrument.hpp:70
constexpr std::string_view settlement_ccy() const noexcept
The currency PnL, fees and notional are denominated in: the base coin for an inverse contract,...
Definition instrument.hpp:115
OptionType option_type
Byte 119 (the cold line's 55): option_type in the low nibble and, from journal format 6,...
Definition instrument.hpp:62
constexpr Qty round_qty(Qty q) const noexcept
Definition instrument.hpp:76
constexpr bool valid_qty(Qty q) const noexcept
Definition instrument.hpp:82
constexpr Notional notional(Price p, Qty q) const noexcept
Notional in the settlement currency: price * qty * multiplier for a linear contract,...
Definition instrument.hpp:88
constexpr Price ticks(std::int64_t n) const noexcept
n ticks as a price distance (tick * n).
Definition instrument.hpp:78
constexpr bool is_derivative() const noexcept
Definition instrument.hpp:118
TradingStatus status
Whether the venue takes orders on it: the venue's at start-up, then each InstrumentRulesMsg's.
Definition instrument.hpp:64
constexpr bool coin_quoted() const noexcept
Definition instrument.hpp:69
constexpr bool enabled() const noexcept
Definition instrument.hpp:67
constexpr Notional inverse_pnl(Price from, Price to, Qty qty) const noexcept
PnL in the base coin of moving qty contracts from from to to: qty * multiplier * (1/from - 1/to).
Definition instrument.hpp:107
constexpr Price round_price(Price p, Side side) const noexcept
Passive rounding: bids down, asks up.
Definition instrument.hpp:73
constexpr Notional pnl_per_tick() const noexcept
PnL change (settlement ccy) for one tick move on one contract.
Definition instrument.hpp:101
constexpr bool valid_price(Price p) const noexcept
Definition instrument.hpp:79
Instruments do not all settle in the same currency: an inverse contract settles in its base coin,...
Definition instrument.hpp:131
bool mixed() const noexcept
Definition instrument.hpp:134
const Instrument * first
first enabled instrument
Definition instrument.hpp:132
const Instrument * other
first enabled instrument that settles in another currency
Definition instrument.hpp:133