SPB Git

Repository Public

AgentMandateViews.swift 27.8 KB 414 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/TradingAgents/AgentMandateViews.swift10// Description      : The mandate and the risks of an agent (what the signer11//                    holds now, the prominent revocation that needs no passkey,12//                    the door to a new passkey-approved mandate, who enforces13//                    each limit) and its configuration with its versions. A14//                    limit can be edited only while the agent is not running,15//                    and never to an empty or unbounded value.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 SPWalletCore9596struct AgentMandateSection: View {97    let model: AppModel98    let d: AgentDetailStore99    let store: AgentsStore100    let spotFlow: SpotGoLiveFlow101    @State private var confirmRevoke = false102103    var body: some View {104        switch d.detail {105        case .spot(let s): spot(s)106        case .perp(let p):107            Card("Mandat de dérivés") {108                if let l = p.live, l.active || l.mandateId != nil {109                    let kind = ModeKind(.live, liveNetwork: l.network)110                    VStack(alignment: .leading, spacing: 6) {111                        HStack { ModeTag(kind: kind); Text(l.active ? "Mandat en vigueur" : "Dernier mandat").fontWeight(.semibold) }112                        Field(label: "Mandat", value: l.mandateId ?? "—", mono: true)113                        Field(label: "Compte / réseau", value: "\(l.accountId ?? "—") · \(l.network ?? "—")")114                        if let c = l.capital { Field(label: "Capital de référence", value: "\(Fmt.amount(c)) USDC") }115                        Text("Mandat et compteurs tels que le SIGNATAIRE les rapporte").font(.caption.weight(.semibold))116                        JSONFacts(value: l.signer, depth: 3, empty: "Le signataire n’a rien rapporté pour ce mandat.")117                    }.modeFramed(kind)118                } else { Text("Aucun mandat de dérivés pour cet agent.").foregroundStyle(.secondary) }119                Text("La préparation, l’approbation, la pause et la révocation du mandat d’un agent de perpétuels sont dans l’onglet Perpétuels.").font(.callout).foregroundStyle(.secondary)120            }121            StatementsCard(can: CustodyFacts.perpCan, cannot: CustodyFacts.perpCannot, notBounded: CustodyFacts.perpNotBounded)122        default:123            Card("Mandat") {124                if let m = d.summary?.mandate { Field(label: "Mandat en vigueur", value: "\(m.kind) · \(m.id)", mono: true) } else { Text("Aucun mandat en vigueur pour cet agent.").foregroundStyle(.secondary) }125                if d.isMarketMaking { Text("Le mandat de cotation, sa liste de contrôle et sa révocation sont dans l’onglet Tenue de marché.").font(.callout).foregroundStyle(.secondary) }126            }127        }128        limits129        draft130    }131132    // MARK: spot133134    @ViewBuilder private func spot(_ s: SpotAgentDetail) -> some View {135        let a = s.agent, live = ModeKind(.live)136        Card("Mandat du coffre", trailing: AnyView(Group { if a.mode == .live { ModeTag(kind: live) } })) {137            if let m = s.mandateStatus {138                Field(label: "État au signataire", value: m.active ? "EN VIGUEUR" : m.revoked ? "Révoqué" : m.expired ? "Expiré" : "Inactif", emphasis: true)139                Field(label: "Expiration", value: "\(Fmt.dateSeconds(m.expiry)) (\(Fmt.relative(m.expiry)))")140                Field(label: "Ordres par jour", value: "\(m.today?.orders.map(String.init) ?? "—") utilisés aujourd’hui sur \(m.maxOrdersPerDay)")141                ForEach(m.maxOrder.keys.sorted(), id: \.self) { asset in142                    let h = a.holdings?.first { $0.asset == asset }, dec = model.network(a.network)?.asset(asset)?.decimals143                    Field(label: "Plafonds \(h?.assetSymbol ?? Fmt.short(asset))", value: "par ordre \(units(m.maxOrder[asset], dec)) · par jour \(units(m.maxDaily[asset], dec)) · vendu aujourd’hui \(units(m.today?.sold?[asset] ?? "0", dec))")144                }145                if let ms = a.mandate { Field(label: "Stratégie épinglée", value: ms.strategySha256, mono: true) }146            } else { Text("Le signataire ne détient aucun mandat pour ce coffre : l’agent ne peut rien signer.").foregroundStyle(.secondary) }147148            if s.mandateStatus?.active == true || a.mode == .live {149                Divider()150                HStack(alignment: .top, spacing: 12) {151                    VStack(alignment: .leading, spacing: 2) {152                        Text("Révocation").font(.headline)153                        Text("Immédiate et définitive, SANS passkey : le signataire ne signe plus aucun échange pour ce coffre et l’agent est arrêté. Les fonds restent dans le coffre ; un nouveau mandat exigera votre passkey.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)154                    }155                    Spacer()156                    Button(role: .destructive) { confirmRevoke = true } label: { Label("Révoquer le mandat", systemImage: "xmark.shield.fill").fontWeight(.semibold) }157                        .buttonStyle(.borderedProminent).tint(Theme.negative).controlSize(.large).disabled(!model.canOperate || d.busy != nil)158                }159            }160            if let n = d.notice { Banner(.info, n) }161            if let e = d.actionError { Banner(.danger, e) }162        }163        .confirmationDialog("Révoquer le mandat de « \(a.name) » ?", isPresented: $confirmRevoke, titleVisibility: .visible) {164            Button("Révoquer le mandat", role: .destructive) { Task { await d.revokeSpotMandate(); await store.refresh() } }165            Button("Annuler", role: .cancel) {}166        } message: { Text("Le signataire cesse immédiatement de signer pour ce coffre et l’agent est arrêté. Les positions détenues par le coffre ne sont pas vendues.") }167168        if a.mode != .live {169            Card("Passer en réel", trailing: AnyView(ModeTag(kind: live))) {170                let version = s.approvedVersion, capable = d.summary?.live171                VStack(alignment: .leading, spacing: 6) {172                    check(version != nil, "Une version de stratégie approuvée par vous est en service", version.map { "\($0.name) \($0.version)" } ?? "Approuvez une version dans l’onglet Stratégie.")173                    check(capable?.capable == true, "Le serveur permet le mode réel pour cet agent", capable?.capable == true ? nil : capable?.reason ?? capable?.code ?? "Vue d’ensemble non lue.")174                    check(s.vault != nil, "Les soldes du coffre sont lisibles sur la chaîne", s.vault == nil ? "Lecture de chaîne en échec." : "Le serveur exigera aussi une réserve de gaz dans le coffre (onglet Coffre).")175                    check(model.network(a.network) != nil, "Le réseau du coffre est dans le registre de ce portefeuille", nil)176                    check(store.killSwitch?.engaged == false, "L’arrêt d’urgence n’est pas engagé", store.killSwitch == nil ? "État inconnu." : nil)177                }178                Text("Préparer ne signe rien : le serveur construit le mandat à partir de vos limites, cette app le vérifie champ par champ et vérifie que le défi de la passkey est son empreinte. Vous verrez ensuite le mandat complet avant d’approuver.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)179                if let e = spotFlow.error { Banner(.danger, e) }180                if spotFlow.step == .done { Banner(.ok, "Mandat approuvé et enregistré au signataire. État de l’agent selon le serveur : \(spotFlow.result.map { AgentText.phase($0.state) } ?? "—").") }181                HStack {182                    Spacer()183                    if spotFlow.step == .preparing { ProgressView().controlSize(.small); Text("Construction et vérification du mandat…").foregroundStyle(.secondary) }184                    ModeButton(title: "Préparer le mandat à approuver…", kind: live, systemImage: "touchid", prominent: true) { Task { await spotFlow.prepare(s) } }185                        .disabled(!model.canOperate || version == nil || capable?.capable != true || spotFlow.step != .idle && spotFlow.step != .done || d.busy != nil)186                }187            }188        }189        StatementsCard(can: CustodyFacts.spotCan, cannot: CustodyFacts.spotCannot, notBounded: CustodyFacts.spotNotBounded)190    }191192    private func units(_ s: String?, _ decimals: Int?) -> String {193        guard let s else { return "—" }194        guard let decimals, let u = try? BaseUnits(s) else { return "\(s) (unités de base)" }195        return Fmt.amount(u.formatted(decimals: decimals))196    }197198    private func check(_ ok: Bool, _ text: String, _ detail: String?) -> some View {199        HStack(alignment: .top, spacing: 8) {200            Image(systemName: ok ? "checkmark.circle.fill" : "circle").foregroundStyle(ok ? Theme.positive : .secondary)201            VStack(alignment: .leading, spacing: 1) { Text(text); if let detail { Text(detail).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } }202        }203    }204205    // MARK: limits and draft206207    @ViewBuilder private var limits: some View {208        Card("Limites de risque de l’agent") {209            if let a = d.agent {210                if let r = a.spotRisk {211                    limit("Plafond par ordre", "\(r.maxOrderUsd.text) USD", "inscrit dans le mandat — appliqué par le signataire")212                    limit("Volume quotidien", "\(r.maxDailyUsd.text) USD", "inscrit dans le mandat — appliqué par le signataire")213                    limit("Ordres par jour", String(r.maxOrdersPerDay), "inscrit dans le mandat — appliqué par le signataire")214                    limit("Validité d’un mandat", "\(r.mandateDays) jour(s)", "inscrit dans le mandat — appliqué par le signataire")215                    limit("Glissement", "\(r.slippageBps) pb (garde du mandat : \(r.mandateSlippageBps) pb)", "garde du mandat appliquée par le signataire")216                    limit("Exposition maximale", "\(AgentCreateForm.plain(r.maxExposurePct)) % du coffre", "moteur de l’API seulement", warn: true)217                    limit("Perte maximale", "\(AgentCreateForm.plain(r.maxLossPct)) % du capital", "moteur de l’API seulement — un écart de prix peut la dépasser", warn: true)218                } else if let r = a.perpRisk {219                    limit("Levier maximal", "×\(r.maxLeverage)", "réglage de levier borné par le signataire sous mandat")220                    limit("Exposition brute", "× \(AgentCreateForm.plain(r.maxGrossExposureX)) du capital", "moteur de risque de l’API", warn: true)221                    limit("Position par instrument", "× \(AgentCreateForm.plain(r.maxPositionX)) du capital", "moteur de risque de l’API", warn: true)222                    limit("Perte quotidienne", "\(AgentCreateForm.plain(r.maxDailyLossPct)) % du capital — fermeture puis arrêt", "moteur de l’API ; sous mandat, plancher de valeur du compte lu par le signataire", warn: true)223                    limit("Perte totale", "\(AgentCreateForm.plain(r.maxTotalLossPct)) % du capital", "moteur de l’API", warn: true)224                    limit("Glissement", "\(r.slippageBps) pb", "moteur de l’API ; écart de prix borné par le mandat")225                    limit("Rééquilibrage minimal", "\(AgentCreateForm.plain(r.minTradePct)) % des fonds propres", "moteur de l’API")226                } else {227                    JSONFacts(value: d.summary?.riskLimits ?? a.risk, depth: 3, empty: "Le serveur n’a publié aucune limite pour cet agent.")228                    Text("Limites telles que le serveur les stocke. En simulation elles sont appliquées par le moteur de l’agent.").font(.caption).foregroundStyle(.secondary)229                }230            }231        }232    }233234    private func limit(_ label: String, _ value: String, _ who: String, warn: Bool = false) -> some View {235        HStack(alignment: .firstTextBaseline, spacing: 12) {236            Text(label).foregroundStyle(.secondary).frame(width: 190, alignment: .leading)237            Text(value).fontWeight(.medium).monospacedDigit().frame(width: 260, alignment: .leading)238            Label(who, systemImage: warn ? "exclamationmark.triangle" : "lock.shield").font(.caption).foregroundStyle(warn ? Theme.warning : Theme.positive).fixedSize(horizontal: false, vertical: true)239            Spacer(minLength: 0)240        }241    }242243    @ViewBuilder private var draft: some View {244        Card("Ce que le serveur ferait approuver pour passer en réel (lecture seule)") {245            if let m = d.mandateDraft {246                Field(label: "Disponible", value: m.available ? "oui" : "non\(m.reason.map { " — \($0)" } ?? "")\(m.code.map { " [\($0)]" } ?? "")")247                if let k = m.kind { Field(label: "Nature du mandat", value: "\(k)\(m.shape.map { " · \($0)" } ?? "")") }248                Field(label: "Approbation", value: m.approval.note)249                if let p = m.pending { Field(label: "Mandat en attente", value: "\(p.mandateId) — \(p.state)", mono: true) }250                if let c = m.checklist { Field(label: "Liste de contrôle", value: c) }251                if let f = m.fields, !f.isNull { Text("Champs").font(.caption.weight(.semibold)); JSONFacts(value: f, depth: 3) }252                if let r = m.readiness, !r.isNull { DisclosureGroup("État de préparation") { JSONFacts(value: r, depth: 3).padding(.top, 6) } }253                Text("Lire ce brouillon ne prépare rien au signataire et n’accorde rien.").font(.caption).foregroundStyle(.secondary)254            } else { Unavailable(what: "Brouillon de mandat", error: d.error("mandateDraft")) }255        }256        .task { await d.loadConfig() }257    }258}259260struct StatementsCard: View {261    let can: [String]; let cannot: [String]; let notBounded: [String]262    var body: some View {263        Card("Ce que le signataire isolé borne — et ne borne pas") {264            StatementList(title: "Sous mandat, la clé PEUT", symbol: "checkmark.circle", color: Theme.positive, items: can)265            StatementList(title: "Elle NE PEUT PAS", symbol: "xmark.circle", color: .secondary, items: cannot)266            StatementList(title: "Le signataire NE BORNE PAS", symbol: "exclamationmark.triangle.fill", color: Theme.negative, items: notBounded)267            Text("Source : décision d’architecture sur la garde des clés (ADR 0001) du serveur. Révoquer une autorité permanente ne demande jamais de passkey et est définitif.").font(.caption).foregroundStyle(.secondary)268        }269    }270}271272// MARK: configuration273274/// Scalar server values edited as text and rebuilt with their original JSON type. An empty or non-finite limit is refused.275enum JSONEdit {276    static func editable(_ v: JSONValue) -> String? {277        switch v { case .int(let i): String(i); case .double(let x): AgentCreateForm.plain(x); case .string(let s): s; case .bool(let b): b ? "true" : "false"; default: nil }278    }279    static func rebuild(_ text: String, like original: JSONValue) -> JSONValue? {280        switch original {281        case .int, .double:282            guard let v = AgentText.decimal(text), v <= 1e12 else { return nil }283            if case .int = original, v == v.rounded() { return .int(Int64(v)) }284            return v == v.rounded() && abs(v) < 9e15 ? .int(Int64(v)) : .double(v)285        case .bool: return text == "true" ? .bool(true) : text == "false" ? .bool(false) : nil286        case .string: return text.trimmingCharacters(in: .whitespaces).isEmpty ? nil : .string(text)287        default: return original288        }289    }290}291292struct AgentConfigSection: View {293    let model: AppModel294    let d: AgentDetailStore295    @State private var editing = false296    @State private var configText: [String: String] = [:]297    @State private var riskText: [String: String] = [:]298    @State private var perp: [String: String] = [:]299    @State private var liftHalt = false300301    private var runtimeConfig: [String: JSONValue] { d.overview?.runtime?.config?.objectValue ?? [:] }302    private var riskLimits: [String: JSONValue] { d.summary?.riskLimits.objectValue ?? [:] }303    private var stopped: Bool { d.summary.map { $0.state != .active && !$0.isWindingDown } ?? false }304305    var body: some View {306        let a = d.agent307        Card("Configuration en service") {308            Field(label: "Version", value: "v\(d.summary?.configVersion ?? a?.configVersion ?? 0)", emphasis: true)309            if let rt = d.overview?.runtime {310                Field(label: "Règle / plateformes", value: "\(rt.rule ?? "—") · \(rt.venues.joined(separator: ", "))")311                JSONFacts(value: rt.config, depth: 3, empty: "Aucun paramètre publié.")312                if let c = rt.counters, !c.isNull { DisclosureGroup("Compteurs du moteur") { JSONFacts(value: c, depth: 3).padding(.top, 6) } }313                if let p = rt.lastPass, !p.isNull { DisclosureGroup("Dernière passe du moteur") { JSONFacts(value: p, depth: 3).padding(.top, 6) } }314            } else if case .perp(let p)? = d.detail {315                Field(label: "Exécution", value: "\(p.execution.kind)\(p.execution.network.map { " · \($0)" } ?? "") — \(p.execution.note)")316                if let r = p.rules, !r.isNull { DisclosureGroup("Simplifications et garde-fous déclarés de la simulation") { JSONFacts(value: r, depth: 3).padding(.top, 6) } }317            } else { Text("Les paramètres de cet agent sont ses marchés, son pas de temps et ses limites (onglet Mandat et risques).").foregroundStyle(.secondary) }318        }319        if let a { editor(a) }320        Card("Versions de configuration") {321            if let v = d.configVersions {322                if v.isEmpty { Text("Aucune version enregistrée.").foregroundStyle(.secondary) }323                ForEach(v, id: \.version) { x in324                    DisclosureGroup("v\(x.version) · \(Fmt.date(x.createdAt)) · \(x.actor) — \(x.reason)") {325                        VStack(alignment: .leading, spacing: 4) { Field(label: "SHA-256", value: x.sha256, mono: true); JSONFacts(value: x.config, depth: 3) }.padding(.top, 6)326                    }327                }328            } else { Unavailable(what: "Versions", error: d.error("configVersions")) }329        }330        .task { await d.loadConfig() }331    }332333    @ViewBuilder private func editor(_ a: Agent) -> some View {334        switch a.resolvedKind {335        case .stream, .supervisor:336            Card("Modifier la configuration et les limites") {337                if !stopped { Text("L’agent doit être en pause ou arrêté pour être reconfiguré.").foregroundStyle(.secondary) }338                else if !editing { Button("Modifier…") { configText = runtimeConfig.compactMapValues(JSONEdit.editable); riskText = riskLimits.compactMapValues(JSONEdit.editable); editing = true }.disabled(!model.canOperate) }339                else {340                    Form {341                        if !configText.isEmpty { SwiftUI.Section("Paramètres") { ForEach(configText.keys.sorted(), id: \.self) { k in TextField(k, text: Binding(get: { configText[k] ?? "" }, set: { configText[k] = $0 })).font(Theme.monoSmall) } } }342                        if !riskText.isEmpty { SwiftUI.Section("Limites de risque") { ForEach(riskText.keys.sorted(), id: \.self) { k in TextField(k, text: Binding(get: { riskText[k] ?? "" }, set: { riskText[k] = $0 })).font(Theme.monoSmall) } } }343                    }.formStyle(.grouped).scrollDisabled(true)344                    let problem = editProblem345                    if let problem { Text(problem).font(.callout).foregroundStyle(Theme.warning) }346                    Text("Les valeurs imbriquées restent inchangées. Une limite ne peut être ni vidée ni rendue illimitée ; le serveur vérifie ses propres bornes.").font(.caption).foregroundStyle(.secondary)347                    HStack {348                        Button("Annuler") { editing = false }349                        Spacer()350                        if d.busy != nil { ProgressView().controlSize(.small) }351                        Button("Enregistrer une nouvelle version") { Task { if await save() { editing = false } } }.buttonStyle(.borderedProminent).disabled(problem != nil || !model.canOperate || d.busy != nil)352                    }353                }354                if let e = d.actionError { Banner(.danger, e) }355            }356        case .perp:357            let sim = ModeKind(.paper)358            Card("Limites de la simulation", trailing: AnyView(ModeTag(kind: sim))) {359                if a.mode == .live { Text("En réel, les limites de l’agent sont celles de son mandat : elles ne se modifient pas ici. Arrêtez l’agent et approuvez un nouveau mandat pour les changer.").foregroundStyle(.secondary) }360                else if let r = a.perpRisk {361                    if !editing {362                        Button("Modifier les limites · PAPIER…") {363                            perp = ["lev": String(r.maxLeverage), "gross": AgentCreateForm.plain(r.maxGrossExposureX), "pos": AgentCreateForm.plain(r.maxPositionX), "day": AgentCreateForm.plain(r.maxDailyLossPct),364                                    "total": AgentCreateForm.plain(r.maxTotalLossPct), "slip": String(r.slippageBps), "min": AgentCreateForm.plain(r.minTradePct)]365                            liftHalt = false; editing = true366                        }.disabled(!model.canOperate)367                    } else {368                        Form {369                            perpField("Levier maximal (entier, 1–5)", "lev"); perpField("Exposition brute (× capital, 0,1–5)", "gross"); perpField("Position par instrument (× capital, 0,05–5)", "pos")370                            perpField("Perte quotidienne (%, 0,01–50)", "day"); perpField("Perte totale (%, 0,01–90)", "total"); perpField("Glissement (pb, 5–100)", "slip"); perpField("Rééquilibrage minimal (%)", "min")371                            Toggle("Lever le disjoncteur du compte simulé", isOn: $liftHalt)372                        }.formStyle(.grouped).scrollDisabled(true)373                        let risk = perpRisk374                        if risk == nil { Text("Chaque limite est obligatoire et doit rester dans ses bornes ; la perte quotidienne ne dépasse pas la perte totale.").font(.callout).foregroundStyle(Theme.warning) }375                        HStack {376                            Button("Annuler") { editing = false }377                            Spacer()378                            ModeButton(title: "Enregistrer les limites", kind: sim, prominent: true) { Task { if let risk, await d.setPerpRisk(risk, liftHalt: liftHalt) { editing = false } } }.disabled(risk == nil || !model.canOperate || d.busy != nil)379                        }380                    }381                } else { Text("Limites illisibles.").foregroundStyle(.secondary) }382                if let e = d.actionError { Banner(.danger, e) }383            }384        default:385            Card("Modifier les limites") { Text("Les limites d’un agent au comptant sont fixées à sa création : elles déterminent le mandat. Pour d’autres limites, créez un nouvel agent.").foregroundStyle(.secondary) }386        }387    }388389    private func perpField(_ label: String, _ key: String) -> some View { TextField(label, text: Binding(get: { perp[key] ?? "" }, set: { perp[key] = $0 })) }390391    private var perpRisk: PerpAgentRisk? {392        func v(_ k: String, _ r: ClosedRange<Double>, integer: Bool = false) -> Double? {393            guard let x = AgentText.decimal(perp[k] ?? ""), r.contains(x), !integer || x == x.rounded() else { return nil }394            return x395        }396        guard let lev = v("lev", 1...5, integer: true), let gross = v("gross", 0.1...5), let pos = v("pos", 0.05...5), let day = v("day", 0.01...50), let total = v("total", 0.01...90),397              let slip = v("slip", 5...100, integer: true), let min = v("min", 0...100), day <= total else { return nil }398        return PerpAgentRisk(maxLeverage: Int(lev), maxGrossExposureX: gross, maxPositionX: pos, maxDailyLossPct: day, maxTotalLossPct: total, slippageBps: Int(slip), minTradePct: min)399    }400401    private var editProblem: String? {402        for (k, t) in configText { if let o = runtimeConfig[k], JSONEdit.rebuild(t, like: o) == nil { return "Paramètre « \(k) » : valeur invalide." } }403        for (k, t) in riskText { if let o = riskLimits[k], JSONEdit.rebuild(t, like: o) == nil { return "Limite « \(k) » : valeur requise, finie et non négative. Une limite ne peut pas être vidée." } }404        return nil405    }406407    private func save() async -> Bool {408        var config = runtimeConfig, risk = riskLimits409        for (k, t) in configText { if let o = runtimeConfig[k], let v = JSONEdit.rebuild(t, like: o) { config[k] = v } }410        for (k, t) in riskText { if let o = riskLimits[k], let v = JSONEdit.rebuild(t, like: o) { risk[k] = v } }411        return await d.updateConfig(config: config == runtimeConfig ? nil : config, risk: risk == riskLimits ? nil : risk)412    }413}414
Files main
Menu

Theme