Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/OpsMonitorTab.swift3// Description: The monitoring screen: capital, result differences, exposure and the three risk books — real, testnet and simulated money always in separate blocks with their own label and never added together — each block with its own date and its own failure state. System health is in OpsHealthCards.swift.4import SwiftUI5import SPWalletCore67struct OpsMonitorTab: View {8 let model: AppModel9 @State private var data: OpsMonitorModel?1011 var body: some View {12 ScrollView {13 VStack(alignment: .leading, spacing: 16) {14 if let data {15 HStack {16 Text("Lecture seule. Les montants en USD sont des estimations arrondies par le serveur ; rien ici n’est un montant à approuver.").font(.callout).foregroundStyle(.secondary)17 Spacer()18 if data.refreshing { ProgressView().controlSize(.small) }19 Button { Task { await data.refresh() } } label: { Label("Relire tout", systemImage: "arrow.clockwise") }.disabled(data.refreshing)20 }21 OpsCapitalCard(model: model, data: data)22 OpsBooksCard(data: data)23 OpsPnlCard(data: data)24 OpsExposureCard(data: data)25 OpsHealthCards(data: data)26 } else { ProgressView().frame(maxWidth: .infinity).padding(40) }27 }.padding(24).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)28 }29 .task {30 let d = data ?? OpsMonitorModel(model: model); data = d31 await d.refresh()32 // the server caches each answer 10 to 30 s: a faster poll would read the same data33 while !Task.isCancelled {34 try? await Task.sleep(for: .seconds(30))35 guard !Task.isCancelled else { return }36 if AppActivity.isActive, !model.isOffline { await d.refresh() }37 }38 }39 }40}4142/// The frame of one monitoring block: title, the server's as-of date, the stale / failed state, then the content when there is a value.43struct OpsSectionCard<T: Sendable, Content: View>: View {44 let title: String45 let section: OpsSection<T>46 let asOf: (T) -> Date?47 let retry: () -> Void48 @ViewBuilder let content: (T) -> Content4950 var body: some View {51 Card(title, trailing: AnyView(HStack(spacing: 8) {52 if section.loading { ProgressView().controlSize(.small) }53 if let v = section.value { OpsAsOf(date: asOf(v) ?? section.fetchedAt, prefix: asOf(v) == nil ? "Reçu" : "Données du serveur") }54 if section.isStale { ProvenanceTag(p: .stale) }55 })) {56 if let v = section.value {57 if let e = section.error { Banner(.warning, "Dernière lecture en échec (\(e)). Les chiffres ci-dessous datent de la lecture précédente.") }58 content(v)59 } else if let e = section.error { OpsUnavailable(what: title, reason: e, retry: retry) }60 else { ProgressView().controlSize(.small) }61 }62 }63}6465// MARK: - Capital6667private struct OpsCapitalCard: View {68 let model: AppModel69 let data: OpsMonitorModel7071 var body: some View {72 OpsSectionCard(title: "Capital", section: data.capital, asOf: { $0.asOf }, retry: { Task { await data.reloadCapital() } }) { c in73 Text("Trois natures d’argent, jamais additionnées : le portefeuille (réel, sur la chaîne), les coffres d’agents (réels en mode LIVE, simulés en papier) et les comptes de dérivés (réels sur réseau principal, fonds de test sur testnet, simulés en papier). Il n’y a volontairement aucun total général.").font(.callout).foregroundStyle(.secondary)74 LazyVGrid(columns: [GridItem(.adaptive(minimum: 250), spacing: 12)], alignment: .leading, spacing: 12) {75 OpsFigure(kind: .real, title: "Portefeuille sur la chaîne", value: c.wallet.usd.map { OpsFmt.usd($0) } ?? "Indisponible",76 note: walletNote(c.wallet), unavailable: c.wallet.usd == nil)77 OpsFigure(kind: .real, title: "Agents en réel (LIVE)", value: OpsFmt.usd(c.totals.agentsLiveUsd), note: "Somme des valeurs connues des agents LIVE")78 OpsFigure(kind: .real, title: "Dérivés — plateformes, réseau principal", value: OpsFmt.usd(c.totals.derivVenueUsd), note: "Somme des comptes lus")79 OpsFigure(kind: .testnet, title: "Dérivés — testnet", value: OpsFmt.usd(c.totals.derivTestnetUsd), note: "Fonds de test : sans valeur, jamais comptés comme capital")80 OpsFigure(kind: .paper, title: "Agents en papier", value: OpsFmt.usd(c.totals.agentsPaperUsd), note: "Simulation")81 OpsFigure(kind: .paper, title: "Dérivés en papier", value: OpsFmt.usd(c.totals.derivPaperUsd), note: "Simulation")82 }83 Text("Positions ouvertes : \(c.counts.openPositions.agents) (agents), \(c.counts.openPositions.derivatives) (dérivés) · ordres ouverts : \(c.counts.openOrders.agents) (agents), \(c.counts.openOrders.derivatives) (dérivés) · agents par état : \(c.counts.agents.keys.sorted().map { "\(OpsText.agentState($0)) \(c.counts.agents[$0] ?? 0)" }.joined(separator: ", ").opsIfEmpty("aucun"))")84 .font(.callout).foregroundStyle(.secondary)85 if !c.agents.isEmpty {86 Divider(); Text("Agents").font(.subheadline.weight(.semibold))87 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {88 GridRow { Text("Agent"); Text("Nature"); Text("État"); Text("Capital alloué"); Text("Valeur"); Text("Positions"); Text("Valeur au") }.font(.caption).foregroundStyle(.secondary)89 ForEach(c.agents) { a in90 GridRow {91 Text(a.name).lineLimit(1)92 OpsBookTag(kind: a.real ? .real : .paper)93 VStack(alignment: .leading, spacing: 0) { Text(OpsText.agentState(a.state)); if let r = a.stopReason { Text(r).font(.caption).foregroundStyle(Theme.warning).lineLimit(2) } }94 Text(OpsFmt.usd(a.capitalUsd)).monospacedDigit()95 Text(a.equityUsd.map { OpsFmt.usd($0) } ?? "Aucun relevé").monospacedDigit().foregroundStyle(a.equityUsd == nil ? .secondary : .primary)96 Text("\(a.positions)").monospacedDigit()97 Text(Fmt.date(a.asOf)).font(.caption).foregroundStyle(.secondary).monospacedDigit()98 }99 }100 }101 }102 if !c.derivatives.isEmpty {103 Divider(); Text("Comptes de dérivés").font(.subheadline.weight(.semibold))104 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {105 GridRow { Text("Compte"); Text("Nature"); Text("Valeur"); Text("Marge utilisée"); Text("Latent"); Text("Pos. / ordres"); Text("Valeur au") }.font(.caption).foregroundStyle(.secondary)106 ForEach(c.derivatives) { d in107 GridRow {108 VStack(alignment: .leading, spacing: 0) {109 Text("\(d.label) · \(d.venue)").lineLimit(1)110 if let h = d.halt { Text("Arrêt : \(h)").font(.caption).foregroundStyle(Theme.negative) }111 if let dv = d.divergence { Text("Divergence : \(dv)").font(.caption).foregroundStyle(Theme.negative) }112 }113 OpsBookTag(kind: d.kind == "paper" ? .paper : d.real ? .real : .testnet)114 Text(d.equity.map { OpsFmt.usd($0) } ?? "Aucun relevé").monospacedDigit().foregroundStyle(d.equity == nil ? .secondary : .primary)115 Text(OpsFmt.usd(d.marginUsed)).monospacedDigit()116 Text(OpsFmt.signedUsd(d.unrealizedPnl)).monospacedDigit().foregroundStyle(Theme.change(d.unrealizedPnl))117 Text("\(d.positions) / \(d.openOrders)").monospacedDigit()118 Text(Fmt.date(d.asOf)).font(.caption).foregroundStyle(.secondary).monospacedDigit()119 }120 }121 }122 }123 }124 }125126 private func walletNote(_ w: MonitorCapital.Wallet) -> String {127 var parts = ["\(w.assets) actifs"]128 if let cad = w.cad { parts.append("≈ " + cad.formatted(.currency(code: "CAD").precision(.fractionLength(2)))) }129 if w.usd == nil { parts.append("aucun prix disponible : le total n’est pas calculé") }130 if w.unpriced > 0 { parts.append("\(w.unpriced) soldes sans prix, hors total") }131 if w.unavailable > 0 { parts.append("\(w.unavailable) soldes illisibles, hors total") }132 return parts.joined(separator: " · ") + (w.isComplete ? "" : " — estimation incomplète")133 }134}135136/// One headline figure with the nature of its money on it.137struct OpsFigure: View {138 let kind: OpsBookKind139 let title: String140 let value: String141 var note: String?142 var unavailable = false143 var body: some View {144 VStack(alignment: .leading, spacing: 4) {145 HStack { OpsBookTag(kind: kind); Spacer(); ProvenanceTag(p: unavailable ? .unavailable : kind.isSimulated ? .simulated : .estimate) }146 Text(title).font(.callout).foregroundStyle(.secondary)147 Text(value).font(.title3.weight(.semibold)).monospacedDigit().foregroundStyle(unavailable ? Theme.negative : .primary)148 if let note { Text(note).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }149 }150 .padding(12).frame(maxWidth: .infinity, alignment: .leading)151 .background(kind.color.opacity(0.05), in: RoundedRectangle(cornerRadius: 10))152 .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(kind.color.opacity(0.4), style: StrokeStyle(lineWidth: 1, dash: kind.isSimulated ? [4, 3] : [])))153 }154}155156// MARK: - Risk books (paper / testnet / real)157158private struct OpsBooksCard: View {159 let data: OpsMonitorModel160161 var body: some View {162 OpsSectionCard(title: "Livres de risque", section: data.summary, asOf: { $0.ts }, retry: { Task { await data.reloadSummary() } }) { s in163 Text("Trois livres séparés du service de risque. Chaque livre a sa propre date et son propre état ; aucun chiffre n’est additionné entre eux.").font(.callout).foregroundStyle(.secondary)164 OpsBookView(kind: .real, title: "Livre réel (réseau principal)", section: s.books.live)165 Divider()166 OpsBookView(kind: .testnet, title: "Livre testnet (fonds de test)", section: s.books.liveTestnet)167 Divider()168 OpsBookView(kind: .paper, title: "Livre papier (simulation)", section: s.books.paper)169 Divider()170 switch s.agentsPnl {171 case .ok(let p, let asOf):172 HStack { Text("Résultat des agents aujourd’hui, par mode").font(.subheadline.weight(.semibold)); Spacer(); OpsAsOf(date: asOf) }173 ForEach(p.today.keys.sorted(), id: \.self) { mode in174 if let m = p.today[mode] {175 HStack {176 OpsBookTag(kind: OpsBookKind(mode: mode))177 Text(m.abs.map { OpsFmt.signedUsd($0) } ?? "Aucun chiffre").monospacedDigit().foregroundStyle(m.abs == nil ? .secondary : Theme.change(m.abs))178 Text("\(m.agents) agents\(m.partial ? " · fenêtre partielle" : "")\(m.reason.map { " · \($0 == "research_no_pnl" ? "la recherche n’a pas de résultat" : $0 == "no_snapshot" ? "aucun relevé" : $0)" } ?? "")").font(.caption).foregroundStyle(.secondary)179 Spacer()180 }181 }182 }183 Text("Jour selon le fuseau \(p.tz). \(p.note == "flows_included" ? "Écarts de valeur : un dépôt ou un retrait dans la journée y est compté." : p.note)").font(.caption).foregroundStyle(.secondary)184 case .failed(let code, _): OpsUnavailable(what: "Résultat des agents aujourd’hui", reason: OpsText.sectionError(code))185 }186 }187 }188}189190private struct OpsBookView: View {191 let kind: OpsBookKind192 let title: String193 let section: DashboardSection<DashboardBook>194195 var body: some View {196 switch section {197 case .failed(let code, _):198 HStack { OpsBookTag(kind: kind); OpsUnavailable(what: title, reason: OpsText.sectionError(code)) }199 case .ok(let b, let asOf):200 VStack(alignment: .leading, spacing: 6) {201 HStack { OpsBookTag(kind: kind); Text(title).font(.subheadline.weight(.semibold)); Spacer(); OpsAsOf(date: asOf) }202 if !b.isComplete { Banner(.warning, "Livre incomplet — sources illisibles : \(b.errors.joined(separator: " ; ")). Les chiffres ci-dessous n’incluent pas ces comptes.") }203 if b.isEmpty && b.isComplete { Text("Aucun compte ni position dans ce livre.").foregroundStyle(.secondary) }204 else {205 HStack(spacing: 22) {206 OpsMini(label: "Valeur des comptes", value: "\(Fmt.amount(b.equity, maxFraction: 2)) USD")207 OpsMini(label: "Exposition brute", value: "\(Fmt.amount(b.grossExposure, maxFraction: 2)) USD")208 OpsMini(label: "Levier du livre", value: b.leverage.map { "\(Fmt.amount($0, maxFraction: 2))×" } ?? "—")209 if let p = b.pnl {210 OpsMini(label: "Réalisé aujourd’hui", value: "\(Fmt.amount(p.realizedToday, maxFraction: 2)) USD")211 OpsMini(label: "Latent aujourd’hui", value: "\(Fmt.amount(p.unrealizedToday, maxFraction: 2)) USD")212 }213 }214 if !b.positions.isEmpty {215 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {216 GridRow { Text("Position"); Text("Sens"); Text("Taille"); Text("Notionnel"); Text("Levier"); Text("Liquidation estimée"); Text("Latent") }.font(.caption).foregroundStyle(.secondary)217 ForEach(Array(b.positions.enumerated()), id: \.offset) { _, p in218 GridRow {219 Text("\(p.asset) · \(p.venue)").lineLimit(1)220 Text(p.side == "long" ? "Long" : p.side == "short" ? "Short" : p.side)221 Text(Fmt.amount(p.size, maxFraction: 6)).monospacedDigit()222 Text("\(Fmt.amount(p.notional, maxFraction: 2)) USD").monospacedDigit()223 Text("\(Fmt.amount(p.leverage, maxFraction: 2))×").monospacedDigit()224 Text(p.liquidationPrice.map { "\(Fmt.amount($0, maxFraction: 4))\(p.liquidationDistanceBps.map { " (à \(Fmt.amount($0, maxFraction: 0)) pb)" } ?? "")" } ?? "—").monospacedDigit()225 Text("\(Fmt.amount(p.unrealizedPnl, maxFraction: 2)) USD").monospacedDigit()226 }227 }228 }229 }230 }231 }232 }233 }234}235236struct OpsMini: View {237 let label: String; let value: String238 var body: some View { VStack(alignment: .leading, spacing: 1) { Text(label).font(.caption).foregroundStyle(.secondary); Text(value).monospacedDigit() } }239}240241// MARK: - PnL242243private struct OpsPnlCard: View {244 let data: OpsMonitorModel245246 var body: some View {247 OpsSectionCard(title: "Écarts de résultat", section: data.pnl, asOf: { $0.asOf }, retry: { Task { await data.reloadPnl() } }) { p in248 Text("Différences de valeur entre deux relevés enregistrés (aujourd’hui, 7 jours, 30 jours ; jour selon le fuseau \(p.tz)). \(p.note == "flows_included" ? "Un dépôt ou un retrait dans la fenêtre est compté comme résultat." : p.note) Ce ne sont pas des performances de stratégie, et les lignes simulées ne se comparent pas aux lignes réelles.").font(.callout).foregroundStyle(.secondary)249 if p.agents.isEmpty && p.derivatives.isEmpty { Text("Aucun agent ni compte de dérivés.").foregroundStyle(.secondary) }250 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {251 GridRow { Text("Ligne"); Text("Nature"); Text("Aujourd’hui"); Text("7 jours"); Text("30 jours"); Text("Valeur"); Text("Au") }.font(.caption).foregroundStyle(.secondary)252 ForEach(p.agents) { a in253 GridRow {254 Text("Agent · \(a.name)").lineLimit(1); OpsBookTag(kind: a.real ? .real : .paper)255 OpsPnlCell(f: a.today); OpsPnlCell(f: a.d7); OpsPnlCell(f: a.d30)256 Text(OpsFmt.usd(a.equity)).monospacedDigit(); Text(Fmt.date(a.asOf)).font(.caption).foregroundStyle(.secondary)257 }258 }259 ForEach(p.derivatives) { d in260 GridRow {261 Text("Dérivés · \(d.label)").lineLimit(1); OpsBookTag(kind: d.kind == "paper" ? .paper : d.real ? .real : .testnet)262 OpsPnlCell(f: d.today); OpsPnlCell(f: d.d7); OpsPnlCell(f: d.d30)263 Text(OpsFmt.usd(d.equity)).monospacedDigit(); Text(Fmt.date(d.asOf)).font(.caption).foregroundStyle(.secondary)264 }265 }266 }267 }268 }269}270271private struct OpsPnlCell: View {272 let f: MonitorPnlFigure?273 var body: some View {274 if let f {275 VStack(alignment: .leading, spacing: 0) {276 Text(OpsFmt.signedUsd(f.abs) + (f.pct.map { " (\(OpsFmt.fraction($0)))" } ?? "")).monospacedDigit().foregroundStyle(Theme.change(f.abs))277 if f.partial { Text("partiel, depuis \(f.from.formatted(date: .abbreviated, time: .omitted))").font(.caption2).foregroundStyle(Theme.warning) }278 }279 } else { Text("Aucun relevé").foregroundStyle(.secondary) }280 }281}282283// MARK: - Exposure284285private struct OpsExposureCard: View {286 let data: OpsMonitorModel287288 var body: some View {289 OpsSectionCard(title: "Exposition par actif", section: data.exposure, asOf: { $0.asOf }, retry: { Task { await data.reloadExposure() } }) { e in290 Text(e.caveat == "spot_and_perp_differ" ? "Le net est une indication de direction, pas un ratio de couverture : le comptant et les perpétuels sont des instruments différents." : e.caveat).font(.callout).foregroundStyle(.secondary)291 table(title: "Réel", kind: .real, rows: e.real)292 Divider()293 table(title: "Simulé et testnet (comptes papier, agents papier, comptes testnet)", kind: .paper, rows: e.simulated)294 }295 }296297 @ViewBuilder private func table(title: String, kind: OpsBookKind, rows: [MonitorExposure.Row]) -> some View {298 HStack { OpsBookTag(kind: kind); Text(title).font(.subheadline.weight(.semibold)) }299 if rows.isEmpty { Text("Aucune exposition.").foregroundStyle(.secondary) }300 else {301 Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 4) {302 GridRow { Text("Actif"); Text("Comptant"); Text("Perp. long"); Text("Perp. short"); Text("Net (indicatif)"); Text("Brut"); Text("") }.font(.caption).foregroundStyle(.secondary)303 ForEach(rows) { r in304 GridRow {305 Text(r.asset).fontWeight(.medium)306 Text(OpsFmt.usd(r.spotUsd)).monospacedDigit(); Text(OpsFmt.usd(r.perpLongUsd)).monospacedDigit(); Text(OpsFmt.usd(r.perpShortUsd)).monospacedDigit()307 Text(OpsFmt.signedUsd(r.netUsd)).monospacedDigit(); Text(OpsFmt.usd(r.grossUsd)).monospacedDigit()308 if r.priced { Text("") } else { Label("Incomplet : une position sans prix", systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.warning) }309 }310 }311 }312 }313 }314}315316extension String {317 func opsIfEmpty(_ other: String) -> String { isEmpty ? other : self }318}319