SPB Git

Repository Public

FuturesExplorerView.swift 18.4 KB 233 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Futures/FuturesExplorerView.swift3// Description: The read-only secondary tab: the markets hub (every spot and perpetual market the server lists across venues, with whether the wallet can trade it and why not), the venue comparator (an itemised cost ESTIMATE under the assumptions the server states, with its disclaimer verbatim) and the private-company contracts (display only — never tradable from the wallet; an implied valuation is shown only as an estimate, with its formula and the published source of that formula). Nothing here can prepare, place or sign anything.4import SwiftUI5import SPWalletCore67struct FutExplorerView: View {8    let model: AppModel9    let store: FuturesStore10    @State private var section = 01112    var body: some View {13        Picker("Vue", selection: $section) { Text("Tous les marchés").tag(0); Text("Comparateur de plateformes").tag(1); Text("Marchés privés").tag(2) }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 560)14        switch section {15        case 0: FutHubView(model: model, store: store)16        case 1: FutCompareView(model: model, store: store)17        default: FutPrivateMarketsView(model: model, store: store)18        }19    }20}2122// MARK: - hub2324private struct FutHubView: View {25    let model: AppModel26    let store: FuturesStore27    @State private var list = FutLoaded<HubList>()28    @State private var search = ""29    @State private var kind = "perp"30    @State private var sort: HubQuery.Sort = .volume31    @State private var selection: String?3233    private var queryId: String { "\(search)|\(kind)|\(sort.rawValue)" }3435    private func load() async {36        let id = queryId37        list.loading = true38        try? await Task.sleep(for: .milliseconds(350))   // typing in the search field: one request once it settles39        guard !Task.isCancelled, id == queryId else { return }40        do {41            let l = try await store.markets.list(HubQuery(kind: kind.isEmpty ? nil : kind, search: search, sort: sort, descending: sort != .symbol, limit: 300))42            if id == queryId { list.set(l) }43        } catch { if id == queryId { list.fail(model.describe(error)) } }44    }4546    var body: some View {47        Card("Explorateur de marchés", trailing: AnyView(ProvenanceTag(p: .estimate, text: "Lecture seule"))) {48            HStack {49                TextField("Rechercher", text: $search).textFieldStyle(.roundedBorder).frame(maxWidth: 240)50                Picker("Type", selection: $kind) { Text("Perpétuels").tag("perp"); Text("Comptant").tag("spot"); Text("Tous").tag("") }.frame(maxWidth: 200)51                Picker("Tri", selection: $sort) {52                    Text("Volume").tag(HubQuery.Sort.volume); Text("Intérêt ouvert").tag(HubQuery.Sort.openInterest); Text("Financement").tag(HubQuery.Sort.funding); Text("Variation").tag(HubQuery.Sort.change); Text("Symbole").tag(HubQuery.Sort.symbol)53                }.frame(maxWidth: 220)54                Spacer()55                if list.loading { ProgressView().controlSize(.small) }56                if let l = list.value { Text("\(l.rows.count) sur \(l.total)" + (l.counts.map { " · \($0.stale) périmé(s)" } ?? "")).font(.caption).foregroundStyle(.secondary) }57            }58            if let e = list.error { Banner(.danger, "Explorateur indisponible : \(e)") }59            if let l = list.value {60                ForEach(l.errors, id: \.self) { Banner(.warning, "Source illisible — liste PARTIELLE : \($0.source) : \($0.message)") }61                ForEach(l.venues.filter { $0.status != "ok" || $0.restriction != nil }) { v in62                    Text("\(v.name) : \(v.status)" + (v.error.map { " — \($0)" } ?? "") + (v.restriction.map { " — \($0)" } ?? "")).font(.caption).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true)63                }64                Table(l.rows, selection: $selection) {65                    TableColumn("Marché") { r in HStack(spacing: 6) { Text(r.symbol).fontWeight(.medium); Text(r.kind == "perp" ? "perp" : "spot").font(.caption2).foregroundStyle(.secondary); if r.stale { Image(systemName: "clock.badge.exclamationmark").foregroundStyle(Theme.warning).help("Donnée périmée") } } }.width(min: 130, ideal: 170)66                    TableColumn("Plateforme") { r in Text(r.venueName ?? r.venue).font(.callout) }.width(min: 90, ideal: 120)67                    TableColumn("Prix") { r in Text(FutNum.exact(r.price)).monospacedDigit().help(r.priceKind == "close_1h" ? "Clôture de la dernière barre horaire consolidée" : "Prix mark de la plateforme") }.width(min: 90, ideal: 120)68                    TableColumn("24 h") { r in Text(FutNum.pct(fraction: r.change24h)).monospacedDigit().foregroundStyle(Theme.change(FutNum.d(r.change24h))) }.width(min: 70, ideal: 80)69                    TableColumn("Volume 24 h") { r in Text(FutNum.compactUSD(r.volume24hUsd)).monospacedDigit() }.width(min: 90, ideal: 110)70                    TableColumn("Intérêt ouvert") { r in Text(FutNum.compactUSD(r.openInterestUsd)).monospacedDigit() }.width(min: 90, ideal: 110)71                    TableColumn("Financement / h") { r in Text(r.funding.map { FutNum.pct(fraction: $0.perHour, digits: 4) } ?? "—").monospacedDigit() }.width(min: 100, ideal: 120)72                    TableColumn("Depuis ce portefeuille") { r in73                        Text(r.tradable ? "négociable côté serveur" : (r.tradableReason ?? r.restriction ?? "non négociable")).font(.caption).foregroundStyle(r.tradable ? .secondary : Theme.warning).lineLimit(2).help(r.tradableReason ?? r.restriction ?? "")74                    }.width(min: 160, ideal: 260)75                }.frame(height: 460)76                if let id = selection, let r = l.rows.first(where: { $0.id == id }) {77                    Text("\(r.id) — source : \(r.source)" + (r.sourceDate.map { " · \(Fmt.relative($0))" } ?? "") + (r.priceOutlier == true ? " · PRIX ABERRANT par rapport aux autres sources" : "") + (r.mapping?.note.map { " · \($0)" } ?? "")).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)78                }79            } else if list.error == nil { ProgressView().frame(maxWidth: .infinity, minHeight: 80) }80            Text("« Négociable côté serveur » décrit ce que le serveur permettrait, verrous compris ; cette app ne propose de nouveaux ordres que sur la plateforme offerte dans l’onglet Marchés.").font(.caption).foregroundStyle(.secondary)81        }82        .task(id: queryId) { await load() }83    }84}8586// MARK: - comparator8788private struct FutCompareView: View {89    let model: AppModel90    let store: FuturesStore91    @State private var underlying = ""92    @State private var side = "long"93    @State private var notional = ""94    @State private var leverage = "1"95    @State private var horizon = "24"96    @State private var result = FutLoaded<VenueComparison>()9798    private var query: CompareQuery? {99        let u = underlying.trimmingCharacters(in: .whitespaces).uppercased()100        guard !u.isEmpty, let n = FutNum.input(notional), let l = FutNum.input(leverage), let h = FutNum.input(horizon) else { return nil }101        return CompareQuery(underlying: u, side: side, notional: n, leverage: l, horizonHours: h)102    }103104    var body: some View {105        Card("Comparateur de plateformes", trailing: AnyView(ProvenanceTag(p: .estimate, text: "Estimations — lecture seule"))) {106            HStack {107                TextField("Sous-jacent (ex. BTC)", text: $underlying).textFieldStyle(.roundedBorder).frame(width: 150)108                Picker("Sens", selection: $side) { Text("Long").tag("long"); Text("Short").tag("short") }.pickerStyle(.segmented).labelsHidden().frame(width: 130)109                TextField("Notionnel ($)", text: $notional).textFieldStyle(.roundedBorder).frame(width: 130)110                TextField("Levier", text: $leverage).textFieldStyle(.roundedBorder).frame(width: 70).help("Hypothèse de calcul uniquement ; part de 1×")111                TextField("Horizon (h)", text: $horizon).textFieldStyle(.roundedBorder).frame(width: 90)112                Spacer()113                if result.loading { ProgressView().controlSize(.small) }114                Button("Comparer") {115                    guard let q = query else { return }116                    result.loading = true117                    Task { do { result.set(try await store.markets.compare(q)) } catch { result.fail(model.describe(error)) } }118                }.disabled(query == nil || result.loading)119            }120            if let e = result.error { Banner(.danger, "Comparaison indisponible : \(e)") }121            if let c = result.value {122                Banner(.info, c.texts.disclaimer)123                ForEach(c.warnings, id: \.self) { Banner(.warning, $0) }124                ForEach(c.errors, id: \.self) { Banner(.warning, "\($0.source) illisible : \($0.message)") }125                ForEach(c.rows, id: \.instrument) { r in126                    VStack(alignment: .leading, spacing: 6) {127                        HStack {128                            Text(r.venueName ?? r.venue).fontWeight(.semibold); Text(r.instrument).font(.caption).foregroundStyle(.secondary)129                            if r.stale { ProvenanceTag(p: .stale) }130                            if r.priceOutlier { ProvenanceTag(p: .stale, text: "Prix aberrant") }131                            Spacer()132                            Text(r.tradable ? "négociable côté serveur" : (r.tradableReason ?? r.restriction ?? "non négociable")).font(.caption).foregroundStyle(r.tradable ? .secondary : Theme.warning).lineLimit(2)133                        }134                        if let e = r.error { Text("Illisible : \(e)").font(.callout).foregroundStyle(Theme.negative) }135                        if let k = r.cost {136                            FutStatGrid(minimum: 150) {137                                figure("Coût total estimé", k.totalCostUsd, unit: " $")138                                figure("Coût total (pb)", k.totalCostBps, unit: " pb")139                                figure("Frais d’entrée", k.entryFeeUsd, unit: " $")140                                figure("Glissement d’entrée", k.entrySlippageUsd, unit: " $")141                                figure("Financement sur l’horizon", k.fundingUsd, unit: " $")142                                figure("Collatéral requis", k.collateralRequiredUsd, unit: " $")143                                figure("Liquidation estimée", k.liquidationPrice, unit: "")144                                figure("Levier max", k.maxLeverage, unit: "×")145                            }146                            if let m = k.missing, !m.isEmpty { Text("Postes non estimables : \(m.joined(separator: ", ")) — aucun total n’est présenté sans eux.").font(.caption).foregroundStyle(Theme.warning) }147                            if let a = k.assumptions, !a.isEmpty { Text("Hypothèses : \(a.joined(separator: " · "))").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }148                        }149                        if let f = r.fees { Text("Barème utilisé : preneur \(f.takerRate), teneur \(f.makerRate) — \(f.source), lu le \(f.asOf)").font(.caption).foregroundStyle(.secondary) }150                    }.padding(10).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))151                }152                ForEach(Array(c.discrepancies.enumerated()), id: \.offset) { _, d in153                    VStack(alignment: .leading, spacing: 3) {154                        Text("Écart de prix \(d.longVenue) / \(d.shortVenue) : brut \(d.grossGapBps.map { FutNum.exact($0, maxFraction: 1) + " pb" } ?? "—"), net estimé \(d.netEdgeEstimateBps.map { FutNum.exact($0, maxFraction: 1) + " pb" } ?? "—")" + (d.reason.map { " — \($0)" } ?? "")).font(.callout)155                        ForEach(d.risks, id: \.code) { Text("Risque : \($0.text)").font(.caption).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true) }156                        Text("Un écart est une estimation, jamais une instruction de négocier.").font(.caption).foregroundStyle(.secondary)157                    }158                }159            }160        }161    }162163    private func figure(_ label: String, _ f: CostFigure?, unit: String) -> some View {164        FutStat(label, f.map { $0.value.map { "≈ " + FutNum.exact($0, maxFraction: 4) + unit } ?? "non calculable" } ?? "—", note: f?.value == nil ? f?.reason : f?.basis)165    }166}167168// MARK: - private markets169170private struct FutPrivateMarketsView: View {171    let model: AppModel172    let store: FuturesStore173    @State private var list = FutLoaded<PrivateMarketList>()174    @State private var selection: String?175176    var body: some View {177        Card("Contrats sur sociétés privées", trailing: AnyView(ProvenanceTag(p: .unavailable, text: "Affichage seulement — non négociable"))) {178            if let e = list.error { Banner(.danger, "Marchés privés indisponibles : \(e)") }179            if let l = list.value {180                Banner(.warning, l.notice.text)181                ForEach(l.venues.filter { $0.status != "ok" }, id: \.venue) { v in Text("\(v.name ?? v.venue) : \(v.status)" + (v.error.map { " — \($0)" } ?? "")).font(.caption).foregroundStyle(Theme.warning) }182                Table(l.markets, selection: $selection) {183                    TableColumn("Société") { m in Text(m.company?.name ?? "—").fontWeight(.medium) }.width(min: 120, ideal: 160)184                    TableColumn("Contrat") { m in Text("\(m.symbol) · \(m.platform ?? m.venue)").font(.callout) }.width(min: 130, ideal: 180)185                    TableColumn("État") { m in Text(m.status + (m.market.frozen == true ? " · prix gelé" : "")).font(.caption).foregroundStyle(m.status == "live" ? .secondary : Theme.warning) }.width(min: 80, ideal: 110)186                    TableColumn("Prix synthétique") { m in187                        HStack(spacing: 4) { Text(FutNum.exact(m.valuation.syntheticPrice.value)).monospacedDigit(); if m.valuation.syntheticPrice.stale { Image(systemName: "clock.badge.exclamationmark").foregroundStyle(Theme.warning).help("Périmé") } }188                    }.width(min: 100, ideal: 130)189                    TableColumn("Unité") { m in Text(m.review.isReviewed ? m.contract.unit.label : "fiche non revue").font(.caption).foregroundStyle(.secondary).lineLimit(2) }.width(min: 110, ideal: 170)190                    TableColumn("Valorisation implicite (estimation)") { m in191                        let v = m.valuation.impliedValuation192                        Text(v.isDerived ? "≈ " + FutNum.compactUSD(v.value) : (v.reason ?? "non dérivée")).font(.callout).foregroundStyle(v.isDerived ? .primary : .secondary).lineLimit(2)193                    }.width(min: 170, ideal: 240)194                }.frame(height: 320)195                if let id = selection, let m = l.markets.first(where: { $0.id == id }) { detail(m) }196                else { Text("Sélectionnez un contrat pour voir la formule de sa valorisation implicite et sa source.").font(.caption).foregroundStyle(.secondary) }197                if let ex = l.excluded, !ex.isEmpty { Text("Contrats exclus par le serveur : " + ex.map { "\($0.id) (\($0.reason))" }.joined(separator: " ; ")).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }198            } else if list.error == nil { ProgressView().frame(maxWidth: .infinity, minHeight: 80) }199        }200        .task { do { list.set(try await store.markets.privateMarkets()) } catch { list.fail(model.describe(error)) } }201    }202203    @ViewBuilder private func detail(_ m: PrivateMarket) -> some View {204        let v = m.valuation, imp = v.impliedValuation205        VStack(alignment: .leading, spacing: 8) {206            HStack { Text("\(m.company?.name ?? m.symbol) — \(m.id)").font(.headline); Spacer(); ProvenanceTag(p: .estimate, text: "Estimations") }207            if let nt = m.notTradable { Banner(.warning, "Non négociable depuis ce portefeuille [\(nt.code)] : \(nt.reasons.joined(separator: " ; "))") }208            if let e = m.error { Banner(.danger, e) }209            Field(label: "Prix synthétique", value: "\(FutNum.exact(v.syntheticPrice.value)) (\(v.syntheticPrice.priceKind ?? "mark")) — source \(v.syntheticPrice.source)" + (FutNum.ms(v.syntheticPrice.ts).map { ", \(Fmt.relative($0))" } ?? "") + (v.syntheticPrice.stale ? " — PÉRIMÉ" : ""))210            Field(label: "Fiche du contrat", value: "\(m.review.state)" + (m.review.validUntil.map { " · valide jusqu’au \($0)" } ?? "") + (m.review.reasons.isEmpty ? "" : " · \(m.review.reasons.joined(separator: " ; "))"))211            if imp.isDerived {212                Field(label: "Valorisation implicite", value: "≈ \(FutNum.exact(imp.value, maxFraction: 0)) $ — ESTIMATION" + (imp.label.map { " (\($0))" } ?? ""), emphasis: true)213                Field(label: "Formule", value: imp.formula ?? "—")214                if let s = imp.formulaSource {215                    Field(label: "Source publiée de la formule", value: "« \(s.quote) » — lu le \(s.readAt)")216                    if let url = URL(string: s.url), url.scheme == "https" { Link(s.url, destination: url).font(.caption) }217                }218            } else {219                Field(label: "Valorisation implicite", value: "non dérivée : \(imp.reason ?? imp.reasonCode ?? "raison non précisée")")220            }221            if let last = v.lastPrivateValuation {222                Field(label: "Dernière valorisation privée", value: "\(last.valueUsd.map { FutNum.compactUSD($0) } ?? last.value ?? "—") — \(last.kind), \(last.date), confiance \(last.confidence) — \(last.detail)")223                if let url = URL(string: last.sourceUrl), url.scheme == "https" { Link(last.sourceUrl, destination: url).font(.caption) }224            } else if let why = v.lastPrivateValuationReason { Field(label: "Dernière valorisation privée", value: "aucune : \(why)") }225            Field(label: "Prime / décote", value: v.premiumDiscount.premiumBps.map { "\(FutNum.exact($0, maxFraction: 0)) pb" + (v.premiumDiscount.caveat.map { " — \($0)" } ?? "") } ?? "non calculable : \(v.premiumDiscount.reason ?? "—")")226            ForEach(v.caveats, id: \.code) { Text("⚠︎ \($0.text)").font(.caption).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true) }227            if let n = m.contract.nature { Field(label: "Nature du contrat", value: n) }228            if let s = m.contract.settlement { Field(label: "Règlement", value: s) }229            if let i = m.contract.ipoConversion { Field(label: "En cas d’introduction en bourse", value: i) }230        }.padding(10).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))231    }232}233
Files main
Menu

Theme