SPB Git

Repository Public

AgentModeWorkspace.swift 28.7 KB 413 lines swift

1// SP Wallet iOS2// File: Features/TradingAgents/AgentModeWorkspace.swift3// Description: The PAPIER and the RÉEL workspaces of an agent — the same blocks (positions, orders, signals, journal, performance,4//              timeline), but each instance reads ONE mode through the Core's mode-scoped calls and shows it under that mode's5//              band. A record or a figure of another mode is an error on screen (mode_mismatch), never a line in the list. The6//              RÉEL workspace also carries the mandate as the signer reports it, the way to go live and the revocation.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import Charts12import SPWalletCore1314enum AgentRecordTab: String, CaseIterable, Identifiable {15    case positions, orders, signals, journal, performance, timeline16    var id: String { rawValue }17    var title: String {18        switch self {19        case .positions: String(localized: "Positions")20        case .orders: String(localized: "Ordres")21        case .signals: String(localized: "Signaux")22        case .journal: String(localized: "Journal")23        case .performance: String(localized: "Performance")24        case .timeline: String(localized: "Chronologie")25        }26    }27}2829/** The mode-scoped records of one agent in ONE mode. Everything stored here passed `ModeGuard.check` against `mode`. */30@MainActor @Observable31final class ModeRecords {32    let agentId: String33    let mode: AgentMode34    var orders: [AgentOrder]?35    var signals: [AgentSignal]?36    var journal: [AgentJournalEntry]?37    var timeline: [AgentTimelineItem]?38    var performance: AgentPerformance?39    var errors: [AgentRecordTab: Error] = [:]40    var loading: Set<AgentRecordTab> = []4142    init(agentId: String, mode: AgentMode) { self.agentId = agentId; self.mode = mode }4344    func load(_ tab: AgentRecordTab, api: AgentsAPI) async {45        guard !loading.contains(tab) else { return }46        loading.insert(tab); defer { loading.remove(tab) }47        do {48            switch tab {49            case .orders: orders = try ModeGuard.scoped(try await api.orders(agentId, mode: mode, limit: 100), heading: mode)50            case .signals: signals = try ModeGuard.scoped(try await api.signals(agentId, mode: mode, limit: 100), heading: mode)51            case .journal: journal = try ModeGuard.scoped(try await api.journal(agentId, mode: mode, limit: 100), heading: mode)52            case .timeline: timeline = try ModeGuard.scoped(try await api.timeline(agentId, mode: mode, limit: 100), heading: mode)53            case .performance:54                let p = try await api.performance(agentId, mode: mode)55                try ModeGuard.check(p.mode, heading: mode)56                performance = p57            case .positions: break58            }59            errors[tab] = nil60        } catch {61            // a refused answer leaves NOTHING on screen for that block: no stale list under an error62            switch tab { case .orders: orders = nil; case .signals: signals = nil; case .journal: journal = nil; case .timeline: timeline = nil; case .performance: performance = nil; case .positions: break }63            errors[tab] = error64        }65    }66}6768struct AgentModeWorkspace: View {69    @Environment(AppModel.self) private var model70    @Environment(\.horizontalSizeClass) private var sizeClass71    let page: AgentPageModel72    let store: AgentsStore73    let mode: AgentMode74    let startLive: () -> Void75    @State private var tab: AgentRecordTab = .positions76    @State private var records: ModeRecords77    @State private var confirmation: AgentConfirmation?7879    init(page: AgentPageModel, store: AgentsStore, mode: AgentMode, startLive: @escaping () -> Void) {80        self.page = page; self.store = store; self.mode = mode; self.startLive = startLive81        _records = State(initialValue: ModeRecords(agentId: page.id, mode: mode))82    }8384    private var bandDetail: String? {85        guard mode == .live, let a = page.agent, a.resolvedKind == .perp else { return nil }86        if case .perp(let d)? = page.detail, let n = d.live?.network ?? a.liveNetwork { return n == "mainnet" ? "MAINNET" : n == "testnet" ? String(localized: "TESTNET · argent de test") : n }87        return nil88    }8990    var body: some View {91        if let a = page.agent {92            AgentModeBand(mode: mode, detail: bandDetail)93            if a.mode != mode {94                Notice(tone: .info, title: String(localized: "L’agent n’est pas dans ce mode en ce moment"),95                       message: String(localized: "Mode actuel : \(AgentModeBadge.name(a.mode)). Ce qui suit est l’historique \(AgentModeBadge.name(mode)) de l’agent, s’il existe."))96            }97            if mode == .live { liveHead(a) }98            ScrollView(.horizontal, showsIndicators: false) {99                HStack(spacing: 6) {100                    ForEach(AgentRecordTab.allCases) { t in101                        Button { tab = t } label: {102                            Text(t.title).font(.system(size: 13.5, weight: .semibold)).padding(.horizontal, 12).frame(minHeight: 36)103                                .foregroundStyle(t == tab ? Theme.ink : Theme.mute)104                                .background(t == tab ? Theme.surface : Color.clear, in: Capsule())105                                .overlay(Capsule().strokeBorder(t == tab ? Theme.hairline : Color.clear, lineWidth: 1))106                        }.buttonStyle(.plain).accessibilityIdentifier("agent.records.\(mode.rawValue).\(t.rawValue)")107                    }108                }109            }110            block(a)111                .task(id: "\(tab.rawValue)-\(store.revision)") { if model.canOperate { await records.load(tab, api: AgentsAPI(model.env.client)) } }112                .agentConfirmation($confirmation)113        }114    }115116    // MARK: live head — mandate, going live, revoking117118    @ViewBuilder private func liveHead(_ a: Agent) -> some View {119        AgentCard(title: String(localized: "Mandat réel")) {120            switch page.detail {121            case .spot(let d):122                SpotMandateStatusView(detail: d)123                if a.mode == .live {124                    Button { revoke(a) } label: { Label(AgentStopAction.revokeMandate.title, systemImage: "xmark.shield.fill") }125                        .buttonStyle(.spDestructive).disabled(!model.canOperate || page.busy != nil).accessibilityIdentifier("agent.live.revoke")126                    Text(String(localized: "Définitif, sans clé d’accès : révoquer ne fait que retirer une autorité.")).font(.spFootnote).foregroundStyle(Theme.mute)127                } else { goLive(a) }128            case .perp(let d):129                PerpLiveBlockView(detail: d)130                if a.mode != .live { goLive(a) }131            default:132                if page.isMarketMaking {133                    Notice(tone: .info, title: String(localized: "Mandat de cotation réel : non disponible dans cette version"),134                           message: String(localized: "L’app ne sait pas encore revérifier localement le mandat de cotation (objet à deux empreintes) avant de le soumettre à ta clé d’accès ; elle refuse donc de l’approuver à l’aveugle. La liste de contrôle et les preuves sont dans « Tenue de marché »."))135                        .accessibilityIdentifier("agent.live.mm.unavailable")136                } else if let r = page.overview?.familyModes?.liveReason {137                    Notice(tone: .info, title: String(localized: "Mode réel indisponible pour cette famille"), message: r).accessibilityIdentifier("agent.live.unavailable")138                } else if page.detail == nil {139                    Text(String(localized: "Indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute)140                } else {141                    Notice(tone: .info, title: String(localized: "Passage en réel non disponible ici pour ce type d’agent"), message: page.overview?.summary.live.reason)142                }143            }144        }145    }146147    @ViewBuilder private func goLive(_ a: Agent) -> some View {148        let live = page.overview?.summary.live149        if let live, !live.capable {150            Notice(tone: .info, title: String(localized: "Cet agent ne peut pas passer en réel"), message: [live.reason, live.code.map { "(\($0))" }].compactMap { $0 }.joined(separator: " ")).accessibilityIdentifier("agent.live.unavailable")151        } else if let r = page.overview?.familyModes?.liveReason {152            Notice(tone: .info, title: String(localized: "Mode réel indisponible pour cette famille"), message: r).accessibilityIdentifier("agent.live.unavailable")153        } else {154            Text(a.resolvedKind == .spot155                 ? String(localized: "Passer en réel = approuver un MANDAT avec ta clé d’accès : le signataire isolé ne signera que des échanges dans ses limites, jusqu’à son expiration. Tu saisis chaque limite, tu relis le mandat vérifié en entier, puis tu approuves.")156                 : String(localized: "Passer en réel = choisir un compte de la plateforme, relire la liste de contrôle du serveur, puis approuver le mandat par DEUX demandes de clé d’accès (signataire, puis API)."))157                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)158            Button(action: startLive) { Label(String(localized: "Passer en réel…"), systemImage: "bolt.fill") }159                .buttonStyle(.spSecondary).disabled(!model.canOperate || page.busy != nil).accessibilityIdentifier("agent.live.start")160        }161    }162163    private func revoke(_ a: Agent) {164        let action = AgentStopAction.revokeMandate165        confirmation = AgentConfirmation(title: action.title + " ?", message: action.consequence(agent: a), button: action.title, destructive: true) {166            await page.act(action.rawValue, model: model, store: store) { try await AgentStopRunner(api: AgentsAPI(model.env.client)).run(action, agent: a) }167        }168    }169170    // MARK: blocks171172    @ViewBuilder private func block(_ a: Agent) -> some View {173        if let e = records.errors[tab] {174            if (e as? APIError)?.code == "mode_mismatch" {175                Notice(tone: .danger, title: String(localized: "Réponse d’un autre mode refusée"), message: String(localized: "Le serveur a répondu avec des données d’un autre mode que \(AgentModeBadge.name(mode)). Elles ne sont pas affichées.") + " (mode_mismatch)")176                    .accessibilityIdentifier("agent.records.mismatch")177            } else { ErrorNotice(error: e) { Task { await records.load(tab, api: AgentsAPI(model.env.client)) } } }178        } else {179            switch tab {180            case .positions: positions(a)181            case .orders: orders182            case .signals: signals183            case .journal: journal184            case .performance: performance185            case .timeline: timeline186            }187        }188    }189190    private func pending(_ loaded: Bool, empty: String) -> some View {191        Group {192            if !model.canOperate { Text(String(localized: "Indisponible hors ligne : ce bloc n’est pas conservé sur l’appareil.")).font(.spCallout).foregroundStyle(Theme.mute) }193            else if loaded { Text(empty).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("agent.records.empty") }194            else { ProgressView().frame(maxWidth: .infinity, minHeight: 80) }195        }196    }197198    private func modeTag() -> some View {199        Text(ModeGuard.label(mode)).font(.system(size: 11, weight: .semibold)).foregroundStyle(mode == .live ? Theme.danger : Theme.warn)200    }201202    @ViewBuilder private func positions(_ a: Agent) -> some View {203        switch (mode, page.detail) {204        case (.paper, .spot(let d)):205            AgentCard(title: String(localized: "Livre PAPIER (avoirs simulés)")) {206                if let p = d.paper {207                    AgentRows(items: p.positions) { pos in FieldRow(label: pos.symbol, value: Money.exact(pos.units) + (pos.usd.map { " · ≈ " + AgentFmt.usd($0) } ?? " · " + String(localized: "valeur inconnue"))) }208                    Divider()209                    FieldRow(label: String(localized: "Réserve simulée (\(p.cashSymbol))"), value: AgentFmt.usd(p.cashUsd))210                    Text(String(localized: "Avoirs SIMULÉS au \(AgentFmt.date(p.asOf)). Ils ne s’ajoutent jamais aux soldes réels du coffre.")).font(.spFootnote).foregroundStyle(Theme.warn)211                } else { Text(String(localized: "Cet agent n’a encore jamais tourné en papier : aucun avoir simulé.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("agent.paper.none") }212            }213        case (.paper, .perp(let d)):214            AgentCard(title: String(localized: "Compte PAPIER de la plateforme (simulé)")) {215                if let acct = d.account {216                    ServerDetail(title: String(localized: "État du compte simulé"), value: acct.state)217                    if acct.positions.isEmpty { Text(String(localized: "Aucune position simulée ouverte.")).font(.spCallout).foregroundStyle(Theme.mute) }218                    ForEach(Array(acct.positions.enumerated()), id: \.offset) { _, p in JSONFields(value: p).padding(.vertical, 4); Divider() }219                    ServerDetail(title: String(localized: "Totaux simulés"), value: acct.totals)220                    Button {221                        let action = AgentStopAction.flattenPaper222                        confirmation = AgentConfirmation(title: action.title + " ?", message: action.consequence(agent: a), button: action.title, destructive: true) {223                            await page.act(action.rawValue, model: model, store: store) { try await AgentStopRunner(api: AgentsAPI(model.env.client)).run(action, agent: a) }224                        }225                    } label: { Label(AgentStopAction.flattenPaper.title, systemImage: "arrow.down.to.line") }226                        .buttonStyle(.spSecondary).disabled(!model.canOperate || page.busy != nil || acct.positions.isEmpty).accessibilityIdentifier("agent.paper.flatten")227                    modeTag()228                } else { Text(String(localized: "Compte papier indisponible.")).font(.spCallout).foregroundStyle(Theme.mute) }229            }230        case (.paper, _):231            AgentCard(title: String(localized: "Livre PAPIER (simulé)")) {232                if let b = page.overview?.runtime?.book {233                    if !b.simulated { Notice(tone: .danger, title: String(localized: "Livre non marqué comme simulé par le serveur"), message: String(localized: "Il n’est pas affiché sous PAPIER.")) }234                    else {235                        ServerDetail(title: String(localized: "Positions simulées"), value: b.positions)236                        ServerDetail(title: String(localized: "Cotations simulées"), value: b.quotes)237                        ServerDetail(title: String(localized: "Paire"), value: b.pair)238                        if let v = b.realizedPnl { FieldRow(label: String(localized: "Résultat réalisé (simulé)"), value: AgentFmt.usd(v)) }239                        if let v = b.fees { FieldRow(label: String(localized: "Frais (simulés)"), value: AgentFmt.usd(v)) }240                        if let v = b.funding { FieldRow(label: String(localized: "Financement (simulé)"), value: AgentFmt.usd(v)) }241                        modeTag()242                    }243                } else { Text(page.detail == nil ? String(localized: "Indisponible hors ligne.") : String(localized: "Aucun livre simulé pour le moment.")).font(.spCallout).foregroundStyle(Theme.mute) }244            }245        case (.live, .spot(let d)):246            AgentCard(title: String(localized: "Soldes du coffre (réels, lus sur la chaîne)")) {247                if let v = d.vault {248                    AgentRows(items: v) { b in FieldRow(label: "\(b.assetSymbol) · \(b.role == "gas" ? String(localized: "frais de réseau seulement") : b.role == "cash" ? String(localized: "réserve") : String(localized: "actif"))", value: Money.exact(b.display) + " " + b.assetSymbol + (b.usd.map { " · ≈ " + AgentFmt.usd($0) } ?? "")) }249                    Text(String(localized: "Ces soldes sont de vrais fonds quel que soit le mode de l’agent.")).font(.spFootnote).foregroundStyle(Theme.mute)250                } else { Text(String(localized: "Lecture de la chaîne indisponible : soldes inconnus (ce n’est pas un coffre vide).")).font(.spCallout).foregroundStyle(Theme.warn) }251            }252        case (.live, .perp(let d)):253            AgentCard(title: String(localized: "Compte de la plateforme (réel)")) {254                if let acct = d.live?.account, !acct.isNull { JSONFields(value: acct); Text(String(localized: "Positions, exécutions et valeur lues sur la plateforme, telles que le serveur les rapporte.")).font(.spFootnote).foregroundStyle(Theme.mute) }255                else { Text(String(localized: "Aucun compte réel rattaché à cet agent.")).font(.spCallout).foregroundStyle(Theme.mute) }256            }257        default:258            Text(page.detail == nil ? String(localized: "Indisponible hors ligne.") : String(localized: "Aucune position réelle : cet agent n’a pas de compte réel ici.")).font(.spCallout).foregroundStyle(Theme.mute).spCard()259        }260    }261262    @ViewBuilder private var orders: some View {263        AgentCard(title: String(localized: "Ordres — \(AgentModeBadge.name(mode))")) {264            if let list = records.orders, !list.isEmpty {265                if sizeClass == .regular {266                    Table(list) {267                        TableColumn(String(localized: "Date")) { Text(AgentFmt.date($0.ts)).font(.spFootnote) }268                        TableColumn(String(localized: "Marché")) { Text($0.instrument ?? "—").font(.spFootnote) }269                        TableColumn(String(localized: "Sens")) { Text(($0.side ?? "—") + ($0.reduceOnly == true ? " · " + String(localized: "réduction") : "")).font(.spFootnote) }270                        TableColumn(String(localized: "Taille · notionnel")) { Text(($0.size ?? "—") + " · " + ($0.notional ?? "—")).font(.spFootnote).monospacedDigit() }271                        TableColumn(String(localized: "Exécuté · prix")) { Text(($0.filledSize ?? "—") + " · " + ($0.avgFillPrice ?? "—")).font(.spFootnote).monospacedDigit() }272                        TableColumn(String(localized: "État")) { Text($0.state + ($0.reason.map { " — " + $0 } ?? "")).font(.spFootnote).foregroundStyle($0.state == "FILLED" ? Theme.emerald : Theme.ink) }273                    }274                    .frame(height: min(520, CGFloat(list.count) * 44 + 60)).accessibilityIdentifier("agent.orders.table")275                } else {276                    AgentRows(items: list) { o in277                        VStack(alignment: .leading, spacing: 3) {278                            HStack { Text((o.instrument ?? "—") + " · " + (o.side ?? "—")).font(.spBody.weight(.medium)); Spacer(); Pill(text: o.state, tone: o.state == "FILLED" ? .ok : ["REJECTED", "FAILED"].contains(o.state) ? .danger : .neutral) }279                            Text(String(localized: "taille \(o.size ?? "—") · notionnel \(o.notional ?? "—") · exécuté \(o.filledSize ?? "—") à \(o.avgFillPrice ?? "—")")).font(.spFootnote).monospacedDigit().foregroundStyle(Theme.mute)280                            if let r = o.reason { Text(r).font(.spFootnote).foregroundStyle(Theme.mute) }281                            Text(AgentFmt.date(o.ts)).font(.system(size: 11.5)).foregroundStyle(Theme.mute)282                        }.padding(.vertical, 8)283                    }284                }285                Text(mode == .live ? String(localized: "Seul l’état FILLED est une exécution.") : String(localized: "Ordres SIMULÉS : aucun n’a atteint une plateforme ni une chaîne.")).font(.spFootnote).foregroundStyle(mode == .live ? Theme.mute : Theme.warn)286            } else { pending(records.orders != nil, empty: String(localized: "Aucun ordre \(AgentModeBadge.name(mode)).")) }287        }288    }289290    @ViewBuilder private var signals: some View {291        AgentCard(title: String(localized: "Signaux — \(AgentModeBadge.name(mode))")) {292            if let list = records.signals, !list.isEmpty {293                if sizeClass == .regular {294                    Table(list) {295                        TableColumn(String(localized: "Date")) { Text(AgentFmt.date($0.ts)).font(.spFootnote) }296                        TableColumn(String(localized: "Décision")) { Text($0.decision ?? $0.status ?? "—").font(.spFootnote) }297                        TableColumn(String(localized: "Raison")) { Text([$0.reason, $0.reasonCode.map { "(\($0))" }].compactMap { $0 }.joined(separator: " ")).font(.spFootnote) }298                        TableColumn(String(localized: "Fonds")) { Text($0.equity ?? "—").font(.spFootnote).monospacedDigit() }299                        TableColumn(String(localized: "Config")) { Text($0.configVersion.map { "v\($0)" } ?? "—").font(.spFootnote) }300                    }301                    .frame(height: min(520, CGFloat(list.count) * 44 + 60)).accessibilityIdentifier("agent.signals.table")302                } else {303                    AgentRows(items: list) { s in304                        VStack(alignment: .leading, spacing: 3) {305                            HStack { Text(s.decision ?? s.status ?? "—").font(.spBody.weight(.medium)); Spacer(); Text(AgentFmt.date(s.ts)).font(.system(size: 11.5)).foregroundStyle(Theme.mute) }306                            if let r = s.reason { Text(r + (s.reasonCode.map { " (\($0))" } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute) }307                            if let t = s.targets, !t.isNull { DisclosureGroup(String(localized: "Cibles")) { JSONFields(value: t) }.font(.spFootnote) }308                        }.padding(.vertical, 8)309                    }310                }311                modeTag()312            } else { pending(records.signals != nil, empty: String(localized: "Aucun signal \(AgentModeBadge.name(mode)).")) }313        }314    }315316    @ViewBuilder private var journal: some View {317        AgentCard(title: String(localized: "Journal — \(AgentModeBadge.name(mode))")) {318            if let list = records.journal, !list.isEmpty {319                AgentRows(items: list) { e in LogLine(ts: e.ts, title: e.title, body: e.body, severity: e.severity, code: e.code, extra: e.data) }320            } else { pending(records.journal != nil, empty: String(localized: "Journal \(AgentModeBadge.name(mode)) vide.")) }321        }322    }323324    @ViewBuilder private var timeline: some View {325        AgentCard(title: String(localized: "Chronologie — \(AgentModeBadge.name(mode))")) {326            if let list = records.timeline, !list.isEmpty {327                AgentRows(items: list) { e in LogLine(ts: e.ts, title: "[\(e.type)] " + e.title, body: e.body, severity: e.severity, code: e.code, extra: nil) }328                    .accessibilityIdentifier("agent.timeline")329            } else { pending(records.timeline != nil, empty: String(localized: "Aucun événement \(AgentModeBadge.name(mode)).")) }330        }331    }332333    @ViewBuilder private var performance: some View {334        if let p = records.performance, p.mode == mode {335            PerformanceView(performance: p, heading: mode)336        } else { pending(false, empty: "").spCard() }337    }338}339340struct LogLine: View {341    let ts: Date342    let title: String343    let body_: String?344    let severity: String?345    let code: String?346    let extra: JSONValue?347    init(ts: Date, title: String, body: String?, severity: String?, code: String?, extra: JSONValue?) { self.ts = ts; self.title = title; body_ = body; self.severity = severity; self.code = code; self.extra = extra }348    private var tone: Tone { severity == "error" || severity == "critical" ? .danger : severity == "warning" || severity == "warn" ? .warn : .neutral }349    var body: some View {350        VStack(alignment: .leading, spacing: 3) {351            HStack(alignment: .top, spacing: 6) {352                Image(systemName: tone == .neutral ? "circle.fill" : tone.icon).font(.system(size: tone == .neutral ? 6 : 12)).foregroundStyle(tone == .neutral ? Theme.mute : tone.color).padding(.top, tone == .neutral ? 6 : 2)353                Text(title).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)354            }355            if let b = body_, !b.isEmpty { Text(b).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }356            Text(AgentFmt.time(ts) + (code.map { " · " + $0 } ?? "")).font(.system(size: 11.5)).foregroundStyle(Theme.mute)357            if let extra, !extra.isNull { DisclosureGroup(String(localized: "Détail")) { JSONFields(value: extra) }.font(.spFootnote) }358        }359        .padding(.vertical, 8)360        .frame(maxWidth: .infinity, alignment: .leading)361    }362}363364/** Performance of ONE mode. The view cannot be built for a heading that is not the performance's own mode. */365struct PerformanceView: View {366    let performance: AgentPerformance367    let heading: AgentMode368369    private func cell(_ title: String, _ f: ModedFigure, _ format: (Double) -> String) -> FigureCell? {370        guard let g = try? ModeGuard.figure(f, heading: heading) else { return nil }371        return FigureCell(title: title, value: g.value.map(format), reason: g.reason, mode: g.mode)372    }373374    var body: some View {375        if performance.mode != heading || heading == .unknown {376            Notice(tone: .danger, title: String(localized: "Réponse d’un autre mode refusée"), message: "mode_mismatch").accessibilityIdentifier("agent.records.mismatch")377        } else {378            let p = performance379            AgentCard(title: String(localized: "Performance — \(AgentModeBadge.name(heading))")) {380                Text(p.label).font(.spFootnote.weight(.semibold)).foregroundStyle(heading == .live ? Theme.danger : Theme.warn).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("agent.performance.label")381                if let curve = try? ModeGuard.scoped(p.equityCurve, heading: heading), curve.count > 1 {382                    let lo = curve.map(\.equity).min() ?? 0, hi = curve.map(\.equity).max() ?? 1383                    Chart(curve, id: \.ts) { pt in384                        LineMark(x: .value("t", pt.ts), y: .value("v", pt.equity)).foregroundStyle(heading == .live ? Theme.series[0] : Theme.series[1]).interpolationMethod(.monotone)385                    }386                    .chartYScale(domain: (lo - (hi - lo) * 0.05)...(hi + (hi - lo) * 0.05 + .leastNonzeroMagnitude))387                    .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { _ in AxisValueLabel().font(.system(size: 11)) } }388                    .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.hairline); AxisValueLabel().font(.system(size: 11)) } }389                    .frame(height: 200)390                    .accessibilityLabel(String(localized: "Courbe de la valeur des fonds, \(AgentModeBadge.name(heading))"))391                    Text(String(localized: "Valeur des fonds (USD) — \(ModeGuard.label(heading)). \(p.points) point(s)") + (p.from.map { ", " + String(localized: "du \(AgentFmt.date($0))") } ?? "") + (p.to.map { " " + String(localized: "au \(AgentFmt.date($0))") } ?? "") + ".")392                        .font(.system(size: 12)).foregroundStyle(Theme.mute)393                } else {394                    Text(String(localized: "Pas assez de points pour une courbe (\(p.points)).")).font(.spCallout).foregroundStyle(Theme.mute)395                }396                ForEach(p.warnings, id: \.self) { w in Notice(tone: .warn, title: w.message, message: "(\(w.code))") }397                let cells: [FigureCell?] = [398                    cell(String(localized: "Rendement total"), p.totalReturn) { AgentFmt.percent(fraction: $0) }, cell(String(localized: "Résultat net"), p.netPnlUsd) { AgentFmt.usd($0) },399                    cell(String(localized: "Repli maximal"), p.maxDrawdown) { AgentFmt.percent(fraction: $0) }, cell(String(localized: "Volatilité"), p.volatility) { AgentFmt.percent(fraction: $0) },400                    cell("Sharpe", p.sharpe) { AgentFmt.number($0, max: 2) }, cell("Sortino", p.sortino) { AgentFmt.number($0, max: 2) },401                    cell(String(localized: "Taux de réussite"), p.winRate) { AgentFmt.percent(fraction: $0) }, cell(String(localized: "Facteur de profit"), p.profitFactor) { AgentFmt.number($0, max: 2) },402                    cell(String(localized: "Rotation"), p.turnover) { AgentFmt.number($0, max: 2) }, cell(String(localized: "Frais"), p.feesUsd) { AgentFmt.usd($0) },403                    cell(String(localized: "Financement"), p.fundingUsd) { AgentFmt.usd($0) }, cell(String(localized: "Glissement"), p.slippageUsd) { AgentFmt.usd($0) },404                ]405                LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 8, alignment: .top)], spacing: 8) {406                    ForEach(Array(cells.compactMap { $0 }.enumerated()), id: \.offset) { _, c in c }407                }408                FieldRow(label: String(localized: "Ordres · positions closes"), value: "\(p.orders) · \(p.closedTrades)")409            }410        }411    }412}413
Files main
Menu

Theme