Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesPaperAccounts.swift10// Description : Paper (simulated) derivatives accounts: list, creation11// with a label and a simulated collateral typed by the12// owner, reset to the initial collateral, the risk policy in13// full and its edition. No key, no venue account, no real14// funds — and every figure says PAPIER.15// Module : Features16// Repository : https://git.spboucher.ai/sp-wallet-ios17// Created : 2026-11-1818// Last Modified : 2026-11-1819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import SPWalletCore9495struct FuturesPaperAccounts: View {96 @Environment(AppModel.self) private var model97 let fm: FuturesModel98 @State private var creating = false99 @State private var editingPolicy = false100 @State private var confirmReset = false101 @State private var busy = false102 @State private var error: Error?103104 var body: some View {105 VStack(alignment: .leading, spacing: Theme.Space.section) {106 if let e = fm.paperError, fm.paperAccounts.value == nil { FuturesError(error: e) { Task { await fm.loadPaper() } } }107 VStack(alignment: .leading, spacing: 8) {108 HStack { SectionHeader(title: String(localized: "Comptes papier")); PaperTag() }109 Text(String(localized: "Comptes simulés : aucun fonds réel, aucune clé, aucun ordre envoyé à une plateforme. Les prix et carnets utilisés sont ceux servis par la plateforme.")).font(.spFootnote).foregroundStyle(Theme.mute)110 if let all = fm.paperAccounts.value {111 if all.isEmpty { Text(String(localized: "Aucun compte papier.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("futures.paper.none") }112 ForEach(all) { a in113 Button { Task { await fm.selectPaper(a.id) } } label: {114 HStack(spacing: 10) {115 Image(systemName: fm.paperID == a.id ? "largecircle.fill.circle" : "circle").foregroundStyle(fm.paperID == a.id ? Theme.blue : Theme.mute)116 VStack(alignment: .leading, spacing: 2) {117 Text(a.label).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(1)118 Text(String(localized: "\(OfferedVenues.name(a.venue)) · valeur \(Fx.usd(a.state.equity)) (\(TradingMode.paper.badge)) · \(a.positions.count) position(s)")).font(.spFootnote).foregroundStyle(Theme.mute)119 }120 Spacer()121 }122 .frame(minHeight: 50).contentShape(Rectangle())123 }124 .buttonStyle(.plain).accessibilityIdentifier("futures.paper.account").accessibilityAddTraits(fm.paperID == a.id ? .isSelected : [])125 }126 } else if fm.paperError == nil { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }127 Button { creating = true } label: { Label(String(localized: "Créer un compte papier"), systemImage: "plus") }128 .buttonStyle(.spSecondary).disabled(!model.canOperate).accessibilityIdentifier("futures.paper.create")129 }130 .spCard()131132 if let a = fm.paperAccount {133 VStack(alignment: .leading, spacing: 0) {134 HStack { SectionHeader(title: a.label); PaperTag() }.padding(.bottom, 6)135 FieldRow(label: String(localized: "Valeur du compte (simulation)"), value: Fx.usd(a.state.equity, exact: true)); Divider()136 FieldRow(label: String(localized: "Collatéral simulé · libre"), value: "\(Fx.usd(a.state.collateral, exact: true)) · \(Fx.usd(a.state.freeCollateral, exact: true))"); Divider()137 if let i = a.initialCollateral { FieldRow(label: String(localized: "Collatéral initial"), value: Fx.usd(i, exact: true)); Divider() }138 if let s = a.settings {139 FieldRow(label: String(localized: "Frais simulés preneur · teneur"), value: "\(Fx.percent(fraction: s.takerFeeRate, dp: 4, signed: false) ?? "—") · \(Fx.percent(fraction: s.makerFeeRate, dp: 4, signed: false) ?? "—")"); Divider()140 FieldRow(label: String(localized: "Levier par instrument (réglages actuels)"), value: (s.leverageByInstrument ?? [:]).sorted { $0.key < $1.key }.map { "\(OfferedVenues.symbol(of: $0.key)) \(Fx.leverage($0.value))" }.joined(separator: ", ").ifEmpty(String(localized: "aucun")))141 if let l = s.liquidationPrice { Divider(); FieldRow(label: String(localized: "Prix de liquidation du moteur papier"), value: l, tone: .warn) }142 }143 }144 .spCard()145 VStack(alignment: .leading, spacing: 0) {146 SectionHeader(title: String(localized: "Politique de risque du compte"), action: model.canOperate ? (title: String(localized: "Modifier"), run: { editingPolicy = true }) : nil).padding(.bottom, 6)147 PolicyRows(policy: a.policy)148 }149 .spCard()150 if let e = error { FuturesError(error: e) }151 Button(role: .destructive) { confirmReset = true } label: { Label(String(localized: "Réinitialiser ce compte papier"), systemImage: "arrow.counterclockwise") }152 .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.paper.reset")153 }154 }155 .sheet(isPresented: $creating) { PaperAccountCreationSheet(fm: fm).wallet(model) }156 .sheet(isPresented: $editingPolicy) { Group { if let a = fm.paperAccount { PolicyEditorSheet(fm: fm, target: .paper(a.id), policy: a.policy) } }.wallet(model) }157 .confirmationDialog(String(localized: "Réinitialiser ce compte papier ?"), isPresented: $confirmReset, titleVisibility: .visible) {158 Button(String(localized: "Réinitialiser"), role: .destructive) { Task { await reset() } }159 Button(String(localized: "Annuler"), role: .cancel) {}160 } message: { Text(String(localized: "Retour au collatéral initial : ordres, exécutions, financement et historique de ce compte simulé sont effacés.")) }161 }162163 private func reset() async {164 guard let id = fm.paperID, !busy else { return }165 busy = true; error = nil166 defer { busy = false }167 do { fm.adopt(paper: try await fm.api.resetPaperAccount(id)) } catch { self.error = error }168 }169}170171private extension String {172 func ifEmpty(_ other: String) -> String { isEmpty ? other : self }173}174175struct PaperAccountCreationSheet: View {176 @Environment(AppModel.self) private var model177 @Environment(\.dismiss) private var dismiss178 let fm: FuturesModel179 @State private var label = ""180 @State private var collateral = ""181 @State private var venue: String? = OfferedVenues.ids.count == 1 ? OfferedVenues.ids[0] : nil182 @State private var busy = false183 @State private var error: Error?184185 private var amount: String? {186 guard case .success(let v) = DecimalInput.parse(collateral), let lo = VenueDecimal("10"), let hi = VenueDecimal("1000000000"), v >= lo, v <= hi else { return nil }187 return v.description188 }189 private var cleanLabel: String { label.trimmingCharacters(in: .whitespacesAndNewlines) }190191 var body: some View {192 NavigationStack {193 ScrollView {194 VStack(alignment: .leading, spacing: Theme.Space.section) {195 ModeBand(mode: .paper)196 VStack(alignment: .leading, spacing: 12) {197 if OfferedVenues.ids.count > 1 {198 Picker(String(localized: "Plateforme simulée"), selection: $venue) { Text(String(localized: "à choisir")).tag(String?.none); ForEach(OfferedVenues.ids, id: \.self) { Text(OfferedVenues.name($0)).tag(String?.some($0)) } }199 } else { FieldRow(label: String(localized: "Plateforme simulée"), value: OfferedVenues.name(OfferedVenues.ids[0])) }200 VStack(alignment: .leading, spacing: 5) {201 Text(String(localized: "Nom du compte")).font(.spFootnote).foregroundStyle(Theme.mute)202 TextField(String(localized: "à saisir"), text: $label).padding(.horizontal, 12).frame(minHeight: 46)203 .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("futures.paper.new.label")204 }205 TypedField(label: String(localized: "Collatéral simulé"), text: $collateral, unit: "USDC", hint: String(localized: "Entre 10 et 1 000 000 000. Argent fictif."), id: "futures.paper.new.collateral")206 }207 .spCard()208 if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.paper.new.error") }209 Button { Task { await create() } } label: { BusyLabel(title: String(localized: "Créer le compte papier"), busy: busy) }210 .buttonStyle(.spPrimary).disabled(busy || amount == nil || cleanLabel.isEmpty || venue == nil || !model.canOperate).accessibilityIdentifier("futures.paper.new.submit")211 }212 .futuresSheetPage()213 }214 .spPage()215 .navigationTitle(String(localized: "Nouveau compte papier")).navigationBarTitleDisplayMode(.inline)216 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { dismiss() } } }217 }218 }219220 private func create() async {221 guard let amount, let venue, !busy else { return }222 busy = true; error = nil223 defer { busy = false }224 do { fm.adopt(paper: try await fm.api.createPaperAccount(PaperAccountCreation(venue: venue, label: cleanLabel, collateral: amount))); dismiss() }225 catch { self.error = error }226 }227}228