Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/DeFi/MarketsLogic.swift10// Description : Pure logic of the Markets screens: which price a row shows11// and how it is MARKED (live, delayed, stale, reconnecting,12// or a dated snapshot) from the explorer's row and the quote13// stream — a price is presented as live only when the stream14// says so now; the words of the unified order state machine;15// the reading of consolidated bars; the comparator's typed16// inputs (no preset notional, leverage or horizon).17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-ios19// Created : 2026-11-1820// Last Modified : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import SPWalletCore9697/** How a displayed figure may be presented. Only `.live` is a live price. */98enum MarketMark: Equatable {99 case live100 case delayed(ageMs: Int64)101 case stale(ageMs: Int64?)102 case reconnecting(ageMs: Int64?)103 /** a value read from the explorer's REST answer `ageMs` ago: dated, not streamed */104 case snapshot(ageMs: Int64?)105 case none106107 var isLive: Bool { self == .live }108 var label: String {109 switch self {110 case .live: String(localized: "en direct")111 case .delayed(let a): String(localized: "retardé · \(Fmt.age(ms: Int(a)) ?? "")")112 case .stale(let a): a.map { String(localized: "périmé · \(Fmt.age(ms: Int($0)) ?? "")") } ?? String(localized: "périmé")113 case .reconnecting(let a): a.map { String(localized: "reconnexion · vu il y a \(Fmt.age(ms: Int($0)) ?? "")") } ?? String(localized: "reconnexion")114 case .snapshot(let a): a.map { String(localized: "instantané · \(Fmt.age(ms: Int($0)) ?? "")") } ?? String(localized: "instantané")115 case .none: String(localized: "pas de prix")116 }117 }118 var tone: Tone {119 switch self { case .live: .ok; case .delayed, .reconnecting: .warn; case .stale: .danger; case .snapshot, .none: .neutral }120 }121 var icon: String {122 switch self {123 case .live: "dot.radiowaves.left.and.right"124 case .delayed: "clock"125 case .stale: "clock.badge.exclamationmark"126 case .reconnecting: "arrow.triangle.2.circlepath"127 case .snapshot: "camera.metering.unknown"128 case .none: "minus"129 }130 }131}132133/** The figures a market row displays, each with where it comes from. */134struct MarketQuoteDisplay: Equatable {135 let price: String?136 /** `mark`, `mid`, `last`, `close_1h`… — what the price IS, as served */137 let priceKind: String?138 let source: String139 let mark: MarketMark140 let change24h: String?141 let funding: String?142143 /**144 - Parameters:145 - row: the explorer's row (REST), read `fetchedAt`.146 - live: the stream's last quote for this market with its freshness NOW, if subscribed and received.147 The stream's quote wins when it carries a price — with ITS freshness, whatever that is: a quote held while the stream is down148 is shown as stale/reconnecting with its age, never replaced by a fresher-looking label. Without it, the REST row is a snapshot.149 */150 static func resolve(row: HubRow, fetchedAt: Date, live: (quote: StreamQuoteMessage, freshness: StreamFreshness)?, now: Date) -> MarketQuoteDisplay {151 if let live, let (p, kind) = streamPrice(live.quote) {152 let mark: MarketMark153 switch live.freshness.state {154 case .live: mark = .live155 case .delayed: mark = .delayed(ageMs: live.freshness.ageMs ?? 0)156 case .stale: mark = .stale(ageMs: live.freshness.ageMs)157 case .reconnecting: mark = .reconnecting(ageMs: live.freshness.ageMs)158 case .none: mark = .none159 }160 return MarketQuoteDisplay(price: p, priceKind: kind, source: live.quote.source, mark: mark, change24h: live.quote.change24h ?? row.change24h, funding: live.quote.funding ?? row.funding?.rate)161 }162 guard let p = row.price else { return MarketQuoteDisplay(price: nil, priceKind: nil, source: row.priceSource ?? row.source, mark: .none, change24h: row.change24h, funding: row.funding?.rate) }163 let elapsed = Int64(max(0, now.timeIntervalSince(fetchedAt)) * 1000)164 let age = row.ageMs.map { Int64($0) + elapsed }165 let stale = row.stale || (age.flatMap { a in row.staleAfterMs.map { a > Int64($0) } } ?? false)166 return MarketQuoteDisplay(price: p, priceKind: row.priceKind, source: row.priceSource ?? row.source, mark: stale ? .stale(ageMs: age) : .snapshot(ageMs: age), change24h: row.change24h, funding: row.funding?.rate)167 }168169 /** The price a stream quote carries, by the order mark → mid → last, with its kind. nil when it carries none. */170 static func streamPrice(_ q: StreamQuoteMessage) -> (String, String)? {171 if let m = q.mark { return (m, "mark") }172 if let m = q.mid { return (m, "mid") }173 if let l = q.last { return (l, "last") }174 return nil175 }176177 static func priceKindLabel(_ k: String?) -> String? {178 switch k {179 case "mark": String(localized: "prix de marque")180 case "mid": String(localized: "milieu du carnet")181 case "last": String(localized: "dernier échange")182 case "close_1h": String(localized: "clôture de la dernière heure")183 case nil: nil184 default: k185 }186 }187}188189enum MarketWords {190 static func kind(_ k: String) -> String { k == "spot" ? String(localized: "comptant") : k == "perp" ? String(localized: "perpétuel") : k }191 static func category(_ c: String?) -> String? {192 switch c { case "crypto": String(localized: "crypto"); case "equity": String(localized: "action"); case "pre_ipo": String(localized: "pré-IPO"); case "commodity": String(localized: "matière première"); case "fx": String(localized: "devise"); default: c }193 }194 static func tradableReason(_ code: String?) -> String {195 switch code {196 case "dydx_jurisdiction": String(localized: "dYdX : exclu de ta juridiction, données de marché seulement")197 case "edgex_jurisdiction": String(localized: "edgeX : exclu de ta juridiction, données de marché seulement")198 case "hl_builder_dex": String(localized: "marché d’un dex tiers de Hyperliquid, non pris en charge")199 case "hl_asset_not_pinned": String(localized: "actif non épinglé par le portefeuille")200 case "gmx_market_not_pinned": String(localized: "marché GMX non épinglé par le portefeuille")201 case "instrument_halted": String(localized: "marché suspendu par la plateforme")202 case "instrument_reduce_only": String(localized: "marché en réduction seulement")203 case "spot_no_swap_route": String(localized: "aucune route d’échange dans le portefeuille")204 case "spot_cash_leg": String(localized: "monnaie de règlement, pas un actif à échanger")205 case nil: String(localized: "non négociable depuis ce portefeuille")206 default: String(localized: "non négociable (\(code ?? ""))")207 }208 }209 static func sort(_ s: HubQuery.Sort) -> String {210 switch s { case .volume: String(localized: "Volume 24 h"); case .openInterest: String(localized: "Intérêt ouvert"); case .funding: String(localized: "Financement"); case .change: String(localized: "Variation 24 h"); case .symbol: String(localized: "Symbole") }211 }212 static func stream(_ s: QuoteStreamState) -> (text: String, tone: Tone, icon: String) {213 switch s {214 case .live: (String(localized: "Flux en direct connecté"), .ok, "dot.radiowaves.left.and.right")215 case .connecting: (String(localized: "Connexion au flux en direct…"), .warn, "arrow.triangle.2.circlepath")216 case .reconnecting(let n, _): (String(localized: "Flux interrompu : reconnexion (essai \(n)). Les prix affichés ne sont plus en direct."), .warn, "arrow.triangle.2.circlepath")217 case .idle: (String(localized: "Flux en direct à l’arrêt : les prix sont des instantanés datés."), .neutral, "pause.circle")218 case .ended(.unauthorized), .ended(.signedOut): (String(localized: "Flux fermé : session terminée. Les prix sont des instantanés datés."), .warn, "lock")219 case .ended(.refused(let st)): (String(localized: "Flux refusé par le serveur (\(st)). Les prix sont des instantanés datés."), .warn, "xmark.circle")220 }221 }222}223224/** Words and tones of the unified order state machine. Only FILLED is a success; UNKNOWN and unrecognized states are neither. */225enum OrderWords {226 static func label(_ s: OrderState) -> String {227 switch s {228 case .created: String(localized: "Créé")229 case .validated: String(localized: "Validé")230 case .awaitingApproval: String(localized: "En attente de ton approbation")231 case .approved: String(localized: "Approuvé, pas encore envoyé")232 case .submitting: String(localized: "Envoi en cours")233 case .submitted: String(localized: "Envoyé à la plateforme, non exécuté")234 case .partiallyFilled: String(localized: "Exécuté en partie")235 case .filled: String(localized: "Exécuté")236 case .cancelled: String(localized: "Annulé")237 case .rejected: String(localized: "Refusé")238 case .failed: String(localized: "Échoué (aucun ordre n’existe)")239 case .unknown: String(localized: "Issue inconnue : vérification en cours")240 case .unrecognized(let raw): String(localized: "État non reconnu par cette version : \(raw)")241 }242 }243 static func tone(_ s: OrderState) -> Tone {244 if s.isSuccess { return .ok }245 if s.isFailure { return .danger }246 if s.isBeingVerified || s.awaitsOwner { return .warn }247 return s == .cancelled ? .neutral : .info248 }249 static func icon(_ s: OrderState) -> String {250 if s.isSuccess { return "checkmark.circle.fill" }251 if s.isFailure { return "xmark.circle.fill" }252 if s.isBeingVerified { return "questionmark.circle.fill" }253 if s.awaitsOwner { return "person.badge.key.fill" }254 return s == .cancelled ? "minus.circle" : "clock.arrow.2.circlepath"255 }256 /** What the state means for the owner, in one sentence, for the states that are easy to misread. */257 static func explanation(_ o: UnifiedOrder) -> String? {258 switch o.status {259 case .submitted: return String(localized: "L’ordre est à la plateforme. Ce n’est pas une exécution.")260 case .partiallyFilled: return String(localized: "Une partie seulement est exécutée ; le reste est encore à la plateforme.")261 case .unknown: return String(localized: "Le serveur ne sait pas encore ce que la plateforme a fait de cet ordre. Il n’est ni exécuté ni échoué : le rapprochement est en cours.")262 case .unrecognized: return String(localized: "Cette version ne connaît pas cet état : il n’est traité ni comme un succès ni comme un échec.")263 case .awaitingApproval: return String(localized: "Rien n’est signé. L’approbation par clé d’accès se fait dans Contrats à terme, dans le parcours de la plateforme.")264 default: return o.status.isTerminal && o.final == false ? String(localized: "Le serveur indique que cet état n’est pas définitif.") : nil265 }266 }267 static func side(_ s: String?) -> String { s == "buy" ? String(localized: "achat") : s == "sell" ? String(localized: "vente") : s == "long" ? "long" : s == "short" ? "short" : (s ?? "—") }268 /** Cancel is offered for every order that is not final; the server decides whether it can still be cancelled. */269 static func canAskCancel(_ o: UnifiedOrder) -> Bool { o.isOpen }270}271272/** One bar of the consolidated series, read from the served object. A bar with an unreadable member is dropped, never patched. */273struct MarketBar: Identifiable, Equatable {274 let ts: Int64275 let open, high, low, close: Double276 let source: String?277 var id: Int64 { ts }278 var date: Date { Date(timeIntervalSince1970: TimeInterval(ts) / 1000) }279280 static func parse(_ bars: [JSONValue]) -> [MarketBar] {281 bars.compactMap { b in282 guard let ts = b["ts"]?.intValue, let o = num(b["open"]), let h = num(b["high"]), let l = num(b["low"]), let c = num(b["close"]) else { return nil }283 return MarketBar(ts: ts, open: o, high: h, low: l, close: c, source: b["source"]?.stringValue)284 }.sorted { $0.ts < $1.ts }285 }286 private static func num(_ v: JSONValue?) -> Double? { v?.doubleValue ?? v?.stringValue.flatMap(Double.init) }287}288289/** What the owner typed for a venue comparison. Nothing is preset: the estimate is for HIS hypothetical position. */290struct CompareDraft: Equatable {291 /** `long` or `short`; nil until chosen */292 var side: String?293 var notional = ""294 var leverage = ""295 var horizonHours = ""296297 static let notionalMax = 1_000_000_000.0, leverageMax = 200.0, horizonMax = 8760.0298299 func problems() -> [String] {300 var p: [String] = []301 if side == nil { p.append(String(localized: "sens")) }302 if let n = RiskInput.positiveDecimal(notional).flatMap(Double.init), n <= Self.notionalMax {} else { p.append(String(localized: "notionnel")) }303 if let l = RiskInput.positiveDecimal(leverage).flatMap(Double.init), l <= Self.leverageMax {} else { p.append(String(localized: "levier")) }304 if let h = RiskInput.decimal(horizonHours).flatMap(Double.init), h <= Self.horizonMax {} else { p.append(String(localized: "horizon")) }305 return p306 }307 func query(underlying: String) -> CompareQuery? {308 guard problems().isEmpty, let side, let n = RiskInput.positiveDecimal(notional), let l = RiskInput.positiveDecimal(leverage), let h = RiskInput.decimal(horizonHours) else { return nil }309 return CompareQuery(underlying: underlying, side: side, notional: n, leverage: l, horizonHours: h)310 }311}312313/** Display rules of a private-company contract sheet: an expired or unreviewed sheet shows no derived number. */314enum PrivateSheet {315 enum Validity: Equatable { case valid(until: String?), expired(until: String), notReviewed(state: String) }316 static func validity(_ r: PrivateMarket.Review, now: Date) -> Validity {317 if r.isExpired(at: now) == true, let u = r.validUntil { return .expired(until: u) }318 if !r.isReviewed { return .notReviewed(state: r.state) }319 return .valid(until: r.validUntil)320 }321 /** The implied valuation is a number ONLY when the sheet is valid AND the server derived it from a published formula. */322 static func impliedValuation(_ m: PrivateMarket, now: Date) -> (value: String?, why: String) {323 let v = m.valuation.impliedValuation324 switch validity(m.review, now: now) {325 case .expired(let u): return (nil, String(localized: "fiche expirée le \(u)"))326 case .notReviewed(let s): return (nil, v.reason ?? String(localized: "fiche non revue (\(s))"))327 case .valid:328 guard v.isDerived, let value = v.value else { return (nil, v.reason ?? String(localized: "formule non publiée")) }329 return (value, v.formula ?? "")330 }331 }332 static func reviewLabel(_ s: String) -> String {333 switch s { case "reviewed": String(localized: "fiche revue"); case "under_review": String(localized: "fiche en cours de revue"); case "not_reviewed": String(localized: "fiche non revue"); default: s }334 }335}336