Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/RsInstrumentView.swift3// Description: The page of one underlying: the candles of the server's consolidated series (candlestick or line), the indicators the app derives from those candles — each labelled as derived, with its window — the underlying's markets venue by venue, and the estimated cost of a hypothetical position across venues. Read-only; no figure here is advice and no control places an order.4import Charts5import SwiftUI6import SPWalletCore78struct RsInstrumentView: View {9 let model: AppModel10 let symbol: String11 let close: () -> Void12 @State private var data: RsInstrumentModel?1314 var body: some View {15 ScrollView {16 VStack(alignment: .leading, spacing: 16) {17 HStack(spacing: 12) {18 Button { close() } label: { Label("Marchés", systemImage: "chevron.left") }19 AssetBadge(symbol: symbol, size: 34)20 VStack(alignment: .leading, spacing: 0) {21 Text(symbol).font(.title.weight(.semibold))22 if let c = data?.detail?.category { Text(RsMarketsText.category(c)).font(.callout).foregroundStyle(.secondary) }23 }24 Spacer()25 Button { Task { await data?.load() } } label: { Label("Relire", systemImage: "arrow.clockwise") }26 }27 if let data {28 RsChartCard(data: data)29 RsVenuesCard(data: data)30 RsCompareCard(data: data)31 } else { ProgressView().frame(maxWidth: .infinity).padding(40) }32 }.padding(24).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)33 }34 .task { if data == nil { let d = RsInstrumentModel(model: model, symbol: symbol); data = d; await d.load() } }35 }36}3738// MARK: - Chart and derived indicators3940private struct RsChartCard: View {41 @Bindable var data: RsInstrumentModel42 @State private var style = "candles"43 @State private var smaWindow = 2044 @State private var emaWindow = 5045 @State private var showSMA = true46 @State private var showEMA = true47 private let rsiWindow = 14, volWindow = 3048 private static let windows = [10, 20, 50, 100, 200]4950 var body: some View {51 Card("Cours — série consolidée du serveur", trailing: AnyView(HStack(spacing: 8) {52 if data.loadingCandles { ProgressView().controlSize(.small) }53 if !data.bars.isEmpty { ProvenanceTag(p: .verified, text: "Barres observées (bourses)") }54 OpsAsOf(date: data.candlesAt, prefix: "Reçu")55 })) {56 if data.hasMarketData == false {57 OpsUnavailable(what: "Chandeliers de \(data.symbol)", reason: "Le collecteur de données de marché du serveur ne suit pas ce symbole : aucune série consolidée n’existe. Les prix par plateforme restent visibles ci-dessous.")58 } else {59 HStack(spacing: 10) {60 Picker("Intervalle", selection: $data.interval) { ForEach(data.intervals.isEmpty ? [data.interval] : data.intervals, id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented).frame(width: 200)61 Picker("Barres", selection: $data.barCount) { ForEach([100, 300, 500, 1000], id: \.self) { Text("\($0) barres").tag($0) } }.frame(width: 130)62 Picker("Tracé", selection: $style) { Text("Chandeliers").tag("candles"); Text("Ligne (clôtures)").tag("line") }.pickerStyle(.segmented).frame(width: 240)63 Spacer()64 Toggle("MMS", isOn: $showSMA).toggleStyle(.checkbox)65 Picker("MMS", selection: $smaWindow) { ForEach(Self.windows, id: \.self) { Text("\($0)").tag($0) } }.frame(width: 70).disabled(!showSMA)66 Toggle("MME", isOn: $showEMA).toggleStyle(.checkbox)67 Picker("MME", selection: $emaWindow) { ForEach(Self.windows, id: \.self) { Text("\($0)").tag($0) } }.frame(width: 70).disabled(!showEMA)68 }.labelsHidden()69 if let e = data.statusError { Text("État du collecteur illisible (\(e)) : la couverture de ce symbole n’est pas confirmée.").font(.caption).foregroundStyle(Theme.warning) }70 if let e = data.candlesError {71 if data.bars.isEmpty { OpsUnavailable(what: "Chandeliers", reason: e) { Task { await data.loadCandles() } } }72 else { Banner(.warning, "Dernière lecture en échec (\(e)). Le graphique date de la lecture précédente.") }73 }74 if !data.bars.isEmpty { charts } else if data.candlesError == nil && !data.loadingCandles { Text("Aucune barre servie pour cet intervalle.").foregroundStyle(.secondary) }75 }76 }77 }7879 @ViewBuilder private var charts: some View {80 let bars = data.bars81 let sma = showSMA ? RsIndicators.sma(bars, window: smaWindow) : []82 let ema = showEMA ? RsIndicators.ema(bars, window: emaWindow) : []83 let width = max(1.0, min(9.0, 620.0 / Double(bars.count)))84 let lows = bars.map(\.low).min() ?? 0, highs = bars.map(\.high).max() ?? 185 Chart {86 if style == "candles" {87 ForEach(bars) { b in88 RuleMark(x: .value("Date", b.date), yStart: .value("Bas", b.low), yEnd: .value("Haut", b.high)).lineStyle(StrokeStyle(lineWidth: 1)).foregroundStyle(b.isUp ? Theme.positive : Theme.negative)89 RectangleMark(x: .value("Date", b.date), yStart: .value("Ouverture", b.open), yEnd: .value("Clôture", b.close), width: .fixed(width)).foregroundStyle(b.isUp ? Theme.positive : Theme.negative)90 }91 } else {92 ForEach(bars) { b in LineMark(x: .value("Date", b.date), y: .value("Clôture", b.close), series: .value("Série", "Clôture")).foregroundStyle(Theme.accent) }93 }94 ForEach(sma) { p in LineMark(x: .value("Date", p.date), y: .value("MMS", p.value), series: .value("Série", "MMS")).foregroundStyle(.orange).lineStyle(StrokeStyle(lineWidth: 1.2, dash: [4, 2])) }95 ForEach(ema) { p in LineMark(x: .value("Date", p.date), y: .value("MME", p.value), series: .value("Série", "MME")).foregroundStyle(.purple).lineStyle(StrokeStyle(lineWidth: 1.2, dash: [4, 2])) }96 }97 .chartYScale(domain: (lows * 0.995)...(highs * 1.005))98 .frame(height: 320)99 .accessibilityLabel("Cours de \(data.symbol), \(bars.count) barres de \(data.interval)")100101 HStack(spacing: 14) {102 if let last = bars.last {103 Text("Dernière barre close : \(Fmt.date(last.date)) UTC d’ouverture · O \(RsFmt.price(last.open)) H \(RsFmt.price(last.high)) B \(RsFmt.price(last.low)) C \(RsFmt.price(last.close))\(last.source.map { " · source \($0)" } ?? "")").font(.caption).monospacedDigit()104 }105 Spacer()106 if showSMA { RsLegend(color: .orange, text: "MMS \(smaWindow) — dérivé\(sma.isEmpty ? " (pas assez de barres)" : "")") }107 if showEMA { RsLegend(color: .purple, text: "MME \(emaWindow) — dérivé\(ema.isEmpty ? " (pas assez de barres)" : "")") }108 }109 provenance110111 Divider()112 HStack { Text("Indicateurs calculés par l’app").font(.subheadline.weight(.semibold)); ProvenanceTag(p: .estimate, text: "Dérivé des barres affichées"); Spacer() }113 Text("Ces valeurs ne sont pas servies par le portefeuille : elles sont calculées sur ce Mac à partir des \(bars.count) barres ci-dessus, avec les fenêtres indiquées. Elles décrivent le passé observé et ne constituent ni une prévision ni un conseil.").font(.caption).foregroundStyle(.secondary)114 indicators(bars)115 }116117 @ViewBuilder private var provenance: some View {118 if let c = data.candles {119 VStack(alignment: .leading, spacing: 2) {120 Text("Règle de consolidation du serveur : \(c.rule)").font(.caption).foregroundStyle(.secondary).textSelection(.enabled)121 Text("Priorité des sources : \((c.priority ?? []).joined(separator: " > ").opsIfEmpty("non fournie")) · barres fournies par source : \(RsJSONText.inline(c.provided)) · heures d’ouverture manquantes dans la fenêtre : \(RsJSONText.inline(c.gaps))").font(.caption).foregroundStyle(.secondary)122 if (c.gaps?.intValue ?? 0) > 0 { Text("La série a des trous : les indicateurs ci-dessous sont calculés sur les barres présentes, sans interpolation.").font(.caption).foregroundStyle(Theme.warning) }123 if data.unreadableBars > 0 { Text("\(data.unreadableBars) barres servies n’ont pas pu être lues et ne sont pas tracées.").font(.caption).foregroundStyle(Theme.warning) }124 }125 }126 }127128 @ViewBuilder private func indicators(_ bars: [RsBar]) -> some View {129 let rsi = RsIndicators.rsi(bars, window: rsiWindow)130 let dd = RsIndicators.drawdown(bars)131 let ppy = RsIndicators.periodsPerYear(interval: data.interval)132 let vol = ppy.flatMap { RsIndicators.realizedVolatility(bars, window: volWindow, periodsPerYear: $0) }133 LazyVGrid(columns: [GridItem(.adaptive(minimum: 230), spacing: 14)], alignment: .leading, spacing: 10) {134 OpsMini(label: "RSI (\(rsiWindow) barres, lissage de Wilder)", value: rsi.last.map { RsFmt.metric($0.value, digits: 1) } ?? "Pas assez de barres")135 OpsMini(label: "Volatilité réalisée (\(volWindow) rendements, annualisée)", value: vol.map { OpsFmt.fraction($0).replacingOccurrences(of: "+", with: "") } ?? (ppy == nil ? "Intervalle non annualisable" : "Pas assez de barres"))136 OpsMini(label: "Repli maximal sur la fenêtre (\(bars.count) barres)", value: dd.map(\.value).min().map { OpsFmt.fraction($0) } ?? "—")137 OpsMini(label: "Repli actuel depuis le plus haut de la fenêtre", value: dd.last.map { OpsFmt.fraction($0.value) } ?? "—")138 }139 if ppy != nil { Text("Annualisation : marché ouvert 24 h/24, 365 jours (\(Int(ppy ?? 0)) barres de \(data.interval) par an), écart-type des rendements logarithmiques clôture à clôture.").font(.caption).foregroundStyle(.secondary) }140 if !rsi.isEmpty {141 Text("RSI \(rsiWindow) — dérivé").font(.caption).foregroundStyle(.secondary)142 Chart {143 ForEach(rsi) { p in LineMark(x: .value("Date", p.date), y: .value("RSI", p.value)).foregroundStyle(Theme.accent) }144 RuleMark(y: .value("70", 70)).foregroundStyle(.secondary.opacity(0.5)).lineStyle(StrokeStyle(lineWidth: 0.8, dash: [3, 3]))145 RuleMark(y: .value("30", 30)).foregroundStyle(.secondary.opacity(0.5)).lineStyle(StrokeStyle(lineWidth: 0.8, dash: [3, 3]))146 }.chartYScale(domain: 0...100).frame(height: 110)147 }148 if dd.count > 1 {149 Text("Repli depuis le plus haut de la fenêtre — dérivé").font(.caption).foregroundStyle(.secondary)150 Chart(dd) { p in AreaMark(x: .value("Date", p.date), y: .value("Repli", p.value * 100)).foregroundStyle(Theme.negative.opacity(0.35)) }151 .chartYAxis { AxisMarks { v in AxisGridLine(); AxisValueLabel { if let d = v.as(Double.self) { Text("\(Int(d)) %") } } } }152 .frame(height: 110)153 }154 }155}156157struct RsLegend: View {158 let color: Color; let text: String159 var body: some View { HStack(spacing: 5) { RoundedRectangle(cornerRadius: 1).fill(color).frame(width: 16, height: 3); Text(text).font(.caption).foregroundStyle(.secondary) } }160}161162// MARK: - Venue by venue163164private struct RsVenuesCard: View {165 let data: RsInstrumentModel166167 var body: some View {168 Card("Marchés de \(data.symbol), plateforme par plateforme", trailing: AnyView(OpsAsOf(date: data.detailAt, prefix: "Reçu"))) {169 if let d = data.detail {170 if let e = data.detailError { Banner(.warning, "Dernière lecture en échec (\(e)). Le tableau date de la lecture précédente.") }171 if !d.errors.isEmpty { Banner(.warning, "Comparaison PARTIELLE — sources sans réponse : " + d.errors.map { "\($0.source) (\($0.message))" }.joined(separator: " ; ")) }172 Text("Lecture seule. Chaque ligne est le prix d’UNE plateforme à SA date ; les prix de plateformes différentes ne sont jamais moyennés.").font(.callout).foregroundStyle(.secondary)173 if d.spot.isEmpty && d.instruments.isEmpty { Text("Aucun marché rattaché à ce sous-jacent.").foregroundStyle(.secondary) }174 if !d.spot.isEmpty { table("Comptant", d.spot) }175 if !d.instruments.isEmpty { table("Perpétuels", d.instruments) }176 if !d.notCompared.isEmpty {177 Divider()178 Text("Même symbole, non rattaché à ce sous-jacent — affiché, jamais comparé").font(.subheadline.weight(.semibold))179 table(nil, d.notCompared)180 }181 } else if let e = data.detailError { OpsUnavailable(what: "Marchés du sous-jacent", reason: e) { Task { await data.loadDetail() } } }182 else { ProgressView().controlSize(.small) }183 }184 }185186 @ViewBuilder private func table(_ title: String?, _ rows: [HubRow]) -> some View {187 if let title { Text(title).font(.subheadline.weight(.semibold)) }188 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {189 GridRow { Text("Plateforme"); Text("Marché"); Text("Prix"); Text("24 h"); Text("Volume 24 h"); Text("Financement / h"); Text("Intérêt ouvert"); Text("Date de la source"); Text("Signalements") }.font(.caption).foregroundStyle(.secondary)190 ForEach(rows) { r in191 GridRow {192 Text(r.venueName ?? r.venue).lineLimit(1)193 VStack(alignment: .leading, spacing: 0) { Text(r.symbol).lineLimit(1); if let m = r.multiplier, m != "1" { Text("multiplicateur \(m)").font(.caption2).foregroundStyle(.secondary) } }194 VStack(alignment: .leading, spacing: 0) { Text(RsFmt.price(r.price)).monospacedDigit(); Text(RsMarketsText.priceKind(r.priceKind)).font(.caption2).foregroundStyle(.secondary) }195 Text(RsFmt.fraction(r.change24h)).monospacedDigit().foregroundStyle(Theme.change(RsFmt.double(r.change24h)))196 Text(RsFmt.compactUsd(r.volume24hUsd)).monospacedDigit()197 Text(r.funding.map { RsFmt.fraction($0.perHour, digits: 4) } ?? "—").monospacedDigit()198 Text(RsFmt.compactUsd(r.openInterestUsd)).monospacedDigit()199 Text(r.sourceDate.map { Fmt.dateSeconds($0) } ?? "non fournie").font(.caption).foregroundStyle(.secondary).monospacedDigit()200 RsRowFlags(row: r)201 }202 }203 }204 }205}206207// MARK: - Cost of a hypothetical position across venues (estimate)208209private struct RsCompareCard: View {210 @Bindable var data: RsInstrumentModel211212 var body: some View {213 Card("Coût estimé d’une position hypothétique, par plateforme", trailing: AnyView(HStack(spacing: 8) { ProvenanceTag(p: .estimate); OpsAsOf(date: data.comparisonAt, prefix: "Reçu") })) {214 Text("Outil de comparaison en lecture seule : le serveur estime, sous les hypothèses qu’il énonce, ce que coûterait UNE position de cette taille sur chaque plateforme. Rien n’est préparé ni placé, et le résultat n’est pas une recommandation.").font(.callout).foregroundStyle(.secondary)215 HStack(spacing: 10) {216 Picker("Sens", selection: $data.side) { Text("Long").tag("long"); Text("Short").tag("short") }.pickerStyle(.segmented).frame(width: 130)217 LabeledContent("Notionnel (USD)") { TextField("1000", text: $data.notional).frame(width: 90).textFieldStyle(.roundedBorder) }218 LabeledContent("Levier") { TextField("2", text: $data.leverage).frame(width: 50).textFieldStyle(.roundedBorder) }219 LabeledContent("Horizon (h)") { TextField("24", text: $data.horizonHours).frame(width: 60).textFieldStyle(.roundedBorder) }220 Picker("Liquidité", selection: $data.liquidity) { Text("Preneur").tag("taker"); Text("Teneur").tag("maker") }.frame(width: 110).labelsHidden()221 Spacer()222 if data.comparing { ProgressView().controlSize(.small) }223 Button("Estimer") { Task { await data.compare() } }.disabled(data.comparisonProblem != nil || data.comparing || data.model.isOffline)224 }225 if let p = data.comparisonProblem { Text(p).font(.caption).foregroundStyle(Theme.negative) }226 if let e = data.comparisonError { Banner(.danger, e) }227 if let c = data.comparison { result(c) }228 }229 }230231 @ViewBuilder private func result(_ c: VenueComparison) -> some View {232 Banner(.info, c.texts.disclaimer)233 Text("Demande telle que comprise par le serveur : \(RsJSONText.inline(c.request))").font(.caption).foregroundStyle(.secondary).textSelection(.enabled)234 if !c.errors.isEmpty { Banner(.warning, "Sources sans réponse : " + c.errors.map { "\($0.source) (\($0.message))" }.joined(separator: " ; ")) }235 ForEach(c.warnings, id: \.self) { Text($0).font(.caption).foregroundStyle(Theme.warning) }236 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 6) {237 GridRow { Text("Plateforme"); Text("Coût total estimé"); Text("Frais entrée / sortie"); Text("Glissement entrée / sortie"); Text("Financement"); Text("Liquidation estimée"); Text("État") }.font(.caption).foregroundStyle(.secondary)238 ForEach(Array(c.rows.enumerated()), id: \.offset) { _, r in239 GridRow(alignment: .top) {240 VStack(alignment: .leading, spacing: 0) { Text(r.venueName ?? r.venue); Text(r.instrument).font(.caption2).foregroundStyle(.secondary).lineLimit(1) }241 if let cost = r.cost {242 VStack(alignment: .leading, spacing: 0) {243 figure(cost.totalCostUsd, unit: "USD").fontWeight(.medium)244 if let b = cost.totalCostBps?.value { Text(RsFmt.bps(b)).font(.caption).foregroundStyle(.secondary) }245 if let m = cost.missing, !m.isEmpty { Text("Non estimé : \(m.joined(separator: ", ")) — pas de total partiel").font(.caption2).foregroundStyle(Theme.warning) }246 }247 VStack(alignment: .leading, spacing: 0) { figure(cost.entryFeeUsd, unit: "USD"); figure(cost.exitFeeUsd, unit: "USD") }248 VStack(alignment: .leading, spacing: 0) { figure(cost.entrySlippageUsd, unit: "USD"); figure(cost.exitSlippageUsd, unit: "USD") }249 figure(cost.fundingUsd, unit: "USD")250 VStack(alignment: .leading, spacing: 0) { figure(cost.liquidationPrice, unit: ""); if let d = cost.liquidationDistanceBps?.value { Text("à \(RsFmt.bps(d))").font(.caption).foregroundStyle(.secondary) } }251 } else {252 Text("Indisponible").foregroundStyle(Theme.negative); Text("—"); Text("—"); Text("—"); Text("—")253 }254 VStack(alignment: .leading, spacing: 2) {255 if let e = r.error { Text(e).font(.caption).foregroundStyle(Theme.negative) }256 if r.stale { ProvenanceTag(p: .stale) }257 if r.priceOutlier { RsFlag(text: "Prix divergent", color: Theme.negative, symbol: "exclamationmark.triangle") }258 if !r.tradable { RsFlag(text: "Non négociable", color: .secondary, symbol: "lock").help(r.tradableReason ?? "") }259 if let f = r.fees { Text("Barème \(f.source), lu le \(f.asOf)").font(.caption2).foregroundStyle(.secondary) }260 }261 }262 }263 }264 let flagged = c.discrepancies.filter(\.flagged)265 if !c.discrepancies.isEmpty {266 DisclosureGroup("Écarts de prix entre plateformes (\(flagged.count) signalés sur \(c.discrepancies.count))") {267 VStack(alignment: .leading, spacing: 8) {268 if let t = c.texts.discrepancy { Banner(.warning, t) }269 ForEach(Array(c.discrepancies.enumerated()), id: \.offset) { _, d in270 VStack(alignment: .leading, spacing: 2) {271 HStack { Text("Long \(d.longVenue) / short \(d.shortVenue)").fontWeight(.medium); ProvenanceTag(p: .estimate); if !d.actionableFromWallet { RsFlag(text: "Non réalisable depuis le portefeuille", color: .secondary, symbol: "lock") } }272 Text("Écart brut \(RsFmt.bps(d.grossGapBps)) · écart net estimé \(RsFmt.bps(d.netEdgeEstimateBps))\(d.reason.map { " · \($0)" } ?? "")").font(.callout).monospacedDigit()273 if !d.assumptions.isEmpty { Text("Hypothèses : " + d.assumptions.map(\.text).joined(separator: " ; ")).font(.caption).foregroundStyle(.secondary) }274 if !d.risks.isEmpty { Text("Risques : " + d.risks.map(\.text).joined(separator: " ; ")).font(.caption).foregroundStyle(Theme.warning) }275 }276 }277 }.padding(.top, 4)278 }279 }280 if let a = c.texts.assumptions, !a.isEmpty { Text("Hypothèses du serveur : " + a.map(\.text).joined(separator: " ; ")).font(.caption).foregroundStyle(.secondary) }281 }282283 private func figure(_ f: CostFigure?, unit: String) -> Text {284 guard let f else { return Text("—") }285 if let v = f.value { return Text("\(RsFmt.price(v))\(unit.isEmpty ? "" : " \(unit)")").monospacedDigit() }286 return Text(f.reason ?? "non estimé").font(.caption).foregroundStyle(.secondary)287 }288}289290enum RsJSONText {291 /// A small server value on one line, as served ("—" when absent).292 static func inline(_ v: JSONValue?) -> String {293 guard let v, !v.isNull else { return "—" }294 switch v {295 case .object(let o): return o.keys.sorted().map { "\($0) : \(inline(o[$0]))" }.joined(separator: ", ").opsIfEmpty("—")296 case .array(let a): return a.map { inline($0) }.joined(separator: ", ").opsIfEmpty("—")297 default: return v.displayText298 }299 }300}301