Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesLiveApprovals.swift10// Description : The passkey approvals of LIVE trading on a venue account:11// one order (review of the verified canonical venue order,12// every field, with its expiry countdown → passkey →13// follow-up until the venue reports resting, filled or14// rejected — an order sent is not an order filled), a15// leverage change (its own canonical object) and the closing16// of a position (paper: placed at once on the simulated17// account; live: the same canonical order review). Every18// object shown here was verified by SPWalletCore (challenge19// == SHA-256 of the object, object == request).20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-ios22// Created : 2026-11-1823// Last Modified : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author : Simon-Pierre Boucher30// Position : Professor of Finance31// Institution : Université du Québec en Outaouais (UQO)32// Department : Département des sciences administratives33// Organization : SP Boucher34//35// Website : https://spboucher.ai36// Git : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General : info@spboucher.ai43// Professional : contact@spboucher.ai44// Direct : simon@spboucher.ai45// Research : research@spboucher.ai46// Development : dev@spboucher.ai47// Support : support@spboucher.ai48// Security/Admin : admin@spboucher.ai49// Notifications : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification : Public76// Distribution : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License : None specified (no license file in this repository)90// Maintainer : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import SPWalletCore99100// MARK: one live order: review → passkey → follow-up101102@MainActor @Observable103final class LiveOrderFlow {104 enum Step: Equatable { case review, tracking }105 let account: LiveAccount106 let proposal: LiveOrderProposal107 /** The request was a market order: the canonical order is then a limit IOC at the worst accepted price. */108 let marketOrigin: Bool109 var step: Step110 var busy = false111 var error: Error?112 var order: LiveOrder113 var venue: LiveOrderResult.Venue?114 var withdrawn = false115116 init(account: LiveAccount, proposal: LiveOrderProposal, marketOrigin: Bool) {117 self.account = account; self.proposal = proposal; self.marketOrigin = marketOrigin118 order = proposal.order119 // nothing (left) to approve: the stored order is shown with its real state120 step = proposal.approvable == nil ? .tracking : .review121 }122123 func approve(_ fm: FuturesModel) async {124 guard let a = proposal.approvable, !busy else { return }125 busy = true; error = nil126 defer { busy = false }127 do {128 let r = try await fm.liveAPI.approveOrder(a, with: fm.app.env.passkeys)129 order = r.order; venue = r.venue; step = .tracking130 } catch PasskeyError.cancelled {131 // dismissed: nothing signed, the proposal stays until it expires or is withdrawn132 } catch let e as APIError where e.isOffline {133 // the answer was lost AFTER the assertion left: never sign again — read the order's real state134 if await refresh(fm), order.state != .riskChecked, order.state.rawValue != "proposed" { step = .tracking } else { error = e }135 } catch { self.error = error }136 }137138 /** Withdraws the proposal (no passkey; before approval nothing was sent to the venue). */139 func withdraw(_ fm: FuturesModel) async {140 guard !busy else { return }141 busy = true142 defer { busy = false }143 do { let r = try await fm.liveAPI.cancelOrder(account.id, clientId: order.clientId); order = r.order; withdrawn = true } catch { self.error = error }144 }145146 /** Reads the order again from the account. True when it was found. */147 @discardableResult func refresh(_ fm: FuturesModel) async -> Bool {148 guard let d = try? await fm.liveAPI.account(account.id) else { return false }149 fm.adopt(live: d)150 guard let o = d.orders.first(where: { $0.clientId == order.clientId }) else { return false }151 order = o152 return true153 }154155 func follow(_ fm: FuturesModel) async {156 while !Task.isCancelled, step == .tracking, !order.final, order.state.isInFlight || order.state.rawValue == "open" || order.state.rawValue == "partially_filled" {157 try? await Task.sleep(for: .seconds(3))158 if Task.isCancelled { return }159 await refresh(fm)160 if order.state.rawValue == "open" { return } // resting: the blotter follows it from here161 }162 }163}164165/** Every field of the canonical venue order the passkey is about to sign. Nothing truncated, nothing folded, nothing animated. */166struct VenueOrderReview: View {167 let order: VenueOrder168 let digest: Data169 let marketOrigin: Bool170 var estimate: LiveOrderEstimate?171172 var body: some View {173 VStack(alignment: .leading, spacing: 14) {174 VStack(alignment: .leading, spacing: 4) {175 Text(String(localized: "Ordre réel · \(OfferedVenues.name(order.venue)) · \(FuturesAccountRef.networkBadge(order.network))")).spEyebrow()176 Text("\(FuturesText.side(order: order.side)) \(Fx.exact(order.size)) \(OfferedVenues.symbol(of: order.instrument))")177 .font(.system(size: 28, weight: .semibold)).tracking(-0.6).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)178 .accessibilityIdentifier("futures.review.headline")179 }180 Rows {181 FieldRow(label: String(localized: "Instrument"), value: order.instrument, mono: true); Divider()182 FieldRow(label: String(localized: "Sens"), value: FuturesText.side(order: order.side), tone: FuturesText.sideTone(order.side)); Divider()183 FieldRow(label: String(localized: "Taille (contrats)"), value: Fx.exact(order.size)); Divider()184 FieldRow(label: String(localized: "Type envoyé à la plateforme"), value: FuturesText.type(order.type) + (marketOrigin ? " — " + String(localized: "ordre au marché borné") : "")); Divider()185 FieldRow(label: marketOrigin ? String(localized: "Prix limite envoyé à la plateforme (pire prix accepté)") : String(localized: "Prix limite envoyé à la plateforme"), value: Fx.exact(order.price))186 .accessibilityIdentifier("futures.review.price")187 Divider()188 if let t = order.triggerPrice { FieldRow(label: String(localized: "Prix de déclenchement"), value: Fx.exact(t)); Divider() }189 FieldRow(label: String(localized: "Réduction seulement"), value: order.reduceOnly ? String(localized: "oui — ne peut qu’alléger la position") : String(localized: "non — peut ouvrir ou augmenter une position")); Divider()190 FieldRow(label: String(localized: "Durée de validité"), value: FuturesText.tif(order.tif))191 }192 Rows {193 FieldRow(label: String(localized: "Compte sur la plateforme (adresse de ce portefeuille)"), value: order.account, mono: true, copyable: true); Divider()194 FieldRow(label: String(localized: "Autorisation utilisée"), value: order.authorizationId, mono: true); Divider()195 FieldRow(label: String(localized: "Identifiant d’ordre côté plateforme (dérivé de la clé de cette tentative)"), value: order.clientId, mono: true); Divider()196 FieldRow(label: String(localized: "Nonce · expiration (ms)"), value: "\(order.nonce) · \(order.expiresAt)", mono: true); Divider()197 ExpiryRow(until: order.expiry); Divider()198 FieldRow(label: String(localized: "Empreinte de l’ordre (défi signé par la clé d’accès)"), value: digest.hex, mono: true, copyable: true)199 }200 if let e = estimate {201 Rows {202 Text(String(localized: "Estimation du serveur (non signée)")).spEyebrow().padding(.bottom, 4)203 FieldRow(label: String(localized: "Exposition notionnelle"), value: Fx.usd(e.notional, exact: true)); Divider()204 FieldRow(label: String(localized: "Marge engagée"), value: Fx.usd(e.initialMargin, exact: true)); Divider()205 FieldRow(label: String(localized: "Frais estimés"), value: Fx.usd(e.fee, exact: true) + (e.feeNote.map { " — \($0)" } ?? "")); Divider()206 FieldRow(label: String(localized: "Levier — réglage actuel de la plateforme"), value: Fx.leverage(e.leverage) + (e.marginMode.map { " · " + String(localized: "marge \(FuturesText.marginMode($0))") } ?? ""))207 if let n = e.liquidationNote { Divider(); FieldRow(label: String(localized: "Prix de liquidation"), value: n, tone: .warn) }208 }209 }210 Notice(tone: .danger, title: String(localized: "Risque de perte"), message: String(localized: "Un contrat perpétuel à effet de levier peut entraîner la perte de toute la marge engagée, par liquidation. Fonds réels."))211 Label(String(localized: "L’app a recalculé cette empreinte à partir des champs affichés, vérifié qu’elle est le défi demandé à ta clé d’accès et que l’ordre est bien celui que tu as saisi. Le signataire isolé la revérifie avant de signer."),212 systemImage: "checkmark.shield.fill").font(.spFootnote).foregroundStyle(Theme.mute)213 }214 }215}216217/** Review or follow-up of one live order, embedded in a sheet by the order ticket and by the closing of a position. */218struct LiveOrderPane: View {219 @Environment(AppModel.self) private var model220 let fm: FuturesModel221 @Bindable var flow: LiveOrderFlow222 let done: () -> Void223224 var body: some View {225 switch flow.step {226 case .review: review227 case .tracking: tracking228 }229 }230231 @ViewBuilder private var review: some View {232 if let a = flow.proposal.approvable {233 ModeBand(mode: .live, network: flow.account.network)234 if flow.proposal.idempotent { Notice(tone: .info, title: String(localized: "Tentative déjà enregistrée"), message: String(localized: "Le serveur a répondu la proposition déjà créée pour cette tentative ; elle a été revérifiée contre ta saisie.")) }235 if let w = flow.proposal.worstPrice, let bps = flow.proposal.slippageBoundBps {236 Notice(tone: .info, title: String(localized: "Pire prix dérivé du carnet par le serveur"), message: String(localized: "\(Fx.exact(w)) (borne de \(bps) pb).") )237 }238 VenueOrderReview(order: a.order, digest: a.approval.digest, marketOrigin: flow.marketOrigin, estimate: flow.proposal.estimate)239 if let e = flow.error { FuturesError(error: e).accessibilityIdentifier("futures.review.error") }240 Countdown(until: a.order.expiry) { left in241 VStack(spacing: 10) {242 if flow.withdrawn {243 Notice(tone: .neutral, title: String(localized: "Proposition retirée"), message: String(localized: "Rien n’a été envoyé à la plateforme."))244 Button(String(localized: "Fermer"), action: done).buttonStyle(.spSecondary)245 } else if left <= 2 {246 Notice(tone: .warn, title: String(localized: "Fenêtre expirée"), message: String(localized: "Rien n’a été signé. Ferme et prépare l’ordre de nouveau : le prix et le carnet ont pu bouger."))247 Button(String(localized: "Fermer"), action: done).buttonStyle(.spSecondary).accessibilityIdentifier("futures.review.close")248 } else {249 Button { Task { await flow.approve(fm) } } label: { BusyLabel(title: String(localized: "Approuver cet ordre RÉEL avec la clé d’accès"), icon: "person.badge.key.fill", busy: flow.busy) }250 .buttonStyle(.spPrimary).disabled(flow.busy || !model.canOperate).accessibilityIdentifier("futures.review.approve")251 Button(String(localized: "Retirer la proposition")) { Task { await flow.withdraw(fm) } }.buttonStyle(.spSecondary).disabled(flow.busy).accessibilityIdentifier("futures.review.withdraw")252 }253 }254 }255 }256 }257258 @ViewBuilder private var tracking: some View {259 let s = OrderStateView.of(live: flow.order.state, final: flow.order.final)260 ModeBand(mode: .live, network: flow.account.network)261 HStack(spacing: 10) {262 if s.isInFlight { ProgressView() } else { Image(systemName: s.symbol).font(.system(size: 22)).foregroundStyle(s.tone.color) }263 Text(s.label).font(.spHeadline).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)264 }265 .accessibilityElement(children: .combine).accessibilityIdentifier("futures.live.orderState")266 if s.isInFlight {267 Notice(tone: .info, title: String(localized: "Un ordre envoyé n’est pas un ordre exécuté"), message: String(localized: "L’app attend ce que la plateforme rapporte : au carnet, exécuté ou rejeté. Rien n’est renvoyé."))268 }269 if flow.order.state == .unknown {270 Notice(tone: .warn, title: String(localized: "La plateforme n’a rien confirmé"), message: String(localized: "L’ordre a peut-être été reçu. Ne le renvoie pas : utilise « Rapprocher avec la plateforme » dans le compte pour lire son état réel."))271 }272 Rows {273 FieldRow(label: String(localized: "Ordre"), value: "\(FuturesText.side(order: flow.order.side)) \(Fx.exact(flow.order.size)) \(OfferedVenues.symbol(of: flow.order.instrument))"); Divider()274 FieldRow(label: String(localized: "Exécuté (rapporté par la plateforme)"), value: Fx.exact(flow.order.filled) + (flow.order.avgFillPrice.map { " @ " + Fx.exact($0) } ?? ""))275 if let v = flow.venue { Divider(); FieldRow(label: String(localized: "Réponse de la plateforme"), value: v.outcome + (v.error.map { " — \($0)" } ?? ""), tone: v.error == nil ? nil : .danger) }276 if let r = flow.order.reason { Divider(); FieldRow(label: String(localized: "Motif"), value: r, tone: .danger) }277 if let id = flow.order.venueOrderId { Divider(); FieldRow(label: String(localized: "Identifiant de la plateforme"), value: id, mono: true, copyable: true) }278 Divider(); FieldRow(label: String(localized: "Clé de la tentative"), value: flow.order.clientId, mono: true)279 }280 if let e = flow.error { FuturesError(error: e) }281 Button(String(localized: "Terminer"), action: done).buttonStyle(.spSecondary).accessibilityIdentifier("futures.live.done")282 .task(id: flow.order.clientId) { await flow.follow(fm) }283 }284}285286/** A sheet around `LiveOrderPane`. It cannot be swiped away while an approval is on screen. */287struct LiveOrderSheet: View {288 let fm: FuturesModel289 let flow: LiveOrderFlow290 @Environment(\.dismiss) private var dismiss291 var body: some View {292 NavigationStack {293 ScrollView { VStack(alignment: .leading, spacing: Theme.Space.section) { LiveOrderPane(fm: fm, flow: flow) { dismiss() } }.futuresSheetPage() }294 .spPage()295 .navigationTitle(flow.step == .review ? String(localized: "Vérifier et approuver") : String(localized: "Suivi de l’ordre")).navigationBarTitleDisplayMode(.inline)296 }297 .interactiveDismissDisabled(flow.step == .review && !flow.withdrawn)298 }299}300301// MARK: leverage change (live): its own canonical object302303struct LeverageSheet: View {304 @Environment(AppModel.self) private var model305 @Environment(\.dismiss) private var dismiss306 let fm: FuturesModel307 let account: LiveAccount308 let instrument: DerivInstrument309 /** The venue's present setting as last read by the server; nil = unknown. */310 let current: CurrentLeverage?311 /** Called with the setting the VENUE reports after an approved change (nil when it confirmed nothing). */312 let changed: (LiveLeverageSetting?) -> Void313314 @State private var leverageText = ""315 @State private var marginMode: DerivMarginMode?316 @State private var prepared: LiveLeverageApproval?317 @State private var result: LiveLeverageResult?318 @State private var highConfirmed = false319 @State private var busy = false320 @State private var error: Error?321322 private var pinnedMax: Int? {323 let table = account.network == "testnet" ? fm.liveConfig?.pinnedAssets.testnet : fm.liveConfig?.pinnedAssets.mainnet324 return table?.first { $0.instrument == instrument.id }?.maxLeverage325 }326 private var maximum: Int? {327 [account.authorization?.policy.maxLeverage, pinnedMax, VenueDecimal(instrument.maxLeverage).flatMap { Int($0.truncated(toDecimals: 0).description) }].compactMap { $0 }.min()328 }329 private var typed: Int? { DecimalInput.wholeNumber(leverageText) }330 private var problem: String? {331 guard !leverageText.isEmpty else { return nil }332 guard let n = typed else { return String(localized: "Levier invalide : nombre entier.") }333 if let m = maximum, n > m { return String(localized: "Au-dessus du maximum permis (\(m)×).") }334 return nil335 }336337 var body: some View {338 NavigationStack {339 ScrollView {340 VStack(alignment: .leading, spacing: Theme.Space.section) {341 ModeBand(mode: .live, network: account.network)342 if let r = result { outcome(r) } else if let p = prepared { review(p) } else { form }343 }344 .futuresSheetPage()345 }346 .spPage()347 .navigationTitle(String(localized: "Levier · \(instrument.symbol)")).navigationBarTitleDisplayMode(.inline)348 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(result == nil ? String(localized: "Annuler") : String(localized: "Fermer")) { dismiss() }.accessibilityIdentifier("futures.leverage.close") } }349 }350 .interactiveDismissDisabled(prepared != nil && result == nil)351 }352353 @ViewBuilder private var form: some View {354 Rows {355 FieldRow(label: String(localized: "Réglage actuel sur la plateforme"), value: current.map { "\(Fx.leverage($0.leverage)) · " + String(localized: "marge \(FuturesText.marginMode($0.marginMode))") } ?? String(localized: "inconnu (pas encore lu)"))356 Divider()357 FieldRow(label: String(localized: "Maximum permis (autorisation, table épinglée, plateforme)"), value: maximum.map { "\($0)×" } ?? String(localized: "inconnu"))358 }359 VStack(alignment: .leading, spacing: 12) {360 TypedField(label: String(localized: "Nouveau levier"), text: $leverageText, unit: "×", hint: String(localized: "Aucune valeur n’est proposée : saisis le levier voulu."), integer: true, id: "futures.leverage.value")361 if let p = problem { Label(p, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger) }362 Text(String(localized: "Mode de marge")).font(.spFootnote).foregroundStyle(Theme.mute)363 HStack(spacing: 8) {364 ForEach([DerivMarginMode.cross, .isolated], id: \.self) { m in365 Button { marginMode = m } label: {366 Label(String(localized: "Marge \(FuturesText.marginMode(m.rawValue))"), systemImage: marginMode == m ? "largecircle.fill.circle" : "circle").frame(maxWidth: .infinity, minHeight: 44)367 }368 .buttonStyle(.bordered).tint(marginMode == m ? Theme.blue : Theme.mute).disabled(!instrument.marginModes.contains(m.rawValue))369 .accessibilityIdentifier("futures.leverage.mode.\(m.rawValue)").accessibilityAddTraits(marginMode == m ? .isSelected : [])370 }371 }372 }373 .spCard()374 if let e = error { FuturesError(error: e) }375 Button { Task { await prepare() } } label: { BusyLabel(title: String(localized: "Préparer le changement"), busy: busy) }376 .buttonStyle(.spPrimary).disabled(busy || typed == nil || problem != nil || marginMode == nil || !model.canOperate).accessibilityIdentifier("futures.leverage.prepare")377 Text(String(localized: "Le levier est un réglage de la plateforme pour cet instrument. Le changer demande ta clé d’accès sur l’objet exact affiché à l’étape suivante.")).font(.spFootnote).foregroundStyle(Theme.mute)378 }379380 @ViewBuilder private func review(_ p: LiveLeverageApproval) -> some View {381 let c = p.change382 VStack(alignment: .leading, spacing: 4) {383 Text(String(localized: "Changement de levier · \(OfferedVenues.name(c.venue)) · \(FuturesAccountRef.networkBadge(c.network))")).spEyebrow()384 Text("\(OfferedVenues.symbol(of: c.instrument)) → \(c.leverage)× · " + String(localized: "marge \(FuturesText.marginMode(c.marginMode))"))385 .font(.system(size: 28, weight: .semibold)).tracking(-0.6).fixedSize(horizontal: false, vertical: true)386 }387 Rows {388 FieldRow(label: String(localized: "Instrument"), value: c.instrument, mono: true); Divider()389 FieldRow(label: String(localized: "Nouveau levier"), value: "\(c.leverage)×"); Divider()390 FieldRow(label: String(localized: "Mode de marge"), value: FuturesText.marginMode(c.marginMode)); Divider()391 FieldRow(label: String(localized: "Réglage actuel (lu par le serveur sur la plateforme)"), value: p.current.map { "\(Fx.leverage($0.leverage)) · \(FuturesText.marginMode($0.marginMode))" } ?? String(localized: "illisible")); Divider()392 FieldRow(label: String(localized: "Compte sur la plateforme"), value: c.account, mono: true, copyable: true); Divider()393 FieldRow(label: String(localized: "Autorisation utilisée"), value: c.authorizationId, mono: true); Divider()394 FieldRow(label: String(localized: "Nonce · expiration (ms)"), value: "\(c.nonce) · \(c.expiresAt)", mono: true); Divider()395 ExpiryRow(until: c.expiry); Divider()396 FieldRow(label: String(localized: "Empreinte du changement (défi signé par la clé d’accès)"), value: p.approval.digest.hex, mono: true, copyable: true)397 }398 if c.leverage >= FuturesOrderForm.highLeverageThreshold {399 let position = fm.liveDetail?.venueState.positions.first { $0.instrument == c.instrument }400 Notice(tone: .danger, title: String(localized: "Levier élevé"),401 message: position?.liquidationPrice.map { String(localized: "Position ouverte : prix de liquidation actuellement rapporté par la plateforme \(Fx.exact($0)), prix de marque \(Fx.exact(position?.markPrice)). Un levier plus élevé rapproche la liquidation.") }402 ?? String(localized: "Aucun prix de liquidation n’est servi pour cet instrument (pas de position ouverte) : la plateforme le rapportera une fois la position ouverte. Plus le levier est élevé, plus la liquidation est proche du prix d’entrée."))403 CheckRow(isOn: $highConfirmed, text: String(localized: "Je confirme vouloir régler le levier de \(OfferedVenues.symbol(of: c.instrument)) à \(c.leverage)×."), tone: .danger, id: "futures.leverage.highConfirm")404 }405 if let e = error { FuturesError(error: e) }406 Countdown(until: c.expiry) { left in407 if left <= 2 {408 Notice(tone: .warn, title: String(localized: "Fenêtre expirée"), message: String(localized: "Rien n’a été signé. Recommence."))409 Button(String(localized: "Revenir au formulaire")) { prepared = nil; highConfirmed = false }.buttonStyle(.spSecondary)410 } else {411 Button { Task { await approve(p) } } label: { BusyLabel(title: String(localized: "Approuver avec la clé d’accès"), icon: "person.badge.key.fill", busy: busy) }412 .buttonStyle(.spPrimary).disabled(busy || !model.canOperate || (c.leverage >= FuturesOrderForm.highLeverageThreshold && !highConfirmed)).accessibilityIdentifier("futures.leverage.approve")413 }414 }415 }416417 @ViewBuilder private func outcome(_ r: LiveLeverageResult) -> some View {418 if let v = r.venue, v.confirmed, let s = v.leverage {419 Notice(tone: .ok, title: String(localized: "La plateforme rapporte maintenant \(Fx.leverage(s.leverage)) · marge \(FuturesText.marginMode(s.marginMode))"), message: String(localized: "Réglage relu sur la plateforme après le changement."))420 } else {421 Notice(tone: .warn, title: String(localized: "Changement envoyé, non confirmé par la plateforme"),422 message: String(localized: "État de l’action : \(r.action.state)") + (r.action.error.map { " — \($0)" } ?? "") + ". " + String(localized: "Le réglage sera relu par le prochain aperçu d’ordre."))423 }424 Button(String(localized: "Terminer")) { dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("futures.leverage.done")425 }426427 private func prepare() async {428 guard let n = typed, let m = marginMode, !busy else { return }429 busy = true; error = nil430 defer { busy = false }431 do { prepared = try await fm.liveAPI.proposeLeverage(for: account, instrument: instrument.id, leverage: n, marginMode: m) } catch { self.error = error }432 }433434 private func approve(_ p: LiveLeverageApproval) async {435 guard !busy else { return }436 busy = true; error = nil437 defer { busy = false }438 do {439 let r = try await fm.liveAPI.approveLeverage(p, with: model.env.passkeys)440 result = r441 changed(r.venue?.confirmed == true ? r.venue?.leverage : nil)442 await fm.loadLiveDetail()443 } catch PasskeyError.cancelled {444 } catch { self.error = error }445 }446}447448// MARK: closing or reducing a position449450struct ClosePositionSheet: View {451 @Environment(AppModel.self) private var model452 @Environment(\.dismiss) private var dismiss453 let fm: FuturesModel454 let ref: FuturesAccountRef455 let position: DerivPosition456457 @State private var percentText = ""458 @State private var slippageText = ""459 @State private var busy = false460 @State private var error: Error?461 @State private var paperKey = AttemptKey<String>()462 @State private var liveKey = AttemptKey<String>()463 @State private var placement: PaperPlacement?464 @State private var flow: LiveOrderFlow?465466 /** The fraction of the position (0 < f ≤ 1) from the typed percentage, exactly. */467 private var fraction: String? {468 guard case .success(let p) = DecimalInput.parse(percentText), p.isPositive, let hundred = VenueDecimal("100"), p <= hundred, let cent = VenueDecimal("0.01") else { return nil }469 return p.multiplied(by: cent).description470 }471 private var slippage: Int? { DecimalInput.wholeNumber(slippageText).flatMap { $0 <= 1000 ? $0 : nil } }472473 var body: some View {474 NavigationStack {475 ScrollView {476 VStack(alignment: .leading, spacing: Theme.Space.section) {477 if let f = flow { LiveOrderPane(fm: fm, flow: f) { dismiss() } }478 else if let p = placement { paperOutcome(p) }479 else { form }480 }481 .futuresSheetPage()482 }483 .spPage()484 .navigationTitle(String(localized: "Fermer ou réduire")).navigationBarTitleDisplayMode(.inline)485 .toolbar { ToolbarItem(placement: .cancellationAction) { if flow == nil { Button(placement == nil ? String(localized: "Annuler") : String(localized: "Fermer")) { dismiss() }.accessibilityIdentifier("futures.close.dismiss") } } }486 }487 .interactiveDismissDisabled(flow?.step == .review && flow?.withdrawn == false)488 }489490 @ViewBuilder private var form: some View {491 if case .live(_, let network) = ref { ModeBand(mode: .live, network: network) } else { ModeBand(mode: .paper) }492 Rows {493 FieldRow(label: String(localized: "Position"), value: "\(FuturesText.side(position: position.side)) \(Fx.exact(position.size)) \(OfferedVenues.symbol(of: position.instrument))", tone: FuturesText.sideTone(position.side)); Divider()494 FieldRow(label: String(localized: "Prix d’entrée · prix de marque"), value: "\(Fx.exact(position.entryPrice)) · \(Fx.exact(position.markPrice))"); Divider()495 FieldRow(label: String(localized: "Résultat latent") + (ref.mode == .paper ? " (\(TradingMode.paper.badge))" : ""), value: Fx.usd(position.unrealizedPnl, exact: true, signed: true), tone: Fx.sign(position.unrealizedPnl) >= 0 ? .ok : .danger)496 }497 VStack(alignment: .leading, spacing: 12) {498 TypedField(label: String(localized: "Part de la position à fermer"), text: $percentText, unit: "%", hint: String(localized: "De 0 à 100 ; 100 ferme toute la position."), id: "futures.close.percent")499 HStack(spacing: 8) {500 ForEach(["25", "50", "100"], id: \.self) { p in501 Button("\(p) %") { percentText = p }.buttonStyle(.bordered).accessibilityIdentifier("futures.close.pct.\(p)")502 }503 }504 TypedField(label: String(localized: "Écart maximal accepté par rapport au carnet"), text: $slippageText, unit: String(localized: "pb"),505 hint: String(localized: "Ordre au marché, réduction seulement, borné à cet écart (1 pb = 0,01 %). Rien n’est présélectionné."), integer: true, id: "futures.close.slippage")506 }507 .spCard()508 if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.close.error") }509 Button { Task { await submit() } } label: {510 BusyLabel(title: ref.mode == .paper ? String(localized: "Fermer sur le compte PAPIER") : String(localized: "Préparer la fermeture RÉELLE"), busy: busy)511 }512 .buttonStyle(.spPrimary).disabled(busy || fraction == nil || slippage == nil || !model.canOperate).accessibilityIdentifier("futures.close.submit")513 Text(ref.mode == .paper ? String(localized: "Simulation : l’ordre est exécuté par le moteur papier contre le carnet servi.")514 : String(localized: "Le serveur prépare un ordre de réduction ; tu vérifieras l’ordre exact puis l’approuveras avec ta clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute)515 }516517 @ViewBuilder private func paperOutcome(_ p: PaperPlacement) -> some View {518 ModeBand(mode: .paper)519 PaperPlacementCard(placement: p)520 Button(String(localized: "Terminer")) { dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("futures.close.done")521 }522523 private func submit() async {524 guard let f = fraction, let s = slippage, !busy else { return }525 busy = true; error = nil526 defer { busy = false }527 let attempt = "\(position.instrument)|\(f)|\(s)"528 do {529 switch ref {530 case .paper(let id):531 placement = try await fm.api.closePaperPosition(id, instrument: position.instrument, fraction: f, slippageBps: s, idempotencyKey: paperKey.key(for: attempt))532 paperKey.finish()533 await fm.loadPaperDetail()534 case .live:535 guard let account = fm.liveAccount else { return }536 let p = try await fm.liveAPI.proposeClose(for: account, position: position, fraction: f, slippageBps: s, idempotencyKey: liveKey.key(for: attempt))537 flow = LiveOrderFlow(account: account, proposal: p, marketOrigin: true)538 }539 } catch { self.error = error }540 }541}542543/** What the paper engine answered for a placed order: its state and its fills, labelled PAPIER. */544struct PaperPlacementCard: View {545 let placement: PaperPlacement546 var body: some View {547 let o = placement.order, s = OrderStateView.of(status: o.status)548 VStack(alignment: .leading, spacing: 10) {549 HStack(spacing: 8) {550 Image(systemName: s.symbol).font(.system(size: 20)).foregroundStyle(s.tone.color)551 Text(s.label).font(.spHeadline)552 Spacer()553 PaperTag()554 }555 .accessibilityElement(children: .combine).accessibilityIdentifier("futures.paper.orderState")556 if let r = o.rejectReason { Notice(tone: .danger, title: String(localized: "Rejeté par le moteur papier"), message: r) }557 VStack(alignment: .leading, spacing: 0) {558 FieldRow(label: String(localized: "Ordre"), value: "\(FuturesText.side(order: o.side)) \(Fx.exact(o.size)) \(OfferedVenues.symbol(of: o.instrument)) · \(FuturesText.type(o.type))"); Divider()559 FieldRow(label: String(localized: "Exécuté (simulation)"), value: Fx.exact(o.filled) + (o.avgFillPrice.map { " @ " + Fx.exact($0) } ?? ""))560 if let w = placement.worstPrice { Divider(); FieldRow(label: String(localized: "Pire prix dérivé par le serveur"), value: Fx.exact(w) + (placement.slippageBoundBps.map { " (\($0) pb)" } ?? "")) }561 ForEach(placement.fills ?? []) { f in562 Divider()563 FieldRow(label: String(localized: "Exécution simulée"), value: "\(Fx.exact(f.size)) @ \(Fx.exact(f.price)) · " + String(localized: "frais \(Fx.exact(f.fee)) \(f.feeAsset)") + (f.closedPnl.map { " · " + String(localized: "résultat \(Fx.usd($0, exact: true, signed: true))") } ?? ""))564 }565 }566 }567 .spCard()568 }569}570