Repository Public
1// SP Wallet iOS2// File: Features/Futures/FuturesHomeView.swift3// Description: Root of the perpetual futures terminal. A top-level PAPIER / RÉEL switch whose band stays on every screen; on4// iPhone: markets, account and positions as tabs, a market page pushed from the list, the order ticket in a sheet5// reached from a bottom bar (one hand); on iPad: three zones (markets | chart and book | ticket and positions).6// Keyboard shortcuts navigate only — none submits an order. Offline: dated snapshots, all trading disabled.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213struct FuturesHomeView: View {14 @Environment(AppModel.self) private var model15 @State private var fm: FuturesModel?1617 var body: some View {18 Group {19 if let fm { FuturesTerminal(fm: fm) } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }20 }21 .spPage()22 .navigationTitle(AppSection.futures.title)23 .onAppear { if fm == nil { fm = FuturesModel(app: model) } }24 }25}2627enum FuturesTab: String, CaseIterable, Identifiable {28 case markets, account, positions29 var id: String { rawValue }30 var title: String {31 switch self {32 case .markets: String(localized: "Marchés")33 case .account: String(localized: "Compte")34 case .positions: String(localized: "Positions")35 }36 }37}3839private struct MarketRoute: Hashable { let instrument: String }4041private struct FuturesTerminal: View {42 @Environment(AppModel.self) private var model43 @Environment(\.horizontalSizeClass) private var sizeClass44 @Environment(\.scenePhase) private var scenePhase45 @Bindable var fm: FuturesModel46 @State private var tab: FuturesTab = .markets47 @State private var pushed: MarketRoute?48 @State private var rightPane: FuturesTab = .markets // regular width: .markets = order ticket49 /** Width actually available to the section (the iPad sidebar, Split View and Stage Manager all reduce it). */50 @State private var width: CGFloat = 051 /** Three zones need room for 300 + chart + 380 pt; below that the single-column terminal is used, even on iPad. */52 private var wide: Bool { sizeClass == .regular && width >= 1040 }5354 var body: some View {55 Group {56 if wide { regular } else { compact.frame(maxWidth: 760).frame(maxWidth: .infinity) }57 }58 .frame(maxWidth: .infinity)59 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }60 .task { await fm.loadMarkets(); await fm.loadAccounts() }61 .task(id: fm.mode) { await fm.loadAccounts() }62 .onChange(of: scenePhase) { _, phase in if phase == .active { fm.resume() } else { fm.suspend() } }63 .onChange(of: model.canOperate) { _, ok in if ok { fm.resume(); Task { await fm.refreshAll() } } else { fm.suspend() } }64 // regular width: leaving the section closes the open market, which releases its stream subscriptions (rows release their own)65 .onDisappear { if wide { fm.closeMarket() } }66 .background { shortcuts }67 .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer(); KeyboardDoneButton() } }68 }6970 // MARK: the mode switch, on every screen7172 private var modeSwitch: some View {73 VStack(alignment: .leading, spacing: 8) {74 Picker(String(localized: "Mode de trading"), selection: $fm.mode) {75 Label(TradingMode.paper.badge, systemImage: "doc.plaintext.fill").tag(TradingMode.paper)76 Label(TradingMode.live.badge, systemImage: "bolt.shield.fill").tag(TradingMode.live)77 }78 .pickerStyle(.segmented).accessibilityIdentifier("futures.mode")79 ModeBand(mode: fm.mode, network: fm.mode == .live ? fm.liveAccount?.network : nil)80 }81 }8283 // MARK: iPhone8485 private var compact: some View {86 ScrollView {87 VStack(alignment: .leading, spacing: Theme.Space.section) {88 FreshnessBanner()89 modeSwitch90 Picker(String(localized: "Écran"), selection: $tab) { ForEach(FuturesTab.allCases) { Text($0.title).tag($0) } }91 .pickerStyle(.segmented).accessibilityIdentifier("futures.tab")92 switch tab {93 case .markets: FuturesMarketsView(fm: fm) { id in pushed = MarketRoute(instrument: id) }94 case .account: accountPane95 case .positions: FuturesBlotter(fm: fm) { id in pushed = MarketRoute(instrument: id) }96 }97 }98 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)99 }100 .refreshable { await fm.refreshAll() }101 .navigationDestination(item: $pushed) { r in CompactMarketPage(fm: fm, instrumentID: r.instrument) { tab = .account; pushed = nil }.wallet(model) }102 }103104 @ViewBuilder private var accountPane: some View {105 switch fm.mode {106 case .paper: FuturesPaperAccounts(fm: fm)107 case .live: FuturesLiveAccounts(fm: fm)108 }109 }110111 // MARK: iPad — three zones112113 private var regular: some View {114 VStack(alignment: .leading, spacing: 10) {115 FreshnessBanner()116 modeSwitch117 HStack(alignment: .top, spacing: 14) {118 ScrollView { FuturesMarketsView(fm: fm, column: true) { id in Task { await fm.open(id) } }.padding(.bottom, 20) }119 .frame(width: 300)120 ScrollView {121 Group {122 if let id = fm.selected { FuturesMarketView(fm: fm, instrumentID: id) }123 else { EmptyState(icon: "chart.line.uptrend.xyaxis", title: String(localized: "Choisis un contrat"), message: String(localized: "Le graphique, le carnet et les transactions s’affichent ici.")) .spCard() }124 }125 .padding(.bottom, 20)126 }127 .frame(maxWidth: .infinity)128 ScrollView {129 VStack(alignment: .leading, spacing: Theme.Space.section) {130 Picker(String(localized: "Panneau"), selection: $rightPane) {131 Text(String(localized: "Ordre")).tag(FuturesTab.markets); Text(FuturesTab.positions.title).tag(FuturesTab.positions); Text(FuturesTab.account.title).tag(FuturesTab.account)132 }133 .pickerStyle(.segmented).accessibilityIdentifier("futures.tab")134 switch rightPane {135 case .markets:136 if let i = fm.selectedInstrument { FuturesOrderTicket(fm: fm, instrument: i) { rightPane = .account } }137 else { EmptyState(icon: "square.and.pencil", title: String(localized: "Aucun contrat choisi")).spCard() }138 case .positions: FuturesBlotter(fm: fm) { id in Task { await fm.open(id) } }139 case .account: accountPane140 }141 }142 .padding(.bottom, 20)143 }144 .frame(width: 380)145 }146 }147 .padding(.horizontal, Theme.Space.gutter).padding(.top, 8)148 .task { if fm.selected == nil, let first = fm.instruments.value?.first(where: { fm.favourites.contains($0.id) }) ?? defaultMarket { await fm.open(first.id) } }149 .onChange(of: fm.instruments.value?.count) { _, _ in if fm.selected == nil, let m = defaultMarket { Task { await fm.open(m.id) } } }150 }151152 /** What the three-zone layout shows first: the most traded contract by served 24 h volume (a display choice, not an order parameter). */153 private var defaultMarket: DerivInstrument? {154 fm.instruments.value?.max { (FuturesMath.double(fm.ticker($0.id)?.volume24h) ?? -1) < (FuturesMath.double(fm.ticker($1.id)?.volume24h) ?? -1) }155 }156157 // MARK: keyboard — navigation only, never an order158159 private var shortcuts: some View {160 Group {161 Button("") { step(-1) }.keyboardShortcut(.upArrow, modifiers: [.command, .option])162 Button("") { step(1) }.keyboardShortcut(.downArrow, modifiers: [.command, .option])163 Button("") { tab = .markets; rightPane = .markets }.keyboardShortcut("m", modifiers: [.command, .option])164 Button("") { tab = .positions; rightPane = .positions }.keyboardShortcut("p", modifiers: [.command, .option])165 Button("") { tab = .account; rightPane = .account }.keyboardShortcut("c", modifiers: [.command, .option])166 }167 .opacity(0).accessibilityHidden(true)168 }169170 /** Previous / next contract of the served list. */171 private func step(_ d: Int) {172 guard let all = fm.instruments.value, !all.isEmpty else { return }173 let i = all.firstIndex { $0.id == fm.selected } ?? (d > 0 ? -1 : all.count)174 let next = all[min(max(i + d, 0), all.count - 1)].id175 if wide { Task { await fm.open(next) } } else { pushed = MarketRoute(instrument: next) }176 }177}178179/** iPhone: the market page, with the order ticket one thumb away at the bottom. */180private struct CompactMarketPage: View {181 @Environment(AppModel.self) private var model182 let fm: FuturesModel183 let instrumentID: String184 let openAccounts: () -> Void185 @State private var ordering = false186187 var body: some View {188 ScrollView {189 VStack(alignment: .leading, spacing: Theme.Space.section) {190 FreshnessBanner()191 ModeBand(mode: fm.mode, network: fm.mode == .live ? fm.liveAccount?.network : nil)192 FuturesMarketView(fm: fm, instrumentID: instrumentID)193 }194 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 20)195 }196 .spPage()197 .refreshable { await fm.open(instrumentID) }198 .navigationTitle(OfferedVenues.symbol(of: instrumentID)).navigationBarTitleDisplayMode(.inline)199 .toolbar {200 ToolbarItem(placement: .topBarTrailing) {201 Button { fm.toggleFavourite(instrumentID) } label: { Image(systemName: fm.favourites.contains(instrumentID) ? "star.fill" : "star") }202 .accessibilityLabel(String(localized: "Favori")).accessibilityIdentifier("futures.market.star")203 }204 }205 .safeAreaInset(edge: .bottom) {206 Button { ordering = true } label: {207 Label(fm.mode == .paper ? String(localized: "Ordre PAPIER…") : String(localized: "Ordre RÉEL…"), systemImage: "square.and.pencil")208 }209 .buttonStyle(.spPrimary).disabled(fm.instrument(instrumentID) == nil && fm.market == nil)210 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 8).background(.bar)211 .accessibilityIdentifier("futures.market.order")212 }213 .sheet(isPresented: $ordering) {214 NavigationStack {215 ScrollView {216 VStack(alignment: .leading, spacing: Theme.Space.section) {217 ModeBand(mode: fm.mode, network: fm.mode == .live ? fm.liveAccount?.network : nil)218 if let i = fm.selectedInstrument ?? fm.instrument(instrumentID) { FuturesOrderTicket(fm: fm, instrument: i) { ordering = false; openAccounts() } }219 }220 .futuresSheetPage()221 }222 .spPage()223 .scrollDismissesKeyboard(.interactively)224 .navigationTitle(String(localized: "Ordre")).navigationBarTitleDisplayMode(.inline)225 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Fermer")) { ordering = false }.accessibilityIdentifier("futures.order.close") } }226 }227 .wallet(model)228 }229 .onDisappear { if fm.selected == instrumentID { fm.closeMarket() } }230 }231}232