Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesBlotter.swift10// Description : Positions, orders, fills and funding payments of the11// account in use (paper or live), as served: entry, mark,12// size, notional, margin, leverage, unrealized and realized13// result, the liquidation price WITH its provenance14// (reported by the venue, or an estimate of the server),15// funding paid; close / reduce, cancel, cancel-all and the16// reconciliation with the venue. Every paper figure is17// tagged PAPIER; a venue that cannot be read is never shown18// as an empty account.19// Module : Features20// Repository : https://git.spboucher.ai/sp-wallet-ios21// Created : 2026-11-1822// Last Modified : 2026-11-1823//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import SwiftUI97import SPWalletCore9899struct FuturesBlotter: View {100 enum Pane: String, CaseIterable { case positions, orders, fills, funding101 var title: String {102 switch self {103 case .positions: String(localized: "Positions")104 case .orders: String(localized: "Ordres")105 case .fills: String(localized: "Exécutions")106 case .funding: String(localized: "Financement")107 }108 }109 }110 @Environment(AppModel.self) private var model111 let fm: FuturesModel112 let openMarket: (String) -> Void113 @State private var pane: Pane = .positions114 @State private var closing: DerivPosition?115 @State private var busy = false116 @State private var error: Error?117 @State private var notice: String?118 @State private var confirmCancelAll = false119120 private var ref: FuturesAccountRef? { fm.accountRef }121 private var paper: Bool { fm.mode == .paper }122123 private var state: DerivAccountState? { paper ? fm.paperAccount?.state : (fm.liveDetail?.venueState.state ?? (model.canOperate ? nil : fm.liveSnapshot?.value.state)) }124 private var positions: [DerivPosition] { paper ? (fm.paperAccount?.positions ?? []) : (fm.liveDetail?.venueState.positions ?? (model.canOperate ? [] : fm.liveSnapshot?.value.positions ?? [])) }125126 var body: some View {127 VStack(alignment: .leading, spacing: Theme.Space.section) {128 if let ref {129 summary(ref)130 Picker(String(localized: "Section"), selection: $pane) { ForEach(Pane.allCases, id: \.self) { Text($0.title).tag($0) } }131 .pickerStyle(.segmented).accessibilityIdentifier("futures.blotter.pane")132 if let e = error { FuturesError(error: e) }133 if let n = notice { Notice(tone: .info, title: n) }134 switch pane {135 case .positions: positionsPane(ref)136 case .orders: ordersPane(ref)137 case .fills: fillsPane138 case .funding: fundingPane139 }140 } else {141 EmptyState(icon: "tray", title: paper ? String(localized: "Aucun compte papier") : String(localized: "Aucun compte réel"),142 message: String(localized: "Les positions et les ordres apparaissent ici une fois un compte créé dans l’onglet Compte."))143 }144 }145 .sheet(item: Binding(get: { closing.map(ClosingItem.init) }, set: { closing = $0?.position })) { item in146 Group { if let ref { ClosePositionSheet(fm: fm, ref: ref, position: item.position) } }.wallet(model)147 }148 .confirmationDialog(String(localized: "Annuler tous les ordres au carnet de ce compte ?"), isPresented: $confirmCancelAll, titleVisibility: .visible) {149 Button(String(localized: "Annuler tous les ordres"), role: .destructive) { Task { await cancelAll() } }150 Button(String(localized: "Ne rien faire"), role: .cancel) {}151 } message: { Text(String(localized: "Aucune position n’est fermée. Aucune clé d’accès n’est demandée pour arrêter.")) }152 }153154 private struct ClosingItem: Identifiable { let position: DerivPosition; var id: String { position.instrument + position.side } }155156 // MARK: summary157158 @ViewBuilder private func summary(_ ref: FuturesAccountRef) -> some View {159 VStack(alignment: .leading, spacing: 10) {160 HStack {161 Text(paper ? (fm.paperAccount?.label ?? "") : (fm.liveAccount?.label ?? "")).font(.spHeadline).lineLimit(1)162 Spacer()163 AccountTag(ref: ref)164 }165 if !paper, let e = fm.liveDetail?.venueState.error {166 Notice(tone: .warn, title: String(localized: "Plateforme illisible pour le moment"), message: String(localized: "\(e). Le compte n’est pas vide pour autant : rien n’est affiché à la place de ce qui n’a pas pu être lu."))167 .accessibilityIdentifier("futures.blotter.venueUnreadable")168 }169 if !paper, !model.canOperate, let snap = fm.liveSnapshot {170 Notice(tone: .warn, title: String(localized: "Instantané du \(snap.savedAt.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Dernier état servi par la plateforme ; il peut avoir changé."), icon: "clock.badge.exclamationmark")171 }172 if paper, fm.paperAccounts.isCached, let at = fm.paperAccounts.savedAt {173 Notice(tone: .warn, title: String(localized: "Instantané du \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Compte papier tel que servi à cette date."), icon: "clock.badge.exclamationmark")174 }175 if let s = state {176 HStack(alignment: .top, spacing: 10) {177 StatTile(label: String(localized: "Valeur du compte"), value: Fx.usd(s.equity), tag: ref)178 StatTile(label: String(localized: "Collatéral libre"), value: Fx.usd(s.freeCollateral), tag: ref)179 StatTile(label: String(localized: "Marge utilisée"), value: Fx.usd(s.marginUsed), tag: ref)180 }181 .accessibilityIdentifier("futures.blotter.summary")182 if let w = s.withdrawable { Text(String(localized: "Retirable : \(Fx.usd(w)) · marge de maintien : \(Fx.usd(s.maintenanceMargin)) · lu \(Money.age(s.ts))")).font(.system(size: 12)).foregroundStyle(Theme.mute) }183 if paper, let t = fm.paperAccount?.totals {184 Text(String(localized: "Résultat réalisé \(Fx.usd(t.realizedPnl, signed: true)) · frais \(Fx.usd(t.feesPaid)) · financement net \(Fx.usd(t.fundingNet, signed: true)) · liquidations \(t.liquidations ?? 0) — \(TradingMode.paper.badge)"))185 .font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)186 }187 } else if paper || fm.liveDetail?.venueState.error == nil {188 Text(model.canOperate ? String(localized: "État du compte en cours de lecture…") : String(localized: "État du compte indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute)189 }190 if !paper {191 HStack(spacing: 8) {192 Button { Task { await reconcile() } } label: { Label(String(localized: "Rapprocher avec la plateforme"), systemImage: "arrow.triangle.2.circlepath").frame(maxWidth: .infinity, minHeight: 40) }193 .buttonStyle(.bordered).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.blotter.reconcile")194 Button(role: .destructive) { confirmCancelAll = true } label: { Label(String(localized: "Annuler tout"), systemImage: "xmark.circle").frame(maxWidth: .infinity, minHeight: 40) }195 .buttonStyle(.bordered).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.blotter.cancelAll")196 }197 }198 }199 .spCard()200 }201202 // MARK: positions203204 @ViewBuilder private func positionsPane(_ ref: FuturesAccountRef) -> some View {205 if positions.isEmpty {206 if !paper, fm.liveDetail?.venueState.error != nil { EmptyState(icon: "questionmark.circle", title: String(localized: "Positions inconnues"), message: String(localized: "La plateforme n’a pas pu être lue.")) }207 else { EmptyState(icon: "square.stack.3d.up.slash", title: String(localized: "Aucune position ouverte"), message: paper ? String(localized: "Compte papier : simulation.") : nil).accessibilityIdentifier("futures.blotter.noPosition") }208 }209 ForEach(positions, id: \.self) { p in210 VStack(alignment: .leading, spacing: 8) {211 HStack(spacing: 8) {212 Button { openMarket(p.instrument) } label: { Text(OfferedVenues.symbol(of: p.instrument)).font(.spHeadline).foregroundStyle(Theme.ink) }.buttonStyle(.plain)213 Pill(text: FuturesText.side(position: p.side) + " · " + Fx.leverage(p.leverage), tone: FuturesText.sideTone(p.side), icon: p.side == "long" ? "arrow.up.right" : "arrow.down.right")214 Spacer()215 AccountTag(ref: ref)216 }217 HStack(alignment: .top, spacing: 10) {218 StatTile(label: String(localized: "Taille"), value: Fx.exact(p.size))219 StatTile(label: String(localized: "Entrée"), value: Fx.exact(p.entryPrice))220 StatTile(label: String(localized: "Marque"), value: Fx.exact(p.markPrice))221 }222 HStack(alignment: .top, spacing: 10) {223 StatTile(label: String(localized: "Notionnel"), value: notional(p))224 StatTile(label: String(localized: "Marge · \(FuturesText.marginMode(p.marginMode))"), value: Fx.usd(p.margin))225 StatTile(label: String(localized: "Résultat latent"), value: Fx.usd(p.unrealizedPnl, signed: true), tone: Fx.sign(p.unrealizedPnl) >= 0 ? .ok : .danger, tag: paper ? ref : nil)226 }227 VStack(alignment: .leading, spacing: 0) {228 LiquidationRow(price: p.liquidationPrice, provenance: LiquidationProvenance.of(p), venueApplies: !paper)229 if let r = p.realizedPnl { Divider(); FieldRow(label: String(localized: "Résultat réalisé") + (paper ? " (\(TradingMode.paper.badge))" : ""), value: Fx.usd(r, exact: true, signed: true)) }230 if let f = p.fundingPaid { Divider(); FieldRow(label: String(localized: "Financement payé") + (paper ? " (\(TradingMode.paper.badge))" : ""), value: Fx.usd(f, exact: true)) }231 }232 Button { closing = p } label: { Label(String(localized: "Fermer ou réduire"), systemImage: "arrow.uturn.down").frame(maxWidth: .infinity, minHeight: 40) }233 .buttonStyle(.bordered).disabled(!model.canOperate).accessibilityIdentifier("futures.position.close.\(OfferedVenues.symbol(of: p.instrument))")234 }235 .spCard()236 }237 }238239 private func notional(_ p: DerivPosition) -> String {240 guard let s = VenueDecimal(p.size), let m = VenueDecimal(p.markPrice) else { return "—" }241 return Fx.usd(s.multiplied(by: m).description)242 }243244 // MARK: orders245246 @ViewBuilder private func ordersPane(_ ref: FuturesAccountRef) -> some View {247 if paper {248 let open = fm.paperAccount?.openOrders ?? [], history = (fm.paperDetail?.orders ?? []).filter { o in !open.contains { $0.clientId == o.clientId } }249 orderList(title: String(localized: "Ordres ouverts"), orders: open, cancellable: true, ref: ref)250 orderList(title: String(localized: "Historique"), orders: Array(history.prefix(40)), cancellable: false, ref: ref)251 } else {252 let mine = fm.liveDetail?.orders ?? []253 VStack(alignment: .leading, spacing: 6) {254 SectionHeader(title: String(localized: "Au carnet de la plateforme"))255 let resting = fm.liveDetail?.venueState.openOrders ?? []256 if resting.isEmpty { Text(fm.liveDetail?.venueState.error == nil ? String(localized: "Aucun ordre au carnet, selon la plateforme.") : String(localized: "Inconnu : plateforme illisible.")).font(.spCallout).foregroundStyle(Theme.mute) }257 ForEach(resting, id: \.clientId) { o in orderRow(o, state: OrderStateView.of(status: o.status), cancel: nil); Divider() }258 }259 .spCard()260 VStack(alignment: .leading, spacing: 6) {261 SectionHeader(title: String(localized: "Ordres de ce portefeuille"))262 if mine.isEmpty { Text(String(localized: "Aucun ordre.")).font(.spCallout).foregroundStyle(Theme.mute) }263 ForEach(mine.prefix(40)) { o in264 let s = OrderStateView.of(live: o.state, final: o.final)265 liveOrderRow(o, state: s)266 Divider()267 }268 }269 .spCard()270 }271 }272273 private func orderList(title: String, orders: [DerivOrder], cancellable: Bool, ref: FuturesAccountRef) -> some View {274 VStack(alignment: .leading, spacing: 6) {275 HStack { SectionHeader(title: title); AccountTag(ref: ref) }276 if orders.isEmpty { Text(String(localized: "Aucun ordre.")).font(.spCallout).foregroundStyle(Theme.mute) }277 ForEach(orders, id: \.clientId) { o in278 orderRow(o, state: OrderStateView.of(status: o.status), cancel: cancellable ? { Task { await cancelPaper(o.clientId) } } : nil)279 Divider()280 }281 }282 .spCard()283 }284285 private func orderRow(_ o: DerivOrder, state s: OrderStateView, cancel: (() -> Void)?) -> some View {286 HStack(alignment: .top, spacing: 8) {287 VStack(alignment: .leading, spacing: 3) {288 Text("\(FuturesText.side(order: o.side)) \(Fx.exact(o.size)) \(OfferedVenues.symbol(of: o.instrument))").font(.system(size: 14.5, weight: .semibold)).foregroundStyle(FuturesText.sideTone(o.side).color)289 Text(FuturesText.type(o.type) + (o.price.map { " @ " + Fx.exact($0) } ?? "") + (o.triggerPrice.map { " · " + String(localized: "déclenchement \(Fx.exact($0))") } ?? "") + (o.reduceOnly ? " · " + String(localized: "réduction") : ""))290 .font(.system(size: 12.5)).foregroundStyle(Theme.mute)291 Label(s.label + (s.isFilled || o.filled != "0" ? " · " + String(localized: "exécuté \(Fx.exact(o.filled))") + (o.avgFillPrice.map { " @ " + Fx.exact($0) } ?? "") : ""), systemImage: s.symbol)292 .font(.system(size: 12.5, weight: .medium)).foregroundStyle(s.tone.color)293 if let r = o.rejectReason { Text(r).font(.system(size: 12)).foregroundStyle(Theme.danger) }294 }295 Spacer(minLength: 4)296 if let cancel { Button(String(localized: "Annuler"), role: .destructive, action: cancel).buttonStyle(.bordered).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.order.cancel") }297 }298 .padding(.vertical, 4)299 }300301 private func liveOrderRow(_ o: LiveOrder, state s: OrderStateView) -> some View {302 HStack(alignment: .top, spacing: 8) {303 VStack(alignment: .leading, spacing: 3) {304 Text("\(FuturesText.side(order: o.side)) \(Fx.exact(o.size)) \(OfferedVenues.symbol(of: o.instrument))").font(.system(size: 14.5, weight: .semibold)).foregroundStyle(FuturesText.sideTone(o.side).color)305 Text(FuturesText.type(o.type) + (o.price.map { " @ " + Fx.exact($0) } ?? "") + (o.reduceOnly ? " · " + String(localized: "réduction") : "") + (o.origin.map { " · \($0)" } ?? ""))306 .font(.system(size: 12.5)).foregroundStyle(Theme.mute)307 Label(s.label + (o.filled != "0" ? " · " + String(localized: "exécuté \(Fx.exact(o.filled))") + (o.avgFillPrice.map { " @ " + Fx.exact($0) } ?? "") : ""), systemImage: s.symbol)308 .font(.system(size: 12.5, weight: .medium)).foregroundStyle(s.tone.color)309 if let r = o.reason { Text(r).font(.system(size: 12)).foregroundStyle(Theme.danger) }310 }311 Spacer(minLength: 4)312 if !o.final { Button(String(localized: "Annuler"), role: .destructive) { Task { await cancelLive(o.clientId) } }.buttonStyle(.bordered).disabled(busy || !model.canOperate) }313 }314 .padding(.vertical, 4)315 }316317 // MARK: fills and funding318319 @ViewBuilder private var fillsPane: some View {320 let fills = paper ? (fm.paperDetail?.fills ?? []) : (fm.liveDetail?.fills ?? [])321 VStack(alignment: .leading, spacing: 6) {322 HStack { SectionHeader(title: String(localized: "Exécutions")); if let ref { AccountTag(ref: ref) } }323 if fills.isEmpty { Text(String(localized: "Aucune exécution.")).font(.spCallout).foregroundStyle(Theme.mute) }324 ForEach(fills.prefix(60)) { f in325 VStack(alignment: .leading, spacing: 2) {326 HStack {327 Text("\(FuturesText.side(order: f.side)) \(Fx.exact(f.size)) \(OfferedVenues.symbol(of: f.instrument)) @ \(Fx.exact(f.price))").font(.system(size: 14, weight: .semibold)).foregroundStyle(FuturesText.sideTone(f.side).color)328 if f.liquidation { Pill(text: String(localized: "liquidation"), tone: .danger, icon: "exclamationmark.triangle.fill") }329 }330 Text(String(localized: "frais \(Fx.exact(f.fee)) \(f.feeAsset)") + (f.closedPnl.map { " · " + String(localized: "résultat \(Fx.usd($0, exact: true, signed: true))") } ?? "") + " · " + f.ts.formatted(date: .abbreviated, time: .standard))331 .font(.system(size: 12.5)).foregroundStyle(Theme.mute)332 }333 .padding(.vertical, 4)334 Divider()335 }336 }337 .spCard()338 }339340 @ViewBuilder private var fundingPane: some View {341 let rows = paper ? (fm.paperDetail?.funding ?? []) : (fm.liveDetail?.funding ?? [])342 VStack(alignment: .leading, spacing: 6) {343 HStack { SectionHeader(title: String(localized: "Paiements de financement")); if let ref { AccountTag(ref: ref) } }344 if rows.isEmpty { Text(String(localized: "Aucun paiement de financement.")).font(.spCallout).foregroundStyle(Theme.mute) }345 ForEach(rows.prefix(60), id: \.self) { r in346 HStack {347 VStack(alignment: .leading, spacing: 2) {348 Text(OfferedVenues.symbol(of: r.instrument)).font(.system(size: 14, weight: .semibold))349 Text(String(localized: "taux \(Fx.percent(fraction: r.rate, dp: 5) ?? r.rate) · taille \(Fx.exact(r.size)) · \(r.ts.formatted(date: .abbreviated, time: .shortened))")).font(.system(size: 12.5)).foregroundStyle(Theme.mute)350 }351 Spacer()352 Text(Fx.usd(r.amount, exact: true, signed: true)).font(.system(size: 14, weight: .semibold)).monospacedDigit().foregroundStyle(Fx.sign(r.amount) >= 0 ? Theme.emerald : Theme.danger)353 }354 .padding(.vertical, 4)355 Divider()356 }357 Text(String(localized: "Montant négatif = payé par le compte.")).font(.system(size: 12)).foregroundStyle(Theme.mute)358 }359 .spCard()360 }361362 // MARK: actions (stopping never asks for a passkey)363364 private func run(_ work: () async throws -> Void) async {365 guard !busy else { return }366 busy = true; error = nil; notice = nil367 defer { busy = false }368 do { try await work() } catch { self.error = error }369 }370371 private func cancelPaper(_ clientId: String) async {372 guard let id = fm.paperID else { return }373 await run { _ = try await fm.api.cancelPaperOrder(id, clientId: clientId); await fm.loadPaperDetail() }374 }375376 private func cancelLive(_ clientId: String) async {377 guard let id = fm.liveID else { return }378 await run {379 let r = try await fm.liveAPI.cancelOrder(id, clientId: clientId)380 notice = r.sent == false ? String(localized: "Proposition retirée : rien n’avait été envoyé à la plateforme.") : String(localized: "Annulation demandée à la plateforme ; état de l’ordre : \(OrderStateView.of(live: r.order.state, final: r.order.final).label)")381 await fm.loadLiveDetail()382 }383 }384385 private func cancelAll() async {386 guard let id = fm.liveID else { return }387 await run {388 let r = try await fm.liveAPI.cancelAll(id)389 notice = String(localized: "Annulations demandées : \(r.requested), acceptées par la plateforme : \(r.accepted), échecs : \(r.failed.count)") + (r.remaining.map { " · " + String(localized: "encore au carnet : \($0.count)") } ?? " · " + String(localized: "reste au carnet : illisible"))390 await fm.loadLiveDetail()391 }392 }393394 private func reconcile() async {395 guard let id = fm.liveID else { return }396 await run {397 let r = try await fm.liveAPI.reconcile(id)398 fm.adopt(live: r.account)399 notice = String(localized: "Rapprochement : \(r.reconciled) ordres, \(r.fills) exécutions, \(r.funding) paiements de financement lus sur la plateforme.") + (r.divergence.map { " " + String(localized: "Divergence : \($0)") } ?? "")400 }401 }402}403