Repository Public
1// SP Wallet iOS2// File: Features/DeFi/MarketUnderlyingView.swift3// Description: One underlying: the chart of the consolidated bars (interval picker, the consolidation rule and the source of the4// bars as served), every market of it venue by venue with price, funding and freshness, and the venue comparator —5// an ESTIMATE for a hypothetical position the owner types (side, notional, leverage, horizon; nothing preset), with6// the server's disclaimer verbatim. A simulation and a comparison, never an execution: trading starts in Échanger or7// Contrats à terme.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import SwiftUI12import Charts13import SPWalletCore1415struct MarketUnderlyingView: View {16 @Environment(AppModel.self) private var model17 @Environment(Router.self) private var router18 let symbol: String19 let live: MarketsLive20 var focus: HubRow?2122 @State private var detail = Loaded<HubUnderlyingDetail>()23 @State private var fetchedAt = Date()24 @State private var status = Loaded<MarketDataStatus>()25 @State private var interval: String?26 @State private var candles = Loaded<MarketCandles>()27 @State private var candlesProblem: String?28 @State private var selected: MarketBar?29 @State private var draft = CompareDraft()30 @State private var comparison: VenueComparison?31 @State private var comparing = false32 @State private var compareError: Error?3334 var body: some View {35 ScrollView {36 VStack(alignment: .leading, spacing: Theme.Space.section) {37 FreshnessBanner()38 header39 chartCard40 venuesCard41 compareCard42 actionsCard43 }44 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)45 .frame(maxWidth: 900).frame(maxWidth: .infinity)46 }47 .spPage()48 .navigationTitle(symbol).navigationBarTitleDisplayMode(.inline)49 .onAppear { live.attach(model.env.client) }50 .task { await load() }51 .task(id: interval) { await loadCandles() }52 .refreshable { await load(); await loadCandles() }53 }5455 private var rows: [HubRow] { (detail.value?.spot ?? []) + (detail.value?.instruments ?? []) }56 private func display(_ r: HubRow) -> MarketQuoteDisplay { MarketQuoteDisplay.resolve(row: r, fetchedAt: fetchedAt, live: detail.live ? live.live(r.id) : nil, now: live.now) }5758 private func load() async {59 detail = await SnapshotRead.read(HubUnderlyingDetail.self, path: "/markets-hub/underlyings/\(APIClient.segment(symbol))", key: "markets-underlying-\(symbol)", app: model, current: detail)60 fetchedAt = detail.savedAt ?? Date()61 status = await SnapshotRead.read(MarketDataStatus.self, path: "/market-data/status", key: "markets-data-status", app: model, current: status)62 if interval == nil, let s = status.value, s.symbols.contains(where: { $0.uppercased() == symbol.uppercased() }) {63 // the first interval the server lists that is at least hourly, else its first: a display choice, not a market figure64 interval = s.intervals.first { $0 == "1h" } ?? s.intervals.first65 }66 }6768 private func loadCandles() async {69 guard let interval else { return }70 candlesProblem = nil71 var slot = Loaded<MarketCandles>()72 slot = await SnapshotRead.read(MarketCandles.self, path: "/market-data/candles", query: ["symbol": symbol, "interval": interval, "limit": "300"], key: "markets-candles-\(symbol)-\(interval)", app: model, current: slot)73 if let c = slot.value, c.symbol.uppercased() != symbol.uppercased() || c.interval != interval {74 // the answer is for another series: refused, never drawn under this title75 slot = Loaded<MarketCandles>(); candlesProblem = String(localized: "Le serveur a répondu pour une autre série : rien n’est affiché.")76 }77 candles = slot; selected = nil78 }7980 // MARK: header8182 private var header: some View {83 let main = focus.flatMap { f in rows.first { $0.id == f.id } } ?? focus ?? rows.first84 return HStack(spacing: 14) {85 AssetIcon(symbol: symbol, size: 52)86 VStack(alignment: .leading, spacing: 3) {87 HStack(spacing: 6) {88 Text(symbol).font(.spHeadline).foregroundStyle(Theme.ink)89 if let c = MarketWords.category(detail.value?.category ?? focus?.category) { Pill(text: c) }90 }91 if let r = main {92 let d = display(r)93 Text(Fmt.price(d.price) ?? String(localized: "prix indisponible")).font(.system(size: 30, weight: .semibold)).tracking(-0.6).monospacedDigit()94 .foregroundStyle(d.mark.isLive || d.price == nil ? Theme.ink : Theme.mute).accessibilityIdentifier("market.price")95 Label(d.mark.label + " · " + (r.venueName ?? r.venue) + (MarketQuoteDisplay.priceKindLabel(d.priceKind).map { " · \($0)" } ?? ""), systemImage: d.mark.icon)96 .font(.spFootnote.weight(.semibold)).foregroundStyle(d.mark.tone.color).accessibilityIdentifier("market.mark")97 if let c = Fmt.fractionChange(d.change24h) { Text(c.text + " · 24 h").font(.spCallout.weight(.semibold)).foregroundStyle(c.up ? Theme.emerald : Theme.danger) }98 }99 }100 Spacer()101 }102 }103104 // MARK: chart105106 private var chartCard: some View {107 VStack(alignment: .leading, spacing: 12) {108 SectionHeader(title: String(localized: "Historique consolidé"))109 if let c = candles.value {110 let bars = MarketBar.parse(c.bars)111 if bars.count > 1 {112 let lo = bars.map(\.low).min() ?? 0, hi = bars.map(\.high).max() ?? 1113 let up = (bars.last?.close ?? 0) >= (bars.first?.close ?? 0)114 if let s = selected {115 Text(Money.price(s.close, .usd) + " · " + s.date.formatted(date: .abbreviated, time: .shortened) + (s.source.map { " · \($0)" } ?? "")).font(.spFootnote.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink)116 }117 Chart(bars) { b in118 LineMark(x: .value("t", b.date), y: .value("p", b.close)).foregroundStyle(up ? Theme.emerald : Theme.danger).interpolationMethod(.monotone)119 if let s = selected, s.ts == b.ts { RuleMark(x: .value("t", s.date)).foregroundStyle(Theme.mute.opacity(0.5)); PointMark(x: .value("t", s.date), y: .value("p", s.close)).foregroundStyle(Theme.ink) }120 }121 .chartYScale(domain: (lo - (hi - lo) * 0.05)...(hi + (hi - lo) * 0.05 + .leastNonzeroMagnitude))122 .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { _ in AxisValueLabel().font(.system(size: 11)) } }123 .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.hairline); AxisValueLabel().font(.system(size: 11)) } }124 .chartOverlay { proxy in125 GeometryReader { geo in126 Rectangle().fill(.clear).contentShape(Rectangle())127 .gesture(DragGesture(minimumDistance: 0).onChanged { v in128 guard let plot = proxy.plotFrame else { return }129 let x = v.location.x - geo[plot].origin.x130 if let d: Date = proxy.value(atX: x) { selected = bars.min { abs($0.date.timeIntervalSince(d)) < abs($1.date.timeIntervalSince(d)) } }131 }.onEnded { _ in selected = nil })132 }133 }134 .frame(height: 210)135 .accessibilityLabel(String(localized: "Graphique des clôtures de \(symbol), intervalle \(c.interval)"))136 .accessibilityIdentifier("market.chart")137 } else { EmptyState(icon: "chart.xyaxis.line", title: String(localized: "Pas assez de barres pour tracer un graphique")) }138 if !candles.live { Label(String(localized: "Instantané du \(candles.savedAt?.formatted(date: .abbreviated, time: .shortened) ?? "—")"), systemImage: "clock.badge.exclamationmark").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn) }139 Text(String(localized: "Clôtures des barres consolidées, en USD. Règle du serveur : « \(c.rule) ». Sources, par priorité : \((c.priority ?? []).joined(separator: ", ")). Dernière barre : \(bars.last.map { $0.date.formatted(date: .abbreviated, time: .shortened) } ?? "—"). Ce ne sont pas des prix d’exécution."))140 .font(.system(size: 12)).foregroundStyle(Theme.mute)141 } else if let p = candlesProblem { Notice(tone: .danger, title: p) }142 else if let e = candles.error { ErrorNotice(error: e) }143 else if interval != nil { ProgressView().frame(maxWidth: .infinity, minHeight: 120) }144 else if let s = status.value {145 EmptyState(icon: "chart.xyaxis.line", title: String(localized: "Pas de série consolidée pour \(symbol)"), message: String(localized: "Le serveur consolide des barres pour \(s.symbols.count) actifs ; celui-ci n’en fait pas partie."))146 .accessibilityIdentifier("market.chart.none")147 } else if let e = status.error { ErrorNotice(error: e) }148 else { ProgressView().frame(maxWidth: .infinity, minHeight: 120) }149 if let s = status.value, interval != nil {150 Picker(String(localized: "Intervalle"), selection: Binding(get: { interval ?? "" }, set: { interval = $0 })) {151 ForEach(s.intervals, id: \.self) { Text($0).tag($0) }152 }.pickerStyle(.segmented).accessibilityIdentifier("market.interval")153 }154 }.spCard()155 }156157 // MARK: venues158159 private var venuesCard: some View {160 VStack(alignment: .leading, spacing: 4) {161 SectionHeader(title: String(localized: "Marchés de \(symbol), plateforme par plateforme"))162 if let d = detail.value {163 if !detail.live { Label(String(localized: "Instantané du \(detail.savedAt?.formatted(date: .abbreviated, time: .shortened) ?? "—")"), systemImage: "clock.badge.exclamationmark").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn) }164 if !d.errors.isEmpty { Notice(tone: .warn, title: String(localized: "Liste partielle"), message: d.errors.map { "\($0.source) : \($0.message)" }.joined(separator: " · ")) }165 if rows.isEmpty { Text(String(localized: "Aucun marché listé pour cet actif.")).font(.spCallout).foregroundStyle(Theme.mute) }166 ForEach(rows) { r in167 venueRow(r).onAppear { live.appeared(r.id) }.onDisappear { live.disappeared(r.id) }168 if r.id != rows.last?.id { Divider() }169 }170 if !d.notCompared.isEmpty {171 Text(String(localized: "Mêmes lettres, autre sous-jacent : affichés, jamais comparés")).spEyebrow().padding(.top, 10)172 ForEach(d.notCompared) { r in173 FieldRow(label: (r.venueName ?? r.venue) + " · " + r.symbol, value: (Fmt.price(r.price) ?? String(localized: "indisponible")) + (r.mapping?.unmapped.map { " · \($0)" } ?? "") + (r.mapping?.note.map { " · \($0)" } ?? ""))174 }175 }176 } else if let e = detail.error { ErrorNotice(error: e) { Task { await load() } } }177 else { ProgressView().frame(maxWidth: .infinity, minHeight: 80) }178 }.spCard()179 }180181 private func venueRow(_ r: HubRow) -> some View {182 let d = display(r)183 return VStack(alignment: .leading, spacing: 5) {184 HStack(alignment: .firstTextBaseline) {185 Text((r.venueName ?? r.venue) + " · " + MarketWords.kind(r.kind)).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)186 Spacer()187 Text(Fmt.price(d.price) ?? String(localized: "indisponible")).font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundStyle(d.mark.isLive || d.price == nil ? Theme.ink : Theme.mute)188 }189 HStack(spacing: 6) {190 Text(r.id).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute)191 Spacer()192 Label(d.mark.label, systemImage: d.mark.icon).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(d.mark.tone.color)193 }194 Text([String(localized: "source : \(d.source)"), MarketQuoteDisplay.priceKindLabel(d.priceKind),195 r.funding.flatMap { f in Fmt.ratePercent(d.funding ?? f.rate).map { String(localized: "financement \($0) / \(f.intervalSec / 3600) h (annualisé \(Fmt.ratePercent(f.annualised, digits: 2) ?? "—"))") } },196 Fmt.usdCompact(r.volume24hUsd).map { String(localized: "volume 24 h \($0)") }, Fmt.usdCompact(r.openInterestUsd).map { String(localized: "intérêt ouvert \($0)") },197 r.maxLeverage.map { String(localized: "levier max. de la plateforme \($0) ×") }].compactMap { $0 }.joined(separator: " · "))198 .font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)199 if r.priceOutlier == true { Label(String(localized: "Prix très éloigné des autres plateformes"), systemImage: "exclamationmark.triangle.fill").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.warn) }200 if !r.tradable { Label(MarketWords.tradableReason(r.tradableReason), systemImage: "eye").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.mute) }201 else if r.paper == true, r.kind == "perp" { Text(String(localized: "Négociable en PAPIER ; en RÉEL selon les verrous du serveur.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }202 if let x = r.restriction { Text(x).font(.system(size: 12)).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true) }203 }204 .padding(.vertical, 8)205 .accessibilityElement(children: .combine)206 .accessibilityIdentifier("market.venue.\(r.venue)")207 }208209 // MARK: comparator210211 private var compareCard: some View {212 VStack(alignment: .leading, spacing: 10) {213 SectionHeader(title: String(localized: "Comparateur de plateformes"))214 Notice(tone: .info, title: String(localized: "Simulation et comparaison, pas une exécution"),215 message: String(localized: "Coût estimé d’UNE position hypothétique que tu décris, à partir d’un instantané des données publiques. Rien n’est préparé, rien n’est signé."), icon: "function")216 Picker(String(localized: "Sens"), selection: Binding(get: { draft.side ?? "" }, set: { draft.side = $0.isEmpty ? nil : $0 })) {217 Text(String(localized: "Sens ?")).tag(""); Text("Long").tag("long"); Text("Short").tag("short")218 }.pickerStyle(.segmented).accessibilityIdentifier("compare.side")219 HStack(spacing: 8) {220 input(String(localized: "Notionnel USD"), $draft.notional, "compare.notional")221 input(String(localized: "Levier ×"), $draft.leverage, "compare.leverage")222 input(String(localized: "Horizon h"), $draft.horizonHours, "compare.horizon")223 }224 let problems = draft.problems()225 if !problems.isEmpty { Text(String(localized: "À saisir : \(problems.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute) }226 Button { Task { await compare() } } label: { HStack { if comparing { ProgressView() }; Text(String(localized: "Estimer sur chaque plateforme")) } }227 .buttonStyle(.spSecondary).disabled(!problems.isEmpty || comparing || model.offlineBrowsing).accessibilityIdentifier("compare.run")228 if let e = compareError { ErrorNotice(error: e).accessibilityIdentifier("compare.error") }229 if let c = comparison { comparisonResult(c) }230 }.spCard()231 }232233 private func input(_ placeholder: String, _ text: Binding<String>, _ id: String) -> some View {234 TextField(placeholder, text: text).keyboardType(.decimalPad).font(.spBody).monospacedDigit()235 .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier(id)236 }237238 private func compare() async {239 guard let q = draft.query(underlying: symbol) else { return }240 comparing = true; compareError = nil; defer { comparing = false }241 do { comparison = try await MarketsAPI(model.env.client).compare(q) } catch { compareError = error; comparison = nil }242 }243244 private func figure(_ f: CostFigure?, unit: String = "") -> String {245 guard let f else { return String(localized: "non fourni") }246 if let v = f.value { return Money.brief(v, maxFraction: 4) + unit }247 return String(localized: "indisponible") + (f.reason.map { " (\($0))" } ?? "")248 }249250 @ViewBuilder private func comparisonResult(_ c: VenueComparison) -> some View {251 Text(c.texts.disclaimer).font(.spFootnote.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("compare.disclaimer")252 Text(String(localized: "Demande comprise par le serveur : \(JSONFields.text(c.request["side"] ?? .null)) · notionnel \(JSONFields.text(c.request["notional"] ?? .null)) USD · levier \(JSONFields.text(c.request["leverage"] ?? .null)) × · horizon \(JSONFields.text(c.request["horizonHours"] ?? .null)) h · lu \(Fmt.date(ms: c.ts) ?? "—")"))253 .font(.system(size: 12)).foregroundStyle(Theme.mute)254 ForEach(c.warnings, id: \.self) { w in Notice(tone: .warn, title: w) }255 if !c.errors.isEmpty { Notice(tone: .warn, title: String(localized: "Comparaison partielle"), message: c.errors.map { "\($0.source) : \($0.message)" }.joined(separator: " · ")) }256 ForEach(Array(c.rows.enumerated()), id: \.offset) { _, r in257 VStack(alignment: .leading, spacing: 0) {258 HStack {259 Text(r.venueName ?? r.venue).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)260 Spacer()261 if r.stale { Pill(text: String(localized: "périmé"), tone: .danger, icon: "clock.badge.exclamationmark") }262 if !r.tradable { Pill(text: String(localized: "consultation"), tone: .neutral, icon: "eye") }263 }264 Text(r.instrument + (Fmt.age(ms: r.ageMs).map { " · " + String(localized: "données vieilles de \($0)") } ?? "")).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).padding(.bottom, 4)265 if let e = r.error { Notice(tone: .warn, title: String(localized: "Plateforme illisible"), message: e) }266 else {267 FieldRow(label: String(localized: "Prix : marque · indice · milieu"), value: [r.price?.mark, r.price?.index, r.price?.mid].map { $0.map { Money.brief($0, maxFraction: 4) } ?? "—" }.joined(separator: " · "))268 Divider(); FieldRow(label: String(localized: "Écart acheteur-vendeur"), value: figure(r.cost?.spreadBps, unit: " pb"))269 Divider(); FieldRow(label: String(localized: "Financement"), value: r.funding.map { (Fmt.ratePercent($0.perHour, digits: 5) ?? "—") + " / h" + ($0.assumption.map { " — \($0)" } ?? "") } ?? String(localized: "non servi"))270 Divider(); FieldRow(label: String(localized: "Frais : preneur · teneur"), value: r.fees.map { "\(Fmt.ratePercent($0.takerRate, digits: 3) ?? "—") · \(Fmt.ratePercent($0.makerRate, digits: 3) ?? "—")\n\($0.source)\n" + String(localized: "barème lu le \($0.asOf)") } ?? String(localized: "non servis"))271 if let cost = r.cost {272 Divider(); FieldRow(label: String(localized: "Glissement d’entrée · de sortie (USD, estimé)"), value: figure(cost.entrySlippageUsd) + " · " + figure(cost.exitSlippageUsd))273 Divider(); FieldRow(label: String(localized: "Frais d’entrée · de sortie (USD, estimé)"), value: figure(cost.entryFeeUsd) + " · " + figure(cost.exitFeeUsd))274 Divider(); FieldRow(label: String(localized: "Financement sur l’horizon (USD, estimé)"), value: figure(cost.fundingUsd))275 Divider(); FieldRow(label: String(localized: "Coût total ESTIMÉ"), value: cost.totalCostUsd?.value.map { Money.brief($0, maxFraction: 4) + " USD · " + figure(cost.totalCostBps, unit: " pb") }276 ?? String(localized: "pas de total : \((cost.missing ?? []).joined(separator: ", "))"))277 Divider(); FieldRow(label: String(localized: "Collatéral requis · prix de liquidation (estimés)"), value: figure(cost.collateralRequiredUsd, unit: " USD") + " · " + figure(cost.liquidationPrice))278 if let a = cost.assumptions, !a.isEmpty { DisclosureGroup(String(localized: "Hypothèses de l’estimation")) { Text(a.joined(separator: "\n")).font(.system(size: 12)).foregroundStyle(Theme.mute).frame(maxWidth: .infinity, alignment: .leading) }.font(.spFootnote.weight(.semibold)) }279 }280 if let x = r.tradableReason, !r.tradable { Text(MarketWords.tradableReason(x)).font(.system(size: 12)).foregroundStyle(Theme.mute).padding(.top, 4) }281 }282 }283 .padding(14).background(Theme.elev.opacity(0.5), in: RoundedRectangle(cornerRadius: Theme.Radius.control))284 .accessibilityIdentifier("compare.row.\(r.venue)")285 }286 let flagged = c.discrepancies.filter { $0.netEdgeEstimateBps != nil }.prefix(4)287 if !flagged.isEmpty {288 Text(String(localized: "Écarts de prix entre plateformes (estimations)")).spEyebrow().padding(.top, 6)289 if let t = c.texts.discrepancy { Text(t).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }290 ForEach(Array(flagged.enumerated()), id: \.offset) { _, d in291 VStack(alignment: .leading, spacing: 3) {292 Text("long \(d.longVenue) · short \(d.shortVenue)").font(.spCallout.weight(.semibold)).foregroundStyle(Theme.ink)293 Text(String(localized: "écart brut \(d.grossGapBps ?? "—") pb · estimation nette après coûts \(d.netEdgeEstimateBps ?? "—") pb") + (d.actionableFromWallet ? "" : " · " + String(localized: "non réalisable depuis ce portefeuille")))294 .font(.spFootnote).foregroundStyle(Theme.mute)295 if !d.risks.isEmpty { Text(String(localized: "Risques : \(d.risks.map(\.text).joined(separator: " "))")).font(.system(size: 12)).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true) }296 }.padding(.vertical, 4)297 }298 }299 }300301 // MARK: actions302303 private var actionsCard: some View {304 let spot = detail.value?.spot.contains { $0.tradable } ?? false305 let perp = detail.value?.instruments.contains { $0.tradable } ?? false306 return VStack(alignment: .leading, spacing: 10) {307 SectionHeader(title: String(localized: "Négocier"))308 Text(String(localized: "Ces boutons ouvrent seulement la section concernée. Rien n’y est prérempli ni préparé depuis cet écran."))309 .font(.spFootnote).foregroundStyle(Theme.mute)310 Button { router.go(.swap) } label: { Label(String(localized: "Ouvrir Échanger"), systemImage: AppSection.swap.icon) }311 .buttonStyle(.spSecondary).disabled(!spot).accessibilityIdentifier("market.goSwap")312 if detail.value != nil, !spot { Text(String(localized: "Aucun marché au comptant de \(symbol) n’est négociable depuis ce portefeuille.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }313 Button { router.go(.futures) } label: { Label(String(localized: "Ouvrir Contrats à terme"), systemImage: AppSection.futures.icon) }314 .buttonStyle(.spSecondary).disabled(!perp).accessibilityIdentifier("market.goFutures")315 if detail.value != nil, !perp { Text(String(localized: "Aucun contrat perpétuel de \(symbol) n’est négociable depuis ce portefeuille.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }316 }.spCard()317 }318}319