Repository Public
1// SP Wallet iOS2// File: Features/TradingAgents/AgentSimulationWorkspace.swift3// Description: The SIMULATION workspace of an agent: the strategy library (pinning a version starts its backtest and approves4// nothing), backtest jobs and their progress, the laboratory report of each version — every figure labelled5// "simulation sur données historiques — ne garantit rien", the look-ahead check and the lab verdict as served — and6// the approval of a strategy version (no passkey: it gives no authority over funds; the server refuses a version7// without a report or whose look-ahead check failed). Research signals and journal are read in research mode only.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import SwiftUI12import SPWalletCore1314struct AgentSimulationWorkspace: View {15 @Environment(AppModel.self) private var model16 let page: AgentPageModel17 let store: AgentsStore18 @State private var library: [LibraryStrategy]?19 @State private var libraryError: Error?20 @State private var verdicts: [LabVerdict] = []21 @State private var job: AgentJob?22 @State private var jobError: Error?23 @State private var confirmation: AgentConfirmation?24 @State private var records: ModeRecords25 @State private var showLibrary = false2627 init(page: AgentPageModel, store: AgentsStore) {28 self.page = page; self.store = store29 _records = State(initialValue: ModeRecords(agentId: page.id, mode: .research))30 }3132 private var api: AgentsAPI { AgentsAPI(model.env.client) }33 private var versions: [StrategyVersion] {34 switch page.detail {35 case .spot(let d): d.versions36 case .perp(let d): d.versions37 default: page.overview?.backtests.versions ?? []38 }39 }40 private var usesLibrary: Bool { page.agent?.resolvedKind == .spot || page.agent?.resolvedKind == .perp }4142 var body: some View {43 if let a = page.agent {44 AgentModeBand(mode: .research)45 if let note = page.overview?.backtests.note { Notice(tone: .info, title: String(localized: "Ce qu’est un backtest, selon le serveur"), message: note) }46 versionsCard(a)47 backtestCard(a)48 if let rec = page.overview?.backtests.recorded, !rec.isNull {49 AgentCard(title: String(localized: "Rejeu enregistré (simulation)")) {50 JSONFields(value: rec)51 SimulationTag()52 }53 }54 if !verdicts.isEmpty {55 AgentCard(title: String(localized: "Verdict du laboratoire")) {56 ForEach(Array(verdicts.enumerated()), id: \.offset) { _, v in LabVerdictView(verdict: v) }57 }58 }59 if usesLibrary { libraryCard(a) }60 researchRecords61 }62 }6364 // MARK: versions and their reports6566 @ViewBuilder private func versionsCard(_ a: Agent) -> some View {67 AgentCard(title: String(localized: "Versions de stratégie de cet agent")) {68 if versions.isEmpty {69 Text(page.detail == nil ? String(localized: "Indisponible hors ligne.") : usesLibrary ? String(localized: "Aucune version épinglée. Choisis-en une dans la bibliothèque ci-dessous : son backtest démarre aussitôt.") : String(localized: "Cet agent applique une règle intégrée : pas de version de bibliothèque."))70 .font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("agent.sim.noversion")71 }72 ForEach(versions) { v in73 VStack(alignment: .leading, spacing: 8) {74 HStack(spacing: 8) {75 Text("\(v.name) · v\(v.version)").font(.spHeadline).foregroundStyle(Theme.ink)76 Pill(text: Self.status(v.status), tone: v.isApproved ? .ok : v.status == "backtesting" ? .info : .neutral).accessibilityIdentifier("agent.sim.status.\(v.name)")77 if a.strategyVersionId == v.id { Pill(text: String(localized: "utilisée par l’agent"), tone: .info) }78 }79 FieldRow(label: String(localized: "Empreinte du code (SHA-256)"), value: v.sha256, mono: true, copyable: true)80 if v.status == "backtesting" { HStack(spacing: 8) { ProgressView(); Text(String(localized: "Backtest en cours…")).font(.spCallout).foregroundStyle(Theme.mute) } }81 LabReportView(version: v, panelChecks: page.overview?.backtests.versions.first { $0.id == v.id }?.simulation.checks)82 if !v.isApproved, v.status != "backtesting", !v.simulation.isEmpty || v.hasReport == true, a.mode != .live {83 Button {84 confirmation = AgentConfirmation(title: String(localized: "Approuver \(v.name) v\(v.version) ?"),85 message: String(localized: "Tu attestes avoir lu ce rapport de SIMULATION. L’agent pourra exécuter cette version en papier, et un futur mandat épinglera son empreinte. Aucune clé d’accès n’est demandée : cette approbation ne donne aucune autorité sur des fonds. Le serveur refuse une version sans rapport ou dont le contrôle d’anticipation a échoué."),86 button: String(localized: "Approuver cette version")) {87 await page.act("approve-\(v.id)", model: model, store: store) {88 let r = try await api.approveStrategyVersion(agentId: a.id, versionId: v.id)89 return r.strategyVersionId == v.id ? String(localized: "Version approuvée · \(AgentStateLabel.of(r.state).text)") : String(localized: "Le serveur n’a pas retenu cette version (état : \(r.state)).")90 }91 }92 } label: { Label(String(localized: "Approuver cette version"), systemImage: "checkmark.seal") }93 .buttonStyle(.spSecondary).disabled(!model.canOperate || page.busy != nil).accessibilityIdentifier("agent.sim.approve")94 }95 }96 .padding(.vertical, 6)97 if v.id != versions.last?.id { Divider() }98 }99 }100 .agentConfirmation($confirmation)101 // a version that is still backtesting: look again a little later (slowly: the report takes about a minute)102 .task(id: versions.map(\.status).joined() + "\(store.revision)") {103 guard versions.contains(where: { $0.status == "backtesting" }), model.canOperate else { return }104 try? await Task.sleep(for: .seconds(6))105 if !Task.isCancelled { await page.load(model, store: store) }106 }107 .task(id: page.agent?.template) { await loadVerdicts() }108 }109110 static func status(_ s: String) -> String {111 switch s {112 case "draft": String(localized: "brouillon, non approuvée")113 case "backtesting": String(localized: "backtest en cours")114 case "approved": String(localized: "approuvée")115 case "retired": String(localized: "retirée")116 case "built_in": String(localized: "règle intégrée")117 default: s118 }119 }120121 // MARK: backtest job122123 @ViewBuilder private func backtestCard(_ a: Agent) -> some View {124 AgentCard(title: String(localized: "Backtest à la demande")) {125 Text(String(localized: "Lance une SIMULATION sur données historiques pour la version utilisée par l’agent. Le résultat est un rapport de simulation, jamais une performance.")).font(.spFootnote).foregroundStyle(Theme.mute)126 if let j = job {127 JobRow(job: j).accessibilityIdentifier("agent.sim.job")128 if !j.status.isFinished { HStack(spacing: 8) { ProgressView(); Text(String(localized: "Suivi de la tâche…")).font(.spFootnote).foregroundStyle(Theme.mute) } }129 if j.status == .failed || (j.error?.isEmpty == false) {130 Notice(tone: .danger, title: String(localized: "Le backtest n’a pas abouti"), message: j.error ?? String(localized: "Le serveur n’a pas donné de raison.")).accessibilityIdentifier("agent.sim.job.error")131 }132 if j.status == .done { ServerDetail(title: String(localized: "Résultat de la tâche (simulation)"), value: j.result); SimulationTag() }133 }134 if let jobError { ErrorNotice(error: jobError).accessibilityIdentifier("agent.sim.job.refused") }135 Button {136 Task {137 jobError = nil138 do { job = try await api.requestBacktest(a.id, versionId: a.strategyVersionId ?? versions.first?.id).job } catch { jobError = error }139 }140 } label: { Label(String(localized: "Demander un backtest"), systemImage: "flask") }141 .buttonStyle(.spSecondary).disabled(!model.canOperate || (job != nil && job?.status.isFinished == false)).accessibilityIdentifier("agent.sim.backtest")142 }143 .task(id: job?.id) {144 guard let id = job?.id else { return }145 // poll slowly until the job ends (the queue is served every 5 s; a failed attempt is retried a minute later)146 for _ in 0..<60 {147 if job?.status.isFinished == true || Task.isCancelled { break }148 try? await Task.sleep(for: .seconds(4))149 if let j = try? await api.job(id) { job = j }150 }151 if job?.status == .done { await page.load(model, store: store) }152 }153 }154155 // MARK: library156157 @ViewBuilder private func libraryCard(_ a: Agent) -> some View {158 AgentCard(title: String(localized: "Bibliothèque de stratégies")) {159 Text(String(localized: "Épingler une version à l’agent lance son backtest. Cela n’écrit aucun code et n’approuve rien.")).font(.spFootnote).foregroundStyle(Theme.mute)160 if !showLibrary {161 Button { showLibrary = true } label: { Label(String(localized: "Afficher la bibliothèque"), systemImage: "books.vertical") }.buttonStyle(.spSecondary).disabled(!model.canOperate).accessibilityIdentifier("agent.sim.library")162 } else if let library {163 if library.isEmpty { Text(String(localized: "La bibliothèque est vide sur ce serveur.")).font(.spCallout).foregroundStyle(Theme.mute) }164 ForEach(library) { s in165 let fits = Self.fits(s, agent: a)166 VStack(alignment: .leading, spacing: 5) {167 HStack { Text("\(s.meta.name) · v\(s.meta.version)").font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink); Spacer(); Text(s.meta.interval).font(.spFootnote).foregroundStyle(Theme.mute) }168 Text(s.generic == true ? String(localized: "Univers libre : les marchés de l’agent (\(s.minSymbols ?? 1) à \(s.maxSymbols ?? 12))") : String(localized: "Univers fixe : \(s.meta.universe.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute)169 Text(s.sha256).font(.system(size: 11, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled)170 if let r = s.readme, !r.isEmpty { DisclosureGroup(String(localized: "Notice de la stratégie")) { Text(r).font(.spFootnote).foregroundStyle(Theme.ink).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.font(.spFootnote) }171 if let why = fits { Text(why).font(.spFootnote).foregroundStyle(Theme.warn) }172 Button {173 confirmation = AgentConfirmation(title: String(localized: "Épingler \(s.meta.name) v\(s.meta.version) ?"), message: String(localized: "La version est épinglée à l’agent par son empreinte et son backtest (une SIMULATION) démarre. Rien n’est approuvé et l’agent ne change pas de mode."), button: String(localized: "Épingler et lancer le backtest")) {174 await page.act("register", model: model, store: store) {175 let r = try await api.registerStrategy(a.id, s)176 return String(localized: "Version épinglée · \(Self.status(r.status))")177 }178 }179 } label: { Text(String(localized: "Épingler à l’agent")).font(.spCallout.weight(.semibold)) }180 .buttonStyle(.bordered).disabled(!model.canOperate || page.busy != nil).accessibilityIdentifier("agent.sim.register.\(s.registrationPath)")181 }182 .padding(.vertical, 8)183 Divider()184 }185 } else if let libraryError { ErrorNotice(error: libraryError) }186 else { ProgressView() }187 }188 .task(id: showLibrary) {189 guard showLibrary, library == nil, model.canOperate else { return }190 do { library = try await (a.resolvedKind == .perp ? api.perpStrategyLibrary() : api.strategyLibrary()); libraryError = nil } catch { libraryError = error }191 }192 }193194 /** A remark only — the server decides. Nil when nothing obvious prevents the registration. */195 static func fits(_ s: LibraryStrategy, agent a: Agent) -> String? {196 if s.generic == true {197 if let lo = s.minSymbols, a.universe.count < lo { return String(localized: "Demande au moins \(lo) marchés ; l’agent en a \(a.universe.count).") }198 if let hi = s.maxSymbols, a.universe.count > hi { return String(localized: "Accepte au plus \(hi) marchés ; l’agent en a \(a.universe.count).") }199 return nil200 }201 return Set(s.meta.universe) == Set(a.universe) ? nil : String(localized: "Son univers fixe diffère des marchés de l’agent : le serveur peut refuser.")202 }203204 private func loadVerdicts() async {205 guard model.canOperate, let t = page.agent?.template else { return }206 if let all = try? await api.templates(), let mine = all.templates.first(where: { $0.id == t }) { verdicts = mine.labVerdicts ?? [] }207 }208209 // MARK: research records210211 @ViewBuilder private var researchRecords: some View {212 AgentCard(title: String(localized: "Décisions en simulation")) {213 Text(String(localized: "En mode simulation l’agent enregistre ses décisions sans passer aucun ordre.")).font(.spFootnote).foregroundStyle(Theme.mute)214 if let e = records.errors[.signals] ?? records.errors[.journal] {215 if (e as? APIError)?.code == "mode_mismatch" { Notice(tone: .danger, title: String(localized: "Réponse d’un autre mode refusée"), message: "mode_mismatch") } else { ErrorNotice(error: e) }216 }217 if let s = records.signals, !s.isEmpty {218 Text(String(localized: "Signaux")).font(.spCallout.weight(.semibold))219 AgentRows(items: Array(s.prefix(30))) { x in LogLine(ts: x.ts, title: x.decision ?? x.status ?? "—", body: x.reason, severity: nil, code: x.reasonCode, extra: x.targets) }220 }221 if let j = records.journal, !j.isEmpty {222 Text(String(localized: "Journal")).font(.spCallout.weight(.semibold))223 AgentRows(items: Array(j.prefix(30))) { e in LogLine(ts: e.ts, title: e.title, body: e.body, severity: e.severity, code: e.code, extra: e.data) }224 }225 if records.signals?.isEmpty == true, records.journal?.isEmpty == true { Text(String(localized: "Rien d’enregistré en simulation pour le moment.")).font(.spCallout).foregroundStyle(Theme.mute) }226 SimulationTag()227 }228 .task(id: store.revision) {229 guard model.canOperate else { return }230 await records.load(.signals, api: api); await records.load(.journal, api: api)231 }232 }233}234235struct SimulationTag: View {236 var body: some View {237 Label(ModeGuard.label(.research), systemImage: "flask.fill").font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.blue)238 }239}240241/** The backtest report of one strategy version. Simulation figures only; each one carries the simulation label. */242struct LabReportView: View {243 let version: StrategyVersion244 /** The checks of the same version as the agent panel serves them (the historical detail of a spot agent does not carry them). */245 var panelChecks: JSONValue?246 private static let splits = ["test", "validation", "train"]247 private static let rows: [(String, String, Bool)] = [248 ("total_return", String(localized: "Rendement total"), true), ("cagr", String(localized: "Rendement annualisé"), true), ("max_drawdown", String(localized: "Repli maximal"), true),249 ("sharpe", "Sharpe", false), ("sortino", "Sortino", false), ("volatility", String(localized: "Volatilité"), true), ("win_rate", String(localized: "Taux de réussite"), true),250 ("profit_factor", String(localized: "Facteur de profit"), false), ("trades", String(localized: "Ordres simulés"), false), ("fees_paid", String(localized: "Frais simulés (USD)"), false),251 ("slippage_paid", String(localized: "Glissement simulé (USD)"), false), ("funding_pnl", String(localized: "Financement simulé (USD)"), false), ("liquidations", String(localized: "Liquidations simulées"), false),252 ]253 static func splitName(_ s: String) -> String {254 switch s { case "test": String(localized: "Test (hors échantillon)"); case "validation": String(localized: "Validation"); case "train": String(localized: "Entraînement"); default: s }255 }256257 private var sim: SimulationFigures { version.simulation }258 private var metrics: [String: JSONValue]? { sim.metrics?.objectValue ?? version.perpSummary?.metrics.map { $0.compactMapValues { $0 } } }259 private var checks: JSONValue? { sim.checks ?? version.perpSummary?.checks ?? panelChecks }260261 var body: some View {262 if let problem = version.perpSummary?.problem {263 Notice(tone: .danger, title: String(localized: "Cette version ne peut pas être approuvée"), message: problem)264 }265 if let m = metrics, !m.isEmpty {266 VStack(alignment: .leading, spacing: 10) {267 Notice(tone: .info, title: String(localized: "Rapport de simulation"), message: String(localized: "Simulation sur données historiques — ne garantit rien. Ce n’est ni un historique de performance ni une promesse."), icon: "flask.fill")268 .accessibilityIdentifier("agent.sim.report")269 lookahead270 ForEach(Self.splits.filter { m[$0]?.objectValue != nil }, id: \.self) { split in271 Text(Self.splitName(split)).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.ink)272 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 8, alignment: .top)], spacing: 8) {273 ForEach(Self.rows.filter { m[split]?[$0.0]?.doubleValue != nil }, id: \.0) { key, title, pct in274 let v = m[split]?[key]?.doubleValue ?? 0275 FigureCell(title: title, value: pct ? AgentFmt.percent(fraction: v) : AgentFmt.number(v, max: 2), reason: nil, mode: sim.mode)276 }277 }278 }279 if let b = sim.benchmarks ?? version.perpSummary?.benchmarks, let bh = b["buy_and_hold"]?["total_return"]?.doubleValue {280 FieldRow(label: version.perpSummary?.buyAndHoldIsSpot == false ? String(localized: "Référence « acheter et garder » (le contrat lui-même, pas le comptant) — simulation") : String(localized: "Référence « acheter et garder » sur la même période — simulation"), value: AgentFmt.percent(fraction: bh))281 }282 if let liq = version.perpSummary?.liquidations, liq.values.contains(where: { $0 > 0 }) {283 Notice(tone: .warn, title: String(localized: "Liquidations dans la simulation"), message: liq.keys.sorted().map { "\(Self.splitName($0)) : \(liq[$0] ?? 0)" }.joined(separator: " · "))284 }285 DisclosureGroup(String(localized: "Rapport complet tel que servi")) {286 ServerDetail(title: String(localized: "Hypothèses et configuration"), value: sim.config ?? version.perpSummary?.config)287 ServerDetail(title: String(localized: "Contrôles"), value: checks)288 ServerDetail(title: String(localized: "Robustesse"), value: sim.robustness ?? version.perpSummary?.robustness)289 ServerDetail(title: String(localized: "Modèle d’exécution"), value: version.perpSummary?.executionModel)290 ServerDetail(title: String(localized: "Biais des données"), value: version.perpSummary?.dataBias)291 }.font(.spCallout)292 }293 } else if version.status != "backtesting" {294 Text(String(localized: "Aucun rapport de simulation pour cette version.")).font(.spFootnote).foregroundStyle(Theme.mute)295 }296 }297298 @ViewBuilder private var lookahead: some View {299 let l = checks?["lookahead"]?.stringValue300 HStack(spacing: 8) {301 Text(String(localized: "Contrôle d’anticipation (look-ahead), tel que servi :")).font(.spFootnote).foregroundStyle(Theme.mute)302 Pill(text: l ?? String(localized: "non rapporté"), tone: l == "pass" ? .ok : l == nil ? .neutral : .danger, icon: l == "pass" ? "checkmark" : nil)303 .accessibilityElement(children: .combine).accessibilityIdentifier("agent.sim.lookahead")304 }305 if let dq = checks?["data_quality"]?.stringValue {306 HStack(spacing: 8) { Text(String(localized: "Qualité des données :")).font(.spFootnote).foregroundStyle(Theme.mute); Pill(text: dq, tone: dq == "pass" ? .ok : .warn) }307 }308 }309}310311/** The laboratory's own out-of-sample verdict, as served. Simulation. */312struct LabVerdictView: View {313 let verdict: LabVerdict314 var body: some View {315 VStack(alignment: .leading, spacing: 6) {316 HStack(spacing: 8) {317 Text(verdict.name + (verdict.version.map { " · v\($0)" } ?? "")).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)318 if verdict.available {319 Pill(text: verdict.significant == true ? String(localized: "significatif selon le labo") : verdict.significant == false ? String(localized: "NON significatif selon le labo") : String(localized: "non tranché"),320 tone: verdict.significant == true ? .ok : verdict.significant == false ? .danger : .neutral)321 }322 }323 if !verdict.available {324 Text(String(localized: "Verdict indisponible : \(verdict.reason ?? "—")")).font(.spFootnote).foregroundStyle(Theme.mute)325 } else {326 if let d = verdict.deflatedSharpe, let t = verdict.deflatedSharpeThreshold { FieldRow(label: String(localized: "Sharpe dégonflé · seuil du labo"), value: "\(AgentFmt.number(d, max: 4)) · \(AgentFmt.number(t, max: 2))" + (verdict.trialsTested.map { " · " + String(localized: "\(Int($0)) essais") } ?? "")) }327 ForEach(["test", "validation", "train"], id: \.self) { k in328 if let s = verdict.splits?[k] ?? nil {329 FieldRow(label: LabReportView.splitName(k) + " — " + ModeGuard.label(.research),330 value: [s.netReturn.map { String(localized: "rendement net \(AgentFmt.percent(fraction: $0))") }, s.netSharpe.map { "Sharpe net \(AgentFmt.number($0, max: 2))" }, s.maxDrawdown.map { String(localized: "repli \(AgentFmt.percent(fraction: $0))") }].compactMap { $0 }.joined(separator: " · "),331 tone: (s.netReturn ?? 0) < 0 ? .danger : nil)332 if let stop = s.stop { Text(String(localized: "Arrêté par sa propre limite : \(stop.reason) (\(stop.code))")).font(.spFootnote).foregroundStyle(Theme.warn) }333 }334 }335 if let c = verdict.checks { Text(c.keys.sorted().map { "\($0) : \(c[$0] ?? "")" }.joined(separator: " · ")).font(.spFootnote).foregroundStyle(Theme.mute) }336 if let s = verdict.statement { Text(s).font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true) }337 if verdict.liveCapable == false { Text(String(localized: "Non éligible au réel selon le labo (portée : \(verdict.scope ?? "—")).")).font(.spFootnote).foregroundStyle(Theme.warn) }338 }339 SimulationTag()340 }341 .padding(.vertical, 6)342 }343}344