Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/Futures/FuturesAccountView.swift10// Description : The account of the current mode — a paper account11// (SIMULATION) or the live venue account (testnet /12// mainnet), never both: equity, collateral, free collateral,13// margin used, positions with their liquidation price as14// served (the venue's own figure, or the paper engine's15// estimate, labelled), open orders, order history, fills,16// funding payments and risk events. A venue that could not17// be read is shown as unavailable, never as an empty18// account. Cancels and reduce-only closes are always19// offered: they are never behind the server locks.20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-macos22// 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 Charts99import SPWalletCore100101/// Operations on a PAPER account: everything here is simulated by the server and can never reach a venue or the signer.102@MainActor @Observable final class FutPaperOps {103 let model: AppModel104 let store: FuturesStore105 private(set) var busy = false106 var error: String?107 var notice: String?108 @ObservationIgnored private var closeKey: (key: String, fingerprint: String)?109110 init(model: AppModel, store: FuturesStore) { self.model = model; self.store = store }111112 private func run(_ body: () async throws -> Void) async {113 guard model.canOperate, !busy else { return }114 busy = true; error = nil; notice = nil115 defer { busy = false }116 do { try await body() } catch { self.error = model.describe(error) }117 }118119 func create(venue: String, label: String, collateral: String) async {120 await run {121 let d = try await store.deriv.createPaperAccount(PaperAccountCreation(venue: venue, label: label, collateral: collateral))122 await store.loadAccounts()123 store.paperId = d.account.id; store.adopt(d)124 notice = "Compte papier « \(d.account.label) » créé avec \(FutNum.usd(d.account.state.collateral)) de collatéral simulé."125 }126 }127 func reset() async {128 guard let id = store.paperId else { return }129 await run { store.adopt(try await store.deriv.resetPaperAccount(id)); notice = "Compte papier remis à son collatéral initial : ordres, exécutions et historique simulés effacés." }130 }131 func cancel(clientId: String) async {132 guard let id = store.paperId else { return }133 await run {134 let o = try await store.deriv.cancelPaperOrder(id, clientId: clientId)135 notice = "Ordre simulé \(o.instrument) : \(FutOrderStatePill.text(o.status))."136 await store.refreshAccount()137 }138 }139 func close(_ p: DerivPosition, fraction: String, slippageBps: Int) async {140 guard let id = store.paperId else { return }141 await run {142 let fp = "\(id)|\(p.instrument)|\(p.side)|\(p.size)|\(fraction)|\(slippageBps)"143 if closeKey?.fingerprint != fp { closeKey = (APIClient.newIdempotencyKey(), fp) }144 let r = try await store.deriv.closePaperPosition(id, instrument: p.instrument, fraction: fraction, slippageBps: slippageBps, idempotencyKey: closeKey!.key)145 closeKey = nil146 notice = "Clôture simulée \(p.instrument) : \(FutOrderStatePill.text(r.order.status))" + (r.order.avgFillPrice.map { ", exécutée à \(FutNum.exact($0))" } ?? "") + (r.order.rejectReason.map { " — \($0)" } ?? "") + (r.worstPrice.map { " (pire prix accepté \(FutNum.exact($0)))" } ?? "")147 await store.refreshAccount()148 }149 }150}151152struct FutAccountView: View {153 let model: AppModel154 @Bindable var store: FuturesStore155 let ops: FutLiveOps156 let open: (String) -> Void157 @State private var paper: FutPaperOps?158159 var body: some View {160 Group {161 switch store.mode {162 case .paper: if let paper { FutPaperAccountView(model: model, store: store, paper: paper, open: open) } else { ProgressView() }163 case .testnet, .mainnet: FutLiveAccountView(model: model, store: store, ops: ops, open: open)164 }165 }166 .task { if paper == nil { paper = FutPaperOps(model: model, store: store) } }167 }168}169170// MARK: - paper171172private struct FutPaperAccountView: View {173 let model: AppModel174 @Bindable var store: FuturesStore175 @Bindable var paper: FutPaperOps176 let open: (String) -> Void177 @State private var creating = false178 @State private var newVenue = ""179 @State private var newLabel = ""180 @State private var newCollateral = ""181 @State private var confirmReset = false182183 private var paperVenues: [DerivVenue] { (store.venues.value ?? []).filter { $0.paper == true } }184185 var body: some View {186 Card("Comptes papier", trailing: AnyView(ProvenanceTag(p: .simulated, text: "SIMULATION — aucun fonds réel"))) {187 if let e = store.paperAccounts.error { Banner(.danger, "Comptes papier indisponibles : \(e)") }188 HStack {189 if let list = store.paperAccounts.value, !list.isEmpty {190 Picker("Compte", selection: Binding(get: { store.paperId }, set: { store.paperId = $0 })) {191 ForEach(list) { a in Text("\(a.label) — \(a.venue)").tag(Optional(a.id)) }192 }.frame(maxWidth: 360)193 } else if store.paperAccounts.value != nil { Text("Aucun compte papier.").foregroundStyle(.secondary) }194 Spacer()195 if paper.busy { ProgressView().controlSize(.small) }196 Button("Nouveau compte papier…") { creating.toggle(); if newVenue.isEmpty { newVenue = paperVenues.first?.id ?? "" } }197 Button("Réinitialiser…", role: .destructive) { confirmReset = true }.disabled(store.paperId == nil || !model.canOperate || paper.busy)198 .confirmationDialog("Réinitialiser ce compte papier ?", isPresented: $confirmReset) {199 Button("Effacer l’historique simulé et revenir au collatéral initial", role: .destructive) { Task { await paper.reset() } }200 } message: { Text("Ordres, exécutions, financement et courbe de valeur simulés de ce compte seront effacés. Aucun fonds réel n’est concerné.") }201 }202 if creating {203 Form {204 Picker("Plateforme simulée", selection: $newVenue) { ForEach(paperVenues) { Text($0.name).tag($0.id) } }205 TextField("Nom du compte", text: $newLabel)206 TextField("Collatéral simulé (10 à 1 000 000 000)", text: $newCollateral, prompt: Text("montant en dollars simulés"))207 }.formStyle(.grouped).scrollDisabled(true)208 if paperVenues.isEmpty { Text("Le serveur n’offre de compte papier sur aucune plateforme pour l’instant.").font(.callout).foregroundStyle(.secondary) }209 HStack {210 Spacer()211 Button("Créer le compte SIMULÉ") {212 guard let c = FutNum.input(newCollateral) else { return }213 Task { await paper.create(venue: newVenue, label: newLabel.trimmingCharacters(in: .whitespaces), collateral: c); if paper.error == nil { creating = false; newLabel = ""; newCollateral = "" } }214 }.buttonStyle(.borderedProminent).tint(FutMode.paper.color)215 .disabled(newVenue.isEmpty || newLabel.trimmingCharacters(in: .whitespaces).isEmpty || FutNum.input(newCollateral) == nil || !model.canOperate || paper.busy)216 }217 }218 if let e = paper.error { Banner(.danger, e) }219 if let n = paper.notice { Banner(.info, n) }220 }221 if let e = store.paperDetail.error { Banner(.warning, "Dernière lecture du compte en échec : \(e)" + (store.paperDetail.at.map { " — données du \(Fmt.dateSeconds($0))" } ?? "")) }222 if let d = store.currentPaperDetail {223 let a = d.account224 FutStateCard(title: "État du compte « \(a.label) »", mode: .paper, state: a.state, unavailable: nil) {225 FutStat("Collatéral initial", FutNum.usd(a.initialCollateral))226 FutStat("PnL réalisé (simulé)", FutNum.usd(a.totals?.realizedPnl), color: Theme.change(FutNum.d(a.totals?.realizedPnl)))227 FutStat("Frais payés (simulés)", FutNum.usd(a.totals?.feesPaid))228 FutStat("Financement net (simulé)", FutNum.usd(a.totals?.fundingNet), color: Theme.change(FutNum.d(a.totals?.fundingNet)))229 FutStat("Liquidations simulées", a.totals?.liquidations.map(String.init) ?? "—")230 }231 if let how = a.settings?.liquidationPrice { Text("Prix de liquidation des positions papier : \(how)").font(.caption).foregroundStyle(.secondary) }232 FutEquityCard(points: d.equity, mode: .paper)233 FutPositionsCard(model: model, store: store, mode: .paper, positions: a.positions, busy: paper.busy, open: open) { p, f, s in Task { await paper.close(p, fraction: f, slippageBps: s) } }234 FutOrdersCard(title: "Ordres ouverts", mode: .paper, rows: a.openOrders.map(FutOrderRow.init), empty: "Aucun ordre simulé au carnet.", busy: paper.busy || !model.canOperate) { id in Task { await paper.cancel(clientId: id) } }235 FutOrdersCard(title: "Historique des ordres", mode: .paper, rows: d.orders.map(FutOrderRow.init), empty: "Aucun ordre simulé.", busy: true, cancel: nil)236 FutFillsCard(mode: .paper, fills: d.fills)237 FutFundingCard(mode: .paper, payments: d.funding)238 FutRiskEventsCard(events: d.riskEvents)239 } else if store.paperId != nil, store.paperDetail.error == nil {240 ProgressView().frame(maxWidth: .infinity, minHeight: 100)241 }242 }243}244245// MARK: - live246247private struct FutLiveAccountView: View {248 let model: AppModel249 @Bindable var store: FuturesStore250 @Bindable var ops: FutLiveOps251 let open: (String) -> Void252 @State private var confirmCancelAll = false253254 var body: some View {255 let mode = store.mode256 if let e = store.liveAccounts.error { Banner(.danger, "Comptes de plateforme indisponibles : \(e)") }257 if let a = store.liveAccount {258 Card("Compte \(a.label)", trailing: AnyView(FutModeBadge(mode: mode))) {259 Field(label: "Adresse du compte", value: a.account, mono: true)260 Field(label: "Plateforme / réseau", value: "\(a.venue) · \(a.network)")261 Field(label: "Mode du compte", value: a.mode.rawValue + (a.tradable ? " — nouveau risque permis" : " — nouveau risque refusé"))262 ForEach(store.liveBlockers, id: \.self) { Banner(.warning, $0) }263 if let dv = a.divergence { Banner(.danger, "Divergence entre le portefeuille et la plateforme : \(dv)") }264 HStack {265 if ops.isBusy { ProgressView().controlSize(.small); Text(ops.busyText ?? "").font(.callout).foregroundStyle(.secondary) }266 Spacer()267 Button("Rapprocher avec la plateforme") { Task { await ops.reconcile() } }.disabled(!model.canOperate || ops.isBusy)268 Button("Actualiser") { Task { await store.refreshAccount() } }269 }270 if let e = ops.error { Banner(.danger, e) }271 if let n = ops.notice { Banner(.info, n) }272 }273 if let e = store.liveDetail.error { Banner(.danger, "Lecture du compte en échec : \(e)" + (store.liveDetail.at.map { " — ce qui suit date du \(Fmt.dateSeconds($0))" } ?? "")) }274 if let d = store.currentLiveDetail {275 let vs = d.venueState276 if let e = vs.error { Banner(.danger, "La plateforme n’a pas pu être lue : \(e). Les soldes et positions sont INDISPONIBLES — ce n’est pas un compte vide.") }277 FutStateCard(title: "État du compte sur la plateforme", mode: mode, state: vs.state, unavailable: vs.error ?? (vs.state == nil ? "état non fourni" : nil)) { EmptyView() }278 if let o = ops.trackedOrder { FutTrackedOrderCard(ops: ops, order: o, mode: mode) }279 FutEquityCard(points: d.equity, mode: mode)280 if vs.error == nil {281 FutPositionsCard(model: model, store: store, mode: mode, positions: vs.positions, busy: ops.isBusy, open: open) { p, f, s in Task { await ops.proposeClose(p, fraction: f, slippageBps: s) } }282 FutOrdersCard(title: "Ordres au carnet de la plateforme", mode: mode, rows: vs.openOrders.map(FutOrderRow.init), empty: "Aucun ordre au carnet selon la plateforme.", busy: true, cancel: nil)283 }284 let pending = d.orders.filter { !$0.final }285 Card("Ordres en cours suivis par le portefeuille", trailing: AnyView(Button("Tout annuler sur la plateforme…", role: .destructive) { confirmCancelAll = true }.disabled(!model.canOperate || ops.isBusy)286 .confirmationDialog("Annuler tous les ordres au carnet de ce compte ?", isPresented: $confirmCancelAll) {287 Button("Annuler tous les ordres (\(mode.badge))", role: .destructive) { Task { await ops.cancelAll() } }288 } message: { Text("La plateforme est interrogée pour chaque ordre. Aucune position n’est clôturée. Aucune passkey n’est requise pour arrêter.") })) {289 FutOrdersTable(rows: pending.map(FutOrderRow.init), empty: "Aucun ordre en cours.", busy: !model.canOperate || ops.isBusy) { id in Task { await ops.cancel(orderClientId: id) } }290 }291 FutOrdersCard(title: "Historique des ordres", mode: mode, rows: d.orders.map(FutOrderRow.init), empty: "Aucun ordre.", busy: true, cancel: nil)292 FutFillsCard(mode: mode, fills: d.fills)293 FutFundingCard(mode: mode, payments: d.funding)294 FutRiskEventsCard(events: d.riskEvents)295 } else if store.liveDetail.error == nil {296 ProgressView().frame(maxWidth: .infinity, minHeight: 100)297 }298 } else if store.liveAccounts.value != nil {299 EmptyState(symbol: "person.crop.rectangle.badge.plus", title: "Aucun compte \(mode == .mainnet ? "réel" : "testnet")", detail: "Le compte de plateforme se crée dans l’onglet « Plateforme et collatéral ». Il est créé en lecture seule.")300 }301 }302}303304// MARK: - shared cards305306struct FutStateCard<Extra: View>: View {307 let title: String308 let mode: FutMode309 let state: DerivAccountState?310 /// Non-nil: the state could not be read — every figure shows as unavailable.311 let unavailable: String?312 @ViewBuilder var extra: Extra313314 var body: some View {315 Card(title, trailing: AnyView(FutModeBadge(mode: mode))) {316 let s = unavailable == nil ? state : nil317 FutStatGrid {318 FutStat("Valeur du compte (equity)", s.map { FutNum.usd($0.equity) })319 FutStat("Collatéral", s.map { FutNum.usd($0.collateral) })320 FutStat("Collatéral libre", s.map { FutNum.usd($0.freeCollateral) })321 FutStat("Marge utilisée", s.map { FutNum.usd($0.marginUsed) })322 FutStat("Marge de maintien", s.map { $0.maintenanceMargin.map { FutNum.usd($0) } ?? "non publiée" })323 FutStat("Retirable", s.map { $0.withdrawable.map { FutNum.usd($0) } ?? "non publié" })324 extra325 }326 if let s { Text("Lu \(Fmt.relative(s.ts)) — source : \(s.source == "paper" ? "moteur papier (simulation)" : s.source == "venue" ? "la plateforme" : s.source)").font(.caption).foregroundStyle(.secondary) }327 }328 }329}330331struct FutEquityCard: View {332 let points: [DerivEquityPoint]333 let mode: FutMode334 var body: some View {335 let pts = points.compactMap { p in Double(p.equity).map { (p.ts, $0) } }.sorted { $0.0 < $1.0 }336 if pts.count > 1 {337 Card("Valeur du compte dans le temps", trailing: AnyView(FutModeBadge(mode: mode))) {338 Chart(pts, id: \.0) { p in LineMark(x: .value("Date", p.0), y: .value("Valeur", p.1)).foregroundStyle(mode.color) }339 .chartYScale(domain: .automatic(includesZero: false)).chartYAxis { AxisMarks(position: .trailing) }.frame(height: 150)340 .accessibilityLabel("Courbe de la valeur du compte")341 Text("Points enregistrés par le serveur ; les dépôts et retraits y figurent comme des variations.").font(.caption).foregroundStyle(.secondary)342 }343 }344 }345}346347struct FutPositionsCard: View {348 let model: AppModel349 let store: FuturesStore350 let mode: FutMode351 let positions: [DerivPosition]352 let busy: Bool353 let open: (String) -> Void354 let close: (DerivPosition, String, Int) -> Void355 @State private var selected: String?356 @State private var fraction = "1"357 @State private var slippage = "50"358 @State private var confirm = false359360 private func key(_ p: DerivPosition) -> String { "\(p.instrument)|\(p.side)" }361362 var body: some View {363 Card("Positions", trailing: AnyView(FutModeBadge(mode: mode))) {364 if positions.isEmpty { Text("Aucune position ouverte.").foregroundStyle(.secondary) }365 ForEach(positions, id: \.self) { p in366 let live = store.price(p.instrument)367 let mark = FutNum.d(live.freshness?.isLive == true ? live.mark : p.markPrice) ?? FutNum.d(p.markPrice)368 let size = FutNum.d(p.size), liq = FutNum.d(p.liquidationPrice)369 VStack(alignment: .leading, spacing: 8) {370 HStack(spacing: 10) {371 FutSideText(side: p.side)372 Button(p.instrument) { open(p.instrument) }.buttonStyle(.link).fontWeight(.medium)373 Text("\(FutNum.exact(p.leverage))× · marge \(p.marginMode == "cross" ? "croisée" : p.marginMode == "isolated" ? "isolée" : p.marginMode)").font(.callout).foregroundStyle(.secondary)374 Spacer()375 Text("PnL latent \(FutNum.usd(p.unrealizedPnl))").fontWeight(.semibold).foregroundStyle(Theme.change(FutNum.d(p.unrealizedPnl))).monospacedDigit()376 }377 FutStatGrid(minimum: 130) {378 FutStat("Taille", FutNum.exact(p.size))379 FutStat("Prix d’entrée", FutNum.exact(p.entryPrice))380 FutStat("Prix (mark)", FutNum.exact(p.markPrice))381 FutStat("Notionnel", size.flatMap { s in mark.map { FutNum.approx(s * $0) + " $" } } ?? "—", note: "taille × prix")382 FutStat("Marge", FutNum.usd(p.margin))383 FutStat("Prix de liquidation", p.liquidationPrice.map { FutNum.exact($0) } ?? "non fourni",384 color: p.liquidationPrice == nil ? .secondary : Theme.warning,385 note: p.liquidationPrice == nil ? "la source n’en publie pas pour cette position" : p.liquidationPriceIsVenueReported ? "chiffre de la plateforme" : "estimation du moteur papier")386 FutStat("Distance à la liquidation", liq.flatMap { l in mark.flatMap { m in m > 0 ? "≈ " + (abs(m - l) / m * 100).formatted(.number.precision(.fractionLength(2))) + " %" : nil } } ?? "—", note: "par rapport au prix affiché")387 FutStat("Financement cumulé", p.fundingPaid.map { FutNum.usd($0) } ?? "non publié", note: "payé (positif) ou reçu")388 FutStat("PnL réalisé", p.realizedPnl.map { FutNum.usd($0) } ?? "non publié")389 }390 HStack {391 Picker("Part à clôturer", selection: Binding(get: { selected == key(p) ? fraction : "1" }, set: { selected = key(p); fraction = $0 })) {392 Text("25 %").tag("0.25"); Text("50 %").tag("0.5"); Text("75 %").tag("0.75"); Text("100 %").tag("1")393 }.pickerStyle(.segmented).frame(width: 260).labelsHidden()394 TextField("pb", text: $slippage).textFieldStyle(.roundedBorder).frame(width: 60).help("Glissement maximal en points de base par rapport au carnet (1 à 500)")395 Text("pb max").font(.caption).foregroundStyle(.secondary)396 Spacer()397 Button(mode == .paper ? "Clôturer (SIMULÉ)…" : "Préparer la clôture (\(mode.badge))…") { selected = key(p); confirm = true }398 .disabled(busy || !model.canOperate || Int(slippage).map { (1...500).contains($0) } != true)399 }400 Text("Clôture en réduction seule, au marché, bornée par ce glissement. Toujours disponible, même quand les nouveaux ordres sont fermés." + (mode == .paper ? "" : " L’ordre exact vous est montré avant votre passkey.")).font(.caption).foregroundStyle(.secondary)401 }402 .padding(10).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))403 .confirmationDialog("Clôturer \(p.instrument) ?", isPresented: Binding(get: { confirm && selected == key(p) }, set: { if !$0 { confirm = false } })) {404 let f = selected == key(p) ? fraction : "1"405 Button(mode == .paper ? "Clôturer \(Self.percent(f)) (simulation)" : "Préparer la clôture de \(Self.percent(f))") { if let s = Int(slippage) { close(p, f, s) } }406 } message: { Text(mode == .paper ? "Ordre simulé en réduction seule : aucun fonds réel." : "Rien n’est envoyé maintenant : le serveur prépare l’ordre réducteur, que vous vérifierez puis approuverez avec votre passkey.") }407 }408 }409 }410 static func percent(_ f: String) -> String { (Double(f).map { Int(($0 * 100).rounded()) } ?? 100).description + " %" }411}412413/// One order for a table, whichever engine it comes from; states are kept verbatim.414struct FutOrderRow: Identifiable {415 let id: String416 let instrument, side, type, size, tif, state, filled: String417 let price, avg, reason, source: String?418 let reduceOnly: Bool419 let final: Bool420 let at: Date?421422 init(_ o: DerivOrder) {423 id = o.clientId + (o.venueOrderId ?? ""); instrument = o.instrument; side = o.side; type = o.type; size = o.size; tif = o.tif; state = o.status; filled = o.filled424 price = o.price; avg = o.avgFillPrice; reason = o.rejectReason; source = nil; reduceOnly = o.reduceOnly425 final = ["filled", "cancelled", "rejected"].contains(o.status); at = o.updatedAt ?? o.createdAt426 clientId = o.clientId427 }428 init(_ o: LiveOrder) {429 id = o.clientId; instrument = o.instrument; side = o.side; type = o.type; size = o.size; tif = o.tif; state = o.state.rawValue; filled = o.filled430 price = o.price; avg = o.avgFillPrice; reason = o.reason; source = o.source; reduceOnly = o.reduceOnly; final = o.final; at = o.updatedAt ?? o.createdAt431 clientId = o.clientId432 }433 let clientId: String434}435436struct FutOrdersCard: View {437 let title: String438 let mode: FutMode439 let rows: [FutOrderRow]440 let empty: String441 let busy: Bool442 let cancel: ((String) -> Void)?443 var body: some View {444 Card(title, trailing: AnyView(FutModeBadge(mode: mode))) { FutOrdersTable(rows: rows, empty: empty, busy: busy, cancel: cancel) }445 }446}447448struct FutOrdersTable: View {449 let rows: [FutOrderRow]450 let empty: String451 let busy: Bool452 let cancel: ((String) -> Void)?453 var body: some View {454 if rows.isEmpty { Text(empty).foregroundStyle(.secondary) } else {455 Table(rows) {456 TableColumn("Date") { r in Text(Fmt.date(r.at)).font(.callout) }.width(min: 110, ideal: 130)457 TableColumn("Instrument") { r in HStack(spacing: 6) { FutSideText(side: r.side); Text(r.instrument); if r.reduceOnly { Text("réd.").font(.caption2).foregroundStyle(.secondary) } } }.width(min: 150, ideal: 190)458 TableColumn("Type") { r in Text("\(r.type) · \(r.tif)").font(.callout) }.width(min: 80, ideal: 100)459 TableColumn("Taille") { r in Text(FutNum.exact(r.size)).monospacedDigit() }.width(min: 70, ideal: 90)460 TableColumn("Prix") { r in Text(FutNum.exact(r.price)).monospacedDigit() }.width(min: 80, ideal: 100)461 TableColumn("Exécuté") { r in Text(FutNum.exact(r.filled) + (r.avg.map { " à \(FutNum.exact($0))" } ?? "")).monospacedDigit() }.width(min: 110, ideal: 150)462 TableColumn("État") { r in FutOrderStatePill(raw: r.state).help(r.reason ?? "") }.width(min: 150, ideal: 220)463 TableColumn("") { r in464 if let cancel, !r.final { Button("Annuler") { cancel(r.clientId) }.disabled(busy) }465 else if let why = r.reason { Text(why).font(.caption).foregroundStyle(.secondary).lineLimit(2).help(why) }466 }.width(min: 80, ideal: 160)467 }468 .frame(height: CGFloat(min(rows.count, 10)) * 30 + 36)469 }470 }471}472473struct FutFillsCard: View {474 let mode: FutMode475 let fills: [DerivFill]476 var body: some View {477 Card("Exécutions", trailing: AnyView(FutModeBadge(mode: mode))) {478 if fills.isEmpty { Text("Aucune exécution.").foregroundStyle(.secondary) } else {479 Table(fills) {480 TableColumn("Date") { f in Text(Fmt.date(f.ts)).font(.callout) }.width(min: 110, ideal: 130)481 TableColumn("Instrument") { f in HStack(spacing: 6) { FutSideText(side: f.side); Text(f.instrument); if f.liquidation { Text("LIQUIDATION").font(.caption2.weight(.bold)).foregroundStyle(Theme.negative) } } }.width(min: 150, ideal: 200)482 TableColumn("Taille") { f in Text(FutNum.exact(f.size)).monospacedDigit() }.width(min: 70, ideal: 90)483 TableColumn("Prix") { f in Text(FutNum.exact(f.price)).monospacedDigit() }.width(min: 80, ideal: 100)484 TableColumn("Frais") { f in Text("\(FutNum.exact(f.fee)) \(f.feeAsset)").monospacedDigit() }.width(min: 90, ideal: 120)485 TableColumn("PnL clôturé") { f in Text(f.closedPnl.map { FutNum.usd($0) } ?? "—").monospacedDigit().foregroundStyle(Theme.change(FutNum.d(f.closedPnl))) }.width(min: 90, ideal: 120)486 TableColumn("Source") { f in Text(f.source ?? (mode == .paper ? "paper" : "—")).font(.caption).foregroundStyle(.secondary) }.width(min: 60, ideal: 80)487 }.frame(height: CGFloat(min(fills.count, 10)) * 28 + 36)488 }489 }490 }491}492493struct FutFundingCard: View {494 let mode: FutMode495 let payments: [DerivFundingPayment]496 var body: some View {497 Card("Paiements de financement du compte", trailing: AnyView(FutModeBadge(mode: mode))) {498 if payments.isEmpty { Text("Aucun paiement de financement enregistré.").foregroundStyle(.secondary) } else {499 ForEach(Array(payments.prefix(40).enumerated()), id: \.offset) { _, p in500 HStack {501 Text(Fmt.date(p.ts)).foregroundStyle(.secondary).frame(width: 150, alignment: .leading)502 Text(p.instrument).frame(maxWidth: .infinity, alignment: .leading)503 Text("taux \(FutNum.pct(fraction: p.rate, digits: 4)) · taille \(FutNum.exact(p.size))").font(.callout).foregroundStyle(.secondary)504 Text(FutNum.usd(p.amount)).monospacedDigit().foregroundStyle(Theme.change(FutNum.d(p.amount))).frame(width: 130, alignment: .trailing)505 }.font(.callout)506 }507 Text("Montant négatif : payé ; positif : reçu." + (payments.count > 40 ? " 40 plus récents sur \(payments.count)." : "")).font(.caption).foregroundStyle(.secondary)508 }509 }510 }511}512513struct FutRiskEventsCard: View {514 let events: [DerivRiskEvent]515 var body: some View {516 if !events.isEmpty {517 Card("Événements de risque du compte") {518 ForEach(events.prefix(25)) { e in519 HStack(alignment: .firstTextBaseline) {520 Text(Fmt.date(e.ts)).foregroundStyle(.secondary).frame(width: 150, alignment: .leading)521 Text(e.kind + (e.code.map { " · \($0)" } ?? "")).font(Theme.monoSmall).frame(width: 220, alignment: .leading)522 Text(e.message).frame(maxWidth: .infinity, alignment: .leading).fixedSize(horizontal: false, vertical: true)523 }.font(.callout)524 }525 }526 }527 }528}529