SPB Git

Repository Public

AgentsLogic.swift 39.8 KB 670 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/TradingAgents/AgentsLogic.swift10// Description      : The rules of the trading-agent screens, kept apart from11//                    the views so that they are tested: how a mode is named12//                    (SIMULATION / PAPIER / RÉEL, TESTNET / MAINNET — "argent13//                    réel" only when the Core says so), how a server state is14//                    worded, the guard that refuses a figure of one mode under15//                    the heading of another, the stop actions (none of them16//                    takes a passkey), and the forms where the owner types17//                    every limit himself (no default, expiry mandatory).18// Module           : Features19// Repository       : https://git.spboucher.ai/sp-wallet-ios20// Created          : 2026-11-1821// Last Modified    : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import SPWalletCore9798// MARK: mode naming99100/** The badge of a mode: always a word and an icon, never a colour alone. */101struct AgentModeBadge: Equatable, Sendable {102    let text: String103    let tone: Tone104    let icon: String105    /** True only when the Core's `tradesRealMoney` said so. */106    let realMoney: Bool107108    static func of(_ a: Agent) -> AgentModeBadge {109        // the server keeps the mode of a stopped agent: a live agent that is STOPPED trades nothing any more, and must not read as trading real money110        if a.mode == .live, a.state == "STOPPED" { return AgentModeBadge(text: String(localized: "RÉEL · arrêté"), tone: .neutral, icon: "bolt.slash.fill", realMoney: false) }111        return of(mode: a.mode, kind: a.resolvedKind, liveNetwork: a.liveNetwork, tradesRealMoney: a.tradesRealMoney)112    }113114    /** `tradesRealMoney` is the Core's verdict; nil when the record at hand cannot tell (a summary without its network). */115    static func of(mode: AgentMode, kind: AgentKind, liveNetwork: String?, tradesRealMoney: Bool?) -> AgentModeBadge {116        switch mode {117        case .research: return AgentModeBadge(text: String(localized: "SIMULATION"), tone: .info, icon: "flask.fill", realMoney: false)118        case .paper: return AgentModeBadge(text: String(localized: "PAPIER"), tone: .warn, icon: "doc.plaintext.fill", realMoney: false)119        case .live:120            let real = tradesRealMoney == true121            if kind == .perp {122                switch liveNetwork {123                case "mainnet": return AgentModeBadge(text: real ? String(localized: "RÉEL · MAINNET · argent réel") : String(localized: "RÉEL · MAINNET"), tone: .danger, icon: "bolt.fill", realMoney: real)124                case "testnet": return AgentModeBadge(text: String(localized: "RÉEL · TESTNET · argent de test"), tone: .warn, icon: "bolt.badge.clock.fill", realMoney: false)125                default: return AgentModeBadge(text: String(localized: "RÉEL · réseau non précisé"), tone: .danger, icon: "bolt.fill", realMoney: false)126                }127            }128            return AgentModeBadge(text: real ? String(localized: "RÉEL · argent réel") : String(localized: "RÉEL"), tone: .danger, icon: "bolt.fill", realMoney: real)129        case .unknown: return AgentModeBadge(text: String(localized: "MODE INCONNU"), tone: .neutral, icon: "questionmark.circle", realMoney: false)130        }131    }132133    /** The plain name of a mode for headings and for the label next to a figure. */134    static func name(_ m: AgentMode) -> String {135        switch m {136        case .research: String(localized: "SIMULATION")137        case .paper: String(localized: "PAPIER")138        case .live: String(localized: "RÉEL")139        case .unknown: String(localized: "MODE INCONNU")140        }141    }142143    /** What the mode means, in one sentence. */144    static func meaning(_ m: AgentMode) -> String {145        switch m {146        case .research: String(localized: "Simulation sur données historiques — ne garantit rien. Aucun ordre n’est passé.")147        case .paper: String(localized: "Ordres et exécutions simulés sur les marchés du moment. Aucun argent ne bouge.")148        case .live: String(localized: "Ordres réels, signés par le signataire isolé dans les limites du mandat approuvé.")149        case .unknown: String(localized: "Mode non reconnu par cette version de l’app : rien n’est supposé.")150        }151    }152}153154/** A figure may only be shown under the heading of its own mode. Anything else is an error on screen, never a number. */155enum ModeGuard {156    static func mismatch(got: AgentMode, heading: AgentMode) -> APIError {157        APIError(status: 200, code: "mode_mismatch", message: "a \(got.rawValue) figure was about to be shown under the \(heading.rawValue) heading: refused")158    }159    static func check(_ got: AgentMode, heading: AgentMode) throws {160        guard got == heading, got != .unknown else { throw mismatch(got: got, heading: heading) }161    }162    static func figure(_ f: ModedFigure, heading: AgentMode) throws -> ModedFigure { try check(f.mode, heading: heading); return f }163    static func scoped<V>(_ s: ModeScoped<V>, heading: AgentMode) throws -> V { try check(s.mode, heading: heading); return s.value }164165    /** The label that travels with every figure: the mode's name, and for a simulation what it is worth. */166    static func label(_ m: AgentMode) -> String {167        switch m {168        case .research: String(localized: "simulation sur données historiques — ne garantit rien")169        case .paper: String(localized: "papier — ordres simulés, aucun argent n’a bougé")170        case .live: String(localized: "réel")171        case .unknown: String(localized: "mode inconnu")172        }173    }174}175176// MARK: state wording177178struct AgentStateLabel: Equatable, Sendable {179    let text: String180    let tone: Tone181    let icon: String182183    /** The historical state text of the server. A state this code does not know is shown verbatim. */184    static func of(_ state: String) -> AgentStateLabel {185        switch state {186        case "CREATED": AgentStateLabel(text: String(localized: "Créé, jamais démarré"), tone: .neutral, icon: "circle.dashed")187        case "AWAITING_APPROVAL": AgentStateLabel(text: String(localized: "Stratégie approuvée, à démarrer"), tone: .info, icon: "hourglass")188        case "PAPER_TRADING": AgentStateLabel(text: String(localized: "En marche"), tone: .ok, icon: "play.circle.fill")189        case "RUNNING": AgentStateLabel(text: String(localized: "En marche"), tone: .ok, icon: "play.circle.fill")190        case "LIVE": AgentStateLabel(text: String(localized: "En marche"), tone: .ok, icon: "play.circle.fill")191        case "PAUSED": AgentStateLabel(text: String(localized: "En pause"), tone: .warn, icon: "pause.circle.fill")192        case "STOPPING": AgentStateLabel(text: String(localized: "Arrêt en cours : clôture des positions"), tone: .warn, icon: "arrow.down.to.line.circle.fill")193        case "STOPPED": AgentStateLabel(text: String(localized: "Arrêté"), tone: .neutral, icon: "stop.circle.fill")194        default: AgentStateLabel(text: state, tone: .neutral, icon: "questionmark.circle")195        }196    }197    static func isRunning(_ state: String) -> Bool { ["PAPER_TRADING", "RUNNING", "LIVE"].contains(state) }198    static func isPaused(_ state: String) -> Bool { state == "PAUSED" }199    static func isWindingDown(_ state: String) -> Bool { state == "STOPPING" }200}201202extension VaultReturnState {203    var label: String {204        switch self {205        case .requested: String(localized: "Demandé, pas encore signé")206        case .signed: String(localized: "Signé, pas encore diffusé")207        case .broadcast: String(localized: "Diffusé, non confirmé")208        case .confirmed: String(localized: "Confirmé par le réseau")209        case .failed: String(localized: "Échoué")210        case .notSent: String(localized: "Signé mais non diffusé (diffusion désactivée sur ce serveur)")211        case .unknown: String(localized: "État inconnu")212        }213    }214    var tone: Tone { self == .confirmed ? .ok : self == .failed ? .danger : self == .notSent ? .warn : self == .unknown ? .neutral : .info }215}216217extension AgentJobStatus {218    var label: String {219        switch self {220        case .queued: String(localized: "En file d’attente")221        case .running: String(localized: "En cours")222        case .done: String(localized: "Terminé")223        case .failed: String(localized: "Échoué")224        case .cancelled: String(localized: "Annulé")225        case .unknown: String(localized: "État inconnu")226        }227    }228    var tone: Tone { self == .done ? .ok : self == .failed ? .danger : self == .cancelled || self == .unknown ? .neutral : .info }229}230231// MARK: stopping — never a passkey232233/** Everything that removes risk. None of these calls takes an authenticator: stopping never waits for a passkey. */234enum AgentStopAction: String, CaseIterable, Sendable {235    case pause, stop, revokeMandate, flattenPaper, pullQuotes, flattenInventory, engageKillSwitch236237    var requiresPasskey: Bool { false }238    /** Cannot be undone from this screen. */239    var isFinal: Bool { self == .stop || self == .revokeMandate }240241    var title: String {242        switch self {243        case .pause: String(localized: "Mettre en pause")244        case .stop: String(localized: "Arrêter")245        case .revokeMandate: String(localized: "Révoquer le mandat")246        case .flattenPaper: String(localized: "Clore les positions (papier)")247        case .pullQuotes: String(localized: "Retirer les cotations")248        case .flattenInventory: String(localized: "Retirer les cotations et clore l’inventaire")249        case .engageKillSwitch: String(localized: "Engager l’arrêt d’urgence")250        }251    }252253    /** What the confirmation says before the single tap that runs it. */254    func consequence(agent a: Agent?) -> String {255        let live = a?.mode == .live256        switch self {257        case .pause:258            if live, a?.resolvedKind == .spot { return String(localized: "Aucune nouvelle exposition. Le mandat de cet agent est révoqué chez le signataire tout de suite : reprendre en réel demandera un nouveau mandat approuvé par ta clé d’accès.") }259            if live { return String(localized: "Aucune nouvelle exposition. Les positions sont CONSERVÉES sur le compte et le mandat reste actif.") }260            return String(localized: "L’agent ne prend plus de décision tant qu’il est en pause. Aucune clé d’accès n’est demandée.")261        case .stop:262            if live, a?.resolvedKind == .perp { return String(localized: "Définitif pour ce mandat : il est révoqué et les positions sont closes par des ordres en réduction seule pendant la période de clôture annoncée par le serveur. Aucune clé d’accès n’est demandée.") }263            if live { return String(localized: "Définitif pour ce mandat : il est révoqué chez le signataire. Les fonds restent dans le coffre. Aucune clé d’accès n’est demandée.") }264            return String(localized: "L’agent s’arrête maintenant. Aucune clé d’accès n’est demandée.")265        case .revokeMandate: return String(localized: "Définitif : le mandat est révoqué chez le signataire et l’agent s’arrête. Repasser en réel demandera un nouveau mandat approuvé par ta clé d’accès. Les fonds restent dans le coffre.")266        case .flattenPaper: return String(localized: "Toutes les positions du compte PAPIER sont closes par des ordres simulés en réduction seule. Rien n’atteint la plateforme.")267        case .pullQuotes: return String(localized: "Toutes les cotations en attente sont retirées maintenant. L’inventaire est conservé.")268        case .flattenInventory: return String(localized: "Les cotations sont retirées et l’inventaire est clos par des ordres en réduction seule.")269        case .engageKillSwitch: return String(localized: "Plus aucun agent, clé ou mandat ne peut ajouter de risque tant que l’arrêt n’est pas levé. Le lever demande ta clé d’accès, dans « Risque et limites ».")270        }271    }272}273274/** Runs the stop actions. The signature carries no authenticator: there is no way to make a stop wait for a passkey. */275struct AgentStopRunner: Sendable {276    let api: AgentsAPI277278    /** Returns the state the SERVER answered, to be displayed as it is. */279    func run(_ action: AgentStopAction, agent a: Agent) async throws -> String {280        switch action {281        case .pause:282            let s = try await api.pause(a.id)283            return AgentStateLabel.of(s.phase).text284        case .stop:285            if a.resolvedKind == .perp, a.mode == .live {286                let d = try await api.stopPerpLive(a.id)287                let state = AgentStateLabel.of(d.agent.state).text288                guard let w = d.windDown else { return state }289                return [state, w.text, w.until.map { String(localized: "Clôture jusqu’au \($0.formatted(date: .abbreviated, time: .shortened))") },290                        w.openPositions.map { String(localized: "\($0) position(s) ouverte(s)") }].compactMap { $0 }.joined(separator: " · ")291            }292            let s = try await api.stop(a.id)293            return AgentStateLabel.of(s.phase).text + (s.isWindingDown ? " · " + String(localized: "clôture en cours") : "")294        case .revokeMandate: return AgentStateLabel.of(try await api.revokeMandate(a.id).state).text295        case .flattenPaper:296            let r = try await api.flattenPerpPaper(a.id)297            return String(localized: "\(r.orders.count) ordre(s) simulé(s) · \(r.positionsLeft) position(s) restante(s) (papier)")298        case .pullQuotes: return Self.describe(try await api.pullQuotes(a.id))299        case .flattenInventory: return Self.describe(try await api.flattenInventory(a.id))300        case .engageKillSwitch:301            let k = try await api.engageKillSwitch()302            return k.engaged ? String(localized: "Arrêt d’urgence engagé") : String(localized: "Le serveur n’a PAS confirmé l’arrêt d’urgence")303        }304    }305306    static func describe(_ r: MarketMakingCommandResult) -> String {307        let how: String = switch r.taken {308        case "engine": String(localized: "pris par la session en cours")309        case "queued": String(localized: "mis en file pour la session")310        case "direct": String(localized: "exécuté directement sur la plateforme")311        case "nothing": String(localized: "rien à faire : aucune session réelle et rien sur une plateforme")312        default: r.taken313        }314        return [r.command + " : " + how, r.note].compactMap { $0 }.joined(separator: " — ")315    }316}317318// MARK: typed limits319320enum LimitInput {321    /** Accepts "," as the decimal separator; no thousands separator, no sign, no exponent. */322    static func normalized(_ s: String) -> String { s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".") }323    static func usd(_ s: String) -> USDLimit? { try? USDLimit(normalized(s)) }324    static func int(_ s: String) -> Int? {325        let t = s.trimmingCharacters(in: .whitespaces)326        guard !t.isEmpty, t.count <= 9, t.allSatisfy(\.isASCII), t.allSatisfy(\.isNumber) else { return nil }327        return Int(t)328    }329    static func number(_ s: String) -> Double? {330        let t = normalized(s)331        guard t.range(of: #"^\d{1,9}(\.\d{1,8})?$"#, options: .regularExpression) != nil else { return nil }332        return Double(t)333    }334    /** Canonical decimal text of a server amount (so that "100" and "100.0" compare equal). */335    static func canonical(_ s: String) -> String? { usd(s)?.text }336}337338/**339 Going live with a spot agent. The limits of a spot agent are fixed when it is created (the server has no route to change them) and340 the mandate is built from them; the owner types every one of them again here, and the mandate the server prepares is then compared341 by the Core with what was TYPED. Every field starts empty; nothing is pre-selected.342 */343struct SpotLiveForm: Equatable, Sendable {344    enum Field: String, CaseIterable, Sendable { case budget, maxOrder, maxDaily, ordersPerDay, lossPct, days, assets }345346    var budget = ""347    var maxOrder = ""348    var maxDaily = ""349    var ordersPerDay = ""350    var lossPct = ""351    /** Validity of the mandate, days. Mandatory: there is no "no expiry". */352    var days = ""353    /** Registry assets the owner ticked (ids of `Agent.holdings`). */354    var assets: Set<String> = []355356    func isEmpty(_ f: Field) -> Bool {357        switch f {358        case .budget: budget.isEmpty359        case .maxOrder: maxOrder.isEmpty360        case .maxDaily: maxDaily.isEmpty361        case .ordersPerDay: ordersPerDay.isEmpty362        case .lossPct: lossPct.isEmpty363        case .days: days.isEmpty364        case .assets: assets.isEmpty365        }366    }367368    /** Why a field cannot be used yet. An empty field has no message: it is simply missing. */369    func problem(_ f: Field, agent a: Agent) -> String? {370        guard !isEmpty(f) else { return nil }371        let risk = a.spotRisk372        func differs(_ stored: String) -> String { String(localized: "Différent de la limite fixée à la création de l’agent (\(stored)). Les limites d’un agent spot ne se modifient pas : crée un autre agent pour d’autres limites.") }373        switch f {374        case .budget:375            guard let v = LimitInput.usd(budget) else { return String(localized: "Montant invalide.") }376            guard let stored = LimitInput.canonical(a.capitalUsdc) else { return String(localized: "Le budget de l’agent est illisible : passage en réel impossible ici.") }377            return v.text == stored ? nil : differs(stored + " USD")378        case .maxOrder:379            guard let v = LimitInput.usd(maxOrder) else { return String(localized: "Montant invalide.") }380            guard let r = risk else { return String(localized: "Les limites de l’agent sont illisibles.") }381            return v == r.maxOrderUsd ? nil : differs(r.maxOrderUsd.text + " USD")382        case .maxDaily:383            guard let v = LimitInput.usd(maxDaily) else { return String(localized: "Montant invalide.") }384            guard let r = risk else { return String(localized: "Les limites de l’agent sont illisibles.") }385            return v == r.maxDailyUsd ? nil : differs(r.maxDailyUsd.text + " USD")386        case .ordersPerDay:387            guard let v = LimitInput.int(ordersPerDay), v >= 1 else { return String(localized: "Nombre entier d’au moins 1.") }388            guard let r = risk else { return String(localized: "Les limites de l’agent sont illisibles.") }389            return v == r.maxOrdersPerDay ? nil : differs(String(r.maxOrdersPerDay))390        case .lossPct:391            guard let v = LimitInput.number(lossPct), v > 0, v <= 100 else { return String(localized: "Pourcentage entre 0 et 100.") }392            guard let r = risk else { return String(localized: "Les limites de l’agent sont illisibles.") }393            return v == r.maxLossPct ? nil : differs(AgentFmt.number(r.maxLossPct) + " %")394        case .days:395            guard let v = LimitInput.int(days), v >= 1, v <= 90 else { return String(localized: "Durée de 1 à 90 jours : un mandat a toujours une date d’expiration.") }396            guard let r = risk else { return String(localized: "Les limites de l’agent sont illisibles.") }397            return v == r.mandateDays ? nil : differs(String(localized: "\(r.mandateDays) jours"))398        case .assets:399            let all = Set((a.holdings ?? []).map(\.asset))400            return assets == all ? nil : String(localized: "Coche chaque actif que le mandat autorisera. Un mandat spot couvre tous les actifs de l’agent : pour en retirer un, crée un autre agent.")401        }402    }403404    var missing: [Field] { Field.allCases.filter(isEmpty) }405    func isComplete(agent a: Agent) -> Bool { missing.isEmpty && Field.allCases.allSatisfy { problem($0, agent: a) == nil } }406407    /**408     What the mandate must say, built from what was TYPED (never from a default): the Core then refuses any mandate that says409     something else. The vault, the strategy hash and the slippage rule are not typed — they come from the agent and are reviewed.410     */411    func expectation(detail d: SpotAgentDetail, network n: Network) throws -> SpotMandateExpectation {412        let a = d.agent413        guard isComplete(agent: a) else { throw ApprovalError.inconsistent("the limits were not all entered") }414        guard n.id == a.network else { throw ApprovalError.inconsistent("network") }415        guard let order = LimitInput.usd(maxOrder), let daily = LimitInput.usd(maxDaily), let count = LimitInput.int(ordersPerDay), let validity = LimitInput.int(days) else { throw ApprovalError.inconsistent("limits") }416        guard let risk = a.spotRisk else { throw ApprovalError.unsupported("the agent's limits cannot be read exactly") }417        guard let index = a.vaultIndex, a.hasVault else { throw ApprovalError.unsupported("the agent has no vault") }418        guard let v = d.approvedVersion else { throw ApprovalError.unsupported("no approved strategy version") }419        let chosen = try (a.holdings ?? []).filter { assets.contains($0.asset) }.map { h -> SpotMandateExpectation.Asset in420            guard let def = n.asset(h.asset) else { throw ApprovalError.unsupported("asset \(h.asset) is not in the registry of \(n.id)") }421            return .init(id: h.asset, symbol: h.assetSymbol, decimals: def.decimals, isCash: h.isCash)422        }423        return SpotMandateExpectation(vault: a.vaultAddress, vaultIndex: index, network: a.network, assets: chosen, maxOrderUsd: order, maxDailyUsd: daily, maxOrdersPerDay: count,424                                      slippageBps: risk.slippageBps, mandateDays: validity, strategySha256: v.sha256, agentName: a.name)425    }426}427428/** Going live with a perp agent: the venue account is chosen (never pre-selected), the validity and the leverage ceiling are typed. */429struct PerpLiveForm: Equatable, Sendable {430    var accountId: String?431    var days = ""432    var maxLeverage = ""433434    func daysProblem(maxDays: Int?) -> String? {435        guard !days.isEmpty else { return nil }436        guard let v = LimitInput.int(days), v >= 1 else { return String(localized: "Durée en jours entiers, au moins 1 : un mandat a toujours une date d’expiration.") }437        if let maxDays, v > maxDays { return String(localized: "Au plus \(maxDays) jours sur ce compte.") }438        return nil439    }440    func leverageProblem(agent a: Agent) -> String? {441        guard !maxLeverage.isEmpty else { return nil }442        guard let v = LimitInput.int(maxLeverage), v >= 1 else { return String(localized: "Levier entier d’au moins 1.") }443        guard let r = a.perpRisk else { return String(localized: "Les limites de l’agent sont illisibles.") }444        return v == r.maxLeverage ? nil : String(localized: "Différent du levier maximal de l’agent (\(r.maxLeverage)×). Change d’abord les limites de l’agent en simulation, ou saisis ce levier.")445    }446    /** Enough to ask the server for the checklist of this account over this validity. */447    func canAskReadiness(maxDays: Int?) -> Bool { accountId != nil && !days.isEmpty && daysProblem(maxDays: maxDays) == nil }448    func isComplete(agent a: Agent, maxDays: Int?) -> Bool { canAskReadiness(maxDays: maxDays) && !maxLeverage.isEmpty && leverageProblem(agent: a) == nil }449    var typedDays: Int? { LimitInput.int(days) }450}451452// MARK: creation forms — every limit typed, nothing defaulted; a new agent is never live453454struct SpotCreateForm: Equatable, Sendable {455    var name = ""456    var mission = ""457    var network: String?458    var symbols: Set<String> = []459    var cash: String?460    var interval: String?461    var capital = ""462    var exposurePct = ""463    var lossPct = ""464    var maxOrder = ""465    var maxDaily = ""466    var ordersPerDay = ""467    var mandateDays = ""468    var slippageBps = ""469470    /** The first thing that is missing or out of the server's bounds, or nil when the request can be built. */471    func problem(maxSymbols: Int) -> String? {472        if name.trimmingCharacters(in: .whitespaces).isEmpty { return String(localized: "Donne un nom à l’agent.") }473        if network == nil { return String(localized: "Choisis le réseau du coffre.") }474        if symbols.isEmpty { return String(localized: "Choisis au moins un marché.") }475        if symbols.count > maxSymbols { return String(localized: "Au plus \(maxSymbols) marchés.") }476        if cash == nil { return String(localized: "Choisis la monnaie de réserve.") }477        if interval == nil { return String(localized: "Choisis l’intervalle de décision.") }478        guard LimitInput.usd(capital) != nil else { return String(localized: "Saisis le budget maximal (USD).") }479        guard let e = LimitInput.number(exposurePct), e >= 1, e <= 100 else { return String(localized: "Saisis l’exposition maximale (1 à 100 %).") }480        guard let l = LimitInput.number(lossPct), l >= 1, l <= 100 else { return String(localized: "Saisis la limite de perte (1 à 100 %).") }481        guard let o = LimitInput.usd(maxOrder), let ov = Double(o.text), ov >= 1, ov <= 100_000 else { return String(localized: "Saisis le plafond par ordre (1 à 100 000 USD).") }482        guard let d = LimitInput.usd(maxDaily), let dv = Double(d.text), dv >= 1, dv <= 1_000_000 else { return String(localized: "Saisis le plafond de volume par jour (1 à 1 000 000 USD).") }483        if dv < ov { return String(localized: "Le plafond par jour ne peut pas être inférieur au plafond par ordre.") }484        guard let n = LimitInput.int(ordersPerDay), n >= 1, n <= 200 else { return String(localized: "Saisis le nombre d’ordres par jour (1 à 200).") }485        guard let m = LimitInput.int(mandateDays), m >= 1, m <= 90 else { return String(localized: "Saisis la durée d’un futur mandat (1 à 90 jours).") }486        guard let s = LimitInput.int(slippageBps), s >= 5, s <= 300 else { return String(localized: "Saisis le glissement toléré (5 à 300 pb).") }487        _ = (e, l, n, m, s)488        return nil489    }490491    func request(assets: [String: String], maxSymbols: Int) -> SpotAgentCreateRequest? {492        guard problem(maxSymbols: maxSymbols) == nil, let network, let cash, let interval, let cap = LimitInput.usd(capital), let e = LimitInput.number(exposurePct), let l = LimitInput.number(lossPct),493              let o = LimitInput.usd(maxOrder), let d = LimitInput.usd(maxDaily), let n = LimitInput.int(ordersPerDay), let m = LimitInput.int(mandateDays), let s = LimitInput.int(slippageBps) else { return nil }494        return SpotAgentCreateRequest(name: name.trimmingCharacters(in: .whitespaces), mission: mission.trimmingCharacters(in: .whitespaces), network: network, universe: symbols.sorted(), assets: assets, cash: cash, interval: interval,495                                      capitalUsdc: cap.text, risk: SpotAgentRisk(maxExposurePct: e, maxLossPct: l, maxOrderUsd: o, maxDailyUsd: d, maxOrdersPerDay: n, mandateDays: m, slippageBps: s))496    }497}498499struct PerpCreateForm: Equatable, Sendable {500    var name = ""501    var mission = ""502    var instruments: Set<String> = []503    var interval: String?504    var capital = ""505    var maxLeverage = ""506    var grossX = ""507    var positionX = ""508    var dailyLossPct = ""509    var totalLossPct = ""510    var slippageBps = ""511    var minTradePct = ""512513    func problem(maxInstruments: Int, minCapital: String) -> String? {514        if name.trimmingCharacters(in: .whitespaces).isEmpty { return String(localized: "Donne un nom à l’agent.") }515        if instruments.isEmpty { return String(localized: "Choisis au moins un contrat.") }516        if instruments.count > maxInstruments { return String(localized: "Au plus \(maxInstruments) contrats.") }517        if interval == nil { return String(localized: "Choisis l’intervalle de décision.") }518        guard let c = LimitInput.usd(capital), let cv = Double(c.text), cv >= (Double(minCapital) ?? 50) else { return String(localized: "Saisis le capital simulé (au moins \(minCapital) USDC).") }519        guard let lev = LimitInput.int(maxLeverage), lev >= 1, lev <= 5 else { return String(localized: "Saisis le levier maximal (entier de 1 à 5).") }520        guard let g = LimitInput.number(grossX), g >= 0.1, g <= 5 else { return String(localized: "Saisis l’exposition brute maximale (0,1 à 5 × le capital).") }521        guard let p = LimitInput.number(positionX), p >= 0.05, p <= 5 else { return String(localized: "Saisis la position maximale par contrat (0,05 à 5 × le capital).") }522        guard let dl = LimitInput.number(dailyLossPct), dl >= 0.01, dl <= 50 else { return String(localized: "Saisis la perte maximale par jour (0,01 à 50 %).") }523        guard let tl = LimitInput.number(totalLossPct), tl >= 0.01, tl <= 90 else { return String(localized: "Saisis la perte maximale totale (0,01 à 90 %).") }524        if dl > tl { return String(localized: "La perte par jour ne peut pas dépasser la perte totale.") }525        guard let s = LimitInput.int(slippageBps), s >= 5, s <= 100 else { return String(localized: "Saisis le glissement toléré (5 à 100 pb).") }526        guard let mt = LimitInput.number(minTradePct), mt > 0, mt <= 100 else { return String(localized: "Saisis le seuil minimal d’un rééquilibrage (% des fonds).") }527        _ = (cv, lev, g, p, s, mt)528        return nil529    }530531    func risk() -> PerpAgentRisk? {532        guard let lev = LimitInput.int(maxLeverage), let g = LimitInput.number(grossX), let p = LimitInput.number(positionX), let dl = LimitInput.number(dailyLossPct), let tl = LimitInput.number(totalLossPct),533              let s = LimitInput.int(slippageBps), let mt = LimitInput.number(minTradePct) else { return nil }534        return PerpAgentRisk(maxLeverage: lev, maxGrossExposureX: g, maxPositionX: p, maxDailyLossPct: dl, maxTotalLossPct: tl, slippageBps: s, minTradePct: mt)535    }536537    func request(maxInstruments: Int, minCapital: String) -> PerpAgentCreateRequest? {538        guard problem(maxInstruments: maxInstruments, minCapital: minCapital) == nil, let interval, let c = LimitInput.usd(capital), let r = risk() else { return nil }539        return PerpAgentCreateRequest(name: name.trimmingCharacters(in: .whitespaces), mission: mission.trimmingCharacters(in: .whitespaces), instruments: instruments.sorted(), interval: interval, capitalUsdc: c.text, risk: r)540    }541}542543/** An agent from a template: the template's proposals are shown as hints; every limit is typed by the owner. */544struct TemplateCreateForm: Equatable, Sendable {545    var name = ""546    var mission = ""547    var strategyPath: String?548    var capital = ""549    /** One text per key of the template's `defaults.risk`, empty at start. */550    var risk: [String: String] = [:]551    /** One text per key of the template's `defaults.config`. Filled only by the owner (typing, or the explicit "use the proposed parameters"). */552    var config: [String: String] = [:]553554    /** Text → the JSON type the template uses for that key. Nil when the text does not fit that type. */555    static func value(_ text: String, like proposal: JSONValue) -> JSONValue? {556        let t = text.trimmingCharacters(in: .whitespaces)557        guard !t.isEmpty else { return nil }558        switch proposal {559        case .bool: return t == "true" || t == "oui" ? .bool(true) : t == "false" || t == "non" ? .bool(false) : nil560        case .int: return LimitInput.int(t).map { .int(Int64($0)) } ?? LimitInput.number(t).map { .double($0) }561        case .double: return LimitInput.number(t).map { $0 == $0.rounded() && abs($0) < 1e15 ? .int(Int64($0)) : .double($0) }562        case .string(let s):563            // numeric text stays numeric text ("250"); a word (policy name) is kept as typed564            if Double(s) != nil { return LimitInput.number(t).map { _ in .string(LimitInput.normalized(t)) } }565            return .string(t)566        default: return nil567        }568    }569    static func text(_ v: JSONValue) -> String {570        switch v { case .string(let s): s; case .int(let i): String(i); case .double(let d): AgentFmt.plain(d); case .bool(let b): b ? "true" : "false"; default: "" }571    }572573    func problem(template t: AgentTemplate) -> String? {574        if name.trimmingCharacters(in: .whitespaces).isEmpty { return String(localized: "Donne un nom à l’agent.") }575        if !t.installed.isEmpty, strategyPath == nil { return String(localized: "Choisis la version de stratégie.") }576        if t.kind != "supervisor", LimitInput.usd(capital) == nil { return String(localized: "Saisis le capital (USD).") }577        for k in t.defaults.risk.keys.sorted() {578            guard let p = t.defaults.risk[k], let s = risk[k], Self.value(s, like: p) != nil else { return String(localized: "Saisis la limite « \(k) ».") }579        }580        for k in t.defaults.config.keys.sorted() {581            guard let p = t.defaults.config[k], let s = config[k], Self.value(s, like: p) != nil else { return String(localized: "Saisis le paramètre « \(k) ».") }582        }583        return nil584    }585586    func request(template t: AgentTemplate) -> TemplateAgentCreateRequest? {587        guard problem(template: t) == nil else { return nil }588        var r: [String: JSONValue] = [:], c: [String: JSONValue] = [:]589        for (k, p) in t.defaults.risk { if let v = risk[k].flatMap({ Self.value($0, like: p) }) { r[k] = v } }590        for (k, p) in t.defaults.config { if let v = config[k].flatMap({ Self.value($0, like: p) }) { c[k] = v } }591        let installed = t.installed.first { $0.path == strategyPath }592        let universe = installed.map { $0.generic == true ? ($0.defaultUniverse ?? t.defaults.universe) : $0.universe } ?? t.defaults.universe593        return TemplateAgentCreateRequest(template: t.id, name: name.trimmingCharacters(in: .whitespaces), mission: mission.trimmingCharacters(in: .whitespaces), strategyPath: strategyPath,594                                          universe: universe.isEmpty ? nil : universe, venues: t.defaults.venues.isEmpty ? nil : t.defaults.venues,595                                          capitalUsdc: t.kind == "supervisor" && capital.isEmpty ? t.defaults.capitalUsdc : (LimitInput.usd(capital)?.text ?? capital), risk: r, config: c.isEmpty ? nil : c)596    }597}598599// MARK: offline snapshots (keys prefixed `agents-`)600601/** What is kept of an agent's overview for read-only consultation. Public information only. */602struct AgentOverviewSnapshot: Codable, Sendable, Equatable {603    let id: String604    let name: String605    let mission: String606    let kind: AgentKind607    let family: String608    let phase: String609    let mode: AgentMode610    let venue: String611    let network: String?612    let universe: [String]613    let interval: String614    let capitalUsd: String615    let riskLimits: JSONValue616    let configVersion: Int617    let strategyName: String?618    let strategyVersion: String?619    let strategySha256: String?620    let stopReason: String?621622    init(_ s: AgentSummary) {623        id = s.id; name = s.name; mission = s.mission; kind = s.kind; family = s.family; phase = s.phase; mode = s.mode; venue = s.venue; network = s.network; universe = s.universe624        interval = s.interval; capitalUsd = s.capitalUsd; riskLimits = s.riskLimits; configVersion = s.configVersion625        strategyName = s.strategy?.name; strategyVersion = s.strategy?.version; strategySha256 = s.strategy?.sha256; stopReason = s.stopReason626    }627}628629enum AgentsCacheKey {630    static let list = "agents-list"631    static let killSwitch = "agents-kill-switch"632    static func overview(_ id: String) -> String { "agents-overview-\(id)" }633}634635// MARK: formatting636637enum AgentFmt {638    static func number(_ v: Double, max: Int = 4) -> String { v.formatted(.number.precision(.fractionLength(0...max))) }639    static func plain(_ v: Double) -> String { v == v.rounded() && abs(v) < 1e15 ? String(Int64(v)) : String(v) }640    static func percent(fraction v: Double) -> String { (v * 100).formatted(.number.precision(.fractionLength(0...2))) + " %" }641    static func usd(_ v: Double) -> String { v.formatted(.currency(code: "USD").precision(.fractionLength(2...2))) }642    static func date(_ d: Date) -> String { d.formatted(date: .abbreviated, time: .shortened) }643    static func time(_ d: Date) -> String { d.formatted(date: .numeric, time: .standard) }644    /** Text of a scalar JSON value as the server sent it. */645    static func json(_ v: JSONValue?) -> String? {646        switch v {647        case .string(let s)?: s648        case .int(let i)?: String(i)649        case .double(let d)?: number(d, max: 6)650        case .bool(let b)?: b ? String(localized: "oui") : String(localized: "non")651        default: nil652        }653    }654    /** Family identifier → words (`market_making` → "market making"); unknown families are shown as they are. */655    static func family(_ f: String?) -> String {656        switch f {657        case "custom"?: String(localized: "sur mesure")658        case "momentum"?: String(localized: "momentum")659        case "mean_reversion"?: String(localized: "retour à la moyenne")660        case "stat_arb"?: String(localized: "arbitrage statistique")661        case "funding_arb"?: String(localized: "arbitrage de financement")662        case "cross_exchange"?: String(localized: "arbitrage entre plateformes")663        case "market_making"?: String(localized: "tenue de marché")664        case "risk_manager"?: String(localized: "gestion du risque")665        case let f?: f.replacingOccurrences(of: "_", with: " ")666        case nil: String(localized: "famille non précisée")667        }668    }669}670
Files main
Menu

Theme