SPB Git

Repository Public

FuturesMarketsView.swift 13.0 KB 235 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/Futures/FuturesMarketsView.swift10// Description      : The list of perpetual contracts of the offered venue(s),11//                    as served: price, 24 h change, funding rate, open12//                    interest, maximum leverage. Search, favourites kept on the13//                    device, live figures from the quote stream for the rows14//                    that are on screen only (a row that leaves the screen is15//                    unsubscribed); a figure that is not live says so.16// Module           : Features17// Repository       : https://git.spboucher.ai/sp-wallet-ios18// Created          : 2026-11-1819// Last Modified    : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import SPWalletCore9596struct FuturesMarketsView: View {97    @Environment(AppModel.self) private var model98    let fm: FuturesModel99    /** Regular width: the list is a column and highlights the open market. */100    var column = false101    let onSelect: (String) -> Void102    @State private var query = ""103    @State private var onlyFavourites = false104    @FocusState private var searching: Bool105106    private var rows: [DerivInstrument] {107        let q = query.trimmingCharacters(in: .whitespaces).uppercased()108        return (fm.instruments.value ?? [])109            .filter { (q.isEmpty || $0.symbol.uppercased().contains(q) || $0.base.uppercased().contains(q)) && (!onlyFavourites || fm.favourites.contains($0.id)) }110            .sorted { a, b in111                let fa = fm.favourites.contains(a.id), fb = fm.favourites.contains(b.id)112                if fa != fb { return fa }113                let va = FuturesMath.double(fm.ticker(a.id)?.volume24h) ?? -1, vb = FuturesMath.double(fm.ticker(b.id)?.volume24h) ?? -1114                return va != vb ? va > vb : a.symbol < b.symbol115            }116    }117118    var body: some View {119        VStack(alignment: .leading, spacing: 10) {120            HStack(spacing: 8) {121                HStack(spacing: 6) {122                    Image(systemName: "magnifyingglass").foregroundStyle(Theme.mute)123                    TextField(String(localized: "Rechercher un contrat"), text: $query)124                        .textInputAutocapitalization(.characters).autocorrectionDisabled().focused($searching)125                        .accessibilityIdentifier("futures.markets.search")126                    if !query.isEmpty { Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.mute) }.accessibilityLabel(String(localized: "Effacer la recherche")) }127                }128                .padding(.horizontal, 12).frame(minHeight: 44)129                .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))130                Button { onlyFavourites.toggle() } label: {131                    Image(systemName: onlyFavourites ? "star.fill" : "star").font(.system(size: 17, weight: .semibold))132                        .foregroundStyle(onlyFavourites ? Theme.warn : Theme.mute).frame(width: 44, height: 44)133                        .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))134                }135                .accessibilityLabel(String(localized: "Favoris seulement")).accessibilityAddTraits(onlyFavourites ? .isSelected : [])136                .accessibilityIdentifier("futures.markets.favouritesOnly")137            }138            // navigation only: ⌘F focuses the search139            .background { Button("") { searching = true }.keyboardShortcut("f", modifiers: .command).opacity(0).accessibilityHidden(true) }140141            if let at = fm.instruments.savedAt, fm.instruments.isCached {142                Notice(tone: .warn, title: String(localized: "Liste du \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Instantané : les prix affichés ne sont pas à jour."), icon: "clock.badge.exclamationmark")143            }144            ForEach(fm.readErrors, id: \.self) { e in Notice(tone: .warn, title: String(localized: "\(OfferedVenues.name(e.venue)) illisible"), message: e.message) }145            streamNotice146147            if fm.instruments.value == nil {148                if let e = fm.instruments.error { FuturesError(error: e) { Task { await fm.loadMarkets() } } }149                else { ProgressView().frame(maxWidth: .infinity, minHeight: 160) }150            } else if rows.isEmpty {151                EmptyState(icon: "magnifyingglass", title: onlyFavourites && query.isEmpty ? String(localized: "Aucun favori") : String(localized: "Aucun contrat ne correspond"),152                           message: onlyFavourites && query.isEmpty ? String(localized: "Touche l’étoile d’un contrat pour le garder ici. Les favoris restent sur cet appareil.") : nil)153            } else {154                LazyVStack(spacing: 0) {155                    ForEach(rows) { i in156                        MarketRow(fm: fm, instrument: i, selected: column && fm.selected == i.id, dense: column) { onSelect(i.id) }157                            .onAppear { fm.rowAppeared(i.id) }158                            .onDisappear { fm.rowDisappeared(i.id) }159                        if i.id != rows.last?.id { Divider() }160                    }161                }162                .spCard(padding: column ? 8 : 12)163                Text(String(localized: "Prix de marque, variation 24 h, financement par période et intérêt ouvert tels que servis par \(OfferedVenues.ids.map(OfferedVenues.name).joined(separator: ", ")). \(rows.count) contrats."))164                    .font(.system(size: 12)).foregroundStyle(Theme.mute)165            }166        }167    }168169    @ViewBuilder private var streamNotice: some View {170        if model.canOperate {171            switch fm.streamState {172            case .reconnecting: Notice(tone: .warn, title: String(localized: "Flux en reconnexion"), message: String(localized: "Les prix affichés ne sont plus tenus à jour tant que le flux n’est pas rétabli."), icon: "arrow.triangle.2.circlepath").accessibilityIdentifier("futures.stream.down")173            case .ended: Notice(tone: .warn, title: String(localized: "Flux fermé"), message: String(localized: "Les prix affichés sont les derniers reçus ; ils ne sont plus en direct."), icon: "bolt.slash.fill").accessibilityIdentifier("futures.stream.down")174            default: EmptyView()175            }176        }177    }178}179180private struct MarketRow: View {181    let fm: FuturesModel182    let instrument: DerivInstrument183    let selected: Bool184    let dense: Bool185    let open: () -> Void186187    var body: some View {188        let id = instrument.id189        let change = fm.change24h(id), fresh = fm.freshness(id)190        HStack(spacing: 6) {191            Button { fm.toggleFavourite(id) } label: {192                Image(systemName: fm.favourites.contains(id) ? "star.fill" : "star").font(.system(size: 15))193                    .foregroundStyle(fm.favourites.contains(id) ? Theme.warn : Theme.mute.opacity(0.6)).frame(width: 36, height: 44)194            }195            .buttonStyle(.plain)196            .accessibilityLabel(fm.favourites.contains(id) ? String(localized: "Retirer \(instrument.symbol) des favoris") : String(localized: "Ajouter \(instrument.symbol) aux favoris"))197            .accessibilityIdentifier("futures.markets.star.\(instrument.symbol)")198            Button(action: open) {199                HStack(spacing: 8) {200                    VStack(alignment: .leading, spacing: 3) {201                        HStack(spacing: 6) {202                            Text(instrument.symbol).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(1)203                            Text(String(localized: "max \(Fx.leverage(instrument.maxLeverage))")).font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.mute)204                                .padding(.horizontal, 6).padding(.vertical, 2).background(Theme.elev, in: Capsule())205                            if instrument.status != "active" { Pill(text: instrument.status, tone: .warn) }206                        }207                        HStack(spacing: 8) {208                            Text(String(localized: "Fin. \(Fx.percent(fraction: fm.fundingRate(id), dp: 5) ?? "—")")).lineLimit(1)209                            if !dense { Text(String(localized: "IO \(Fx.openInterestUSD(fm.openInterest(id), mark: fm.mark(id)))")).lineLimit(1) }210                        }211                        .font(.system(size: 12)).monospacedDigit().foregroundStyle(Theme.mute)212                    }213                    Spacer(minLength: 6)214                    VStack(alignment: .trailing, spacing: 3) {215                        Text(fm.mark(id).map { Fx.exact($0) } ?? String(localized: "indisponible")).font(.system(size: 15, weight: .semibold)).monospacedDigit()216                            .foregroundStyle(fm.mark(id) == nil ? Theme.warn : Theme.ink).lineLimit(1).minimumScaleFactor(0.7)217                        HStack(spacing: 5) {218                            FreshnessMark(freshness: fresh, showLive: false).labelStyle(.iconOnly)219                            if let t = Fx.percent(fraction: change, signed: false) {220                                Text((Fx.sign(change) > 0 ? "▲ " : Fx.sign(change) < 0 ? "▼ " : "") + t).font(.system(size: 12.5, weight: .semibold)).monospacedDigit()221                                    .foregroundStyle(Fx.sign(change) >= 0 ? Theme.emerald : Theme.danger)222                            } else { Text("—").font(.system(size: 12.5)).foregroundStyle(Theme.mute) }223                        }224                    }225                }226                .frame(minHeight: 54).contentShape(Rectangle())227            }228            .buttonStyle(.plain)229            .accessibilityIdentifier("futures.markets.row.\(instrument.symbol)")230        }231        .padding(.horizontal, 4)232        .background(selected ? Theme.elev : .clear, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))233    }234}235
Files main
Menu

Theme