SPB Git

Repository Public

MarketsModels.swift 20.7 KB 430 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/MarketsModels.swift3// Description: The market explorer and the venue comparator (/api/v1/markets-hub, services/api/src/markets-hub/hub.ts, compare.ts),4//              the private-company contracts (/api/v1/private-markets, services/api/src/private-markets/service.ts — DISPLAY ONLY)5//              and the consolidated bars (/api/v1/market-data, services/api/src/market/routes.ts). Shapes as the web client reads6//              them (apps/web/src/markets.ts, privateMarkets.ts). Every price keeps its source, its timestamp and its staleness;7//              a figure the server could not compute is nil WITH its reason, never a number.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213public struct HubFunding: Codable, Sendable, Hashable { public let rate: String; public let intervalSec: Int; public let perHour: String; public let annualised: String; public let assumption: String? }1415/** One market of the explorer (spot symbol or perpetual). Prices are decimal strings as the source gave them. */16public struct HubRow: Decodable, Sendable, Hashable, Identifiable {17    public struct Mapping: Decodable, Sendable, Hashable { public let rule: String?; public let unmapped: String?; public let note: String? }18    public struct NetworkAsset: Decodable, Sendable, Hashable { public let network: String; public let asset: String }19    public let id: String20    /** `spot` or `perp` */21    public let kind: String22    public let venue: String23    public let venueName: String?24    public let symbol: String25    public let base: String26    public let quote: String27    public let status: String28    public let underlying: String?29    public let category: String?30    public let multiplier: String?31    public let mapping: Mapping?32    public let price: String?33    /** what `price` is: `mark` (a venue's mark price) or `close_1h` (the close of the last consolidated hourly bar) */34    public let priceKind: String?35    public let unitPrice: String?36    public let change24h: String?37    public let volume24hUsd: String?38    public let funding: HubFunding?39    public let openInterest: String?40    public let openInterestUsd: String?41    public let maxLeverage: String?42    /** false: the wallet cannot trade this market; `tradableReason` says why */43    public let tradable: Bool44    public let tradableReason: String?45    public let paper: Bool?46    public let restriction: String?47    /** unix ms at which the SOURCE produced the row */48    public let sourceTs: Int?49    public let ageMs: Int?50    /** older than its freshness bound, or the source could not be refreshed: must be shown */51    public let stale: Bool52    public let staleAfterMs: Int?53    /** where the row comes from (a venue, the consolidated market data) */54    public let source: String55    public let networks: [NetworkAsset]?56    public let priceSource: String?57    public let priceOutlier: Bool?58    public var sourceDate: Date? { sourceTs.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } }59}6061public struct HubVenue: Decodable, Sendable, Hashable, Identifiable {62    public let id: String; public let name: String63    /** `ok`, `stale`, `error` */64    public let status: String65    public let rows: Int?; public let ageMs: Int?; public let restriction: String?; public let error: String?66}6768public struct HubList: Decodable, Sendable, Equatable {69    public struct Counts: Decodable, Sendable, Equatable { public let spot, perp, tradable, stale: Int }70    public struct Cache: Decodable, Sendable, Equatable { public let ageMs: Int; public let ttlMs: Int }71    public let rows: [HubRow]72    public let total: Int73    public let offset: Int74    public let limit: Int75    public let counts: Counts?76    public let venues: [HubVenue]77    /** sources that did not answer: the list is partial */78    public let errors: [SourceError]79    public let locks: [ExecutionLock]?80    public let cache: Cache?81    public let ts: Int82}8384public struct HubQuery: Sendable, Equatable {85    public enum Sort: String, Sendable, CaseIterable { case volume, openInterest, funding, change, symbol }86    public var kind: String?87    public var venue: String?88    /** `crypto`, `equity`, `pre_ipo`, `commodity`, `fx` */89    public var category: String?90    public var search: String?91    public var tradable: Bool?92    public var sort: Sort93    public var descending: Bool94    public var limit: Int95    public var offset: Int96    public init(kind: String? = nil, venue: String? = nil, category: String? = nil, search: String? = nil, tradable: Bool? = nil, sort: Sort = .volume, descending: Bool = true, limit: Int = 50, offset: Int = 0) {97        self.kind = kind; self.venue = venue; self.category = category; self.search = search; self.tradable = tradable; self.sort = sort; self.descending = descending; self.limit = limit; self.offset = offset98    }99}100101public struct HubUnderlying: Decodable, Sendable, Hashable {102    public let underlying: String; public let category: String?; public let venues: [String]; public let instruments: Int103    /** listed on more than one venue */104    public let comparable: Bool105    public let volume24hUsd: String?106}107108public struct HubUnderlyingDetail: Decodable, Sendable, Equatable {109    public let underlying: String110    public let category: String?111    public let spot: [HubRow]112    public let instruments: [HubRow]113    /** same letters, not mapped to this underlying: shown, never compared */114    public let notCompared: [HubRow]115    public let errors: [SourceError]116}117118/** One figure of the comparator: `value` nil WITH `reason` when an input is missing; `basis` says what it was computed from. */119public struct CostFigure: Decodable, Sendable, Hashable { public let value: String?; public let reason: String?; public let basis: String? }120121public struct VenueCost: Decodable, Sendable, Equatable {122    /** `order_book` or `pool` */123    public let executionModel: String?124    public let midPrice, spreadBps, sizeBase, entryAvgPrice, entrySlippageBps, fundingRatePerHour, collateralRequiredUsd, liquidationPrice, liquidationDistanceBps, maxLeverage: CostFigure?125    public let entrySlippageUsd, exitSlippageUsd, entryFeeUsd, exitFeeUsd, fundingUsd: CostFigure?126    public let totalCostUsd, totalCostBps: CostFigure?127    /** cost items that could not be estimated: the total is then nil, never a partial sum presented as a total */128    public let missing: [String]?129    public let assumptions: [String]?130}131132public struct CompareRow: Decodable, Sendable, Equatable {133    public struct Price: Decodable, Sendable, Equatable { public let mark: String?; public let index: String?; public let mid: String? }134    public struct Depth: Decodable, Sendable, Equatable { public let bps: String; public let bidUsd: String; public let askUsd: String; public let bidComplete: Bool; public let askComplete: Bool }135    public struct Fees: Decodable, Sendable, Equatable { public let takerRate: String; public let makerRate: String; public let source: String; public let asOf: String }136    public struct Maintenance: Decodable, Sendable, Equatable { public let fraction: String; public let basis: String }137    public let venue: String138    public let venueName: String?139    public let instrument: String140    public let symbol: String?141    public let underlying: String?142    public let multiplier: String?143    public let alternatives: [String]?144    public let tradable: Bool145    public let tradableReason: String?146    public let restriction: String?147    public let price: Price?148    public let depth: [Depth]?149    public let depthReason: String?150    /** the fee schedule used, with its source and the date it was read */151    public let fees: Fees?152    public let funding: HubFunding?153    public let maintenance: Maintenance?154    /** an itemised ESTIMATE; nil when the venue could not be read (`error`) */155    public let cost: VenueCost?156    public let priceOutlier: Bool157    public let ageMs: Int?158    public let stale: Bool159    public let staleAfterMs: Int?160    public let error: String?161}162163public struct CodedText: Decodable, Sendable, Hashable { public let code: String; public let text: String }164165/** A price gap between two venues: an ESTIMATE under stated assumptions, with its risks. Never an instruction to trade. */166public struct VenueDiscrepancy: Decodable, Sendable, Equatable {167    public struct Costs: Decodable, Sendable, Equatable { public let feesUsd: String; public let exitSlippageUsd: String; public let fundingUsd: String }168    public let longVenue, shortVenue: String169    public let longInstrument, shortInstrument: String?170    public let grossGapBps: String?171    public let netEdgeEstimateBps: String?172    public let costsUsd: Costs?173    public let flagged: Bool174    public let reason: String?175    public let actionableFromWallet: Bool176    public let assumptions: [CodedText]177    public let risks: [CodedText]178}179180public struct VenueComparison: Decodable, Sendable, Equatable {181    public struct Texts: Decodable, Sendable, Equatable { public let disclaimer: String; public let discrepancy: String?; public let assumptions: [CodedText]? }182    public let underlying: String183    public let category: String?184    /** the request as the server understood it */185    public let request: JSONValue186    public let rows: [CompareRow]187    public let discrepancies: [VenueDiscrepancy]188    /** the disclaimer is displayed with the comparison, verbatim */189    public let texts: Texts190    public let warnings: [String]191    public let errors: [SourceError]192    public let ts: Int193    public let source: String?194}195196public struct CompareQuery: Sendable, Equatable {197    public let underlying: String198    /** `long` or `short` */199    public let side: String200    /** position notional in USD (not the collateral), decimal text */201    public let notional: String202    public let leverage: String203    public let horizonHours: String204    /** `taker` or `maker` */205    public let liquidity: String?206    public let minNetEdgeBps: String?207    public init(underlying: String, side: String, notional: String, leverage: String, horizonHours: String, liquidity: String? = nil, minNetEdgeBps: String? = nil) {208        self.underlying = underlying; self.side = side; self.notional = notional; self.leverage = leverage; self.horizonHours = horizonHours; self.liquidity = liquidity; self.minNetEdgeBps = minNetEdgeBps209    }210}211212// MARK: private markets (display only)213214/** One figure with where it comes from, when it was read, and whether it is older than its freshness bound. */215public struct SourcedDatum: Decodable, Sendable, Hashable {216    public let value: String?217    public let source: String218    /** unix ms */219    public let ts: Int?220    public let stale: Bool221    public let intervalSec: Int?222    public let unit: String?223    public let unitLabel: String?224    /** `mark` or `frozen mark` */225    public let priceKind: String?226}227228public struct PrivateReference: Decodable, Sendable, Hashable {229    public let company: String?230    public let valueUsd: String?231    public let value: String?232    /** `primary_round`, `tender`, `secondary_estimate`, `ipo_range`, `press_estimate` */233    public let kind: String234    public let detail: String235    public let date: String236    public let sourceUrl: String237    /** `high`, `medium`, `low` */238    public let confidence: String239}240241public struct PrivatePosition: Decodable, Sendable, Hashable { public let side: String; public let size: String }242public struct PrivateCaveat: Decodable, Sendable, Hashable { public let code: String; public let text: String; public let data: JSONValue? }243244/** How a synthetic price relates to a company valuation: each derived figure carries its FORMULA, or is nil with the reason. */245public struct PrivateValuation: Decodable, Sendable, Equatable {246    public struct Derived: Decodable, Sendable, Equatable {247        public let value: String?248        /** the formula in words; nil = nothing was derived */249        public let formula: String?250        public let reason: String?251        public let source: String?252        public let ts: Int?253        public let position: PrivatePosition?254        /** true: the exposure is for a HYPOTHETICAL position, not one the wallet holds */255        public let hypothetical: Bool?256    }257    public struct FormulaSource: Decodable, Sendable, Equatable { public let url: String; public let quote: String; public let readAt: String }258    public struct Implied: Decodable, Sendable, Equatable {259        public let value: String?260        public let formula: String?261        public let formulaId: String?262        /** where the contract's own documentation states the convention the formula relies on */263        public let formulaSource: FormulaSource?264        public let asOf: Int?265        public let label: String?266        public let reason: String?267        /** `not_reviewed`, `under_review`, `per_share_no_share_count`, `unit_not_published`, `delisted_frozen`, `no_price`, `no_formula` */268        public let reasonCode: String?269        public var isDerived: Bool { value != nil && formula != nil }270    }271    public struct Premium: Decodable, Sendable, Equatable { public let premiumBps: String?; public let reason: String?; public let caveat: String? }272    public let syntheticPrice: SourcedDatum273    public let contractMarketValue: Derived274    public let notionalExposure: Derived275    public let impliedValuation: Implied276    public let lastPrivateValuation: PrivateReference?277    public let lastPrivateValuationReason: String?278    public let premiumDiscount: Premium279    public let caveats: [PrivateCaveat]280}281282/** One synthetic contract on a private company. NEVER tradable from this wallet: `tradable` is always false and `notTradable` says why. */283public struct PrivateMarket: Decodable, Sendable, Equatable, Identifiable {284    public struct Company: Decodable, Sendable, Equatable { public let slug: String; public let name: String }285    /** The review of the contract sheet: a sheet past `validUntil`, or not `reviewed`, shows no unit and no derived valuation. */286    public struct Review: Decodable, Sendable, Equatable {287        /** `reviewed`, `under_review`, `not_reviewed` */288        public let state: String289        public let reasons: [String]290        public let reviewedAt: String?291        /** EXPIRY of the contract sheet (date text as served) */292        public let validUntil: String?293        public let fingerprintChecked: Bool?294        public var isReviewed: Bool { state == "reviewed" }295        public var validUntilDate: Date? { validUntil.flatMap { ISO8601.parse($0) ?? ISO8601.parse($0 + "T00:00:00Z") } }296        /** true when the sheet states an expiry that has passed; nil when it states none or it cannot be read */297        public func isExpired(at now: Date) -> Bool? { validUntilDate.map { $0 <= now } }298    }299    public struct Unit: Decodable, Sendable, Equatable { public let kind: String; public let label: String }300    public struct Contract: Decodable, Sendable, Equatable {301        public let nature: String?302        public let unit: Unit303        public let quoteCurrency: String?304        public let collateral: String?305        public let underlying: String?306        public let contractSize: String?307        public let multiplier: JSONValue?308        public let settlement: String?309        public let ipoConversion: String?310        public let oracle: String?311        public let liquidation: String?312        public let maxLeverage: String?313        public let margin: String?314        public let onChainDescription: String?315        public let unconfirmedConvention: JSONValue?316        public let sources: [String]?317    }318    public struct Market: Decodable, Sendable, Equatable {319        public let price, oracle, mid, funding, openInterest, openInterestUsd, volume24h, volumeBase24h: SourcedDatum?320        /** true: the venue no longer updates this price */321        public let frozen: Bool?322    }323    public struct NotTradable: Decodable, Sendable, Equatable { public let code: String; public let reasons: [String] }324    public let id: String325    public let venue: String326    public let platform: String?327    public let `operator`: String?328    public let symbol: String329    public let company: Company?330    /** `live`, `delisted`, `halted`, `reduce_only` */331    public let status: String332    public let review: Review333    public let contract: Contract334    public let market: Market335    public let valuation: PrivateValuation336    public let tradable: Bool337    public let notTradable: NotTradable?338    public let error: String?339}340341public struct PrivateDivergence: Decodable, Sendable, Equatable {342    public struct Leg: Decodable, Sendable, Equatable { public let id: String; public let price: String; public let ts: Int? }343    public let unit: String?; public let unitLabel: String?; public let contracts: [Leg]; public let spreadBps: String; public let note: String?344}345public struct PrivateCompany: Decodable, Sendable, Equatable {346    public let slug: String; public let name: String; public let note: String?347    public let contracts: [String]?348    public let lastPrivateValuation: PrivateReference?349    public let divergence: [PrivateDivergence]?350}351public struct PrivateVenue: Decodable, Sendable, Equatable { public let venue: String; public let name: String?; public let status: String; public let error: String?; public let ts: Int?; public let instruments: Int? }352public struct PrivateNotice: Decodable, Sendable, Equatable { public let tradable: Bool; public let code: String; public let text: String }353354public struct PrivateMarketList: Decodable, Sendable, Equatable {355    public struct Excluded: Decodable, Sendable, Equatable { public let id: String; public let company: String?; public let reason: String; public let liveCategory: String? }356    public struct NoAdapter: Decodable, Sendable, Equatable { public let venue: String; public let note: String }357    public let markets: [PrivateMarket]358    public let companies: [PrivateCompany]359    public let excluded: [Excluded]?360    public let venues: [PrivateVenue]361    public let venuesWithoutAdapter: [NoAdapter]?362    /** displayed with the list, verbatim: these contracts are not tradable from the wallet */363    public let notice: PrivateNotice364    public let position: PrivatePosition?365    public let ts: Int366}367368public struct PrivateMarketDetail: Decodable, Sendable, Equatable {369    public struct Sibling: Decodable, Sendable, Equatable { public let id: String; public let platform: String?; public let price: SourcedDatum; public let unit: PrivateMarket.Unit; public let review: String }370    public let market: PrivateMarket371    /** top of book and candles as served (each carries its own `ts`, `stale`, `source` or `error`) */372    public let book: JSONValue?373    public let candles: JSONValue?374    public let references: [PrivateReference]375    public let company: PrivateCompany?376    public let sameCompany: [Sibling]?377    public let notice: PrivateNotice378    public let position: PrivatePosition?379    public let ts: Int380}381382/** Every contract on one company, side by side. `merged` is always null: contracts of different venues are never averaged. */383public struct PrivateCompanyDetail: Decodable, Sendable, Equatable {384    public struct Info: Decodable, Sendable, Equatable { public let slug: String?; public let name: String; public let note: String? }385    public let company: Info386    public let contracts: [PrivateMarket]387    public let delisted: [PrivateMarket]388    public let references: [PrivateReference]389    public let lastPrivateValuation: PrivateReference?390    public let divergence: [PrivateDivergence]391    public let mergedReason: String?392    public let venues: [PrivateVenue]?393    public let notice: PrivateNotice394    public let position: PrivatePosition?395    public let ts: Int396    public let source: String?397}398399// MARK: consolidated market data400401/** One bar of the consolidated series. Kept as served: the bar's own fields say which source provided it. */402public struct MarketCandles: Decodable, Sendable, Equatable {403    public let symbol: String404    public let interval: String405    /** the consolidation rule, verbatim (one whole bar of the first source that has it; never a blend) */406    public let rule: String407    public let priority: [String]?408    public let gaps: JSONValue?409    /** how many bars each source provided */410    public let provided: JSONValue?411    public let bars: [JSONValue]412}413414public struct MarketDataStatus: Decodable, Sendable, Equatable {415    public struct Quality: Decodable, Sendable, Equatable {416        public let symbol: String; public let interval: String; public let status: String; public let fresh: Bool417        public let checkedAt: JSONValue?; public let lastTs: JSONValue?; public let gaps: JSONValue?; public let maxDeviationBps: JSONValue?418        public let failures: JSONValue?; public let window: JSONValue?; public let provided: JSONValue?; public let sources: JSONValue?419    }420    public let symbols: [String]421    public let intervals: [String]422    public let priority: JSONValue?423    public let rule: String424    public let thresholds: JSONValue?425    public let sources: JSONValue?426    public let coverage: JSONValue?427    public let quality: [Quality]428    public let rejectedSinceStart: JSONValue?429}430
Files main
Menu

Theme