SPB Git

Repository Public

FuturesOrderTicket.swift 32.9 KB 508 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/Futures/FuturesOrderTicket.swift10// Description      : THE order form of the app. Instrument, side (not11//                    preselected), type, size in contracts or USD with exact12//                    decimals, prices, reduce-only, time in force, and the13//                    leverage — never defaulted: the owner chooses it, or14//                    explicitly keeps the setting displayed as « réglage actuel15//                    » ; from 5× an extra confirmation names the liquidation16//                    information the server's preview gave. Paper: preview →17//                    place on the simulated account. Live: preview → proposal →18//                    review of the verified canonical order → passkey19//                    (FuturesLiveApprovals). The app computes no liquidation20//                    price and places nothing by itself.21// Module           : Features22// Repository       : https://git.spboucher.ai/sp-wallet-ios23// Created          : 2026-11-1824// Last Modified    : 2026-11-1825//26// =============================================================================27// AUTHOR & PROFESSIONAL AFFILIATION28// =============================================================================29//30// Author           : Simon-Pierre Boucher31// Position         : Professor of Finance32// Institution      : Université du Québec en Outaouais (UQO)33// Department       : Département des sciences administratives34// Organization     : SP Boucher35//36// Website          : https://spboucher.ai37// Git              : https://git.spboucher.ai38//39// =============================================================================40// OFFICIAL CONTACT DIRECTORY41// =============================================================================42//43// General          : info@spboucher.ai44// Professional     : contact@spboucher.ai45// Direct           : simon@spboucher.ai46// Research         : research@spboucher.ai47// Development      : dev@spboucher.ai48// Support          : support@spboucher.ai49// Security/Admin   : admin@spboucher.ai50// Notifications    : notifications@spboucher.ai51//52// Preferred Contact: support@spboucher.ai53//54// =============================================================================55// COPYRIGHT & INTELLECTUAL PROPERTY56// =============================================================================57//58// Copyright (c) 202659// Simon-Pierre Boucher60//61// All rights reserved where applicable.62//63// This file is governed by the applicable project license,64// copyright notices, institutional agreements and relevant law.65//66// Unless expressly authorized by the applicable license or67// rights holder, copying, redistribution, sublicensing,68// publication and commercial exploitation are not permitted.69//70// Existing third-party rights and notices remain unaffected.71//72// =============================================================================73// CONFIDENTIALITY & SECURITY74// =============================================================================75//76// Classification   : Public77// Distribution     : Public repository; use is governed by the project license78// Security Contact : admin@spboucher.ai79//80// Access to this source does not independently grant permission81// to redistribute or disclose confidential materials.82//83// Do not embed credentials, private keys, access tokens,84// certificates or confidential personal information.85//86// =============================================================================87// LICENSE & MAINTENANCE88// =============================================================================89//90// License          : None specified (no license file in this repository)91// Maintainer       : Simon-Pierre Boucher92// Technical Contact: dev@spboucher.ai93//94// =============================================================================95// END OF SP BOUCHER SOURCE HEADER96// =============================================================================9798import SwiftUI99import SPWalletCore100101@MainActor @Observable102final class OrderTicketModel {103    var form = FuturesOrderForm()104    var leverageText = ""105    var busy = false106    var error: Error?107    var paperPreview: (request: PaperOrderRequest, preview: PaperOrderPreview)?108    var livePreview: (request: LiveOrderRequest, preview: LiveOrderPreview)?109    /** The order for which the owner ticked the high-leverage confirmation; any change of the order unticks it. */110    var highConfirmedFor: FuturesOrderForm.Built?111    var placement: PaperPlacement?112    var flow: LiveOrderFlow?113    /** The venue's setting as it reported it after an approved leverage change. */114    var leverageRead: LiveLeverageSetting?115    private var paperKey = AttemptKey<PaperOrderRequest>()116    private var liveKey = AttemptKey<LiveOrderRequest>()117118    func reset(keepSide: Bool = false) {119        let side = form.side120        form = FuturesOrderForm(); if keepSide { form.side = side }121        leverageText = ""; error = nil; paperPreview = nil; livePreview = nil; highConfirmedFor = nil; placement = nil122    }123124    func previewPaper(_ fm: FuturesModel, account: PaperAccountID, order: FuturesOrderForm.Built) async {125        guard !busy else { return }126        busy = true; error = nil127        defer { busy = false }128        let r = order.paperRequest129        do { paperPreview = (r, try await fm.api.previewPaperOrder(account, order: r)) } catch { paperPreview = nil; self.error = error }130    }131132    func placePaper(_ fm: FuturesModel, account: PaperAccountID, order: FuturesOrderForm.Built) async {133        guard !busy else { return }134        busy = true; error = nil135        defer { busy = false }136        let r = order.paperRequest137        do {138            placement = try await fm.api.placePaperOrder(account, order: r, idempotencyKey: paperKey.key(for: r))139            paperKey.finish(); paperPreview = nil; highConfirmedFor = nil140            await fm.loadPaperDetail()141        } catch let e as APIError where e.isOffline {142            self.error = e   // the key is kept: sending the same order again answers the same order143        } catch { paperKey.finish(); paperPreview = nil; self.error = error }144    }145146    func previewLive(_ fm: FuturesModel, account: LiveAccountID, order: FuturesOrderForm.Built) async {147        guard !busy else { return }148        busy = true; error = nil149        defer { busy = false }150        let r = order.liveRequest151        do {152            let p = try await fm.liveAPI.previewOrder(account, order: r)153            livePreview = (r, p); leverageRead = nil154            // the setting the owner chose to keep is no longer the venue's: he chooses again155            if case .keepCurrent(let kept) = form.leverage, let now = p.estimate?.leverage, !VenueDecimal.same(kept, now) { form.leverage = .none }156        } catch { livePreview = nil; self.error = error }157    }158159    func proposeLive(_ fm: FuturesModel, account: LiveAccount, order: FuturesOrderForm.Built) async {160        guard !busy else { return }161        busy = true; error = nil162        defer { busy = false }163        let r = order.liveRequest164        do {165            let p = try await fm.liveAPI.proposeOrder(for: account, order: r, idempotencyKey: liveKey.key(for: r))166            flow = LiveOrderFlow(account: account, proposal: p, marketOrigin: r.type == .market)167        } catch let e as APIError where e.isOffline { self.error = e }168        catch { liveKey.finish(); self.error = error }169    }170171    /** The review sheet closed: whatever happened to that attempt, the next order is a new one. */172    func flowEnded(_ fm: FuturesModel) async {173        liveKey.finish(); flow = nil; livePreview = nil; highConfirmedFor = nil174        await fm.loadLiveDetail()175    }176}177178struct FuturesOrderTicket: View {179    @Environment(AppModel.self) private var model180    let fm: FuturesModel181    let instrument: DerivInstrument182    /** Opens the accounts screen (no account yet, or a live account that cannot trade). */183    let openAccounts: () -> Void184    @State private var ticket = OrderTicketModel()185    @State private var leverageSheet = false186187    private var ref: FuturesAccountRef? { fm.accountRef }188    private var mark: String? { fm.mark(instrument.id) }189    private var venueMax: Int { VenueDecimal(instrument.maxLeverage).flatMap { Int($0.truncated(toDecimals: 0).description) } ?? 1 }190    private var maxLeverage: Int {191        guard fm.mode == .paper, let p = fm.paperAccount?.policy, let m = VenueDecimal(p.maxLeverage).flatMap({ Int($0.truncated(toDecimals: 0).description) }) else { return venueMax }192        return min(venueMax, m)193    }194    /** « Réglage actuel » : the paper account's setting for THIS instrument, or the venue's as the server last read it. */195    private var currentLeverage: CurrentLeverage? {196        switch fm.mode {197        case .paper: return fm.paperAccount?.settings?.leverageByInstrument?[instrument.id].map { CurrentLeverage(leverage: $0, marginMode: "") }198        case .live:199            if let r = ticket.leverageRead { return CurrentLeverage(leverage: r.leverage, marginMode: r.marginMode) }200            if let e = ticket.livePreview?.preview.estimate, ticket.livePreview?.request.instrument == instrument.id, let l = e.leverage { return CurrentLeverage(leverage: l, marginMode: e.marginMode ?? "") }201            return fm.liveDetail?.venueState.positions.first { $0.instrument == instrument.id }.map { CurrentLeverage(leverage: $0.leverage, marginMode: $0.marginMode) }202        }203    }204    private var built: (order: FuturesOrderForm.Built?, problems: [FuturesOrderForm.Problem]) {205        ticket.form.build(instrument: instrument, mark: mark, maxLeverage: maxLeverage, leverageRequired: fm.mode == .paper)206    }207    private var previewState: OrderGate.PreviewState {208        guard let o = built.order else { return .missing }209        switch fm.mode {210        case .paper: guard let p = ticket.paperPreview else { return .missing }; return p.request == o.paperRequest ? .current(riskAccepted: p.preview.risk.ok && p.preview.estimate?.status != "rejected") : .outdated211        case .live: guard let p = ticket.livePreview else { return .missing }; return p.request == o.liveRequest ? .current(riskAccepted: p.preview.risk.ok) : .outdated212        }213    }214    private var leverageChosen: Bool { ticket.form.leverage != .none }215    private var highConfirmed: Bool { built.order != nil && ticket.highConfirmedFor == built.order }216    private var blockers: [OrderGate.Blocker] {217        OrderGate.blockers(order: built.order, leverageChosen: leverageChosen, preview: previewState, highLeverageConfirmed: highConfirmed, canOperate: model.canOperate && ref != nil, busy: ticket.busy)218    }219    private var liveTradable: Bool { fm.liveAccount?.tradable == true }220221    var body: some View {222        @Bindable var ticket = ticket223        VStack(alignment: .leading, spacing: 14) {224            HStack {225                Text(String(localized: "Ordre · \(instrument.symbol)")).font(.spHeadline)226                Spacer()227                if let ref { AccountTag(ref: ref) }228            }229            accountNotice230            if let p = ticket.placement {231                PaperPlacementCard(placement: p)232                Button(String(localized: "Nouvel ordre")) { ticket.reset() }.buttonStyle(.spSecondary).accessibilityIdentifier("futures.order.new")233            } else {234                formFields235                leverageCard236                problems237                if let e = ticket.error { FuturesError(error: e).accessibilityIdentifier("futures.order.error") }238                Button { Task { await preview() } } label: { BusyLabel(title: String(localized: "Aperçu du serveur (risque, marge, frais)"), busy: ticket.busy && previewState != .current(riskAccepted: true)) }239                    .buttonStyle(.spSecondary).disabled(built.order == nil || ticket.busy || !model.canOperate || ref == nil).accessibilityIdentifier("futures.order.preview")240                previewCard241                highLeverageConfirmation242                Button { Task { await submit() } } label: {243                    BusyLabel(title: fm.mode == .paper ? String(localized: "Placer l’ordre PAPIER") : String(localized: "Préparer l’ordre RÉEL"), icon: fm.mode == .paper ? "doc.plaintext.fill" : "bolt.shield.fill", busy: false)244                }245                .buttonStyle(.spPrimary).disabled(!blockers.isEmpty).accessibilityIdentifier("futures.order.submit")246                if let b = blockers.first, b != .busy { Label(b.text, systemImage: "info.circle").font(.spFootnote).foregroundStyle(Theme.mute).accessibilityElement(children: .combine).accessibilityIdentifier("futures.order.blocker") }247                Text(fm.mode == .paper ? String(localized: "Simulation : exécuté par le moteur papier du serveur, sans fonds réels.")248                     : String(localized: "Rien n’est envoyé à la plateforme à cette étape : tu vérifieras l’ordre exact, puis ta clé d’accès l’approuvera.")).font(.spFootnote).foregroundStyle(Theme.mute)249            }250        }251        .spCard()252        .onChange(of: instrument.id) { _, _ in ticket.reset() }253        .onChange(of: fm.mode) { _, _ in ticket.reset() }254        .sheet(isPresented: Binding(get: { ticket.flow != nil }, set: { if !$0 { Task { await ticket.flowEnded(fm) } } })) {255            Group { if let f = ticket.flow { LiveOrderSheet(fm: fm, flow: f) } }.wallet(model)256        }257        .sheet(isPresented: $leverageSheet) {258            Group { if let a = fm.liveAccount {259                LeverageSheet(fm: fm, account: a, instrument: instrument, current: currentLeverage) { setting in260                    ticket.leverageRead = setting261                    // the owner just chose this setting and the venue confirmed it: it is his explicit choice for this order262                    ticket.form.leverage = setting.map { .keepCurrent($0.leverage) } ?? .none263                }264            } }.wallet(model)265        }266    }267268    // MARK: account state269270    @ViewBuilder private var accountNotice: some View {271        if !model.canOperate {272            Notice(tone: .warn, title: String(localized: "Trading indisponible hors ligne"), message: String(localized: "Un ordre exige le serveur. Les données affichées sont un instantané."), icon: "wifi.slash")273        } else if ref == nil {274            Notice(tone: .info, title: fm.mode == .paper ? String(localized: "Aucun compte papier") : String(localized: "Aucun compte réel sélectionné"),275                   message: fm.mode == .paper ? String(localized: "Crée un compte papier pour simuler des ordres.") : String(localized: "Les comptes réels, leurs verrous et leur autorisation sont dans l’onglet Compte."))276            Button(String(localized: "Ouvrir les comptes"), action: openAccounts).buttonStyle(.spSecondary).accessibilityIdentifier("futures.order.openAccounts")277        } else if fm.mode == .live, let a = fm.liveAccount {278            if let h = a.halted { Notice(tone: .danger, title: String(localized: "Nouveaux ordres arrêtés sur ce compte"), message: h, icon: "hand.raised.fill") }279            if !a.tradable {280                Notice(tone: .warn, title: String(localized: "Ce compte ne peut pas ouvrir de risque maintenant"),281                       message: String(localized: "Mode \(FuturesText.accountMode(a.mode.rawValue)). Le serveur refusera l’aperçu ou la proposition avec son motif exact (verrou, mode, autorisation expirée)."), icon: "lock.fill")282                    .accessibilityIdentifier("futures.order.notTradable")283            }284        }285    }286287    // MARK: fields288289    @ViewBuilder private var formFields: some View {290        @Bindable var ticket = ticket291        HStack(spacing: 8) {292            sideButton(.buy, title: "Long", icon: "arrow.up.right", tone: .ok, id: "futures.order.side.long")293            sideButton(.sell, title: "Short", icon: "arrow.down.right", tone: .danger, id: "futures.order.side.short")294        }295        let kinds = FuturesOrderForm.Kind.supported(by: fm.venue(instrument.venue)?.capabilities?.orderTypes)296        Picker(String(localized: "Type d’ordre"), selection: $ticket.form.kind) { ForEach(kinds, id: \.self) { Text($0.label).tag($0) } }297            .pickerStyle(.segmented).accessibilityIdentifier("futures.order.kind")298        Picker(String(localized: "Unité de la taille"), selection: $ticket.form.unit) {299            Text(String(localized: "Contrats (\(instrument.base))")).tag(FuturesOrderForm.Unit.contracts)300            Text("USD").tag(FuturesOrderForm.Unit.usd)301        }302        .pickerStyle(.segmented).accessibilityIdentifier("futures.order.unit")303        TypedField(label: String(localized: "Taille"), text: $ticket.form.sizeText, unit: ticket.form.unit == .usd ? "USD" : instrument.base,304                   hint: String(localized: "Pas de lot \(Fx.exact(instrument.lotSize)) \(instrument.base)") + (instrument.minOrderSize.map { " · " + String(localized: "minimum \(Fx.exact($0))") } ?? ""), id: "futures.order.size")305        if let o = built.order {306            VStack(alignment: .leading, spacing: 2) {307                if ticket.form.unit == .usd { Text(String(localized: "Taille résultante : \(Fx.exact(o.size.description)) \(instrument.base) (arrondie vers le bas au pas de lot)")) }308                if let n = o.notional, let r = o.referencePrice {309                    Text(String(localized: "Notionnel : \(Fx.usd(n.description, exact: true)) = taille × \(Fx.exact(r.description))") + " (" + (o.referenceIsMark ? String(localized: "prix de marque servi, indicatif") : String(localized: "prix limite saisi")) + ")")310                } else { Text(String(localized: "Notionnel : donné par l’aperçu du serveur.")) }311            }312            .font(.system(size: 12.5)).monospacedDigit().foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)313            .accessibilityIdentifier("futures.order.notional")314        }315        if ticket.form.kind.isTrigger {316            TypedField(label: String(localized: "Prix de déclenchement"), text: $ticket.form.triggerText, unit: instrument.quote, hint: String(localized: "Pas de cotation \(Fx.exact(instrument.tickSize))"), id: "futures.order.trigger")317        }318        if ticket.form.kind != .market {319            TypedField(label: ticket.form.kind.isTrigger ? String(localized: "Prix limite après déclenchement") : String(localized: "Prix limite"), text: $ticket.form.priceText, unit: instrument.quote,320                       hint: String(localized: "Pas de cotation \(Fx.exact(instrument.tickSize))") + (mark.map { " · " + String(localized: "marque \(Fx.exact($0))") } ?? ""), id: "futures.order.price")321        } else {322            TypedField(label: String(localized: "Écart maximal accepté par rapport au carnet"), text: $ticket.form.slippageText, unit: String(localized: "pb"),323                       hint: String(localized: "Le serveur borne l’ordre au marché à cet écart et en dérive le pire prix (1 pb = 0,01 %). Rien n’est présélectionné."), integer: true, id: "futures.order.slippage")324        }325        if ticket.form.kind == .limit {326            let tifs = fm.venue(instrument.venue)?.capabilities?.tif ?? ["gtc"]327            Picker(String(localized: "Durée de validité"), selection: $ticket.form.tif) {328                ForEach([DerivTimeInForce.gtc, .ioc, .alo].filter { tifs.contains($0.rawValue) }, id: \.self) { Text($0.rawValue.uppercased()).tag($0) }329            }330            .pickerStyle(.segmented).accessibilityIdentifier("futures.order.tif")331            Text(FuturesText.tif(ticket.form.tif.rawValue)).font(.system(size: 12)).foregroundStyle(Theme.mute)332        }333        Toggle(isOn: $ticket.form.reduceOnly) {334            VStack(alignment: .leading, spacing: 1) {335                Text(String(localized: "Réduction seulement")).font(.spCallout.weight(.semibold))336                Text(String(localized: "L’ordre ne peut qu’alléger une position existante.")).font(.system(size: 12)).foregroundStyle(Theme.mute)337            }338        }339        .tint(Theme.blue).accessibilityIdentifier("futures.order.reduceOnly")340    }341342    private func sideButton(_ side: DerivOrderSide, title: String, icon: String, tone: Tone, id: String) -> some View {343        let on = ticket.form.side == side344        return Button { ticket.form.side = side } label: {345            Label(title, systemImage: icon).font(.system(size: 16, weight: .semibold)).frame(maxWidth: .infinity, minHeight: 48)346                .foregroundStyle(on ? Theme.surface : tone.color)347                .background(on ? tone.color : tone.color.opacity(0.12), in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))348                .overlay(alignment: .topTrailing) { if on { Image(systemName: "checkmark.circle.fill").font(.system(size: 13)).foregroundStyle(Theme.surface).padding(6) } }349        }350        .buttonStyle(.plain).accessibilityIdentifier(id).accessibilityAddTraits(on ? .isSelected : [])351    }352353    // MARK: leverage — never defaulted354355    @ViewBuilder private var leverageCard: some View {356        @Bindable var ticket = ticket357        if ticket.form.reduceOnly {358            Text(String(localized: "Levier : sans objet pour un ordre de réduction seulement.")).font(.spFootnote).foregroundStyle(Theme.mute)359        } else {360            VStack(alignment: .leading, spacing: 10) {361                HStack {362                    Text(String(localized: "Levier")).font(.spCallout.weight(.semibold))363                    Spacer()364                    if let t = ticket.form.leverage.text { Pill(text: String(localized: "choisi : \(t)"), tone: .info, icon: "checkmark") .accessibilityIdentifier("futures.order.leverage.chosen") }365                    else { Pill(text: String(localized: "à choisir"), tone: .warn, icon: "exclamationmark.circle") }366                }367                let cur = currentLeverage368                Text(cur.map { c in369                    fm.mode == .paper ? String(localized: "Réglage actuel de ce compte papier pour \(instrument.symbol) : \(Fx.leverage(c.leverage))")370                        : String(localized: "Réglage actuel de la plateforme pour \(instrument.symbol) : \(Fx.leverage(c.leverage))") + (c.marginMode.isEmpty ? "" : " · " + String(localized: "marge \(FuturesText.marginMode(c.marginMode))"))371                } ?? (fm.mode == .paper ? String(localized: "Réglage actuel : aucun pour cet instrument sur ce compte papier.") : String(localized: "Réglage actuel de la plateforme : inconnu tant que l’aperçu du serveur ne l’a pas lu.")))372                    .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)373                    .accessibilityIdentifier("futures.order.leverage.current")374                if fm.mode == .paper {375                    TypedField(label: String(localized: "Levier pour cet ordre"), text: $ticket.leverageText, unit: "×", hint: String(localized: "Nombre entier de 1 à \(maxLeverage). Aucune valeur n’est proposée."), integer: true, id: "futures.order.leverage")376                        .onChange(of: ticket.leverageText) { _, t in377                            if let n = DecimalInput.wholeNumber(t) { ticket.form.leverage = .set(n) } else if case .set = ticket.form.leverage { ticket.form.leverage = .none } else if !t.isEmpty { ticket.form.leverage = .none }378                        }379                    if let c = cur {380                        Button { ticket.leverageText = ""; ticket.form.leverage = .keepCurrent(c.leverage) } label: { Label(String(localized: "Garder le réglage actuel (\(Fx.leverage(c.leverage)))"), systemImage: "equal.circle") }381                            .buttonStyle(.bordered).accessibilityIdentifier("futures.order.leverage.keep")382                    }383                } else {384                    HStack(spacing: 8) {385                        if let c = cur {386                            Button { ticket.form.leverage = .keepCurrent(c.leverage) } label: { Label(String(localized: "Utiliser \(Fx.leverage(c.leverage))"), systemImage: "equal.circle").frame(maxWidth: .infinity, minHeight: 40) }387                                .buttonStyle(.bordered).accessibilityIdentifier("futures.order.leverage.keep")388                        }389                        Button { leverageSheet = true } label: { Label(String(localized: "Changer…"), systemImage: "slider.horizontal.3").frame(maxWidth: .infinity, minHeight: 40) }390                            .buttonStyle(.bordered).disabled(!model.canOperate || fm.liveAccount == nil).accessibilityIdentifier("futures.order.leverage.change")391                    }392                    Text(String(localized: "Sur un compte réel, le levier est un réglage de la plateforme : le changer est une opération à part, approuvée par ta clé d’accès.")).font(.system(size: 12)).foregroundStyle(Theme.mute)393                }394            }395            .padding(12)396            .background(Theme.elev.opacity(0.6), in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))397        }398    }399400    @ViewBuilder private var problems: some View {401        let shown = built.problems.filter { !$0.isMissingField }402        ForEach(Array(shown.enumerated()), id: \.offset) { _, p in403            Label(p.text, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true)404        }405    }406407    // MARK: preview408409    @ViewBuilder private var previewCard: some View {410        switch fm.mode {411        case .paper:412            if let p = ticket.paperPreview {413                VStack(alignment: .leading, spacing: 8) {414                    HStack { Text(String(localized: "Aperçu du serveur")).spEyebrow(); Spacer(); PaperTag() }415                    if previewState == .outdated { Notice(tone: .warn, title: String(localized: "Aperçu périmé"), message: String(localized: "Le formulaire a changé depuis cet aperçu.")) }416                    verdict(p.preview.risk)417                    if let e = p.preview.estimate {418                        if e.status == "rejected" { Notice(tone: .danger, title: String(localized: "Le moteur papier rejetterait cet ordre"), message: e.rejectReason) }419                        VStack(alignment: .leading, spacing: 0) {420                            FieldRow(label: String(localized: "Exposition notionnelle (estimation)"), value: Fx.estimate(e.notional)); Divider()421                            FieldRow(label: String(localized: "Levier appliqué"), value: Fx.leverage(e.leverage)); Divider()422                            FieldRow(label: String(localized: "Marge engagée (estimation)"), value: Fx.estimate(e.initialMargin)); Divider()423                            FieldRow(label: String(localized: "Frais (estimation)"), value: Fx.estimate(e.fee)); Divider()424                            if let a = e.avgFillPrice { FieldRow(label: String(localized: "Prix moyen d’exécution simulé"), value: Fx.exact(a) + (e.slippageBps.map { " · " + String(localized: "glissement \(Fx.exact($0)) pb") } ?? "")); Divider() }425                            if let f = e.filledSize { FieldRow(label: String(localized: "Exécuté tout de suite · restant au carnet"), value: "\(Fx.exact(f)) · \(Fx.exact(e.restingSize ?? "0"))"); Divider() }426                            LiquidationRow(price: e.liquidationPrice?.value, provenance: LiquidationProvenance.of(e.liquidationPrice), venueApplies: false); Divider()427                            FieldRow(label: String(localized: "Collatéral libre après (estimation)"), value: Fx.estimate(e.freeCollateralAfter))428                        }429                    }430                    lossNotice(paper: true)431                }432            }433        case .live:434            if let p = ticket.livePreview {435                VStack(alignment: .leading, spacing: 8) {436                    HStack { Text(String(localized: "Aperçu du serveur")).spEyebrow(); Spacer(); if let ref { AccountTag(ref: ref) } }437                    if previewState == .outdated { Notice(tone: .warn, title: String(localized: "Aperçu périmé"), message: String(localized: "Le formulaire a changé depuis cet aperçu.")) }438                    verdict(p.preview.risk)439                    if let e = p.preview.estimate {440                        VStack(alignment: .leading, spacing: 0) {441                            FieldRow(label: String(localized: "Exposition notionnelle (estimation)"), value: Fx.estimate(e.notional)); Divider()442                            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))") } ?? "")); Divider()443                            FieldRow(label: String(localized: "Marge engagée (estimation)"), value: Fx.estimate(e.initialMargin)); Divider()444                            FieldRow(label: String(localized: "Frais (estimation)"), value: Fx.estimate(e.fee) + (e.feeNote.map { " — \($0)" } ?? "")); Divider()445                            if let px = e.price { FieldRow(label: String(localized: "Prix retenu par le serveur"), value: Fx.exact(px) + (e.mark.map { " · " + String(localized: "marque \(Fx.exact($0))") } ?? "")); Divider() }446                            FieldRow(label: String(localized: "Prix de liquidation"), value: e.liquidationNote ?? String(localized: "non fourni par le serveur ni par la plateforme"), tone: .warn); Divider()447                            FieldRow(label: String(localized: "Collatéral libre après (estimation)"), value: Fx.estimate(e.freeCollateralAfter))448                        }449                    }450                    lossNotice(paper: false)451                }452            }453        }454    }455456    @ViewBuilder private func verdict(_ v: DerivRiskVerdict) -> some View {457        if let r = v.refusal { RefusalNotice(refusal: r).accessibilityElement(children: .combine).accessibilityIdentifier("futures.order.riskRefused") }458        else { Label(String(localized: "Accepté par le contrôle de risque du serveur"), systemImage: "checkmark.shield.fill").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.emerald).accessibilityElement(children: .combine).accessibilityIdentifier("futures.order.riskOk") }459    }460461    private func lossNotice(paper: Bool) -> some View {462        Notice(tone: paper ? .info : .danger, title: String(localized: "Risque de perte"),463               message: paper ? String(localized: "Sur un compte réel, un contrat perpétuel à effet de levier peut faire perdre toute la marge engagée par liquidation. Ici : simulation, aucun fonds réel.")464                : String(localized: "Un contrat perpétuel à effet de levier peut faire perdre toute la marge engagée, par liquidation. Fonds réels."))465    }466467    /** From 5×: one more explicit confirmation, in front of what the preview said about the liquidation. */468    @ViewBuilder private var highLeverageConfirmation: some View {469        if let o = built.order, o.needsHighLeverageConfirmation, case .current = previewState, let lev = o.leverage.text {470            let served: String = {471                switch fm.mode {472                case .paper:473                    let e = ticket.paperPreview?.preview.estimate474                    if let liq = e?.liquidationPrice?.value {475                        return String(localized: "Distance de liquidation selon l’aperçu : prix de référence \(Fx.exact(e?.avgFillPrice ?? e?.price ?? mark)) → liquidation estimée par le serveur \(Fx.exact(liq)).")476                    }477                    return String(localized: "Le serveur n’a fourni aucune estimation de liquidation pour cet ordre.")478                case .live:479                    return ticket.livePreview?.preview.estimate?.liquidationNote.map { String(localized: "Liquidation, selon l’aperçu du serveur : « \($0) »") } ?? String(localized: "Le serveur n’a fourni aucune information de liquidation pour cet ordre.")480                }481            }()482            VStack(alignment: .leading, spacing: 6) {483                Notice(tone: .danger, title: String(localized: "Levier élevé : \(lev)"), message: served).accessibilityIdentifier("futures.order.highNotice")484                CheckRow(isOn: Binding(get: { highConfirmed }, set: { ticket.highConfirmedFor = $0 ? o : nil }),485                         text: String(localized: "Je confirme cet ordre avec un levier de \(lev), en connaissance de cette information de liquidation."), tone: .danger, id: "futures.order.highConfirm")486            }487        }488    }489490    // MARK: actions491492    private func preview() async {493        guard let o = built.order, let ref else { return }494        switch ref {495        case .paper(let id): await ticket.previewPaper(fm, account: id, order: o)496        case .live(let id, _): await ticket.previewLive(fm, account: id, order: o)497        }498    }499500    private func submit() async {501        guard blockers.isEmpty, let o = built.order, let ref else { return }502        switch ref {503        case .paper(let id): await ticket.placePaper(fm, account: id, order: o)504        case .live: if let a = fm.liveAccount { await ticket.proposeLive(fm, account: a, order: o) }505        }506    }507}508
Files main
Menu

Theme