Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesMarketView.swift10// Description : One perpetual contract: header (mark, 24 h change,11// freshness), candlestick chart with interval picker and12// crosshair, the order book as the Core rebuilt and verified13// it (otherwise « carnet indisponible »), recent trades, the14// funding rates the venue applied, and the instrument's15// specifications as served. Read-only market data: the order16// ticket is `FuturesOrderTicket`.17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-ios19// 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 Charts96import SPWalletCore9798struct FuturesMarketView: View {99 @Environment(AppModel.self) private var model100 let fm: FuturesModel101 let instrumentID: String102 @State private var crosshair: CandleBar?103104 private var instrument: DerivInstrument? { fm.instrument(instrumentID) ?? (fm.market?.instrument.id == instrumentID ? fm.market?.instrument : nil) }105106 var body: some View {107 VStack(alignment: .leading, spacing: Theme.Space.section) {108 header109 if let e = fm.marketError, fm.market == nil { FuturesError(error: e) { Task { await fm.open(instrumentID) } } }110 chartCard111 bookCard112 tradesCard113 fundingCard114 specsCard115 }116 .task(id: instrumentID) { await fm.open(instrumentID) }117 }118119 // MARK: header120121 private var header: some View {122 let mark = fm.mark(instrumentID), change = fm.change24h(instrumentID)123 return VStack(alignment: .leading, spacing: 10) {124 HStack(alignment: .firstTextBaseline, spacing: 10) {125 VStack(alignment: .leading, spacing: 2) {126 Text(OfferedVenues.symbol(of: instrumentID)).font(.spTitle).foregroundStyle(Theme.ink)127 Text(String(localized: "Contrat perpétuel · \(OfferedVenues.name(OfferedVenues.venue(of: instrumentID)))")).font(.spFootnote).foregroundStyle(Theme.mute)128 }129 Spacer()130 VStack(alignment: .trailing, spacing: 2) {131 Text(mark.map { Fx.exact($0) } ?? String(localized: "indisponible")).font(.system(size: 26, weight: .semibold)).monospacedDigit()132 .foregroundStyle(mark == nil ? Theme.warn : Theme.ink).lineLimit(1).minimumScaleFactor(0.6)133 .accessibilityIdentifier("futures.market.mark")134 if let t = Fx.percent(fraction: change, signed: false) {135 Text((Fx.sign(change) > 0 ? "▲ " : Fx.sign(change) < 0 ? "▼ " : "") + t + " · 24 h").font(.spCallout.weight(.semibold)).monospacedDigit().lineLimit(1)136 .foregroundStyle(Fx.sign(change) >= 0 ? Theme.emerald : Theme.danger)137 }138 TimelineView(.periodic(from: .now, by: 2)) { ctx in FreshnessMark(freshness: fm.freshness(instrumentID, now: ctx.date)).lineLimit(1) }139 }140 }141 HStack(alignment: .top, spacing: 10) {142 StatTile(label: instrument.map { String(localized: "Fin. / \(Fx.interval(seconds: $0.fundingIntervalSec))") } ?? String(localized: "Financement"),143 value: Fx.percent(fraction: fm.fundingRate(instrumentID), dp: 5) ?? "—")144 StatTile(label: String(localized: "Intérêt ouvert"), value: Fx.openInterestUSD(fm.openInterest(instrumentID), mark: mark))145 StatTile(label: String(localized: "Volume 24 h"), value: Fx.compactUSD(FuturesMath.double(fm.volume24h(instrumentID))))146 StatTile(label: String(localized: "Levier max."), value: Fx.leverage(instrument?.maxLeverage))147 }148 Text(String(localized: "Prix de marque de la plateforme. Ce n’est pas un prix d’exécution.")).font(.system(size: 12)).foregroundStyle(Theme.mute)149 }150 .spCard()151 }152153 // MARK: chart154155 private var chartCard: some View {156 VStack(alignment: .leading, spacing: 10) {157 SectionHeader(title: String(localized: "Chandeliers"))158 if let c = crosshair ?? fm.candles.last {159 Text("O \(Fx.exact(c.open)) H \(Fx.exact(c.high)) B \(Fx.exact(c.low)) C \(Fx.exact(c.close))")160 .font(.system(size: 12, design: .monospaced)).foregroundStyle(crosshair == nil ? Theme.mute : Theme.ink).lineLimit(1).minimumScaleFactor(0.6)161 .accessibilityIdentifier("futures.market.ohlc")162 Text(c.at.formatted(date: .abbreviated, time: .shortened) + (crosshair == nil ? " · " + String(localized: "dernière bougie") : "")).font(.system(size: 11.5)).foregroundStyle(Theme.mute)163 }164 if fm.candles.count > 1 { CandleChart(bars: fm.candles, crosshair: $crosshair).frame(height: 240).accessibilityIdentifier("futures.market.chart") }165 else if let e = fm.candlesError { FuturesError(error: e) { Task { await fm.loadCandles() } } }166 else if model.offlineBrowsing { EmptyState(icon: "wifi.slash", title: String(localized: "Graphique indisponible hors ligne")) }167 else { ProgressView().frame(maxWidth: .infinity, minHeight: 240) }168 Picker(String(localized: "Intervalle"), selection: Binding(get: { fm.interval }, set: { i in crosshair = nil; Task { await fm.setInterval(i) } })) {169 ForEach(DerivCandleInterval.allCases, id: \.self) { Text($0.rawValue).tag($0) }170 }171 .pickerStyle(.segmented).accessibilityIdentifier("futures.market.interval")172 Text(String(localized: "Bougies servies par \(fm.candleSource ?? OfferedVenues.name(OfferedVenues.venue(of: instrumentID))) ; la dernière se met à jour par le flux. Appuie sur le graphique et glisse pour lire une bougie."))173 .font(.system(size: 12)).foregroundStyle(Theme.mute)174 }175 .spCard()176 }177178 // MARK: book179180 private var bookCard: some View {181 VStack(alignment: .leading, spacing: 8) {182 SectionHeader(title: String(localized: "Carnet d’ordres"))183 if let b = fm.book, b.id == instrumentID {184 BookLadder(book: b)185 Text(String(localized: "\(b.depth) niveaux par côté, source \(b.source). Carnet reconstruit et vérifié (séquence et somme de contrôle) par l’app."))186 .font(.system(size: 12)).foregroundStyle(Theme.mute)187 } else {188 Notice(tone: .neutral, title: String(localized: "Carnet indisponible"),189 message: !model.canOperate ? String(localized: "Le carnet exige le flux en direct.") : (fm.bookNote ?? String(localized: "En attente d’un instantané cohérent du serveur.")), icon: "tray")190 .accessibilityIdentifier("futures.market.bookUnavailable")191 }192 }193 .spCard()194 }195196 // MARK: trades197198 private var tradesCard: some View {199 VStack(alignment: .leading, spacing: 6) {200 SectionHeader(title: String(localized: "Transactions récentes"))201 if fm.trades.isEmpty {202 Text(fm.market?.errors?["trades"].map { String(localized: "Indisponible : \($0)") } ?? String(localized: "Aucune transaction reçue.")).font(.spCallout).foregroundStyle(Theme.mute)203 } else {204 HStack { Text(String(localized: "Prix")); Spacer(); Text(String(localized: "Taille")); Spacer(); Text(String(localized: "Heure")) }.font(.system(size: 11.5)).foregroundStyle(Theme.mute)205 ForEach(fm.trades.prefix(14)) { t in206 HStack {207 Label(Fx.exact(t.price), systemImage: t.side == "buy" ? "arrow.up.right" : "arrow.down.right").foregroundStyle(t.side == "buy" ? Theme.emerald : Theme.danger)208 Spacer(); Text(Fx.exact(t.size)).foregroundStyle(Theme.ink)209 Spacer(); Text(t.at.formatted(date: .omitted, time: .standard)).foregroundStyle(Theme.mute)210 }211 .font(.system(size: 12.5, design: .monospaced)).lineLimit(1)212 .accessibilityElement(children: .combine)213 .accessibilityLabel((t.side == "buy" ? String(localized: "Achat") : String(localized: "Vente")) + " \(t.size) @ \(t.price)")214 }215 }216 }217 .spCard()218 }219220 // MARK: funding221222 private var fundingCard: some View {223 VStack(alignment: .leading, spacing: 8) {224 SectionHeader(title: String(localized: "Historique du financement"))225 if let f = fm.funding, !f.history.isEmpty {226 let rows = f.history.sorted { $0.ts < $1.ts }227 Chart(rows, id: \.ts) { r in228 let v = (Double(r.rate) ?? 0) * 100229 BarMark(x: .value("t", r.ts), y: .value("%", v)).foregroundStyle(v >= 0 ? Theme.emerald : Theme.danger)230 }231 .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { _ in AxisValueLabel().font(.system(size: 11)) } }232 .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 3)) { _ in AxisGridLine().foregroundStyle(Theme.hairline); AxisValueLabel().font(.system(size: 11)) } }233 .frame(height: 110)234 .accessibilityLabel(String(localized: "Taux de financement appliqués, en pourcentage par période"))235 ForEach(rows.suffix(4).reversed(), id: \.ts) { r in236 HStack { Text(r.ts.formatted(date: .abbreviated, time: .shortened)).foregroundStyle(Theme.mute); Spacer(); Text(Fx.percent(fraction: r.rate, dp: 5) ?? r.rate).monospacedDigit() }.font(.system(size: 12.5))237 }238 Text(String(localized: "Taux appliqués par la plateforme toutes les \(Fx.interval(seconds: f.intervalSec)), en % du notionnel (positif : les longs paient). Source \(f.source ?? "—"). Ce ne sont pas les paiements d’un compte."))239 .font(.system(size: 12)).foregroundStyle(Theme.mute)240 } else if let e = fm.fundingError { FuturesError(error: e) }241 else if fm.funding != nil { Text(String(localized: "Aucun taux servi sur la période.")).font(.spCallout).foregroundStyle(Theme.mute) }242 else if model.offlineBrowsing { Text(String(localized: "Indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }243 else { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }244 }245 .spCard()246 }247248 // MARK: specifications249250 @ViewBuilder private var specsCard: some View {251 if let i = instrument {252 VStack(alignment: .leading, spacing: 0) {253 SectionHeader(title: String(localized: "Spécifications")).padding(.bottom, 4)254 FieldRow(label: String(localized: "Identifiant"), value: i.id, mono: true); Divider()255 FieldRow(label: String(localized: "Pas de cotation (tick)"), value: Fx.exact(i.tickSize)); Divider()256 FieldRow(label: String(localized: "Pas de lot"), value: Fx.exact(i.lotSize) + " " + i.base); Divider()257 if let m = i.minOrderSize { FieldRow(label: String(localized: "Taille minimale"), value: Fx.exact(m) + " " + i.base); Divider() }258 if let m = i.minNotional { FieldRow(label: String(localized: "Notionnel minimal"), value: Fx.usd(m, exact: true)); Divider() }259 FieldRow(label: String(localized: "Levier maximal de la plateforme"), value: Fx.leverage(i.maxLeverage)); Divider()260 FieldRow(label: String(localized: "Modes de marge"), value: i.marginModes.map(FuturesText.marginMode).joined(separator: ", ")); Divider()261 FieldRow(label: String(localized: "Collatéral · règlement"), value: "\(i.collateral) · \(i.settlement)"); Divider()262 FieldRow(label: String(localized: "Période de financement"), value: Fx.interval(seconds: i.fundingIntervalSec)); Divider()263 FieldRow(label: String(localized: "Méthode du prix de marque"), value: i.markPriceMethod); Divider()264 FieldRow(label: String(localized: "État"), value: i.status, tone: i.status == "active" ? nil : .warn); Divider()265 FieldRow(label: String(localized: "Paliers de marge"), value: String(localized: "non servis par le serveur"), tone: .neutral)266 }267 .spCard()268 }269 }270}271272/** Candlesticks: a wick (low–high) and a body (open–close) per bar; rising and falling bars also differ by fill, not only by hue. */273struct CandleChart: View {274 let bars: [CandleBar]275 @Binding var crosshair: CandleBar?276 @State private var picked: Date?277278 var body: some View {279 let lo = bars.map(\.l).min() ?? 0, hi = bars.map(\.h).max() ?? 1, pad = (hi - lo) * 0.06280 let width = MarkDimension.ratio(0.62)281 Chart {282 ForEach(bars) { b in283 RuleMark(x: .value("t", b.at), yStart: .value("bas", b.l), yEnd: .value("haut", b.h)).lineStyle(StrokeStyle(lineWidth: 1)).foregroundStyle(b.up ? Theme.emerald : Theme.danger)284 RectangleMark(x: .value("t", b.at), yStart: .value("ouverture", b.o), yEnd: .value("clôture", b.c == b.o ? b.o + (hi - lo) * 0.001 : b.c), width: width)285 .foregroundStyle(b.up ? Theme.emerald.opacity(0.55) : Theme.danger)286 }287 if let s = crosshair {288 RuleMark(x: .value("t", s.at)).lineStyle(StrokeStyle(lineWidth: 0.8, dash: [3, 3])).foregroundStyle(Theme.mute)289 RuleMark(y: .value("clôture", s.c)).lineStyle(StrokeStyle(lineWidth: 0.8, dash: [3, 3])).foregroundStyle(Theme.mute)290 .annotation(position: .top, alignment: .trailing) { Text(Fx.exact(s.close)).font(.system(size: 10.5, design: .monospaced)).padding(.horizontal, 4).background(Theme.elev, in: Capsule()) }291 }292 }293 .chartYScale(domain: (lo - pad)...(hi + pad + .leastNonzeroMagnitude))294 .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { _ in AxisValueLabel().font(.system(size: 11)) } }295 .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 5)) { _ in AxisGridLine().foregroundStyle(Theme.hairline); AxisValueLabel().font(.system(size: 11)) } }296 // the system's own selection gesture: it does not take the page's vertical scrolling297 .chartXSelection(value: $picked)298 .onChange(of: picked) { _, d in crosshair = d.flatMap { d in bars.min { abs($0.at.timeIntervalSince(d)) < abs($1.at.timeIntervalSince(d)) } } }299 .accessibilityLabel(String(localized: "Graphique en chandeliers, \(bars.count) bougies"))300 }301}302303/** Asks above (best at the bottom), bids below (best at the top), each level with its size and a bar of the cumulated size. */304private struct BookLadder: View {305 let book: LiveBook306 private let shown = 8307308 var body: some View {309 let asks = Array(book.asks.prefix(shown)), bids = Array(book.bids.prefix(shown))310 let ca = cumulated(asks), cb = cumulated(bids), top = max(ca.last ?? 0, cb.last ?? 0, .leastNonzeroMagnitude)311 VStack(spacing: 1) {312 HStack { Text(String(localized: "Prix")); Spacer(); Text(String(localized: "Taille")) }.font(.system(size: 11.5)).foregroundStyle(Theme.mute).padding(.bottom, 2)313 ForEach(Array(asks.enumerated()).reversed(), id: \.offset) { i, l in level(l, share: ca[i] / top, ask: true) }314 HStack {315 Text(String(localized: "meilleure vente \(asks.first.map { Fx.exact($0.price) } ?? "—")")); Spacer(); Text(String(localized: "meilleur achat \(bids.first.map { Fx.exact($0.price) } ?? "—")"))316 }317 .font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.mute).padding(.vertical, 5).lineLimit(1).minimumScaleFactor(0.7)318 ForEach(Array(bids.enumerated()), id: \.offset) { i, l in level(l, share: cb[i] / top, ask: false) }319 }320 .accessibilityIdentifier("futures.market.book")321 }322323 private func cumulated(_ levels: [StreamLevel]) -> [Double] {324 var acc = 0.0325 return levels.map { acc += Double($0.size) ?? 0; return acc }326 }327328 private func level(_ l: StreamLevel, share: Double, ask: Bool) -> some View {329 HStack {330 Text(Fx.exact(l.price)).foregroundStyle(ask ? Theme.danger : Theme.emerald)331 Spacer()332 Text(Fx.exact(l.size)).foregroundStyle(Theme.ink)333 }334 .font(.system(size: 12.5, design: .monospaced)).lineLimit(1)335 .padding(.horizontal, 6).frame(height: 22)336 .background(alignment: .trailing) {337 GeometryReader { g in338 Rectangle().fill((ask ? Theme.danger : Theme.emerald).opacity(0.13)).frame(width: g.size.width * min(max(share, 0), 1)).frame(maxWidth: .infinity, alignment: .trailing)339 }340 }341 .accessibilityElement(children: .combine)342 .accessibilityLabel((ask ? String(localized: "Vente") : String(localized: "Achat")) + " \(l.size) @ \(l.price)")343 }344}345