SPB Git

Repository Public

FuturesSupport.swift 11.0 KB 217 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Futures/FuturesSupport.swift3// Description: Shared vocabulary of the derivatives terminal: the three trading modes that are never mixed (paper simulation, venue testnet, venue mainnet) with their colours, display helpers for the server's decimal strings (the strings stay exact; a Double is only ever used to sort, to draw or to label an approximation), and the small building blocks every sub-screen uses.4import SwiftUI5import SPWalletCore67/// The three books of the terminal. A figure of one mode is never added to a figure of another.8enum FutMode: String, CaseIterable, Identifiable, Sendable {9    case paper, testnet, mainnet10    var id: String { rawValue }11    var title: String {12        switch self { case .paper: "Simulation (papier)"; case .testnet: "Testnet de la plateforme"; case .mainnet: "Réel (mainnet)" }13    }14    var badge: String {15        switch self { case .paper: "SIMULATION"; case .testnet: "TESTNET"; case .mainnet: "RÉEL" }16    }17    var color: Color {18        switch self { case .paper: Color(red: 0.42, green: 0.36, blue: 0.82); case .testnet: Color(red: 0.10, green: 0.55, blue: 0.70); case .mainnet: Theme.negative }19    }20    var symbol: String {21        switch self { case .paper: "testtube.2"; case .testnet: "hammer"; case .mainnet: "bolt.shield" }22    }23    var explanation: String {24        switch self {25        case .paper: "Compte simulé par le serveur : aucune clé, aucun compte de plateforme, aucun fonds réel. Les ordres sont exécutés par le moteur papier contre le carnet réel."26        case .testnet: "Compte du testnet de la plateforme : vraie plateforme de test, collatéral fictif. Les ordres passent par le signataire isolé."27        case .mainnet: "Compte réel sur la plateforme : fonds réels. Chaque ordre est approuvé par votre passkey sur l’objet exact que la plateforme recevra."28        }29    }30    /// The venue network of a live mode; nil for paper.31    var network: String? { switch self { case .paper: nil; case .testnet: "testnet"; case .mainnet: "mainnet" } }32}3334/// The mode's label on a figure or a button: colour AND text, never colour alone.35struct FutModeBadge: View {36    let mode: FutMode37    var body: some View {38        Label(mode.badge, systemImage: mode.symbol).font(.caption.weight(.bold)).foregroundStyle(mode.color)39            .padding(.horizontal, 7).padding(.vertical, 3).background(mode.color.opacity(0.14), in: Capsule())40            .accessibilityLabel("Mode \(mode.title)")41    }42}4344/// Display of the server's decimal strings.45enum FutNum {46    /// For sorting, drawing and labelled approximations only — never to compute an amount that is sent or shown as exact.47    static func d(_ s: String?) -> Double? { guard let s, !s.isEmpty else { return nil }; return Double(s) }4849    /// An exact decimal string, grouped; "—" when absent.50    static func exact(_ s: String?, maxFraction: Int? = nil) -> String { Fmt.amount(s, maxFraction: maxFraction) }5152    /// A dollar figure of an account (equity, margin, notional…): the server's string cut to cents for reading.53    static func usd(_ s: String?) -> String { guard let s, !s.isEmpty else { return "—" }; return Fmt.amount(s, maxFraction: 2) + " $" }5455    /// A fraction ("0.0123") as a signed percentage.56    static func pct(fraction s: String?, digits: Int = 2) -> String {57        guard let v = d(s) else { return "—" }58        return (v >= 0 ? "+" : "−") + abs(v * 100).formatted(.number.precision(.fractionLength(digits))) + " %"59    }6061    static func compactUSD(_ s: String?) -> String {62        guard let v = d(s) else { return "—" }63        return v.formatted(.number.notation(.compactName).precision(.fractionLength(0...2))) + " $"64    }65    static func compact(_ s: String?) -> String {66        guard let v = d(s) else { return "—" }67        return v.formatted(.number.notation(.compactName).precision(.fractionLength(0...2)))68    }69    static func approx(_ v: Double?, digits: Int = 2) -> String {70        guard let v, v.isFinite else { return "—" }71        return "≈ " + v.formatted(.number.precision(.fractionLength(0...digits)))72    }73    static func ms(_ t: Int?) -> Date? { t.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } }7475    /// What the user typed, as the decimal text the server parses: dot separator, no grouping. Nil when it is not a plain positive decimal.76    static func input(_ raw: String) -> String? {77        let t = raw.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")78        guard let v = VenueDecimal(t), v.isPositive else { return nil }79        return v.description80    }81}8283/// A labelled figure of a summary grid. `value == nil` renders the explicit unavailable state, never a zero.84struct FutStat: View {85    let label: String86    let value: String?87    var color: Color = .primary88    var note: String?89    init(_ label: String, _ value: String?, color: Color = .primary, note: String? = nil) { self.label = label; self.value = value; self.color = color; self.note = note }90    var body: some View {91        VStack(alignment: .leading, spacing: 2) {92            Text(label).font(.caption).foregroundStyle(.secondary)93            if let value { Text(value).font(.title3.weight(.medium)).monospacedDigit().foregroundStyle(color).textSelection(.enabled).lineLimit(1).minimumScaleFactor(0.7) }94            else { Label("Indisponible", systemImage: "xmark.octagon").font(.callout).foregroundStyle(Theme.negative) }95            if let note { Text(note).font(.caption2).foregroundStyle(.secondary).lineLimit(2) }96        }.frame(maxWidth: .infinity, alignment: .leading).accessibilityElement(children: .combine)97    }98}99100/// A row of `FutStat`s that wraps on narrow windows.101struct FutStatGrid<Content: View>: View {102    var minimum: CGFloat = 150103    @ViewBuilder var content: Content104    var body: some View {105        LazyVGrid(columns: [GridItem(.adaptive(minimum: minimum), spacing: 14, alignment: .topLeading)], alignment: .leading, spacing: 12) { content }106    }107}108109/// A server lock or capability: ON / OFF with the server's own reason when it is off.110struct FutLockRow: View {111    let name: String112    let on: Bool?113    let reason: String?114    var body: some View {115        HStack(alignment: .firstTextBaseline, spacing: 10) {116            Image(systemName: on == true ? "lock.open.fill" : on == false ? "lock.fill" : "questionmark.circle").foregroundStyle(on == true ? Theme.positive : on == false ? Theme.warning : .secondary).frame(width: 18)117            VStack(alignment: .leading, spacing: 2) {118                HStack(spacing: 8) {119                    Text(name).font(Theme.monoSmall)120                    Text(on == true ? "ouvert" : on == false ? "fermé par le serveur" : "état illisible").font(.caption.weight(.medium)).foregroundStyle(on == true ? Theme.positive : on == false ? Theme.warning : .secondary)121                }122                if let reason, !reason.isEmpty { Text(reason).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }123            }124        }.accessibilityElement(children: .combine)125    }126}127128/// The verbatim state of an order, coloured by what it means — only a state the server calls final and filled reads as done.129struct FutOrderStatePill: View {130    let raw: String131    static func text(_ raw: String) -> String {132        switch raw {133        case "proposed": "Proposé (rien n’est envoyé)"134        case "risk_checked": "Contrôlé, en attente de votre passkey"135        case "authorized": "Approuvé, signature en cours"136        case "signed": "Signé, non confirmé par la plateforme"137        case "submitted": "Envoyé, non confirmé par la plateforme"138        case "pending": "En attente"139        case "open": "Au carnet (en attente d’exécution)"140        case "partially_filled": "Partiellement exécuté"141        case "filled": "Exécuté"142        case "cancelled": "Annulé"143        case "rejected": "Rejeté"144        case "triggered": "Déclenché"145        case "unknown": "Inconnu : la plateforme n’a rien confirmé"146        default: raw147        }148    }149    var body: some View {150        let color: Color = raw == "filled" ? Theme.positive : ["rejected", "unknown"].contains(raw) ? Theme.negative : ["cancelled"].contains(raw) ? .secondary : Theme.warning151        Text(Self.text(raw)).font(.caption.weight(.medium)).foregroundStyle(color).padding(.horizontal, 7).padding(.vertical, 2).background(color.opacity(0.13), in: Capsule())152            .help("État rapporté par le serveur : \(raw)")153    }154}155156/// How fresh a displayed price is, in words and colour.157struct FutFreshnessDot: View {158    let freshness: StreamFreshness?159    /// The date of the REST snapshot shown when no live quote exists.160    var snapshotAt: Date?161    var body: some View {162        let (color, text): (Color, String) = {163            switch freshness?.state {164            case .live: (Theme.positive, "En direct")165            case .delayed: (Theme.warning, "Retardé" + age)166            case .stale: (Theme.negative, "Périmé" + age)167            case .reconnecting: (Theme.warning, "Reconnexion du flux…")168            case .some(.none), nil: (.secondary, snapshotAt.map { "Instantané \(Fmt.relative($0))" } ?? "Aucune donnée")169            }170        }()171        Circle().fill(color).frame(width: 7, height: 7).help(text).accessibilityLabel(text)172    }173    private var age: String { freshness?.ageMs.map { " (\($0 / 1000) s)" } ?? "" }174}175176struct FutSideText: View {177    let side: String178    var body: some View {179        let long = side == "long" || side == "buy"180        Text(side == "long" ? "LONG" : side == "short" ? "SHORT" : side == "buy" ? "ACHAT" : side == "sell" ? "VENTE" : side.uppercased())181            .font(.caption.weight(.bold)).foregroundStyle(long ? Theme.positive : Theme.negative)182    }183}184185/// A result of the last read of one source: the value, or why it is unavailable — and when.186struct FutLoaded<T> {187    var value: T?188    var error: String?189    var at: Date?190    var loading = false191    mutating func set(_ v: T) { value = v; error = nil; at = Date(); loading = false }192    mutating func fail(_ e: String) { error = e; loading = false }193}194195/// The header of a sheet that asks for a passkey: title, mode, and a close button that withdraws nothing by itself.196struct FutSheetHeader: View {197    let title: String198    var mode: FutMode?199    var body: some View {200        HStack { Text(title).font(.title2.weight(.semibold)); Spacer(); if let mode { FutModeBadge(mode: mode) } }.padding(20)201    }202}203204extension View {205    /// Runs `action` now and then every `seconds` while the view is on screen and the app is active.206    func futPolling(every seconds: Double, id: some Equatable & Sendable, _ action: @escaping @MainActor () async -> Void) -> some View {207        task(id: id) {208            await action()209            while !Task.isCancelled {210                try? await Task.sleep(for: .seconds(seconds))211                guard !Task.isCancelled else { return }212                if AppActivity.isActive { await action() }213            }214        }215    }216}217
Files main
Menu

Theme