Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/TradingAgents/AgentDetailSections.swift10// Description : The reading sections of an agent: alerts, positions,11// timeline, orders, signals, journal and performance. Every12// list and figure belongs to ONE mode, framed with that13// mode's colour and label; paper and real are shown side by14// side, never added. A source that failed is shown as15// unavailable, a missing statistic with the server's reason.16// Module : Features17// Repository : https://git.spboucher.ai/sp-wallet-macos18// Created : 2026-11-1819// Last Modified : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import Charts95import SPWalletCore9697/// Chooses the mode of the mode-scoped lists; the band below names what is being looked at.98struct ModeScopePicker: View {99 @Bindable var d: AgentDetailStore100 var body: some View {101 VStack(alignment: .leading, spacing: 8) {102 Picker("Mode affiché", selection: $d.viewMode) {103 ForEach([AgentMode.research, .paper, .live], id: \.self) { Text(ModeKind($0, liveNetwork: d.agent?.liveNetwork).short).tag($0) }104 }.pickerStyle(.segmented).frame(maxWidth: 420)105 ModeHeaderBand(kind: ModeKind(d.viewMode, liveNetwork: d.agent?.liveNetwork))106 }107 }108}109110struct Unavailable: View {111 let what: String112 let error: String?113 var body: some View {114 if let error { Banner(.danger, "\(what) indisponible : \(error)") } else { HStack(spacing: 8) { ProgressView().controlSize(.small); Text("Lecture…").foregroundStyle(.secondary) } }115 }116}117118struct IndexedRow<T>: Identifiable { let id: Int; let value: T }119120// MARK: overview121122struct AgentOverviewSection: View {123 let model: AppModel124 let d: AgentDetailStore125126 var body: some View {127 alerts128 positions129 Card("Chronologie (signal → décision → ordre → exécution → erreur)") {130 ModeScopePicker(d: d)131 let kind = ModeKind(d.viewMode, liveNetwork: d.agent?.liveNetwork)132 if let items = d.timeline[d.viewMode] {133 if items.isEmpty { Text("Aucun événement dans ce mode.").foregroundStyle(.secondary) }134 else {135 Table(items.prefix(200).enumerated().map { IndexedRow(id: $0.offset, value: $0.element) }) {136 TableColumn("Date") { r in Text(Fmt.dateSeconds(r.value.ts)).monospacedDigit() }.width(150)137 TableColumn("Type") { r in Text(r.value.type) }.width(90)138 TableColumn("Événement") { r in Text(r.value.title + (r.value.body.map { " — \($0)" } ?? "")).lineLimit(2).help(r.value.body ?? r.value.title).foregroundStyle(severityColor(r.value.severity)) }139 TableColumn("Code") { r in Text(r.value.code ?? "") .font(.caption) }.width(140)140 }.frame(height: min(CGFloat(items.prefix(200).count) * 30 + 34, 380)).modeFramed(kind)141 }142 } else { Unavailable(what: "Chronologie", error: d.error("timeline.\(d.viewMode.rawValue)")) }143 }144 }145146 @ViewBuilder private var alerts: some View {147 let a = d.agent, list = alertItems148 Card("Alertes") {149 if list.isEmpty { Label("Aucune alerte signalée par le serveur pour cet agent.", systemImage: "checkmark.circle").foregroundStyle(.secondary) }150 ForEach(Array(list.enumerated()), id: \.offset) { _, x in Banner(x.0, x.1) }151 if let j = d.journal[d.viewMode]?.filter({ ["warning", "error", "critical"].contains($0.severity ?? "") }).prefix(8), !j.isEmpty {152 Text("Derniers avertissements du journal · \(ModeKind(d.viewMode, liveNetwork: a?.liveNetwork).short)").font(.caption).foregroundStyle(.secondary)153 ForEach(Array(j)) { e in154 HStack(alignment: .firstTextBaseline, spacing: 8) {155 Image(systemName: e.severity == "warning" ? "exclamationmark.triangle.fill" : "exclamationmark.octagon.fill").foregroundStyle(severityColor(e.severity))156 Text(Fmt.dateSeconds(e.ts)).font(.caption).monospacedDigit().foregroundStyle(.secondary)157 Text(e.title + (e.body.map { " — \($0)" } ?? "")).font(.callout).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)158 }159 }160 }161 }162 }163164 private var alertItems: [(Banner.Kind, String)] {165 var out: [(Banner.Kind, String)] = []166 guard let a = d.agent else { return out }167 if let r = a.stopReason, !r.isEmpty { out.append((.warning, "Motif d’arrêt : \(r)")) }168 for (label, v) in [("Suspension", a.hold), ("Signalement", a.flag), ("Fermeture en cours", a.flattening)] {169 if let v, !v.isNull, v.boolValue != false { out.append((.warning, "\(label) : \(JSONFlat.rows(v).map { "\($0.key) = \($0.value)" }.joined(separator: " · "))")) }170 }171 if case .spot(let s)? = d.detail {172 if let m = s.mandateStatus {173 if m.revoked { out.append((.info, "Le mandat de cet agent est révoqué au signataire.")) }174 else if m.expired { out.append((.warning, "Le mandat a expiré le \(Fmt.date(m.expiry)) : plus aucun échange n’est signé.")) }175 else if m.active, m.expiry.timeIntervalSinceNow < 3 * 86_400 { out.append((.warning, "Le mandat expire \(Fmt.relative(m.expiry)).")) }176 }177 if s.vault == nil, a.hasVault { out.append((.danger, "Les soldes du coffre n’ont pas pu être lus sur la chaîne. Ce n’est pas un coffre vide.")) }178 }179 if case .perp(let p)? = d.detail {180 if let h = p.account?.halt { out.append((.warning, "Disjoncteur du compte PAPIER : \(h)")) }181 if let e = p.live?.exit { out.append((.warning, "Sortie du réel (\(Fmt.date(e.ts))) : \(e.reason) [\(e.code)]")) }182 for h in p.live?.holds ?? [] { out.append((.warning, "Retenue \(h.symbol) (\(h.bar)) : \(h.reason) [\(h.code)]")) }183 if let w = p.windDown { out.append((.warning, "Fermeture en cours\(w.until.map { " jusqu’au \(Fmt.date($0))" } ?? "") : \(w.text ?? "") · \(w.openPositions.map(String.init) ?? "?") position(s), \(w.openOrders.map(String.init) ?? "?") ordre(s) ouverts.")) }184 }185 if let h = d.overview?.runtime?.hold, !h.isNull, h.boolValue != false { out.append((.warning, "Suspension du moteur : \(JSONFlat.rows(h).map { "\($0.key) = \($0.value)" }.joined(separator: " · "))")) }186 if let w = d.overview?.worker?.lease, !w.active, d.summary?.state == .active { out.append((.warning, "L’agent est actif mais le bail de son travailleur a expiré : il n’est peut-être traité par aucun processus.")) }187 for j in d.overview?.jobs.filter({ $0.status == .failed || $0.deadLettered == true }).prefix(3) ?? [] { out.append((.warning, "Tâche \(j.kind) en échec\(j.error.map { " : \($0)" } ?? "").")) }188 return out189 }190191 @ViewBuilder private var positions: some View {192 switch d.detail {193 case .spot(let s):194 Card("Coffre — soldes réels", trailing: AnyView(ProvenanceTag(p: s.vault == nil ? .unavailable : .verified))) {195 if let v = s.vault {196 if v.isEmpty { Text("Le coffre ne détient rien sur ce réseau.").foregroundStyle(.secondary) }197 ForEach(v) { b in VaultBalanceRow(balance: b) }198 Text("Ces soldes sont de l’argent réel quel que soit le mode de l’agent. Détail, dépôt et retour dans l’onglet Coffre.").font(.caption).foregroundStyle(.secondary)199 } else { Banner(.danger, "Soldes illisibles sur la chaîne pour l’instant. Ce n’est pas un solde nul.") }200 }201 if let p = s.paper {202 let kind = ModeKind(.paper)203 Card("Positions simulées", trailing: AnyView(ModeTag(kind: kind))) {204 VStack(alignment: .leading, spacing: 6) {205 ForEach(p.positions, id: \.symbol) { x in206 HStack { AssetBadge(symbol: x.symbol, size: 24); Text(x.symbol).fontWeight(.medium); Spacer(); Text("\(Fmt.amount(x.units, maxFraction: 8)) · \(AgentText.usd(x.usd).map { "≈ \($0)" } ?? "valeur inconnue")").monospacedDigit() }207 }208 HStack { Text("Liquidités simulées (\(p.cashSymbol))"); Spacer(); Text(AgentText.usd(p.cashUsd) ?? "—").monospacedDigit() }209 Text("Portefeuille PAPIER au \(Fmt.date(p.asOf)) : rien de ceci n’existe sur la chaîne et rien ne s’ajoute aux soldes réels du coffre.").font(.caption).foregroundStyle(.secondary)210 }.modeFramed(kind)211 }212 }213 case .perp(let p):214 if let acct = p.account {215 let kind = ModeKind(.paper)216 Card("Positions du compte simulé", trailing: AnyView(ModeTag(kind: kind))) {217 VStack(alignment: .leading, spacing: 8) {218 JSONFacts(value: acct.state, depth: 1, empty: "État du compte simulé indisponible.")219 Text("Positions (\(acct.positions.count))").font(.callout.weight(.medium))220 JSONList(items: acct.positions, empty: "Aucune position simulée.")221 }.modeFramed(kind)222 }223 }224 if let l = p.live, l.active || l.account != nil {225 let kind = ModeKind(.live, liveNetwork: l.network)226 Card("Compte réel sur la plateforme", trailing: AnyView(ModeTag(kind: kind))) {227 JSONFacts(value: l.account, depth: 2, empty: "Le compte de la plateforme n’a pas été lu.").modeFramed(kind)228 }229 }230 case .runtime:231 if let b = d.overview?.runtime?.book {232 let kind = ModeKind(b.simulated ? .paper : d.summary?.mode ?? .unknown)233 Card("Carnet de l’agent", trailing: AnyView(ModeTag(kind: kind))) {234 VStack(alignment: .leading, spacing: 8) {235 HStack(spacing: 10) {236 ModeFigure(label: "PnL réalisé", value: AgentText.usd(b.realizedPnl), kind: kind, reason: "non rapporté")237 ModeFigure(label: "Frais", value: AgentText.usd(b.fees), kind: kind, reason: "non rapporté")238 ModeFigure(label: "Financement", value: AgentText.usd(b.funding), kind: kind, reason: "non rapporté")239 }240 Text("Positions").font(.callout.weight(.medium)); JSONFacts(value: b.positions, empty: "Aucune position.")241 if let q = b.quotes, !q.isNull { Text("Cotations").font(.callout.weight(.medium)); JSONFacts(value: q) }242 if let pr = b.pair, !pr.isNull { Text("Paire").font(.callout.weight(.medium)); JSONFacts(value: pr) }243 }.modeFramed(kind)244 }245 } else { Card("Positions") { Text("Cet agent ne publie pas de carnet de positions.").foregroundStyle(.secondary) } }246 case nil: EmptyView()247 }248 }249}250251func severityColor(_ s: String?) -> Color {252 switch s { case "error", "critical": Theme.negative; case "warning": Theme.warning; default: .primary }253}254255struct VaultBalanceRow: View {256 let balance: VaultBalance257 var body: some View {258 HStack(spacing: 10) {259 AssetBadge(symbol: balance.assetSymbol, size: 26)260 VStack(alignment: .leading, spacing: 1) {261 Text("\(balance.assetSymbol) — \(balance.name)").fontWeight(.medium)262 Text(balance.role == "gas" ? "gaz (paie les frais, non négocié)" : balance.role == "cash" ? "monnaie de règlement" : "actif négocié").font(.caption).foregroundStyle(.secondary)263 }264 Spacer()265 VStack(alignment: .trailing, spacing: 1) {266 Text("\(Fmt.amount(balance.display, maxFraction: 8)) \(balance.assetSymbol)").monospacedDigit()267 Text(AgentText.usd(balance.usd).map { "≈ \($0)" } ?? "sans prix").font(.caption).foregroundStyle(.secondary)268 }269 }.accessibilityElement(children: .combine)270 }271}272273// MARK: activity274275struct AgentActivitySection: View {276 let d: AgentDetailStore277 enum Kind: String, CaseIterable { case orders = "Ordres", signals = "Signaux", journal = "Journal" }278 @State private var what: Kind = .orders279280 var body: some View {281 let m = d.viewMode, kind = ModeKind(m, liveNetwork: d.agent?.liveNetwork)282 Card("Activité") {283 ModeScopePicker(d: d)284 Picker("Liste", selection: $what) { ForEach(Kind.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).frame(maxWidth: 320).labelsHidden()285 switch what {286 case .orders:287 if m == .research { Text("La recherche n’émet aucun ordre : ses résultats sont des rapports de backtest (onglet Stratégie).").foregroundStyle(.secondary) }288 if let rows = d.orders[m] {289 if rows.isEmpty { Text("Aucun ordre dans ce mode.").foregroundStyle(.secondary) }290 else {291 Table(rows) {292 TableColumn("Date") { o in Text(Fmt.dateSeconds(o.ts)).monospacedDigit() }.width(150)293 TableColumn("Marché") { o in Text(o.instrument ?? "—") }.width(120)294 TableColumn("Sens") { o in Text((o.side ?? "—") + (o.reduceOnly == true ? " · réducteur" : "")) }.width(110)295 TableColumn("Taille / notionnel") { o in Text("\(Fmt.amount(o.size, maxFraction: 8)) / \(Fmt.amount(o.notional, maxFraction: 2))").monospacedDigit() }.width(170)296 TableColumn("Exécuté") { o in Text(o.filledSize.map { "\(Fmt.amount($0, maxFraction: 8)) @ \(Fmt.amount(o.avgFillPrice, maxFraction: 6))" } ?? "—").monospacedDigit() }.width(170)297 TableColumn("État") { o in Text(o.state).fontWeight(o.state == "FILLED" ? .semibold : .regular).foregroundStyle(["REJECTED", "FAILED"].contains(o.state) ? Theme.negative : .primary) }.width(100)298 TableColumn("Motif") { o in Text(o.reason ?? o.detail ?? "").lineLimit(1).help(o.detail ?? o.reason ?? "") }299 }.frame(height: min(CGFloat(rows.count) * 28 + 34, 420)).modeFramed(kind)300 Text("Seul l’état FILLED est une exécution. \(m == .live ? "Ordres réels, tels que la plateforme ou la chaîne les a rapportés." : "Ordres et exécutions SIMULÉS : aucun argent n’a bougé.")").font(.caption).foregroundStyle(.secondary)301 }302 } else { Unavailable(what: "Ordres", error: d.error("orders.\(m.rawValue)")) }303 case .signals:304 if let rows = d.signals[m] {305 if rows.isEmpty { Text("Aucun signal dans ce mode.").foregroundStyle(.secondary) }306 else {307 Table(rows) {308 TableColumn("Date") { s in Text(Fmt.dateSeconds(s.ts)).monospacedDigit() }.width(150)309 TableColumn("Décision") { s in Text(s.decision ?? "—") }.width(110)310 TableColumn("État") { s in Text(s.status ?? "—") }.width(90)311 TableColumn("Fonds propres") { s in Text(Fmt.amount(s.equity, maxFraction: 2)).monospacedDigit() }.width(110)312 TableColumn("Cibles") { s in Text(s.targets.map(JSONFlat.text) ?? "—").lineLimit(1).help(s.targets?.displayText ?? "") }313 TableColumn("Raison") { s in Text([s.reasonCode, s.reason].compactMap { $0 }.joined(separator: " — ")).lineLimit(1).help(s.reason ?? "") }314 }.frame(height: min(CGFloat(rows.count) * 28 + 34, 420)).modeFramed(kind)315 }316 } else { Unavailable(what: "Signaux", error: d.error("signals.\(m.rawValue)")) }317 case .journal:318 if let rows = d.journal[m] {319 if rows.isEmpty { Text("Journal vide dans ce mode.").foregroundStyle(.secondary) }320 else {321 Table(rows) {322 TableColumn("Date") { e in Text(Fmt.dateSeconds(e.ts)).monospacedDigit() }.width(150)323 TableColumn("Type") { e in Text(e.kind) }.width(100)324 TableColumn("Entrée") { e in Text(e.title + (e.body.map { " — \($0)" } ?? "")).lineLimit(2).help(e.body ?? e.title).foregroundStyle(severityColor(e.severity)) }325 TableColumn("Code") { e in Text(e.code ?? "").font(.caption) }.width(140)326 TableColumn("Config.") { e in Text(e.configVersion.map { "v\($0)" } ?? "") }.width(50)327 }.frame(height: min(CGFloat(rows.count) * 30 + 34, 420)).modeFramed(kind)328 }329 } else { Unavailable(what: "Journal", error: d.error("journal.\(m.rawValue)")) }330 }331 HStack { Spacer(); Button("Relire") { Task { await d.loadScoped() } } }332 }333 }334}335336// MARK: performance337338struct AgentPerformanceSection: View {339 let d: AgentDetailStore340341 var body: some View {342 Banner(.info, "Les performances sont lues mode par mode et ne sont JAMAIS additionnées. La recherche n’a pas de performance : ses chiffres sont des backtests (onglet Stratégie). Une performance passée, simulée ou réelle, ne promet rien.")343 ForEach([AgentMode.paper, .live], id: \.self) { m in344 let kind = ModeKind(m, liveNetwork: d.agent?.liveNetwork)345 Card(m == .paper ? "Performance sur papier" : "Performance en réel", trailing: AnyView(ModeTag(kind: kind))) {346 if let p = d.performance[m] { block(p, kind) } else { Unavailable(what: "Performance", error: d.error("performance.\(m.rawValue)")) }347 }348 }349 .task { await d.loadPerformance() }350 }351352 @ViewBuilder private func block(_ p: AgentPerformance, _ kind: ModeKind) -> some View {353 let partial = !p.warnings.isEmpty354 VStack(alignment: .leading, spacing: 10) {355 Text(p.label).font(.callout.weight(.medium)).textSelection(.enabled)356 Text("\(p.points) point(s)\(p.from.map { " du \(Fmt.date($0))" } ?? "")\(p.to.map { " au \(Fmt.date($0))" } ?? "") · \(p.orders) ordre(s) · \(p.closedTrades) transaction(s) clôturée(s)").font(.caption).foregroundStyle(.secondary)357 ForEach(p.warnings, id: \.self) { w in Banner(.warning, "Chiffres partiels — \(w.message) [\(w.code)]") }358 if p.points == 0 { Text("Aucune donnée dans ce mode : aucun chiffre n’est affiché.").foregroundStyle(.secondary) }359 else {360 LazyVGrid(columns: [GridItem(.adaptive(minimum: 170), alignment: .topLeading)], alignment: .leading, spacing: 10) {361 fig("PnL net", p.netPnlUsd, kind, partial, AgentText.usd, signed: true)362 fig("Rendement total", p.totalReturn, kind, partial, AgentText.ratio, signed: true)363 fig("Repli maximal", p.maxDrawdown, kind, partial, AgentText.ratio)364 fig("Volatilité annualisée", p.volatility, kind, partial, AgentText.ratio)365 fig("Sharpe", p.sharpe, kind, partial) { AgentText.number($0) }366 fig("Sortino", p.sortino, kind, partial) { AgentText.number($0) }367 fig("Taux de réussite", p.winRate, kind, partial, AgentText.ratio)368 fig("Facteur de profit", p.profitFactor, kind, partial) { AgentText.number($0) }369 fig("Rotation", p.turnover, kind, partial) { AgentText.number($0) }370 fig("Frais", p.feesUsd, kind, partial, AgentText.usd)371 fig("Financement", p.fundingUsd, kind, partial, AgentText.usd)372 fig("Glissement", p.slippageUsd, kind, partial, AgentText.usd)373 }374 let curve = p.equityCurve.value375 if curve.count > 1 {376 Chart(curve, id: \.ts) { pt in LineMark(x: .value("Date", pt.ts), y: .value("Fonds propres", pt.equity)).foregroundStyle(kind.color) }377 .chartYScale(domain: .automatic(includesZero: false)).frame(height: 180)378 .accessibilityLabel("Courbe des fonds propres, \(kind.title)")379 Text("Fonds propres · \(kind.title)").font(.caption).foregroundStyle(kind.color)380 }381 }382 }.modeFramed(kind)383 }384385 private func fig(_ label: String, _ f: ModedFigure, _ kind: ModeKind, _ partial: Bool, _ format: (Double?) -> String?, signed: Bool = false) -> ModeFigure {386 // the figure carries its own mode: it is shown under that mode's colour, whatever block it sits in387 ModeFigure(label: label, value: format(f.value), kind: ModeKind(f.mode, liveNetwork: kind.liveNetwork), reason: f.reason, partial: partial && f.value != nil, tint: signed ? f.value.map { Theme.change($0) } : nil)388 }389}390