Repository Public
1// SP Wallet iOS2// File: Features/TradingAgents/AgentMarketMakingWorkspace.swift3// Description: Market-making agents. The backend's own evidence is shown as it is (the laboratory study and the simulation are4// NEGATIVE), then — PAPIER and RÉEL never on the same screen — the session, its quotes, fills and attribution of one5// mode, the go-live checklist and its acknowledgements as served, the server locks by name, and the owner commands6// that only remove risk (pull the quotes, flatten the inventory) or resume quoting. Approving a live quoting mandate7// is NOT offered in this version: the app cannot yet verify that object locally, so it refuses to approve it blind.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import SwiftUI12import SPWalletCore1314@MainActor @Observable15final class MarketMakingModel {16 let agentId: String17 var evidence: MarketMakingEvidence?18 var bounds: MarketMakingBounds?19 var view: MarketMakingView?20 var fills: [MarketMakingFill]?21 var performance: MarketMakingPerformance?22 var error: Error?23 var staticError: Error?24 var loadedMode: AgentMode?2526 init(agentId: String) { self.agentId = agentId }2728 func loadStatic(_ api: AgentsAPI) async {29 do {30 if evidence == nil { evidence = try await api.marketMakingEvidence(locale: "fr") }31 if bounds == nil { bounds = try await api.marketMakingBounds() }32 staticError = nil33 } catch { staticError = error }34 }3536 /** One mode at a time; an answer of the other mode is refused by the Core and leaves nothing on screen. */37 func load(_ api: AgentsAPI, mode: AgentMode) async {38 if loadedMode != mode { view = nil; fills = nil; performance = nil }39 loadedMode = mode40 do {41 let v = try await api.marketMaking(agentId, mode: mode)42 let f = try ModeGuard.scoped(try await api.marketMakingFills(agentId, mode: mode, limit: 100), heading: mode)43 let p = try await api.marketMakingPerformance(agentId, mode: mode)44 try ModeGuard.check(p.mode, heading: mode)45 guard loadedMode == mode else { return }46 view = v; fills = f; performance = p; error = nil47 } catch {48 guard loadedMode == mode else { return }49 view = nil; fills = nil; performance = nil; self.error = error50 }51 }52}5354struct AgentMarketMakingWorkspace: View {55 @Environment(AppModel.self) private var model56 @Environment(\.horizontalSizeClass) private var sizeClass57 let page: AgentPageModel58 let store: AgentsStore59 @State private var mm: MarketMakingModel60 @State private var mode: AgentMode = .paper61 @State private var confirmation: AgentConfirmation?62 @State private var ackEvidence = false63 @State private var ackJurisdiction = false64 @State private var testnetNote = ""6566 init(page: AgentPageModel, store: AgentsStore) {67 self.page = page; self.store = store68 _mm = State(initialValue: MarketMakingModel(agentId: page.id))69 }7071 private var api: AgentsAPI { AgentsAPI(model.env.client) }7273 var body: some View {74 if let a = page.agent {75 evidenceCard76 locksCard77 Picker(String(localized: "Mode affiché"), selection: $mode) {78 Text(AgentModeBadge.name(.paper)).tag(AgentMode.paper)79 Text(AgentModeBadge.name(.live)).tag(AgentMode.live)80 }.pickerStyle(.segmented).accessibilityIdentifier("mm.mode")81 AgentModeBand(mode: mode, detail: mode == .live ? mm.view?.session?.network : String(localized: "exécutions SIMULÉES sur des carnets réels"))82 if let e = mm.error {83 if (e as? APIError)?.code == "mode_mismatch" { Notice(tone: .danger, title: String(localized: "Réponse d’un autre mode refusée"), message: "mode_mismatch").accessibilityIdentifier("agent.records.mismatch") }84 else { ErrorNotice(error: e) { Task { await mm.load(api, mode: mode) } } }85 } else if let v = mm.view {86 sessionCard(v)87 commandsCard(a)88 fillsCard89 performanceCard90 if mode == .live { goLiveCard(v) }91 if !v.sessions.isEmpty {92 AgentCard(title: String(localized: "Sessions passées — \(AgentModeBadge.name(mode))")) {93 AgentRows(items: v.sessions) { s in94 FieldRow(label: s.label + " · " + s.instrument, value: [s.state, s.startedAt.map(AgentFmt.date), s.endReason, s.pnl?.totalUsd.map { String(localized: "résultat \($0) USD") }].compactMap { $0 }.joined(separator: " · "))95 }96 }97 }98 } else if model.canOperate { ProgressView().frame(maxWidth: .infinity, minHeight: 100) }99 else { Text(String(localized: "Indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }100 Color.clear.frame(height: 0)101 .task { if model.canOperate { await mm.loadStatic(api) } }102 .task(id: "\(mode.rawValue)-\(store.revision)") { if model.canOperate { await mm.load(api, mode: mode) } }103 .agentConfirmation($confirmation)104 }105 }106107 // MARK: evidence, as it is108109 @ViewBuilder private var evidenceCard: some View {110 AgentCard(title: String(localized: "Preuves du laboratoire et de la simulation")) {111 if let e = mm.evidence {112 Notice(tone: .danger, title: String(localized: "Résultats négatifs, montrés tels quels"), message: String(localized: "Ce qui suit vient du serveur, sans retouche : l’étude du laboratoire et la simulation de cette stratégie. Rien ici ne permet d’attendre un gain."), icon: "exclamationmark.triangle.fill")113 .accessibilityIdentifier("mm.evidence")114 if let r = e.evidence["lab"]?["result"]?.stringValue { FieldRow(label: String(localized: "Étude du laboratoire — résultat"), value: r, tone: .danger) }115 if let r = e.evidence["simulation"]?["result"]?.stringValue { FieldRow(label: String(localized: "Simulation — résultat"), value: r, tone: .danger) }116 if let f = e.evidence["fees"]?.stringValue { FieldRow(label: String(localized: "Frais"), value: f) }117 DisclosureGroup(String(localized: "Toutes les preuves servies")) { JSONFields(value: e.evidence) }.font(.spCallout)118 Text(String(localized: "Durée minimale en papier avant le réel : \(AgentFmt.number(e.minPaperMinutes, max: 0)) minutes.")).font(.spFootnote).foregroundStyle(Theme.mute)119 SimulationTag()120 } else if let s = mm.staticError { ErrorNotice(error: s) }121 else if model.canOperate { ProgressView() }122 else { Text(String(localized: "Indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }123 }124 }125126 @ViewBuilder private var locksCard: some View {127 if let b = mm.bounds {128 AgentCard(title: String(localized: "Verrous du serveur")) {129 ForEach([b.locks.testnet, b.locks.mainnet], id: \.network) { l in130 if let lock = l.lock {131 Notice(tone: .warn, title: String(localized: "\(l.network.uppercased()) verrouillé : \(lock.setting)"), message: "\(lock.message) (\(lock.code))").accessibilityIdentifier("mm.lock.\(l.network)")132 } else {133 FieldRow(label: l.network.uppercased(), value: String(localized: "aucun verrou rapporté (réglages consultés : \(l.consulted.joined(separator: ", ")))"))134 }135 }136 }137 }138 }139140 // MARK: session of ONE mode141142 @ViewBuilder private func sessionCard(_ v: MarketMakingView) -> some View {143 AgentCard(title: String(localized: "Session — \(AgentModeBadge.name(mode))")) {144 if let s = v.session {145 Text(s.label).font(.spCallout.weight(.semibold)).foregroundStyle(mode == .live ? Theme.danger : Theme.warn).accessibilityIdentifier("mm.session.label")146 VStack(alignment: .leading, spacing: 0) {147 FieldRow(label: String(localized: "État"), value: s.state + (s.stale ? " · " + String(localized: "son travailleur n’écrit plus depuis 20 s") : ""), tone: s.stale ? .warn : nil)148 Divider(); FieldRow(label: String(localized: "Contrat"), value: s.instrument + (s.network.map { " · " + $0 } ?? ""))149 if let st = s.status {150 if let p = st.phase { Divider(); FieldRow(label: String(localized: "Phase"), value: p + (st.reason.map { " — " + $0 } ?? "")) }151 if let pos = st.position { Divider(); FieldRow(label: String(localized: "Inventaire"), value: pos + (st.positionUsd.map { " (≈ \($0) USD)" } ?? "")) }152 if let mid = st.mid { Divider(); FieldRow(label: String(localized: "Milieu de carnet"), value: mid) }153 if let m = st.manual { Divider(); FieldRow(label: String(localized: "Commande du propriétaire en vigueur"), value: m, tone: .warn) }154 if let b = st.activeBreakers, !b.isEmpty { Divider(); FieldRow(label: String(localized: "Disjoncteurs actifs"), value: b.joined(separator: ", "), tone: .warn) }155 if let l = st.lock { Divider(); FieldRow(label: String(localized: "Verrou"), value: l, tone: .warn) }156 if let sw = st.switch { Divider(); FieldRow(label: String(localized: "Interrupteur d’homme mort de la plateforme"), value: (sw.armed ? String(localized: "armé") : String(localized: "non armé")) + (sw.deadline.map { " · " + AgentFmt.time($0) } ?? "")) }157 }158 if let p = s.pnl?.totalUsd { Divider(); FieldRow(label: String(localized: "Résultat de la session — \(ModeGuard.label(mode))"), value: p + " USD") }159 }160 if let q = s.status?.quotes, !q.isEmpty {161 Text(String(localized: "Cotations en attente")).font(.spCallout.weight(.semibold))162 AgentRows(items: q) { x in FieldRow(label: "\(x.side) · \(x.state)", value: "\(x.size) @ \(x.price)" + (x.distanceBps.map { " · \($0) pb" } ?? "")) }163 }164 ForEach(Array((s.breakers ?? []).prefix(5).enumerated()), id: \.offset) { _, b in Text(String(localized: "Disjoncteur \(b.code) → \(b.action)") + (b.ts.map { " · " + AgentFmt.time($0) } ?? "")).font(.spFootnote).foregroundStyle(Theme.warn) }165 } else {166 Text(String(localized: "Aucune session \(AgentModeBadge.name(mode)) en cours.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("mm.session.none")167 if mode == .paper { Text(String(localized: "Démarre l’agent en PAPIER avec le bouton « Démarrer… » en bas de la page.")).font(.spFootnote).foregroundStyle(Theme.mute) }168 }169 if let m = v.mandate {170 Divider()171 FieldRow(label: String(localized: "Mandat de cotation enregistré"), value: "\(m.id) · \(m.state)" + (m.phase.map { " · \($0)" } ?? ""), mono: true)172 if let i = m.integrity { Notice(tone: .danger, title: String(localized: "L’approbation enregistrée ne se vérifie plus"), message: i) }173 }174 }175 }176177 // MARK: commands — they only remove risk (or resume inside the same authority)178179 @ViewBuilder private func commandsCard(_ a: Agent) -> some View {180 AgentCard(title: String(localized: "Commandes")) {181 HStack(spacing: 8) {182 Button { ask(.pullQuotes, a) } label: { Text(AgentStopAction.pullQuotes.title).font(.spCallout.weight(.semibold)) }.buttonStyle(.bordered).tint(Theme.danger).accessibilityIdentifier("mm.pull")183 Button { ask(.flattenInventory, a) } label: { Text(String(localized: "Clore l’inventaire")).font(.spCallout.weight(.semibold)) }.buttonStyle(.bordered).tint(Theme.danger).accessibilityIdentifier("mm.flatten")184 }.disabled(!model.canOperate || page.busy != nil)185 Button {186 confirmation = AgentConfirmation(title: String(localized: "Reprendre les cotations ?"), message: String(localized: "L’agent cote de nouveau, uniquement pendant une session en cours. Cela n’ajoute aucune autorité : le mandat et les disjoncteurs décident toujours."), button: String(localized: "Reprendre les cotations")) {187 await page.act("mm-resume", model: model, store: store) { AgentStopRunner.describe(try await api.resumeQuoting(a.id)) }188 }189 } label: { Text(String(localized: "Reprendre les cotations")).font(.spCallout.weight(.semibold)) }.buttonStyle(.bordered).disabled(!model.canOperate || page.busy != nil).accessibilityIdentifier("mm.resume")190 Text(String(localized: "Retirer et clore fonctionnent sous tous les verrous et arrêts, sans clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute)191 }192 }193194 private func ask(_ action: AgentStopAction, _ a: Agent) {195 confirmation = AgentConfirmation(title: action.title + " ?", message: action.consequence(agent: a), button: action.title, destructive: true) {196 await page.act(action.rawValue, model: model, store: store) { try await AgentStopRunner(api: api).run(action, agent: a) }197 }198 }199200 // MARK: fills and attribution of ONE mode201202 @ViewBuilder private var fillsCard: some View {203 AgentCard(title: String(localized: "Exécutions — \(AgentModeBadge.name(mode))")) {204 if let fills = mm.fills, !fills.isEmpty {205 if sizeClass == .regular {206 Table(fills) {207 TableColumn(String(localized: "Heure")) { Text(AgentFmt.time($0.ts)).font(.spFootnote) }208 TableColumn(String(localized: "Sens")) { Text($0.side + ($0.reduce ? " · " + String(localized: "réduction") : "")).font(.spFootnote) }209 TableColumn(String(localized: "Taille @ prix")) { Text("\($0.size) @ \($0.price)").font(.spFootnote).monospacedDigit() }210 TableColumn(String(localized: "Frais")) { Text($0.fee).font(.spFootnote).monospacedDigit() }211 TableColumn(String(localized: "Markout 1 s · 10 s · 60 s (pb)")) { Text([$0.markoutsBps?.s1, $0.markoutsBps?.s10, $0.markoutsBps?.s60].map { $0 ?? "—" }.joined(separator: " · ")).font(.spFootnote).monospacedDigit() }212 }.frame(height: min(480, CGFloat(fills.count) * 44 + 60))213 } else {214 AgentRows(items: fills) { f in FieldRow(label: "\(f.side) · \(AgentFmt.time(f.ts))" + (f.maker ? " · " + String(localized: "teneur") : ""), value: "\(f.size) @ \(f.price) · " + String(localized: "frais \(f.fee)")) }215 }216 Text(mode == .paper ? String(localized: "Exécutions SIMULÉES (modélisées) : aucune n’a eu lieu sur la plateforme.") : String(localized: "Exécutions rapportées par la plateforme.")).font(.spFootnote).foregroundStyle(mode == .paper ? Theme.warn : Theme.mute)217 } else { Text(mm.fills == nil ? "…" : String(localized: "Aucune exécution \(AgentModeBadge.name(mode)).")).font(.spCallout).foregroundStyle(Theme.mute) }218 }219 }220221 @ViewBuilder private var performanceCard: some View {222 if let p = mm.performance, p.mode == mode {223 AgentCard(title: String(localized: "Attribution — \(AgentModeBadge.name(mode))")) {224 Text(p.label).font(.spFootnote.weight(.semibold)).foregroundStyle(mode == .live ? Theme.danger : Theme.warn)225 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 8, alignment: .top)], spacing: 8) {226 FigureCell(title: String(localized: "Résultat total (USD)"), value: p.attribution.totalUsd, reason: nil, mode: p.mode)227 FigureCell(title: String(localized: "Capture d’écart (USD)"), value: p.attribution.spreadCaptureUsd, reason: nil, mode: p.mode)228 FigureCell(title: String(localized: "Résultat d’inventaire (USD)"), value: p.attribution.inventoryPnlUsd, reason: nil, mode: p.mode)229 FigureCell(title: String(localized: "Frais (USD)"), value: p.attribution.feesUsd, reason: nil, mode: p.mode)230 FigureCell(title: String(localized: "Financement (USD)"), value: p.attribution.fundingUsd, reason: nil, mode: p.mode)231 FigureCell(title: String(localized: "Par volume (pb)"), value: p.attribution.bpsOfVolume, reason: String(localized: "non rapporté"), mode: p.mode)232 }233 FieldRow(label: String(localized: "Sessions · exécutions · volume"), value: "\(p.sessions) · \(p.fills) · \(p.volumeUsd) USD")234 ForEach(p.markouts, id: \.horizon) { m in FieldRow(label: String(localized: "Markout \(m.horizon) (\(m.fills) exécutions)"), value: (m.meanBps ?? "—") + " pb") }235 if let n = p.note { Text(n).font(.spFootnote).foregroundStyle(Theme.mute) }236 }237 }238 }239240 // MARK: go-live checklist — displayed and acknowledged as served; the mandate itself is not approvable here241242 private static func stepTitle(_ id: String) -> String {243 switch id {244 case "paper": String(localized: "Session papier assez longue")245 case "evidence": String(localized: "Preuves négatives reconnues")246 case "jurisdiction": String(localized: "Texte de juridiction reconnu")247 case "testnet": String(localized: "Essai sur le testnet attesté")248 case "mandate": String(localized: "Mandat de cotation approuvé")249 case "locks": String(localized: "Verrous du serveur levés")250 default: id251 }252 }253254 @ViewBuilder private func goLiveCard(_ v: MarketMakingView) -> some View {255 AgentCard(title: String(localized: "Liste de contrôle du passage en réel")) {256 let next = v.goLive.nextStep257 ForEach(v.goLive.steps) { s in258 VStack(alignment: .leading, spacing: 4) {259 HStack(alignment: .top, spacing: 8) {260 Image(systemName: s.done ? "checkmark.circle.fill" : "circle").foregroundStyle(s.done ? Theme.emerald : Theme.mute)261 Text(Self.stepTitle(s.id) + " : " + (s.done ? String(localized: "fait") : String(localized: "à faire"))).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink)262 }263 if let m = s.missing { Text(m).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }264 if let ev = s.evidence, !ev.isNull { DisclosureGroup(String(localized: "Trace enregistrée par le serveur")) { JSONFields(value: ev) }.font(.spFootnote) }265 if !s.done, next?.id == s.id { acknowledgement(s.id) }266 }267 .padding(.vertical, 6).accessibilityIdentifier("mm.golive.\(s.id)")268 Divider()269 }270 FieldRow(label: String(localized: "Prêt selon le serveur"), value: v.goLive.ready ? String(localized: "oui") : String(localized: "non"))271 Notice(tone: .info, title: String(localized: "Approbation du mandat de cotation : non disponible dans cette version"),272 message: String(localized: "Le mandat de cotation réel s’approuve par deux empreintes (signataire et API). L’app ne sait pas encore les revérifier localement avant de les présenter à ta clé d’accès : elle refuse donc de l’approuver à l’aveugle. Aucun contournement n’est proposé ici."))273 .accessibilityIdentifier("mm.live.unavailable")274 }275 }276277 @ViewBuilder private func acknowledgement(_ step: String) -> some View {278 if let e = mm.evidence {279 switch step {280 case "evidence":281 Text(e.statement).font(.spBody).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)282 AgentCheckRow(title: String(localized: "J’ai lu les preuves ci-dessus et cette déclaration."), on: ackEvidence, id: "mm.ack.evidence") { ackEvidence.toggle() }283 Button(String(localized: "Enregistrer cette reconnaissance")) { record(.evidence(displayed: e)) }.buttonStyle(.spSecondary).disabled(!ackEvidence || !model.canOperate || page.busy != nil)284 case "jurisdiction":285 Text(e.jurisdiction.text).font(.spBody).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)286 AgentCheckRow(title: String(localized: "J’ai lu ce texte et je le reconnais."), on: ackJurisdiction, id: "mm.ack.jurisdiction") { ackJurisdiction.toggle() }287 Button(String(localized: "Enregistrer cette reconnaissance")) { record(.jurisdiction(displayed: e)) }.buttonStyle(.spSecondary).disabled(!ackJurisdiction || !model.canOperate || page.busy != nil)288 case "testnet":289 TextEntry(label: String(localized: "Ce que tu as fait toi-même sur le testnet (note)"), text: $testnetNote, id: "mm.ack.testnet.note")290 Button(String(localized: "Attester l’essai sur le testnet")) { record(.testnet(note: testnetNote)) }.buttonStyle(.spSecondary).disabled(testnetNote.trimmingCharacters(in: .whitespaces).isEmpty || !model.canOperate || page.busy != nil)291 default: EmptyView()292 }293 }294 }295296 private func record(_ ack: MarketMakingAcknowledgement) {297 Task {298 await page.act("mm-ack", model: model, store: store) {299 let g = try await api.acknowledgeGoLive(page.id, ack, locale: "fr")300 return String(localized: "Liste de contrôle : \(g.steps.filter(\.done).count)/\(g.steps.count) étape(s) faite(s) selon le serveur.")301 }302 ackEvidence = false; ackJurisdiction = false303 }304 }305}306