Repository Public
1// SP Wallet iOS2// File: Features/TradingAgents/AgentCreateFlow.swift3// Description: Creating an agent: from one of the server's templates (its modes, the reason it cannot go live and the laboratory4// verdict shown as served) or custom (spot with a vault, or perpetual contracts on a paper account). Every limit is5// typed by the owner — a template's proposals are hints beside empty fields — and a new agent always starts in6// simulation or on paper: nothing here can create a live agent or a mandate.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213@MainActor @Observable14final class AgentCreateModel {15 enum Kind: Equatable { case choose, template(String), spot, perp }16 var kind: Kind = .choose17 var templates: AgentTemplates?18 var networks: AgentNetworks?19 var venues: PerpVenues?20 var loadError: Error?21 var spot = SpotCreateForm()22 var perp = PerpCreateForm()23 var template = TemplateCreateForm()24 var busy = false25 var error: Error?26 /** What the server answered: id, name, mode, state, warnings. */27 var created: (id: String, name: String, badge: AgentModeBadge, state: String, warnings: [AgentWarning])?2829 func load(_ api: AgentsAPI) async {30 do {31 async let t = api.templates()32 async let n = api.networks()33 async let v = api.perpVenues()34 (templates, networks, venues) = try await (t, n, v)35 loadError = nil36 } catch { loadError = error }37 }3839 func submit(_ api: AgentsAPI) async {40 guard !busy else { return }41 busy = true; error = nil42 defer { busy = false }43 do {44 switch kind {45 case .spot:46 guard let n = networks, let r = spot.request(assets: [:], maxSymbols: n.maxSymbols) else { return }47 let a = try await api.create(r)48 created = (a.id, a.name, AgentModeBadge.of(a), a.state, a.warnings ?? [])49 case .perp:50 guard let v = venues, let r = perp.request(maxInstruments: v.maxInstruments, minCapital: v.minCapital) else { return }51 let a = try await api.create(r)52 created = (a.id, a.name, AgentModeBadge.of(a), a.state, a.warnings ?? [])53 case .template(let id):54 guard let t = templates?.templates.first(where: { $0.id == id }), let r = template.request(template: t) else { return }55 let c = try await api.create(r)56 // a summary carries no venue network: the Core cannot say "real money" from it, and a new agent is never live anyway57 created = (c.agent.id, c.agent.name, AgentModeBadge.of(mode: c.agent.mode, kind: c.agent.kind, liveNetwork: nil, tradesRealMoney: nil), c.agent.phase, c.warnings ?? [])58 case .choose: break59 }60 } catch { self.error = error }61 }62}6364struct AgentCreateFlow: View {65 @Environment(AppModel.self) private var model66 @Environment(\.dismiss) private var dismiss67 /** Called with the id of the created agent when the owner closes the result. */68 let done: (String) -> Void69 @State private var create = AgentCreateModel()7071 private var api: AgentsAPI { AgentsAPI(model.env.client) }7273 var body: some View {74 NavigationStack {75 ScrollView {76 VStack(alignment: .leading, spacing: Theme.Space.section) {77 if !model.canOperate { Notice(tone: .warn, title: String(localized: "Création indisponible hors ligne")) }78 if let c = create.created { result(c) }79 else {80 switch create.kind {81 case .choose: choose82 case .spot: spotForm83 case .perp: perpForm84 case .template(let id): templateForm(id)85 }86 }87 }88 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)89 .frame(maxWidth: 680).frame(maxWidth: .infinity)90 }91 .scrollDismissesKeyboard(.immediately)92 .spPage()93 .navigationTitle(String(localized: "Nouvel agent")).navigationBarTitleDisplayMode(.inline)94 .toolbar {95 ToolbarItem(placement: .cancellationAction) {96 if create.created == nil, create.kind != .choose { Button(String(localized: "Retour")) { create.kind = .choose; create.error = nil }.accessibilityIdentifier("create.back") }97 else { Button(String(localized: "Fermer")) { if let c = create.created { done(c.id) }; dismiss() }.accessibilityIdentifier("create.close") }98 }99 }100 .task { if create.templates == nil, model.canOperate { await create.load(api) } }101 }102 }103104 // MARK: choose105106 @ViewBuilder private var choose: some View {107 Notice(tone: .info, title: String(localized: "Un nouvel agent n’est jamais en réel"), message: String(localized: "Il démarre en simulation ou en papier. Passer en réel est une étape distincte : un mandat que tu approuves avec ta clé d’accès, après avoir saisi chaque limite."))108 if let e = create.loadError { ErrorNotice(error: e) { Task { await create.load(api) } } }109 AgentCard(title: String(localized: "Sur mesure")) {110 Button { create.kind = .spot } label: { choice(String(localized: "Agent spot"), String(localized: "Un coffre sur un réseau, des échanges au comptant. Stratégie de la bibliothèque du laboratoire."), "lock.rectangle.stack.fill") }111 .buttonStyle(.plain).disabled(create.networks == nil).accessibilityIdentifier("create.custom.spot")112 Divider()113 Button { create.kind = .perp } label: { choice(String(localized: "Agent contrats perpétuels"), String(localized: "Un compte PAPIER de la plateforme, levier borné. Créé en simulation."), "chart.line.uptrend.xyaxis") }114 .buttonStyle(.plain).disabled(create.venues == nil).accessibilityIdentifier("create.custom.perp")115 }116 if let t = create.templates {117 AgentCard(title: String(localized: "Gabarits du serveur")) {118 ForEach(Array(t.templates.enumerated()), id: \.element.id) { i, tpl in119 if i > 0 { Divider() }120 Button { create.template = TemplateCreateForm(); create.kind = .template(tpl.id) } label: {121 VStack(alignment: .leading, spacing: 6) {122 choice(tpl.name.text(locale: "fr"), tpl.summary.text(locale: "fr"), "square.stack.3d.up.fill")123 HStack(spacing: 6) { ForEach(tpl.modes, id: \.self) { Pill(text: AgentModeBadge.name($0), tone: $0 == .live ? .danger : $0 == .paper ? .warn : .info) } }124 if let r = tpl.liveReason { Text(r).font(.spFootnote).foregroundStyle(Theme.warn).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true) }125 if !tpl.strategyInstalled { Text(String(localized: "Stratégie non installée sur ce serveur.")).font(.spFootnote).foregroundStyle(Theme.warn) }126 }127 }.buttonStyle(.plain).accessibilityIdentifier("create.template.\(tpl.id)")128 }129 }130 } else if create.loadError == nil { ProgressView().frame(maxWidth: .infinity, minHeight: 80) }131 }132133 private func choice(_ title: String, _ subtitle: String, _ icon: String) -> some View {134 HStack(alignment: .top, spacing: 12) {135 Image(systemName: icon).font(.system(size: 20)).foregroundStyle(Theme.blue).frame(width: 30)136 VStack(alignment: .leading, spacing: 2) {137 Text(title).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)138 Text(subtitle).font(.spFootnote).foregroundStyle(Theme.mute).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)139 }140 Spacer(minLength: 0)141 Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.mute)142 }.frame(minHeight: 48).contentShape(Rectangle())143 }144145 private func chips<T: Hashable>(_ items: [T], selected: @escaping (T) -> Bool, label: @escaping (T) -> String, id: @escaping (T) -> String, tap: @escaping (T) -> Void) -> some View {146 LazyVGrid(columns: [GridItem(.adaptive(minimum: 84), spacing: 8)], alignment: .leading, spacing: 8) {147 ForEach(items, id: \.self) { item in148 let on = selected(item)149 Button { tap(item) } label: {150 Text(label(item)).font(.system(size: 13.5, weight: .semibold)).lineLimit(1).minimumScaleFactor(0.7)151 .frame(maxWidth: .infinity, minHeight: 40).foregroundStyle(on ? Theme.onPrimary : Theme.ink)152 .background(on ? Theme.primary : Theme.elev, in: RoundedRectangle(cornerRadius: 10, style: .continuous))153 }.buttonStyle(.plain).accessibilityIdentifier(id(item)).accessibilityAddTraits(on ? .isSelected : [])154 }155 }156 }157158 private func submitBar(problem: String?, id: String) -> some View {159 VStack(alignment: .leading, spacing: 8) {160 if let e = create.error { ErrorNotice(error: e).accessibilityIdentifier("create.error") }161 if let problem { Text(problem).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("create.problem") }162 Button { Task { await create.submit(api) } } label: { HStack { if create.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Créer l’agent")) } }163 .buttonStyle(.spPrimary).disabled(problem != nil || create.busy || !model.canOperate).accessibilityIdentifier(id)164 Text(String(localized: "Rien n’est signé : créer un agent ne lui donne aucune autorité sur des fonds.")).font(.spFootnote).foregroundStyle(Theme.mute)165 }166 }167168 // MARK: custom spot169170 @ViewBuilder private var spotForm: some View {171 @Bindable var create = create172 if let n = create.networks {173 let net = n.networks.first { $0.id == create.spot.network }174 AgentModeBand(mode: .research, detail: String(localized: "à la création"))175 VStack(alignment: .leading, spacing: 12) {176 TextEntry(label: String(localized: "Nom"), text: $create.spot.name, id: "create.spot.name")177 TextEntry(label: String(localized: "Mission (facultative)"), text: $create.spot.mission, id: "create.spot.mission")178 }.spCard()179 VStack(alignment: .leading, spacing: 10) {180 Text(String(localized: "Réseau du coffre")).font(.spHeadline)181 chips(n.networks.filter(\.enabled).map(\.id), selected: { create.spot.network == $0 }, label: { id in n.networks.first { $0.id == id }?.name ?? id }, id: { "create.spot.network.\($0)" }) {182 create.spot.network = $0; create.spot.symbols = []; create.spot.cash = nil183 }184 if let net {185 if net.feeWarning { Notice(tone: .warn, title: String(localized: "Frais de réseau élevés sur \(net.name)"), message: String(localized: "Ils peuvent peser lourd face à de petits ordres.")) }186 Text(net.gas.map { String(localized: "Réserve de \(net.native) exigée avant le réel : \($0.reserve) (≈ \($0.perOrder) par ordre).") } ?? String(localized: "Réserve de frais inconnue pour ce réseau.")).font(.spFootnote).foregroundStyle(Theme.mute)187 Text(String(localized: "Monnaie de réserve")).font(.spCallout.weight(.medium))188 chips(net.cash.map(\.symbol), selected: { create.spot.cash == $0 }, label: { $0 }, id: { "create.spot.cash.\($0)" }) { create.spot.cash = $0 }189 Text(String(localized: "Marchés (au plus \(n.maxSymbols) ; \(n.maxLiveSymbols) pour un mandat réel)")).font(.spCallout.weight(.medium))190 chips(net.symbols.map(\.symbol), selected: { create.spot.symbols.contains($0) }, label: { s in s + ((net.symbols.first { $0.symbol == s }?.live ?? true) ? "" : " ◦") }, id: { "create.spot.symbol.\($0)" }) {191 if create.spot.symbols.contains($0) { create.spot.symbols.remove($0) } else { create.spot.symbols.insert($0) }192 }193 if net.symbols.contains(where: { !$0.live }) { Text(String(localized: "◦ : papier seulement — le signataire ne peut pas vérifier le prix de ce marché.")).font(.spFootnote).foregroundStyle(Theme.mute) }194 Text(String(localized: "L’actif détenu pour chaque marché est celui que le serveur propose par défaut (affiché dans l’aperçu de l’agent après création).")).font(.spFootnote).foregroundStyle(Theme.mute)195 }196 Text(String(localized: "Intervalle de décision")).font(.spCallout.weight(.medium))197 chips(["1h", "1d"], selected: { create.spot.interval == $0 }, label: { $0 }, id: { "create.spot.interval.\($0)" }) { create.spot.interval = $0 }198 }.spCard()199 VStack(alignment: .leading, spacing: 14) {200 Text(String(localized: "Limites — à saisir toi-même")).font(.spHeadline)201 Text(String(localized: "Elles sont fixées à la création et ne se modifient pas ensuite : un futur mandat réel sera construit à partir d’elles.")).font(.spFootnote).foregroundStyle(Theme.mute)202 LimitField(label: String(localized: "Budget maximal"), text: $create.spot.capital, unit: "USD", id: "create.spot.capital")203 LimitField(label: String(localized: "Exposition maximale hors réserve"), text: $create.spot.exposurePct, unit: "%", hint: "1 – 100", id: "create.spot.exposure")204 LimitField(label: String(localized: "Limite de perte (moteur)"), text: $create.spot.lossPct, unit: "%", hint: "1 – 100", id: "create.spot.loss")205 LimitField(label: String(localized: "Plafond par ordre"), text: $create.spot.maxOrder, unit: "USD", hint: "1 – 100 000", id: "create.spot.maxOrder")206 LimitField(label: String(localized: "Plafond de volume par jour"), text: $create.spot.maxDaily, unit: "USD", hint: "1 – 1 000 000", id: "create.spot.maxDaily")207 LimitField(label: String(localized: "Ordres par jour"), text: $create.spot.ordersPerDay, hint: "1 – 200", integer: true, id: "create.spot.orders")208 LimitField(label: String(localized: "Durée d’un futur mandat"), text: $create.spot.mandateDays, unit: String(localized: "jours"), hint: "1 – 90", integer: true, id: "create.spot.days")209 LimitField(label: String(localized: "Glissement toléré"), text: $create.spot.slippageBps, unit: "pb", hint: "5 – 300", integer: true, id: "create.spot.slippage")210 }.spCard()211 submitBar(problem: create.spot.problem(maxSymbols: n.maxSymbols), id: "create.spot.submit")212 }213 }214215 // MARK: custom perp216217 @ViewBuilder private var perpForm: some View {218 @Bindable var create = create219 if let v = create.venues, let venue = v.venues.first {220 let d = v.riskDefaults221 AgentModeBand(mode: .paper, detail: String(localized: "compte simulé de \(venue.name)"))222 VStack(alignment: .leading, spacing: 12) {223 TextEntry(label: String(localized: "Nom"), text: $create.perp.name, id: "create.perp.name")224 TextEntry(label: String(localized: "Mission (facultative)"), text: $create.perp.mission, id: "create.perp.mission")225 }.spCard()226 VStack(alignment: .leading, spacing: 10) {227 Text(String(localized: "Contrats (au plus \(v.maxInstruments))")).font(.spHeadline)228 let eligible = venue.instruments.filter(\.eligible)229 chips(Array(eligible.prefix(24).map(\.symbol)), selected: { create.perp.instruments.contains($0) }, label: { $0 }, id: { "create.perp.instrument.\($0)" }) {230 if create.perp.instruments.contains($0) { create.perp.instruments.remove($0) } else { create.perp.instruments.insert($0) }231 }232 Text(String(localized: "Les \(min(24, eligible.count)) premiers contrats admissibles de \(venue.name), dans l’ordre du serveur (\(eligible.count) admissibles sur \(venue.instruments.count)).")).font(.spFootnote).foregroundStyle(Theme.mute)233 Text(String(localized: "Intervalle de décision")).font(.spCallout.weight(.medium))234 chips(v.intervals, selected: { create.perp.interval == $0 }, label: { $0 }, id: { "create.perp.interval.\($0)" }) { create.perp.interval = $0 }235 }.spCard()236 VStack(alignment: .leading, spacing: 14) {237 Text(String(localized: "Limites — à saisir toi-même")).font(.spHeadline)238 Text(String(localized: "Les valeurs « suggérées par le serveur » sont indicatives : aucune n’est appliquée si tu ne la saisis pas.")).font(.spFootnote).foregroundStyle(Theme.mute)239 LimitField(label: String(localized: "Capital SIMULÉ"), text: $create.perp.capital, unit: "USDC", hint: String(localized: "au moins \(v.minCapital)"), id: "create.perp.capital")240 LimitField(label: String(localized: "Levier maximal"), text: $create.perp.maxLeverage, unit: "×", hint: String(localized: "1 – 5 · suggéré par le serveur : \(d.maxLeverage)"), integer: true, id: "create.perp.leverage")241 LimitField(label: String(localized: "Exposition brute maximale"), text: $create.perp.grossX, unit: String(localized: "× capital"), hint: String(localized: "0,1 – 5 · suggéré : \(AgentFmt.number(d.maxGrossExposureX))"), id: "create.perp.gross")242 LimitField(label: String(localized: "Position maximale par contrat"), text: $create.perp.positionX, unit: String(localized: "× capital"), hint: String(localized: "0,05 – 5 · suggéré : \(AgentFmt.number(d.maxPositionX))"), id: "create.perp.position")243 LimitField(label: String(localized: "Perte maximale par jour"), text: $create.perp.dailyLossPct, unit: "%", hint: String(localized: "0,01 – 50 · suggéré : \(AgentFmt.number(d.maxDailyLossPct))"), id: "create.perp.dailyLoss")244 LimitField(label: String(localized: "Perte maximale totale"), text: $create.perp.totalLossPct, unit: "%", hint: String(localized: "0,01 – 90 · suggéré : \(AgentFmt.number(d.maxTotalLossPct))"), id: "create.perp.totalLoss")245 LimitField(label: String(localized: "Glissement toléré"), text: $create.perp.slippageBps, unit: "pb", hint: String(localized: "5 – 100 · suggéré : \(d.slippageBps)"), integer: true, id: "create.perp.slippage")246 LimitField(label: String(localized: "Rééquilibrage minimal"), text: $create.perp.minTradePct, unit: "%", hint: String(localized: "suggéré : \(AgentFmt.number(d.minTradePct))"), id: "create.perp.minTrade")247 }.spCard()248 submitBar(problem: create.perp.problem(maxInstruments: v.maxInstruments, minCapital: v.minCapital), id: "create.perp.submit")249 }250 }251252 // MARK: template253254 @ViewBuilder private func templateForm(_ id: String) -> some View {255 @Bindable var create = create256 if let t = create.templates?.templates.first(where: { $0.id == id }) {257 VStack(alignment: .leading, spacing: 8) {258 Text(t.name.text(locale: "fr")).font(.spTitle)259 Text(t.summary.text(locale: "fr")).font(.spCallout).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)260 HStack(spacing: 6) { ForEach(t.modes, id: \.self) { Pill(text: AgentModeBadge.name($0), tone: $0 == .live ? .danger : $0 == .paper ? .warn : .info) } }261 if let r = t.liveReason { Notice(tone: .info, title: String(localized: "Mode réel indisponible pour ce gabarit"), message: r) }262 }263 if let verdicts = t.labVerdicts, !verdicts.isEmpty {264 AgentCard(title: String(localized: "Verdict du laboratoire")) { ForEach(Array(verdicts.enumerated()), id: \.offset) { _, v in LabVerdictView(verdict: v) } }265 }266 VStack(alignment: .leading, spacing: 12) {267 TextEntry(label: String(localized: "Nom"), text: $create.template.name, id: "create.template.name")268 TextEntry(label: String(localized: "Mission (facultative)"), text: $create.template.mission, id: "create.template.mission")269 if !t.installed.isEmpty {270 Text(String(localized: "Version de stratégie")).font(.spCallout.weight(.medium))271 ForEach(t.installed, id: \.path) { s in272 AgentCheckRow(title: "\(s.name) · v\(s.version) · \(s.interval)", subtitle: (s.generic == true ? String(localized: "univers libre") : s.universe.joined(separator: ", ")) + (s.liveCapable ? "" : "\n" + String(localized: "papier seulement : \(s.liveReason ?? "—")")),273 on: create.template.strategyPath == s.path, id: "create.template.strategy.\(s.path)") { create.template.strategyPath = create.template.strategyPath == s.path ? nil : s.path }274 }275 } else if let r = t.rule { FieldRow(label: String(localized: "Règle intégrée"), value: "\(r.name) · v\(r.version)") }276 FieldRow(label: String(localized: "Marchés · plateformes proposés par le gabarit"), value: (t.defaults.universe.isEmpty ? "—" : t.defaults.universe.joined(separator: ", ")) + " · " + (t.defaults.venues.isEmpty ? "—" : t.defaults.venues.joined(separator: ", ")))277 }.spCard()278 VStack(alignment: .leading, spacing: 14) {279 Text(String(localized: "Limites — à saisir toi-même")).font(.spHeadline)280 Text(String(localized: "Le gabarit propose des valeurs ; elles sont indiquées sous chaque champ et ne sont jamais appliquées à ta place.")).font(.spFootnote).foregroundStyle(Theme.mute)281 if t.kind != "supervisor" { LimitField(label: String(localized: "Capital") + (t.kind == "spot" ? "" : " " + String(localized: "SIMULÉ")), text: $create.template.capital, unit: "USD", hint: String(localized: "proposé par le gabarit : \(t.defaults.capitalUsdc)"), id: "create.template.capital") }282 ForEach(t.defaults.risk.keys.sorted(), id: \.self) { k in283 LimitField(label: k, text: Binding(get: { create.template.risk[k] ?? "" }, set: { create.template.risk[k] = $0 }), hint: String(localized: "proposé par le gabarit : \(TemplateCreateForm.text(t.defaults.risk[k] ?? .null))"), id: "create.template.risk.\(k)")284 }285 }.spCard()286 if !t.defaults.config.isEmpty {287 VStack(alignment: .leading, spacing: 14) {288 Text(String(localized: "Paramètres de la stratégie")).font(.spHeadline)289 Button(String(localized: "Recopier les paramètres proposés par le gabarit")) { for (k, v) in t.defaults.config { create.template.config[k] = TemplateCreateForm.text(v) } }290 .buttonStyle(.bordered).font(.spCallout.weight(.semibold)).accessibilityIdentifier("create.template.config.copy")291 Text(String(localized: "Ce bouton ne remplit que ces paramètres, jamais les limites ci-dessus. Tu peux ensuite modifier chaque valeur.")).font(.spFootnote).foregroundStyle(Theme.mute)292 ForEach(t.defaults.config.keys.sorted(), id: \.self) { k in293 let proposal = t.defaults.config[k] ?? .null294 let numeric: Bool = { switch proposal { case .int, .double: return true; case .string(let s): return Double(s) != nil; default: return false } }()295 if numeric {296 LimitField(label: k, text: Binding(get: { create.template.config[k] ?? "" }, set: { create.template.config[k] = $0 }), hint: String(localized: "proposé : \(TemplateCreateForm.text(proposal))"), id: "create.template.config.\(k)")297 } else {298 TextEntry(label: k + " — " + String(localized: "proposé : \(TemplateCreateForm.text(proposal))"), text: Binding(get: { create.template.config[k] ?? "" }, set: { create.template.config[k] = $0 }), id: "create.template.config.\(k)")299 }300 }301 }.spCard()302 }303 submitBar(problem: create.template.problem(template: t), id: "create.template.submit")304 }305 }306307 // MARK: result — the server's answer308309 @ViewBuilder private func result(_ c: (id: String, name: String, badge: AgentModeBadge, state: String, warnings: [AgentWarning])) -> some View {310 VStack(alignment: .leading, spacing: 10) {311 Text(String(localized: "Agent créé")).spEyebrow()312 Text(c.name).font(.spTitle)313 HStack(spacing: 8) { ModeBadgeView(badge: c.badge).accessibilityIdentifier("create.result.badge"); StateLabelView(state: c.state) }314 Text(String(localized: "Mode et état rapportés par le serveur. L’agent n’a aucune autorité sur des fonds.")).font(.spFootnote).foregroundStyle(Theme.mute)315 }.spCard()316 ForEach(c.warnings, id: \.self) { w in Notice(tone: .warn, title: w.message, message: "(\(w.code))") }317 Button(String(localized: "Ouvrir l’agent")) { done(c.id); dismiss() }.buttonStyle(.spPrimary).accessibilityIdentifier("create.open")318 }319}320