Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Futures/FuturesInstrumentView.swift3// Description: The page of one instrument: live header (mark, index, funding, open interest), candlestick or line chart from the backend's candles (the forming bar follows the quote stream), the order book when the venue serves one (stream first, REST snapshot with its date otherwise; GMX's pool figures instead of a book), recent prints, funding history and the contract's facts — next to the order ticket. Everything here is market data: nothing on this page prepares or sends an order by itself.4import SwiftUI5import Charts6import SPWalletCore78/// One bar for drawing. The Doubles are only pixels: the exact strings stay in the server's answer.9struct FutCandle: Identifiable, Equatable {10 let ts: Date11 let open, high, low, close, volume: Double12 var id: Date { ts }13 init?(_ c: DerivCandle) {14 guard let o = Double(c.open), let h = Double(c.high), let l = Double(c.low), let cl = Double(c.close) else { return nil }15 ts = c.ts; open = o; high = h; low = l; close = cl; volume = Double(c.volume) ?? 016 }17 init?(_ m: StreamCandleMessage) {18 guard let o = Double(m.open), let h = Double(m.high), let l = Double(m.low), let cl = Double(m.close) else { return nil }19 ts = Date(timeIntervalSince1970: TimeInterval(m.ts) / 1000); open = o; high = h; low = l; close = cl; volume = Double(m.volume) ?? 020 }21}2223struct FutInstrumentView: View {24 let model: AppModel25 @Bindable var store: FuturesStore26 let ops: FutLiveOps27 let ticket: FutTicketFlow28 let go: (FuturesView.Tab) -> Void2930 @State private var market = FutLoaded<DerivMarket>()31 @State private var candles = FutLoaded<[FutCandle]>()32 @State private var candleSource: String?33 @State private var funding = FutLoaded<DerivFundingHistory>()34 @State private var lineChart = false3536 var body: some View {37 if let id = store.instrumentId {38 HStack(alignment: .top, spacing: 16) {39 VStack(alignment: .leading, spacing: 16) {40 header(id)41 chartCard42 HStack(alignment: .top, spacing: 16) { bookCard(id); tradesCard }43 fundingCard44 factsCard45 }.frame(maxWidth: .infinity, alignment: .leading)46 FutTicketView(model: model, store: store, ops: ops, flow: ticket, go: go).frame(width: 400)47 }48 .futPolling(every: 45, id: id) { await loadMarket(id) }49 .task(id: id) { await loadFunding(id) }50 .futPolling(every: 120, id: "\(id)|\(store.chartInterval.rawValue)") { await loadCandles(id) }51 .onChange(of: store.lastCandle) { _, m in merge(m) }52 } else {53 EmptyState(symbol: "chart.xyaxis.line", title: "Aucun instrument sélectionné", detail: "Choisissez un instrument dans l’onglet Marchés.")54 Button("Voir les marchés") { go(.markets) }55 }56 }5758 // MARK: loading5960 private func loadMarket(_ id: String) async {61 do { let m = try await store.deriv.market(instrument: id); if id == store.instrumentId { market.set(m) } }62 catch { if id == store.instrumentId { market.fail(model.describe(error)) } }63 }64 private func loadCandles(_ id: String) async {65 let interval = store.chartInterval66 candles.loading = true67 do {68 let a = try await store.deriv.candles(instrument: id, interval: interval, limit: 240)69 guard id == store.instrumentId, interval == store.chartInterval else { return }70 candles.set(a.candles.compactMap(FutCandle.init).sorted { $0.ts < $1.ts }); candleSource = a.source71 } catch { if id == store.instrumentId { candles.fail(model.describe(error)) } }72 }73 private func loadFunding(_ id: String) async {74 funding = FutLoaded()75 do { let f = try await store.deriv.fundingHistory(instrument: id, hours: 168); if id == store.instrumentId { funding.set(f) } }76 catch { if id == store.instrumentId { funding.fail(model.describe(error)) } }77 }78 /// The forming bar of the stream replaces or follows the last bar read from the backend.79 private func merge(_ m: StreamCandleMessage?) {80 guard let m, m.id == store.instrumentId, m.interval == store.chartInterval.rawValue, let c = FutCandle(m), var list = candles.value, let last = list.last else { return }81 if c.ts == last.ts { list[list.count - 1] = c } else if c.ts > last.ts { list.append(c); if list.count > 400 { list.removeFirst(list.count - 400) } } else { return }82 candles.value = list83 }8485 // MARK: header8687 private var ticker: DerivTicker? { market.value?.ticker.instrument == store.instrumentId ? market.value?.ticker : store.instrumentId.flatMap { store.tickers[$0] } }88 private var liveQuote: StreamQuoteMessage? { store.instrumentId.flatMap { store.quotes[$0]?.quote } }8990 @ViewBuilder private func header(_ id: String) -> some View {91 let p = store.price(id), inst = store.instrument ?? market.value?.instrument, q = liveQuote, t = ticker92 Card {93 HStack(alignment: .firstTextBaseline, spacing: 10) {94 AssetBadge(symbol: inst?.base ?? id)95 Text(inst?.symbol ?? id).font(.title2.weight(.semibold))96 Text(store.venueInfo(inst?.venue ?? "")?.name ?? (inst?.venue ?? "")).foregroundStyle(.secondary)97 if let s = inst?.status, s != "active" { Text(s == "reduce_only" ? "Réduction seule" : s == "halted" ? "Suspendu" : s).font(.caption.weight(.medium)).foregroundStyle(Theme.warning) }98 Spacer()99 FutFreshnessDot(freshness: p.freshness, snapshotAt: p.snapshotAt)100 Text(p.freshness.map { Self.freshText($0) } ?? (p.snapshotAt.map { "Instantané \(Fmt.relative($0))" } ?? "Aucune donnée")).font(.caption).foregroundStyle(.secondary)101 }102 if let e = market.error { Banner(.warning, "Lecture du marché en échec : \(e)" + (market.at.map { " — données du \(Fmt.dateSeconds($0))" } ?? "")) }103 FutStatGrid(minimum: 135) {104 FutStat("Prix (mark)", p.mark.map { FutNum.exact($0) })105 FutStat("Indice / oracle", FutNum.exact(q?.index ?? t?.index))106 FutStat("Milieu du carnet", FutNum.exact(q?.mid ?? t?.mid))107 FutStat("Variation 24 h", FutNum.pct(fraction: q?.change24h ?? t?.change24h), color: Theme.change(FutNum.d(q?.change24h ?? t?.change24h)))108 FutStat("Volume 24 h", FutNum.compactUSD(q?.volume24h ?? t?.volume24h))109 FutStat("Intérêt ouvert", FutNum.compact(q?.openInterest ?? t?.openInterest) + " " + (inst?.base ?? ""))110 FutStat("Financement", (q?.funding ?? t?.funding) == nil ? "—" : FutNum.pct(fraction: q?.funding ?? t?.funding, digits: 4), note: inst.map { "par intervalle de \(FutMarketsView.interval($0.fundingIntervalSec))" })111 FutStat("Prochain financement", t?.nextFundingTs.map { Fmt.relative($0) } ?? "—")112 }113 }114 }115 static func freshText(_ f: StreamFreshness) -> String {116 switch f.state {117 case .live: "En direct"118 case .delayed: "Retardé" + (f.ageMs.map { " de \($0 / 1000) s" } ?? "")119 case .stale: "PÉRIMÉ" + (f.ageMs.map { " (\($0 / 1000) s)" } ?? "")120 case .reconnecting: "Flux en reconnexion — prix non maintenu"121 case .none: "Aucune donnée en direct"122 }123 }124125 // MARK: chart126127 private var chartCard: some View {128 Card("Graphique", trailing: AnyView(HStack(spacing: 10) {129 Picker("Intervalle", selection: $store.chartInterval) { ForEach(DerivCandleInterval.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).labelsHidden().frame(width: 280)130 Picker("Style", selection: $lineChart) { Image(systemName: "chart.bar.fill").tag(false).accessibilityLabel("Chandeliers"); Image(systemName: "chart.xyaxis.line").tag(true).accessibilityLabel("Ligne") }.pickerStyle(.segmented).labelsHidden().frame(width: 90)131 })) {132 if let list = candles.value, !list.isEmpty {133 let lo = list.map(\.low).min() ?? 0, hi = list.map(\.high).max() ?? 1, pad = max((hi - lo) * 0.04, hi * 0.0005)134 let width = max(1.5, min(9, 620 / CGFloat(list.count)))135 Chart(list) { c in136 if lineChart {137 LineMark(x: .value("Heure", c.ts), y: .value("Clôture", c.close)).foregroundStyle(Theme.accent).interpolationMethod(.linear)138 } else {139 let up = c.close >= c.open140 RuleMark(x: .value("Heure", c.ts), yStart: .value("Bas", c.low), yEnd: .value("Haut", c.high)).foregroundStyle(up ? Theme.positive : Theme.negative).lineStyle(StrokeStyle(lineWidth: 1))141 RectangleMark(x: .value("Heure", c.ts), yStart: .value("Ouverture", c.open), yEnd: .value("Clôture", c.close == c.open ? c.close + pad * 0.02 : c.close), width: .fixed(width)).foregroundStyle(up ? Theme.positive : Theme.negative)142 }143 }144 .chartYScale(domain: (lo - pad)...(hi + pad))145 .chartYAxis { AxisMarks(position: .trailing) }146 .frame(height: 320)147 .accessibilityLabel("Graphique des prix, intervalle \(store.chartInterval.rawValue)")148 if let last = list.last {149 Text("Dernière barre \(Fmt.date(last.ts)) — O \(last.open.formatted()) · H \(last.high.formatted()) · B \(last.low.formatted()) · C \(last.close.formatted())" + (candleSource.map { " · source : \($0)" } ?? "")).font(.caption).foregroundStyle(.secondary).monospacedDigit()150 }151 if let e = candles.error { Text("Dernière actualisation en échec : \(e)").font(.caption).foregroundStyle(Theme.warning) }152 } else if let e = candles.error {153 Banner(.warning, "Chandeliers indisponibles : \(e)")154 } else if candles.loading || candles.value == nil {155 ProgressView().frame(maxWidth: .infinity, minHeight: 120)156 } else {157 EmptyState(symbol: "chart.bar.xaxis", title: "Aucune barre pour cet intervalle")158 }159 }160 }161162 // MARK: book and trades163164 private struct Level: Identifiable { let id: String; let price: String; let size: String; let sizeValue: Double }165166 @ViewBuilder private func bookCard(_ id: String) -> some View {167 let liveBook = store.book.flatMap { $0.id == id ? $0 : nil }168 let rest = market.value?.book169 Card("Carnet d’ordres", trailing: AnyView(Group {170 if let b = liveBook { let f = store.bookFreshness(b); HStack(spacing: 6) { FutFreshnessDot(freshness: f); Text(Self.freshText(f)).font(.caption).foregroundStyle(.secondary) } }171 else if let r = rest { ProvenanceTag(p: .stale, text: "Instantané \(Fmt.relative(r.ts))") }172 })) {173 if let b = liveBook {174 book(asks: b.asks.map { ($0.price, $0.size) }, bids: b.bids.map { ($0.price, $0.size) })175 } else if let r = rest {176 book(asks: r.asks.map { ($0.price, $0.size) }, bids: r.bids.map { ($0.price, $0.size) })177 if let why = store.refusal(of: .book(id, depth: 20)) { Text("Carnet en direct refusé par le flux : \(why)").font(.caption).foregroundStyle(.secondary) }178 } else if let l = market.value?.liquidity {179 Text("Cette plateforme n’a pas de carnet : la liquidité vient d’un pool.").font(.callout).foregroundStyle(.secondary)180 FutStatGrid(minimum: 150) {181 FutStat("Liquidité disponible (long)", FutNum.compactUSD(l.availableLiquidityLongUsd))182 FutStat("Liquidité disponible (short)", FutNum.compactUSD(l.availableLiquidityShortUsd))183 FutStat("Intérêt ouvert long", FutNum.compactUSD(l.openInterestLongUsd))184 FutStat("Intérêt ouvert short", FutNum.compactUSD(l.openInterestShortUsd))185 FutStat("Taux net long / h", FutNum.pct(fraction: l.netRateLongPerHour, digits: 4), note: "positif : le côté reçoit")186 FutStat("Taux net short / h", FutNum.pct(fraction: l.netRateShortPerHour, digits: 4), note: "positif : le côté reçoit")187 FutStat("Oracle min / max", "\(FutNum.exact(l.oracleMin)) / \(FutNum.exact(l.oracleMax))")188 }189 } else if let why = market.value?.errors?["book"] ?? market.value?.errors?["liquidity"] {190 Banner(.warning, "Carnet indisponible : \(why)")191 } else if store.venueInfo(String(id.prefix { $0 != ":" }))?.orderBook == false {192 Text("Le serveur ne sert pas de carnet pour cette plateforme.").foregroundStyle(.secondary)193 } else if market.value == nil, market.error == nil {194 ProgressView().frame(maxWidth: .infinity, minHeight: 80)195 } else {196 Label("Carnet indisponible", systemImage: "xmark.octagon").foregroundStyle(Theme.negative)197 }198 }199 }200201 @ViewBuilder private func book(asks: [(String, String)], bids: [(String, String)]) -> some View {202 let depth = 12203 let a = asks.prefix(depth).map { Level(id: "a" + $0.0, price: $0.0, size: $0.1, sizeValue: Double($0.1) ?? 0) }204 let b = bids.prefix(depth).map { Level(id: "b" + $0.0, price: $0.0, size: $0.1, sizeValue: Double($0.1) ?? 0) }205 let maxSize = max((a + b).map(\.sizeValue).max() ?? 0, .leastNonzeroMagnitude)206 VStack(spacing: 1) {207 HStack { Text("Prix").frame(maxWidth: .infinity, alignment: .leading); Text("Taille").frame(maxWidth: .infinity, alignment: .trailing) }.font(.caption).foregroundStyle(.secondary)208 ForEach(a.reversed()) { l in levelRow(l, color: Theme.negative, maxSize: maxSize) }209 if let ba = a.first, let bb = b.first, let x = Double(ba.price), let y = Double(bb.price), y > 0 {210 Text("Écart ≈ \(((x - y) / ((x + y) / 2) * 10_000).formatted(.number.precision(.fractionLength(1)))) pb").font(.caption).foregroundStyle(.secondary).padding(.vertical, 3)211 }212 ForEach(b) { l in levelRow(l, color: Theme.positive, maxSize: maxSize) }213 }214 .accessibilityElement(children: .contain).accessibilityLabel("Carnet d’ordres, \(a.count) ventes et \(b.count) achats")215 }216 private func levelRow(_ l: Level, color: Color, maxSize: Double) -> some View {217 HStack {218 Text(FutNum.exact(l.price)).foregroundStyle(color).frame(maxWidth: .infinity, alignment: .leading)219 Text(FutNum.exact(l.size)).frame(maxWidth: .infinity, alignment: .trailing)220 }221 .font(Theme.monoSmall).padding(.horizontal, 4).padding(.vertical, 1)222 .background(alignment: .trailing) { GeometryReader { g in Rectangle().fill(color.opacity(0.12)).frame(width: g.size.width * CGFloat(min(1, l.sizeValue / maxSize))).frame(maxWidth: .infinity, alignment: .trailing) } }223 }224225 private var tradesCard: some View {226 Card("Dernières transactions") {227 if !store.trades.isEmpty {228 ForEach(store.trades.prefix(18)) { t in229 HStack {230 Text(FutNum.exact(t.price)).foregroundStyle(t.side == "buy" ? Theme.positive : Theme.negative).frame(maxWidth: .infinity, alignment: .leading)231 Text(FutNum.exact(t.size)).frame(maxWidth: .infinity, alignment: .trailing)232 Text(Date(timeIntervalSince1970: TimeInterval(t.ts) / 1000).formatted(date: .omitted, time: .standard)).foregroundStyle(.secondary).frame(width: 78, alignment: .trailing)233 }.font(Theme.monoSmall)234 }235 } else if let list = market.value?.trades, !list.isEmpty {236 ForEach(list.prefix(18), id: \.id) { t in237 HStack {238 Text(FutNum.exact(t.price)).foregroundStyle(t.side == "buy" ? Theme.positive : Theme.negative).frame(maxWidth: .infinity, alignment: .leading)239 Text(FutNum.exact(t.size)).frame(maxWidth: .infinity, alignment: .trailing)240 Text(t.ts.formatted(date: .omitted, time: .standard)).foregroundStyle(.secondary).frame(width: 78, alignment: .trailing)241 }.font(Theme.monoSmall)242 }243 Text("Instantané du \(Fmt.dateSeconds(market.at))").font(.caption).foregroundStyle(.secondary)244 } else if let why = market.value?.errors?["trades"] {245 Text("Indisponible : \(why)").foregroundStyle(.secondary)246 } else {247 Text("Aucune transaction reçue.").foregroundStyle(.secondary)248 }249 }250 }251252 // MARK: funding and facts253254 private var fundingCard: some View {255 Card("Financement — 7 derniers jours") {256 if let f = funding.value, !f.history.isEmpty {257 let pts = f.history.compactMap { r in Double(r.rate).map { (r.ts, $0 * 100) } }258 Chart(pts, id: \.0) { p in259 BarMark(x: .value("Heure", p.0), y: .value("Taux (%)", p.1)).foregroundStyle(p.1 >= 0 ? Theme.negative.opacity(0.75) : Theme.positive.opacity(0.75))260 }.frame(height: 130).chartYAxis { AxisMarks(position: .trailing) }261 .accessibilityLabel("Historique des taux de financement appliqués")262 let mean = pts.isEmpty ? nil : pts.map(\.1).reduce(0, +) / Double(pts.count)263 Text("Taux appliqués par la plateforme, par intervalle de \(FutMarketsView.interval(f.intervalSec)) (positif : les positions longues paient les courtes). Moyenne de la période : \(mean.map { ($0 >= 0 ? "+" : "−") + abs($0).formatted(.number.precision(.fractionLength(4))) + " %" } ?? "—") — \(pts.count) observations" + (f.source.map { " · source : \($0)" } ?? "") + ". Un taux passé ne dit rien du taux futur.")264 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)265 } else if let e = funding.error {266 Banner(.warning, "Historique de financement indisponible : \(e)")267 } else if funding.value != nil {268 Text("La plateforme n’a publié aucun taux sur la période.").foregroundStyle(.secondary)269 } else { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }270 }271 }272273 @ViewBuilder private var factsCard: some View {274 if let i = store.instrument ?? market.value?.instrument {275 Card("Caractéristiques du contrat") {276 Field(label: "Identifiant", value: i.id, mono: true)277 Field(label: "Type", value: "\(i.kind) · \(i.base)/\(i.quote)" + (i.category.map { " · \($0)" } ?? ""))278 Field(label: "Collatéral / règlement", value: "\(i.collateral) / \(i.settlement)")279 Field(label: "Pas de prix", value: FutNum.exact(i.tickSize))280 Field(label: "Pas de taille", value: "\(FutNum.exact(i.lotSize)) \(i.base)")281 Field(label: "Taille minimale", value: i.minOrderSize.map { "\(FutNum.exact($0)) \(i.base)" } ?? "non publiée")282 Field(label: "Notionnel minimal", value: i.minNotional.map { FutNum.usd($0) } ?? "non publié")283 Field(label: "Levier maximal (plateforme)", value: "\(FutNum.exact(i.maxLeverage))× — une limite, jamais une valeur par défaut")284 Field(label: "Modes de marge", value: i.marginModes.joined(separator: ", "))285 Field(label: "Intervalle de financement", value: FutMarketsView.interval(i.fundingIntervalSec))286 Field(label: "Prix de référence (mark)", value: i.markPriceMethod)287 Field(label: "État", value: i.status)288 if let notes = store.venueInfo(i.venue)?.capabilities?.notes, !notes.isEmpty { Field(label: "Notes de la plateforme", value: notes.joined(separator: "\n")) }289 }290 }291 }292}293