SPB Git

Repository Public

FuturesModel.swift 19.4 KB 402 lines swift

1// SP Wallet iOS2// File: Features/Futures/FuturesModel.swift3// Description: State of the perp terminal: the offered venues' instruments and tickers (with their offline snapshots), the live4//              quote stream subscribed ONLY for what is on screen (rows visible in the list, the open market's book, trades and5//              candles), paper accounts, live accounts with the server's locks and jurisdiction text. Every figure is the6//              server's; a stream that is down turns its figures stale, a book the Core withholds is shown as unavailable.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import OSLog13import SPWalletCore1415/** One recent print, from the REST snapshot or from the stream. */16struct TradePrint: Identifiable, Hashable, Sendable {17    let id: String18    let price: String19    let size: String20    let side: String21    let at: Date22}2324/** One bar for the chart. `Double` only draws; the header shows the server's strings. */25struct CandleBar: Identifiable, Hashable, Sendable {26    let at: Date27    let open, high, low, close, volume: String28    var id: Date { at }29    var o: Double { Double(open) ?? 0 }30    var h: Double { Double(high) ?? 0 }31    var l: Double { Double(low) ?? 0 }32    var c: Double { Double(close) ?? 0 }33    var up: Bool { c >= o }34}3536@MainActor @Observable37final class FuturesModel {38    @ObservationIgnored let app: AppModel39    @ObservationIgnored private let log = Logger(subsystem: "ai.spboucher.spwallet.ios", category: "futures")40    @ObservationIgnored private let stream: QuoteStream41    @ObservationIgnored private var eventsTask: Task<Void, Never>?42    @ObservationIgnored private var flushTask: Task<Void, Never>?43    @ObservationIgnored private var syncTask: Task<Void, Never>?44    @ObservationIgnored private var pendingQuotes: [String: LiveQuote] = [:]45    @ObservationIgnored private var visibleRows: Set<String> = []46    @ObservationIgnored private var subscribed: Set<StreamChannel> = []47    @ObservationIgnored private var suspended = false48    @ObservationIgnored private let defaults: UserDefaults?4950    // markets51    var venues = Loaded<[DerivVenue]>()52    var instruments = Loaded<[DerivInstrument]>()53    var tickers = Loaded<[DerivTicker]>()54    var readErrors: [DerivVenueReadError] = []55    var marketsLoading = false56    var favourites: Set<String> = [] { didSet { defaults?.set(Array(favourites).sorted(), forKey: "futures-favourites") } }57    var selected: String?5859    // stream60    var streamState: QuoteStreamState = .idle61    var quotes: [String: LiveQuote] = [:]62    var venueStatus: [String: StreamVenueStatus] = [:]63    var streamRefusals: [String: String] = [:]6465    // open market66    var market: DerivMarket?67    var marketError: Error?68    var book: LiveBook?69    /** Why no book is shown (the Core withholds it, the channel was refused, the stream is down). */70    var bookNote: String?71    var trades: [TradePrint] = []72    var candles: [CandleBar] = []73    var candlesError: Error?74    var candleSource: String?75    var interval: DerivCandleInterval = .h176    var funding: DerivFundingHistory?77    var fundingError: Error?7879    // accounts80    var mode: TradingMode = .paper81    var paperAccounts = Loaded<[PaperAccount]>()82    var paperID: PaperAccountID?83    var paperDetail: PaperAccountDetail?84    var paperError: Error?85    var liveConfig: LiveConfig?86    var liveConfigError: Error?87    var jurisdiction: JurisdictionAnswer?88    var liveAccounts: [LiveAccount]?89    var liveError: Error?90    var liveID: LiveAccountID?91    var liveDetail: LiveAccountDetail?92    var liveDetailError: Error?93    /** Offline: the venue state last served for the selected live account, with its date. */94    var liveSnapshot: Cached<LiveVenueState>?95    var accountsLoading = false9697    init(app: AppModel) {98        self.app = app99        stream = QuoteStream(client: app.env.client)100        defaults = app.env.configuration.ephemeral ? nil : .standard101        favourites = Set(defaults?.stringArray(forKey: "futures-favourites") ?? [])102    }103104    var api: DerivativesAPI { DerivativesAPI(app.env.client) }105    var liveAPI: DerivativesLiveAPI { DerivativesLiveAPI(app.env.client) }106    var collateralAPI: DerivativesCollateralAPI { DerivativesCollateralAPI(app.env.client) }107    var cache: AppCache { app.env.cache }108    var canOperate: Bool { app.canOperate }109110    // MARK: derived111112    func instrument(_ id: String?) -> DerivInstrument? { id.flatMap { i in instruments.value?.first { $0.id == i } } }113    func ticker(_ id: String) -> DerivTicker? { tickers.value?.first { $0.instrument == id } }114    func venue(_ id: String) -> DerivVenue? { venues.value?.first { $0.id == id } }115    var selectedInstrument: DerivInstrument? { instrument(selected) ?? market.flatMap { $0.instrument.id == selected ? $0.instrument : nil } }116117    /** Freshness of the stream figure of a market, on this device's clock; `.none` when the stream gave nothing. */118    func freshness(_ id: String, now: Date = Date()) -> StreamFreshness {119        guard let q = quotes[id] else { return .evaluate(freshAt: nil, serverStale: false, staleAfterMs: nil, connection: streamState, now: now) }120        return q.freshness(connection: streamState, now: now, venue: venueStatus[q.venue]?.status)121    }122    /** The stream's figure when there is one, otherwise the REST ticker's. Never a mix presented as live: see `freshness`. */123    func mark(_ id: String) -> String? { quotes[id]?.quote.mark ?? ticker(id)?.mark ?? (market?.ticker.instrument == id ? market?.ticker.mark : nil) }124    func change24h(_ id: String) -> String? { quotes[id]?.quote.change24h ?? ticker(id)?.change24h }125    func fundingRate(_ id: String) -> String? { quotes[id]?.quote.funding ?? ticker(id)?.funding }126    func openInterest(_ id: String) -> String? { quotes[id]?.quote.openInterest ?? ticker(id)?.openInterest }127    func volume24h(_ id: String) -> String? { quotes[id]?.quote.volume24h ?? ticker(id)?.volume24h }128129    var paperAccount: PaperAccount? { paperDetail?.account ?? paperAccounts.value?.first { $0.id == paperID } }130    var liveAccount: LiveAccount? { liveDetail?.account ?? liveAccounts?.first { $0.id == liveID } }131    var accountRef: FuturesAccountRef? {132        switch mode {133        case .paper: paperAccount.map { .paper($0.id) }134        case .live: liveAccount.map { .live($0.id, network: $0.network) }135        }136    }137    func toggleFavourite(_ id: String) { if favourites.contains(id) { favourites.remove(id) } else { favourites.insert(id) } }138139    // MARK: markets140141    func loadMarkets() async {142        guard !marketsLoading else { return }143        marketsLoading = true144        defer { marketsLoading = false }145        if instruments.value == nil { await loadMarketSnapshots() }146        guard !app.offlineBrowsing else { return }147        let api = api, venue = OfferedVenues.listingVenue148        async let v = result { try await api.venues() }149        async let i = result { try await api.instruments(venue: venue, locale: FuturesText.locale) }150        async let t = result { try await api.tickers(venue: venue) }151        let (rv, ri, rt) = await (v, i, t)152        switch rv {153        case .success(let a): venues.set(live: a.venues); await cache.save(a.venues, key: "futures-venues")154        case .failure(let e): fail(&venues, e)155        }156        switch ri {157        case .success(let a):158            let offered = a.instruments.filter { OfferedVenues.offers($0.venue) }159            instruments.set(live: offered); readErrors = (a.errors ?? []).filter { OfferedVenues.offers($0.venue) }160            await cache.save(offered, key: "futures-instruments")161        case .failure(let e): fail(&instruments, e)162        }163        switch rt {164        case .success(let a):165            let offered = a.tickers.filter { OfferedVenues.offers(instrument: $0.instrument) }166            tickers.set(live: offered)167            await cache.save(offered, key: "futures-tickers")168        case .failure(let e): fail(&tickers, e)169        }170    }171172    private func loadMarketSnapshots() async {173        if let c = await cache.load([DerivVenue].self, key: "futures-venues") { venues.set(cached: c) }174        if let c = await cache.load([DerivInstrument].self, key: "futures-instruments") { instruments.set(cached: c) }175        if let c = await cache.load([DerivTicker].self, key: "futures-tickers") { tickers.set(cached: c) }176    }177178    private func result<T: Sendable>(_ call: @escaping @Sendable () async throws -> T) async -> Result<T, Error> {179        do { return .success(try await call()) } catch { return .failure(error) }180    }181    private func fail<T>(_ slot: inout Loaded<T>, _ e: Error) {182        if let a = e as? APIError { slot.fail(a); if a.isOffline { app.offline = true } } else { slot.live = false }183    }184185    // MARK: one market186187    func open(_ id: String) async {188        if selected != id { selected = id; market = nil; book = nil; bookNote = nil; trades = []; candles = []; funding = nil; marketError = nil; candlesError = nil; fundingError = nil }189        scheduleSync()190        guard !app.offlineBrowsing else { return }191        let api = api192        do {193            let m = try await api.market(instrument: id)194            guard selected == id else { return }195            market = m; marketError = nil196            if trades.isEmpty { trades = (m.trades ?? []).map { TradePrint(id: $0.id, price: $0.price, size: $0.size, side: $0.side, at: $0.ts) }.sorted { $0.at > $1.at } }197        } catch { if selected == id { marketError = error } }198        await loadCandles()199        do { let f = try await api.fundingHistory(instrument: id, hours: 72); if selected == id { funding = f; fundingError = nil } } catch { if selected == id { fundingError = error } }200    }201202    func loadCandles() async {203        guard let id = selected, !app.offlineBrowsing else { return }204        let iv = interval205        do {206            let a = try await api.candles(instrument: id, interval: iv, limit: 160)207            guard selected == id, interval == iv else { return }208            candles = a.candles.map { CandleBar(at: $0.ts, open: $0.open, high: $0.high, low: $0.low, close: $0.close, volume: $0.volume) }.sorted { $0.at < $1.at }209            candleSource = a.source; candlesError = nil210        } catch { if selected == id { candlesError = error } }211    }212213    func setInterval(_ i: DerivCandleInterval) async {214        guard i != interval else { return }215        interval = i; candles = []216        scheduleSync()217        await loadCandles()218    }219220    func closeMarket() { selected = nil; market = nil; book = nil; trades = []; candles = []; scheduleSync() }221222    // MARK: stream — only what is visible223224    func rowAppeared(_ id: String) { if visibleRows.insert(id).inserted { scheduleSync() } }225    func rowDisappeared(_ id: String) { if visibleRows.remove(id) != nil { scheduleSync() } }226227    private var desiredChannels: Set<StreamChannel> {228        guard !suspended, app.canOperate else { return [] }229        var d = Set(visibleRows.prefix(60).map { StreamChannel.quote($0) })230        if let s = selected { d.formUnion([.quote(s), .book(s, depth: 20), .trades(s), .candle(s, interval: interval.rawValue)]) }231        return Set(d.filter(\.isValid))232    }233234    private func scheduleSync() {235        syncTask?.cancel()236        syncTask = Task { [weak self] in237            try? await Task.sleep(for: .milliseconds(250))238            guard !Task.isCancelled, let self else { return }239            await self.sync()240        }241    }242243    private func sync() async {244        let want = desiredChannels245        let gone = subscribed.subtracting(want), fresh = want.subtracting(subscribed)246        if !gone.isEmpty {247            await stream.unsubscribe(Array(gone))248            for ch in gone where ch.type == .quote { quotes[ch.id] = nil; pendingQuotes[ch.id] = nil }249        }250        if !fresh.isEmpty {251            startListening()252            do { try await stream.subscribe(Array(fresh)) } catch { log.error("stream subscribe refused") ; return }253        }254        subscribed = want255        if want.isEmpty { await stream.stop(); streamState = .idle }256    }257258    private func startListening() {259        guard eventsTask == nil else { return }260        let stream = stream261        eventsTask = Task { [weak self] in262            for await e in await stream.events() { guard let self else { return }; self.handle(e) }263        }264        flushTask = Task { [weak self] in265            while !Task.isCancelled {266                try? await Task.sleep(for: .milliseconds(500))267                guard let self else { return }268                if !self.pendingQuotes.isEmpty { self.quotes.merge(self.pendingQuotes) { _, new in new }; self.pendingQuotes.removeAll() }269            }270        }271    }272273    private func handle(_ e: QuoteStreamEvent) {274        switch e {275        case .state(let s):276            streamState = s277            if s != .live { book = nil; bookNote = Self.note(for: s) }278        case .quote(let q): if subscribed.contains(.quote(q.id)) { pendingQuotes[q.id] = q }279        case .book(let b):280            guard b.id == selected else { return }281            if b.stale { book = nil; bookNote = String(localized: "Le serveur signale un carnet périmé.") } else { book = b; bookNote = nil }282        case .bookResync(let key):283            if let s = selected, key.hasPrefix("book|\(s)|") { book = nil; bookNote = String(localized: "Carnet incohérent (trou ou somme de contrôle fausse) : en attente d’un nouvel instantané.") }284        case .trades(let id, let fresh, _):285            guard id == selected else { return }286            let seen = Set(trades.map(\.id))287            let rows = fresh.filter { !seen.contains($0.id) }.map { TradePrint(id: $0.id, price: $0.price, size: $0.size, side: $0.side, at: Date(timeIntervalSince1970: TimeInterval($0.ts) / 1000)) }288            trades = Array((rows.reversed() + trades).sorted { $0.at > $1.at }.prefix(40))289        case .candle(let c, _):290            guard c.id == selected, c.interval == interval.rawValue, !candles.isEmpty else { return }291            let bar = CandleBar(at: Date(timeIntervalSince1970: TimeInterval(c.ts) / 1000), open: c.open, high: c.high, low: c.low, close: c.close, volume: c.volume)292            if let last = candles.last, last.at == bar.at { candles[candles.count - 1] = bar } else if let last = candles.last, bar.at > last.at { candles.append(bar) }293        case .venue(let v): venueStatus[v.venue] = v294        case .error(let m):295            if let ch = m.channel, m.isPermanentForChannel {296                streamRefusals[ch.key] = m.code297                if ch.type == "book", ch.id == selected { book = nil; bookNote = String(localized: "Le serveur ne sert pas de carnet pour ce marché (\(m.code)).") }298            }299        case .stale(let keys):300            if let s = selected, keys.contains(where: { $0.hasPrefix("book|\(s)|") }) { book = nil; if bookNote == nil { bookNote = Self.note(for: streamState) } }301        default: break302        }303    }304305    private static func note(for s: QuoteStreamState) -> String {306        switch s {307        case .reconnecting, .connecting: String(localized: "Flux en reconnexion : le carnet n’est plus tenu à jour.")308        case .ended(.unauthorized), .ended(.signedOut): String(localized: "Session terminée : le flux est fermé.")309        case .ended(.refused(let status)): String(localized: "Le serveur a refusé le flux (\(status)).")310        default: String(localized: "Flux arrêté.")311        }312    }313314    /** Background: the socket is closed, what is held turns stale at once. */315    func suspend() { suspended = true; Task { await sync() } }316    /** Back in the foreground: subscribe again, and read the list again (what was held is old). */317    func resume() { guard suspended else { return }; suspended = false; scheduleSync(); Task { await loadMarkets() } }318319    // MARK: paper accounts320321    func loadPaper() async {322        if paperAccounts.value == nil, let c = await cache.load([PaperAccount].self, key: "futures-paper-accounts") { paperAccounts.set(cached: c) }323        guard !app.offlineBrowsing else { if paperID == nil { paperID = paperAccounts.value?.first?.id }; return }324        do {325            let all = try await api.paperAccounts().filter { OfferedVenues.offers($0.venue) }326            paperAccounts.set(live: all); paperError = nil327            await cache.save(all, key: "futures-paper-accounts")328            if paperID == nil || !all.contains(where: { $0.id == paperID }) { paperID = all.first?.id; paperDetail = nil }329            await loadPaperDetail()330        } catch { paperError = error; fail(&paperAccounts, error) }331    }332333    func loadPaperDetail() async {334        guard let id = paperID, !app.offlineBrowsing else { return }335        do { let d = try await api.paperAccount(id); if paperID == id { paperDetail = d; paperError = nil } } catch { paperError = error }336    }337338    func selectPaper(_ id: PaperAccountID) async { paperID = id; paperDetail = nil; await loadPaperDetail() }339340    func adopt(paper d: PaperAccountDetail) {341        paperDetail = d; paperID = d.account.id342        var all = paperAccounts.value ?? []343        if let i = all.firstIndex(where: { $0.id == d.account.id }) { all[i] = d.account } else { all.insert(d.account, at: 0) }344        paperAccounts.set(live: all)345        Task { await cache.save(all, key: "futures-paper-accounts") }346    }347348    // MARK: live accounts349350    func loadLive() async {351        guard !app.offlineBrowsing else {352            if let id = liveID { liveSnapshot = await cache.load(LiveVenueState.self, key: "futures-live-state-\(id.rawValue)") }353            return354        }355        let live = liveAPI356        async let c = result { try await live.config(locale: FuturesText.locale) }357        async let a = result { try await live.accounts() }358        async let j = result { try await live.jurisdiction() }359        let (rc, ra, rj) = await (c, a, j)360        switch rc { case .success(let v): liveConfig = v; liveConfigError = nil; case .failure(let e): liveConfigError = e }361        if case .success(let v) = rj { jurisdiction = v }362        switch ra {363        case .success(let all):364            let offered = all.filter { OfferedVenues.offers($0.venue) }365            liveAccounts = offered; liveError = nil366            if liveID == nil || !offered.contains(where: { $0.id == liveID }) { liveID = offered.first?.id; liveDetail = nil }367            await loadLiveDetail()368        case .failure(let e): liveError = e369        }370    }371372    func loadLiveDetail() async {373        guard let id = liveID, !app.offlineBrowsing else { return }374        do { adopt(live: try await liveAPI.account(id)) } catch { liveDetailError = error }375    }376377    func selectLive(_ id: LiveAccountID) async { liveID = id; liveDetail = nil; liveDetailError = nil; await loadLiveDetail() }378379    /** Every live route that answers the account again goes through here. */380    func adopt(live d: LiveAccountDetail) {381        liveDetail = d; liveID = d.account.id; liveDetailError = nil382        if var all = liveAccounts {383            if let i = all.firstIndex(where: { $0.id == d.account.id }) { all[i] = d.account } else { all.insert(d.account, at: 0) }384            liveAccounts = all385        } else { liveAccounts = [d.account] }386        if d.venueState.error == nil { let s = d.venueState, key = "futures-live-state-\(d.account.id.rawValue)"; Task { await cache.save(s, key: key) } }387    }388389    func loadAccounts() async {390        guard !accountsLoading else { return }391        accountsLoading = true392        defer { accountsLoading = false }393        switch mode { case .paper: await loadPaper(); case .live: await loadLive() }394    }395396    func refreshAll() async {397        await loadMarkets()398        await loadAccounts()399        if let s = selected { await open(s) }400    }401}402
Files main
Menu

Theme