Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Futures/FuturesStore.swift3// Description: The read side of the derivatives terminal, shared by its tabs: venues, instruments, tickers, server locks and capabilities, jurisdiction notice, paper and live accounts, and the live quote stream (the Core's websocket, with its own reconnection and freshness verdicts). Every source keeps its own error: a failed read is shown as unavailable, never as an empty or zero account. Nothing here places, prepares or signs anything.4import Foundation5import SPWalletCore67@MainActor @Observable final class FuturesStore {8 let model: AppModel9 let deriv: DerivativesAPI10 let live: DerivativesLiveAPI11 let collateral: DerivativesCollateralAPI12 let gmx: DerivativesGMXAPI13 let risk: RiskAPI14 let markets: MarketsAPI15 let monitor: MonitorAPI16 @ObservationIgnored private let stream: QuoteStream1718 // MARK: selection1920 var mode: FutMode = .paper { didSet { if mode != oldValue { liveDetail = FutLoaded(); Task { await refreshAccount() } } } }21 var venue = "" { didSet { if venue != oldValue { instruments = FutLoaded(); tickers = [:]; Task { await loadMarket() } } } }22 var instrumentId: String? { didSet { if instrumentId != oldValue { book = nil; trades = []; lastCandle = nil; resubscribe() } } }23 var chartInterval: DerivCandleInterval = .h1 { didSet { if chartInterval != oldValue { lastCandle = nil; resubscribe() } } }24 var paperId: PaperAccountID? { didSet { if paperId != oldValue { paperDetail = FutLoaded(); Task { await refreshAccount() } } } }25 /// The owner's own statement, for this session of the screen, that the jurisdiction notice was read. Never persisted, never assumed.26 var jurisdictionRead = false2728 // MARK: what the server said2930 private(set) var venues = FutLoaded<[DerivVenue]>()31 private(set) var instruments = FutLoaded<[DerivInstrument]>()32 private(set) var venueErrors: [DerivVenueReadError] = []33 private(set) var tickers: [String: DerivTicker] = [:]34 private(set) var tickersAt: Date?35 private(set) var tickersError: String?36 private(set) var config = FutLoaded<LiveConfig>()37 private(set) var jurisdiction = FutLoaded<JurisdictionAnswer>()38 private(set) var capabilities = FutLoaded<[ServerCapability]>()39 private(set) var riskState = FutLoaded<RiskState>()40 private(set) var paperAccounts = FutLoaded<[PaperAccount]>()41 private(set) var liveAccounts = FutLoaded<[LiveAccount]>()42 private(set) var paperDetail = FutLoaded<PaperAccountDetail>()43 private(set) var liveDetail = FutLoaded<LiveAccountDetail>()4445 // MARK: live stream4647 private(set) var streamState: QuoteStreamState = .idle48 private(set) var quotes: [String: LiveQuote] = [:]49 private(set) var book: LiveBook?50 private(set) var trades: [StreamTrade] = []51 private(set) var lastCandle: StreamCandleMessage?52 private(set) var streamError: String?53 private(set) var channelRefusals: [String: String] = [:]54 /// The clock the freshness verdicts are evaluated on; advanced by the flush loop so that a silent quote turns stale on screen.55 private(set) var now = Date()5657 @ObservationIgnored private var pending: [String: LiveQuote] = [:]58 @ObservationIgnored private var pendingBook: LiveBook?59 @ObservationIgnored private var streamTask: Task<Void, Never>?60 @ObservationIgnored private var flushTask: Task<Void, Never>?61 @ObservationIgnored private var subscriptionTask: Task<Void, Never>?62 @ObservationIgnored private var channels: Set<StreamChannel> = []63 @ObservationIgnored private var listIds: [String] = []64 /// How many list rows get a live quote; the rest show the REST snapshot with its age (the server caps a connection's subscriptions).65 static let liveRows = 1206667 init(model: AppModel) {68 self.model = model69 let c = model.client70 deriv = DerivativesAPI(c); live = DerivativesLiveAPI(c); collateral = DerivativesCollateralAPI(c); gmx = DerivativesGMXAPI(c)71 risk = RiskAPI(c); markets = MarketsAPI(c); monitor = MonitorAPI(c)72 stream = QuoteStream(client: c)73 }7475 var locale: String { model.settings.locale.lowercased().hasPrefix("fr") ? "fr" : "en" }7677 // MARK: derived7879 var selectedVenue: DerivVenue? { venues.value?.first { $0.id == venue } }80 var instrument: DerivInstrument? { instruments.value?.first { $0.id == instrumentId } }81 func venueInfo(_ id: String) -> DerivVenue? { venues.value?.first { $0.id == id } }8283 /// The live venue account of the current mode (one per venue and network); nil in paper mode or when none exists.84 var liveAccount: LiveAccount? {85 guard let net = mode.network else { return nil }86 if let d = liveDetail.value, d.account.network == net { return d.account }87 return liveAccounts.value?.first { $0.network == net }88 }89 var paperAccount: PaperAccount? {90 if let d = paperDetail.value, d.account.id == paperId { return d.account }91 return paperAccounts.value?.first { $0.id == paperId }92 }93 /// The live detail, only when it belongs to the current mode.94 var currentLiveDetail: LiveAccountDetail? { liveDetail.value.flatMap { $0.account.network == mode.network ? $0 : nil } }95 var currentPaperDetail: PaperAccountDetail? { paperDetail.value.flatMap { $0.account.id == paperId ? $0 : nil } }9697 func capability(_ id: String) -> ServerCapability? { capabilities.value?.first { $0.id == id } }98 func executionLock(_ id: String) -> ExecutionLock? { riskState.value?.locks.first { $0.id == id } }99 var killSwitch: RiskSwitch? { riskState.value?.switches.killSwitch }100 var readOnlySwitch: RiskSwitch? { riskState.value?.switches.readOnly }101102 /// The price to display for an instrument: the stream's quote with its freshness, else the REST ticker with its date.103 func price(_ id: String) -> (mark: String?, freshness: StreamFreshness?, snapshotAt: Date?) {104 if let q = quotes[id], let m = q.quote.mark ?? q.quote.mid ?? q.quote.last {105 return (m, q.freshness(connection: streamState, now: now), nil)106 }107 let t = tickers[id]108 return (t?.mark, nil, t?.ts)109 }110 func bookFreshness(_ b: LiveBook) -> StreamFreshness {111 .evaluate(freshAt: b.freshAt, serverStale: b.stale, staleAfterMs: nil, connection: streamState, now: now)112 }113114 // MARK: loading115116 func loadAll() async {117 async let a: Void = loadVenues()118 async let b: Void = loadLocks()119 async let c: Void = loadAccounts()120 _ = await (a, b, c)121 await loadMarket()122 await refreshAccount()123 }124125 func loadVenues() async {126 venues.loading = true127 do {128 let v = try await deriv.venues().venues129 venues.set(v)130 if venue.isEmpty || !v.contains(where: { $0.id == venue }) { venue = v.first(where: { $0.restriction == nil })?.id ?? v.first?.id ?? "" }131 } catch { venues.fail(model.describe(error)) }132 }133134 /// Server locks, capabilities, jurisdiction notice and the risk engine's switches: read together, each failing alone.135 func loadLocks() async {136 let live = live, monitor = monitor, risk = risk, loc = locale137 async let cfg = futAttempt { try await live.config(locale: loc) }138 async let jur = futAttempt { try await live.jurisdiction() }139 async let cap = futAttempt { try await monitor.health() }140 async let rs = futAttempt { try await risk.state() }141 switch await cfg { case .success(let v): config.set(v); case .failure(let e): config.fail(model.describe(e)) }142 switch await jur { case .success(let v): jurisdiction.set(v); case .failure(let e): jurisdiction.fail(model.describe(e)) }143 switch await cap {144 case .success(let v): if let c = v.capabilities { capabilities.set(c) } else { capabilities.fail("Le serveur n’a pas publié ses capacités.") }145 case .failure(let e): capabilities.fail(model.describe(e))146 }147 switch await rs { case .success(let v): riskState.set(v); case .failure(let e): riskState.fail(model.describe(e)) }148 }149150 func loadRiskState() async {151 do { riskState.set(try await risk.state()) } catch { riskState.fail(model.describe(error)) }152 }153154 func loadAccounts() async {155 let deriv = deriv, live = live156 async let p = futAttempt { try await deriv.paperAccounts() }157 async let l = futAttempt { try await live.accounts() }158 switch await p {159 case .success(let v):160 paperAccounts.set(v)161 if paperId == nil || !v.contains(where: { $0.id == paperId }) { paperId = v.first?.id }162 case .failure(let e): paperAccounts.fail(model.describe(e))163 }164 switch await l { case .success(let v): liveAccounts.set(v); case .failure(let e): liveAccounts.fail(model.describe(e)) }165 }166167 func loadMarket() async {168 guard !venue.isEmpty else { return }169 let v = venue170 instruments.loading = true171 do {172 let a = try await deriv.instruments(venue: v, locale: locale)173 guard v == venue else { return }174 instruments.set(a.instruments.filter { $0.venue == v }); venueErrors = a.errors ?? []175 } catch { if v == venue { instruments.fail(model.describe(error)) } }176 await refreshTickers()177 }178179 func refreshTickers() async {180 guard !venue.isEmpty else { return }181 let v = venue182 do {183 let a = try await deriv.tickers(venue: v)184 guard v == venue else { return }185 tickers = Dictionary(a.tickers.map { ($0.instrument, $0) }, uniquingKeysWith: { _, b in b })186 tickersAt = Date(); tickersError = a.errors?.first { $0.venue == v }?.message187 } catch { if v == venue { tickersError = model.describe(error) } }188 }189190 /// Reads the account of the current mode. The previous value stays on screen with the error when a refresh fails.191 func refreshAccount() async {192 switch mode {193 case .paper:194 guard let id = paperId else { return }195 paperDetail.loading = true196 do { let d = try await deriv.paperAccount(id); if id == paperId { paperDetail.set(d); resubscribe() } }197 catch { if id == paperId { paperDetail.fail(model.describe(error)) } }198 case .testnet, .mainnet:199 guard let net = mode.network, let a = liveAccounts.value?.first(where: { $0.network == net }) else { return }200 liveDetail.loading = true201 do { let d = try await live.account(a.id); if mode.network == net { liveDetail.set(d); resubscribe() } }202 catch { if mode.network == net { liveDetail.fail(model.describe(error)) } }203 }204 }205206 /// An operation answered the account again: show that answer without another round trip.207 func adopt(_ d: LiveAccountDetail) { if d.account.network == mode.network { liveDetail.set(d) } }208 func adopt(_ d: PaperAccountDetail) { if d.account.id == paperId { paperDetail.set(d) } }209210 // MARK: stream211212 func startStream() {213 guard streamTask == nil else { return }214 let s = stream215 streamTask = Task { [weak self] in216 let events = await s.events()217 guard !Task.isCancelled else { return }218 await s.start()219 for await e in events { guard let self else { return }; self.handle(e) }220 }221 flushTask = Task { [weak self] in222 var n = 0223 while !Task.isCancelled {224 try? await Task.sleep(for: .milliseconds(500))225 guard let self, !Task.isCancelled else { return }226 n += 1227 self.flush(advanceClock: n % 4 == 0)228 }229 }230 resubscribe()231 }232233 /// Leaving the screen: the socket is closed; whatever was held stops reading « live » at once.234 func stopStream() {235 streamTask?.cancel(); streamTask = nil236 flushTask?.cancel(); flushTask = nil237 let s = stream238 Task { await s.stop() }239 streamState = .idle; now = Date()240 }241242 /// The rows the markets list shows first (its own sort and filter): they get a live quote.243 func setLiveRows(_ ids: [String]) {244 let cut = Array(ids.prefix(Self.liveRows))245 guard cut != listIds else { return }246 listIds = cut247 resubscribe()248 }249250 private func resubscribe() {251 var want = Set(listIds.map { StreamChannel.quote($0) })252 for p in currentPaperDetail?.account.positions ?? [] { want.insert(.quote(p.instrument)) }253 for p in currentLiveDetail?.venueState.positions ?? [] { want.insert(.quote(p.instrument)) }254 if let id = instrumentId {255 want.insert(.quote(id)); want.insert(.trades(id)); want.insert(.candle(id, interval: chartInterval.rawValue))256 if venueInfo(String(id.prefix { $0 != ":" }))?.orderBook != false { want.insert(.book(id, depth: 20)) }257 }258 want = want.filter(\.isValid)259 guard want != channels else { return }260 let add = Array(want.subtracting(channels)), remove = Array(channels.subtracting(want))261 channels = want262 let s = stream, previous = subscriptionTask263 subscriptionTask = Task { [weak self] in264 await previous?.value265 await s.unsubscribe(remove)266 do { try await s.subscribe(add); self?.streamError = nil }267 catch QuoteStreamError.tooManySubscriptions(let limit) { self?.streamError = "Le flux en direct est limité à \(limit) abonnements : certaines lignes affichent l’instantané." }268 catch { self?.streamError = "Abonnement refusé par le flux : \(error)" }269 }270 }271272 private func handle(_ e: QuoteStreamEvent) {273 switch e {274 case .state(let s): streamState = s; now = Date()275 case .quote(let q): pending[q.id] = q276 case .book(let b): if b.id == instrumentId { pendingBook = b }277 case .bookResync(let key): if let id = instrumentId, key == StreamChannel.book(id, depth: 20).key { pendingBook = nil; book = nil }278 case .trades(let id, let t, _): if id == instrumentId { trades = Array((t.reversed() + trades).prefix(40)) }279 case .candle(let m, _): if m.id == instrumentId, m.interval == chartInterval.rawValue { lastCandle = m }280 case .error(let m):281 if let ch = m.channel { channelRefusals[ch.key] = "\(m.message) [\(m.code)]" } else { streamError = "\(m.message) [\(m.code)]" }282 case .stale: now = Date()283 default: break284 }285 }286287 private func flush(advanceClock: Bool) {288 if !pending.isEmpty { quotes.merge(pending) { _, b in b }; pending = [:] }289 if let b = pendingBook { book = b; pendingBook = nil }290 if advanceClock { now = Date() }291 }292293 func refusal(of channel: StreamChannel) -> String? { channelRefusals[channel.key] }294295 var streamText: String {296 switch streamState {297 case .idle: "Flux en direct arrêté"298 case .connecting: "Connexion au flux en direct…"299 case .live: "Flux en direct connecté"300 case .reconnecting(let attempt, let delay): "Flux interrompu — nouvelle tentative \(attempt) dans \(max(1, delay / 1000)) s ; les prix affichés ne sont plus en direct"301 case .ended(.signedOut), .ended(.unauthorized): "Flux fermé : session terminée"302 case .ended(.refused(let status)): "Flux refusé par le serveur (\(status))"303 }304 }305}306307/// One of several concurrent reads that must each fail alone.308func futAttempt<T: Sendable>(_ body: @Sendable () async throws -> T) async -> Result<T, Error> {309 do { return .success(try await body()) } catch { return .failure(error) }310}311