SPB Git

Repository Public

RsMarketsTab.swift 13.9 KB 235 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/Research/RsMarketsTab.swift10// Description      : The market explorer over the server's markets hub: search,11//                    filters, sort, and for each market its price (and what12//                    kind of price it is), 24 h change, volume, funding and13//                    open interest, with the source, its date and the stale /14//                    outlier flags the server sets. Opening a row shows the15//                    underlying's page. Viewing a market never prepares16//                    anything.17// Module           : Features18// Repository       : https://git.spboucher.ai/sp-wallet-macos19// Created          : 2026-11-1820// Last Modified    : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import SwiftUI95import SPWalletCore9697struct RsMarketsTab: View {98    let model: AppModel99    @State private var data: RsMarketsModel?100    @State private var selection: HubRow.ID?101    @State private var opened: String?102103    var body: some View {104        Group {105            if let symbol = opened { RsInstrumentView(model: model, symbol: symbol) { opened = nil }.id(symbol) }106            else if let data { explorer(data) }107            else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }108        }109        .task {110            if data == nil { let d = RsMarketsModel(model: model); data = d; await d.reload() }111            // the hub's answer is cached a few seconds by the server; a slow refresh keeps prices from silently ageing on screen112            while !Task.isCancelled {113                try? await Task.sleep(for: .seconds(30))114                guard !Task.isCancelled else { return }115                if AppActivity.isActive, !model.isOffline, opened == nil, let d = data, d.rows.count <= 100 { await d.reload() }116            }117        }118    }119120    private func explorer(_ data: RsMarketsModel) -> some View {121        VStack(spacing: 0) {122            RsMarketsFilters(data: data)123            VStack(alignment: .leading, spacing: 6) {124                if let e = data.error { Banner(.danger, e) }125                if !data.sourceErrors.isEmpty { Banner(.warning, "Liste PARTIELLE — sources sans réponse : " + data.sourceErrors.map { "\($0.source) (\($0.message))" }.joined(separator: " ; ")) }126                let bad = data.venues.filter { $0.status != "ok" }127                if !bad.isEmpty { Text("Plateformes dégradées : " + bad.map { "\($0.name) — \($0.status == "stale" ? "périmée" : $0.status == "error" ? "en erreur" : $0.status)\($0.error.map { " (\($0))" } ?? "")" }.joined(separator: " ; ")).font(.caption).foregroundStyle(Theme.warning) }128            }.padding(.horizontal, 24)129            Table(data.rows, selection: $selection) {130                TableColumn("Marché") { r in131                    HStack(spacing: 8) {132                        AssetBadge(symbol: r.base, size: 22)133                        VStack(alignment: .leading, spacing: 0) {134                            Text(r.symbol).fontWeight(.medium).lineLimit(1)135                            Text("\(r.kind == "perp" ? "Perpétuel" : r.kind == "spot" ? "Comptant" : r.kind) · \(r.venueName ?? r.venue)").font(.caption).foregroundStyle(.secondary).lineLimit(1)136                        }137                    }138                }.width(min: 170, ideal: 210)139                TableColumn("Prix") { r in140                    VStack(alignment: .trailing, spacing: 0) {141                        Text(RsFmt.price(r.price)).monospacedDigit()142                        Text(RsMarketsText.priceKind(r.priceKind)).font(.caption2).foregroundStyle(.secondary)143                    }.frame(maxWidth: .infinity, alignment: .trailing)144                }.width(min: 100, ideal: 120)145                TableColumn("24 h") { r in Text(RsFmt.fraction(r.change24h)).monospacedDigit().foregroundStyle(Theme.change(RsFmt.double(r.change24h))).frame(maxWidth: .infinity, alignment: .trailing) }.width(min: 70, ideal: 80)146                TableColumn("Volume 24 h") { r in Text(RsFmt.compactUsd(r.volume24hUsd)).monospacedDigit().frame(maxWidth: .infinity, alignment: .trailing) }.width(min: 90, ideal: 100)147                TableColumn("Financement (annualisé)") { r in Text(r.funding.map { RsFmt.fraction($0.annualised) } ?? "—").monospacedDigit().foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .trailing) }.width(min: 90, ideal: 110)148                TableColumn("Intérêt ouvert") { r in Text(RsFmt.compactUsd(r.openInterestUsd)).monospacedDigit().foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .trailing) }.width(min: 90, ideal: 100)149                TableColumn("Source et date") { r in150                    VStack(alignment: .leading, spacing: 0) {151                        Text(r.priceSource ?? r.source).font(.caption).lineLimit(1)152                        Text(r.sourceDate.map { Fmt.dateSeconds($0) } ?? "date non fournie").font(.caption2).foregroundStyle(.secondary).monospacedDigit()153                    }154                }.width(min: 130, ideal: 150)155                TableColumn("Signalements") { r in RsRowFlags(row: r) }.width(min: 150, ideal: 210)156            }157            .contextMenu(forSelectionType: HubRow.ID.self) { ids in158                if let id = ids.first, let r = data.rows.first(where: { $0.id == id }) { Button("Ouvrir la page de \(r.underlying ?? r.base)") { opened = r.underlying ?? r.base } }159            } primaryAction: { ids in160                if let id = ids.first, let r = data.rows.first(where: { $0.id == id }) { opened = r.underlying ?? r.base }161            }162            .overlay {163                if data.loading && data.rows.isEmpty { ProgressView() }164                else if data.rows.isEmpty { EmptyState(symbol: "chart.bar.xaxis", title: data.loadedAt == nil ? "Marchés non lus" : "Aucun marché ne correspond", detail: data.error) }165            }166            HStack(spacing: 12) {167                Text("\(data.rows.count) sur \(data.total) marchés").font(.callout).foregroundStyle(.secondary)168                if let c = data.counts { Text("\(c.spot) comptant · \(c.perp) perpétuels · \(c.tradable) négociables · \(c.stale) périmés").font(.callout).foregroundStyle(c.stale > 0 ? Theme.warning : .secondary) }169                if data.rows.count < data.total { Button(data.loadingMore ? "Chargement…" : "Charger la suite") { Task { await data.loadMore() } }.disabled(data.loadingMore) }170                Spacer()171                if let id = selection, let r = data.rows.first(where: { $0.id == id }) { Button("Ouvrir \(r.underlying ?? r.base)") { opened = r.underlying ?? r.base } }172                OpsAsOf(date: data.serverDate, prefix: "Réponse du serveur")173            }.padding(.horizontal, 24).padding(.vertical, 8)174            Text("Prix et volumes tels que servis par chaque source, avec leur date. La capitalisation boursière n’est pas publiée par le serveur et n’est donc pas affichée. Double-cliquez une ligne pour ouvrir la page du sous-jacent.")175                .font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 24).padding(.bottom, 8)176        }177    }178}179180private struct RsMarketsFilters: View {181    @Bindable var data: RsMarketsModel182    var body: some View {183        HStack(spacing: 10) {184            TextField("Rechercher un actif ou un marché", text: $data.search).textFieldStyle(.roundedBorder).frame(maxWidth: 260)185            Picker("Nature", selection: $data.kind) { Text("Comptant et perpétuels").tag(""); Text("Comptant").tag("spot"); Text("Perpétuels").tag("perp") }.frame(width: 190)186            Picker("Plateforme", selection: $data.venue) { Text("Toutes plateformes").tag(""); ForEach(data.venues) { Text($0.name).tag($0.id) } }.frame(width: 180)187            Picker("Catégorie", selection: $data.category) {188                Text("Toutes catégories").tag("")189                ForEach(data.categories, id: \.self) { Text(RsMarketsText.category($0)).tag($0) }190                if !data.category.isEmpty, !data.categories.contains(data.category) { Text(RsMarketsText.category(data.category)).tag(data.category) }191            }.frame(width: 170)192            Picker("Tri", selection: $data.sort) { ForEach(HubQuery.Sort.allCases, id: \.self) { Text(RsMarketsText.sort($0)).tag($0) } }.frame(width: 170)193            Button { data.descending.toggle() } label: { Image(systemName: data.descending ? "arrow.down" : "arrow.up") }.help(data.descending ? "Décroissant" : "Croissant")194            Toggle("Négociables", isOn: $data.tradableOnly).toggleStyle(.checkbox).help("Seulement les marchés que le portefeuille peut négocier selon le serveur.")195            Spacer()196            if data.loading { ProgressView().controlSize(.small) }197            Button { Task { await data.reload() } } label: { Image(systemName: "arrow.clockwise") }.disabled(data.loading)198        }.labelsHidden().padding(.horizontal, 24).padding(.vertical, 10)199    }200}201202/// The flags the server sets on a row: shown as text next to the figure, never only as a colour.203struct RsRowFlags: View {204    let row: HubRow205    var body: some View {206        HStack(spacing: 5) {207            if row.stale { ProvenanceTag(p: .stale, text: "Périmé\(row.ageMs.map { " · \(RsFmt.age(ms: $0))" } ?? "")") }208            if row.priceOutlier == true { RsFlag(text: "Prix divergent", color: Theme.negative, symbol: "exclamationmark.triangle") }209            if row.paper == true { RsFlag(text: "Papier", color: .blue, symbol: "testtube.2") }210            if !row.tradable { RsFlag(text: "Non négociable", color: .secondary, symbol: "lock").help(row.tradableReason ?? "Le serveur ne précise pas la raison.") }211            if let r = row.restriction { RsFlag(text: "Restriction", color: Theme.warning, symbol: "hand.raised").help(r) }212            if row.status != "active" && !row.status.isEmpty { RsFlag(text: row.status, color: .secondary, symbol: "pause.circle") }213        }214    }215}216217struct RsFlag: View {218    let text: String; let color: Color; let symbol: String219    var body: some View {220        Label(text, systemImage: symbol).font(.caption).foregroundStyle(color).padding(.horizontal, 6).padding(.vertical, 2).background(color.opacity(0.12), in: Capsule())221    }222}223224enum RsMarketsText {225    static func priceKind(_ k: String?) -> String {226        switch k { case "mark": "prix de référence (mark)"; case "close_1h": "clôture de la dernière barre 1 h"; case nil: "nature non précisée"; case let s?: s }227    }228    static func category(_ c: String) -> String {229        switch c { case "crypto": "Crypto"; case "equity": "Actions"; case "pre_ipo": "Pré-introduction"; case "commodity": "Matières premières"; case "fx": "Devises"; default: c }230    }231    static func sort(_ s: HubQuery.Sort) -> String {232        switch s { case .volume: "Volume 24 h"; case .openInterest: "Intérêt ouvert"; case .funding: "Financement"; case .change: "Variation 24 h"; case .symbol: "Symbole" }233    }234}235
Files main
Menu

Theme