Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesLogic.swift10// Description : The pure logic of the perp terminal, kept apart from the11// screens so that it is unit-tested: reading a typed number12// without guessing, exact decimal arithmetic on the Core's13// `VenueDecimal` (size from a USD amount, notional, steps),14// the order form and what blocks it (no default leverage,15// explicit confirmation from 5×), the separation of paper16// and live requests, the provenance of a liquidation price,17// and the wording of order states (an order sent is not an18// order filled). Nothing here invents a figure: what is not19// served is absent.20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-ios22// Created : 2026-11-1823// Last Modified : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author : Simon-Pierre Boucher30// Position : Professor of Finance31// Institution : Université du Québec en Outaouais (UQO)32// Department : Département des sciences administratives33// Organization : SP Boucher34//35// Website : https://spboucher.ai36// Git : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General : info@spboucher.ai43// Professional : contact@spboucher.ai44// Direct : simon@spboucher.ai45// Research : research@spboucher.ai46// Development : dev@spboucher.ai47// Support : support@spboucher.ai48// Security/Admin : admin@spboucher.ai49// Notifications : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification : Public76// Distribution : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License : None specified (no license file in this repository)90// Maintainer : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import Foundation98import SPWalletCore99100// MARK: typed numbers101102/** A number typed by the owner → an exact decimal, or the reason it is refused. Port of the web rule (apps/web/src/amount.ts). */103enum DecimalInput {104 enum Failure: Error, Equatable { case empty, invalid, ambiguous }105106 /** - Parameter decimalSeparator: the screen's own (« , » in French, "." in English). Both marks are accepted in both. */107 static func parse(_ text: String, decimalSeparator: String = Locale.current.decimalSeparator ?? ".") -> Result<VenueDecimal, Failure> {108 let soft: Set<Character> = [" ", "\u{00a0}", "\u{202f}", "\u{2009}", "'", "’"]109 let s = text.trimmingCharacters(in: .whitespacesAndNewlines)110 guard !s.isEmpty else { return .failure(.empty) }111 guard s.allSatisfy({ $0.isASCII && $0.isNumber || $0 == "," || $0 == "." || soft.contains($0) }), s.contains(where: \.isNumber) else { return .failure(.invalid) }112 let commas = s.filter { $0 == "," }.count, dots = s.filter { $0 == "." }.count113 var intPart = s, frac = ""114 var hard: Character?115 func split(at mark: Character) { let i = s.lastIndex(of: mark)!; intPart = String(s[..<i]); frac = String(s[s.index(after: i)...]) }116 if commas > 0, dots > 0 {117 // the one that comes LAST is the decimal separator and occurs once; the other groups thousands118 let dec: Character = s.lastIndex(of: ",")! > s.lastIndex(of: ".")! ? "," : "."119 guard (dec == "," ? commas : dots) == 1 else { return .failure(.invalid) }120 split(at: dec); hard = dec == "," ? "." : ","121 } else if commas + dots > 1 {122 hard = commas > 0 ? "," : "." // several times: thousands separators only123 } else if commas + dots == 1 {124 let mark: Character = commas == 1 ? "," : "."125 if String(mark) != decimalSeparator, !s.contains(where: soft.contains), s.range(of: "^[1-9][0-9]{0,2}[.,][0-9]{3}$", options: .regularExpression) != nil {126 return .failure(.ambiguous) // « 1.000 » in French: one thousand or one? never guessed127 }128 split(at: mark)129 }130 guard frac.allSatisfy(\.isNumber), let digits = ungroup(intPart, hard: hard, soft: soft) else { return .failure(.invalid) }131 var i = String(digits.drop(while: { $0 == "0" }))132 if i.isEmpty { i = "0" }133 guard let v = VenueDecimal(frac.isEmpty ? i : i + "." + frac), !v.isNegative else { return .failure(.invalid) }134 return .success(v)135 }136137 /** Digits of an integer part written with thousands separators; nil when the groups are not 1–3 digits then threes. */138 private static func ungroup(_ int: String, hard: Character?, soft: Set<Character>) -> String? {139 let hasSoft = int.contains(where: soft.contains), hasHard = hard.map { int.contains($0) } ?? false140 if !hasSoft, !hasHard { return int.allSatisfy(\.isNumber) ? int : nil }141 if hasSoft, hasHard { return nil }142 let groups = int.split(omittingEmptySubsequences: false) { hasHard ? $0 == hard : soft.contains($0) }.map(String.init)143 guard let first = groups.first, (1...3).contains(first.count), first.allSatisfy(\.isNumber),144 groups.dropFirst().allSatisfy({ $0.count == 3 && $0.allSatisfy(\.isNumber) }) else { return nil }145 return groups.joined()146 }147148 /** A positive whole number (leverage, days, orders per day, basis points). No separator, no sign. */149 static func wholeNumber(_ text: String) -> Int? {150 let s = text.trimmingCharacters(in: .whitespaces)151 guard !s.isEmpty, s.count <= 9, s.allSatisfy({ $0.isASCII && $0.isNumber }), let n = Int(s), n > 0 else { return nil }152 return n153 }154}155156// MARK: exact arithmetic on the Core's decimals157158enum FuturesMath {159 /** Decimals of a step that is a power of ten at most 1 ("0.001" → 3, "1" → 0); nil for any other step (0.5, 10…). */160 static func decimals(ofStep step: String) -> Int? {161 guard let d = VenueDecimal(step), d.isPositive else { return nil }162 let t = d.description163 if t == "1" { return 0 }164 guard t.hasPrefix("0."), t.last == "1", t.dropFirst(2).dropLast().allSatisfy({ $0 == "0" }) else { return nil }165 return t.count - 2166 }167168 /** Is `v` a multiple of `step`? nil when this cannot be decided here (the server decides: `price_not_on_tick`, `size_not_on_lot`). */169 static func isOnStep(_ v: VenueDecimal, step: String) -> Bool? {170 guard let st = VenueDecimal(step), st.isPositive else { return nil }171 if let d = decimals(ofStep: step) { return v.scale <= d }172 let s = max(v.scale, st.scale)173 guard let a = v.units(decimals: s), let b = st.units(decimals: s), b.count <= 18, let divisor = UInt64(b), divisor > 0 else { return nil }174 var rem: UInt64 = 0175 for ch in a.utf8 { rem = (rem * 10 + UInt64(ch - 48)) % divisor } // divisor < 10^18: no overflow176 return rem == 0177 }178179 /**180 The greatest size with `lotDecimals` decimals whose cost at `price` does not exceed `usd` — found digit by digit with the181 Core's exact product and comparison only (no division, no floating point). Zero when even one lot costs more.182 */183 static func size(forUSD usd: VenueDecimal, price: VenueDecimal, lotDecimals: Int) -> VenueDecimal? {184 guard usd.isPositive, price.isPositive, lotDecimals >= 0, lotDecimals <= 18 else { return nil }185 // size ≤ usd / price ≤ usd × 10^scale(price): that many integer digits are enough186 let intDigits = usd.description.prefix { $0 != "." }.count + price.scale + 1187 guard intDigits + lotDecimals <= VenueDecimal.maxDigits - 2 else { return nil }188 var digits = [Int](repeating: 0, count: intDigits + lotDecimals)189 func value(_ d: [Int]) -> VenueDecimal? {190 var i = d.prefix(intDigits).map(String.init).joined()191 i = String(i.drop(while: { $0 == "0" })); if i.isEmpty { i = "0" }192 let f = d.suffix(lotDecimals).map(String.init).joined()193 return VenueDecimal(f.isEmpty ? i : i + "." + f)194 }195 for k in digits.indices {196 for candidate in stride(from: 9, through: 1, by: -1) {197 digits[k] = candidate198 guard let v = value(digits) else { return nil }199 if v.multiplied(by: price) <= usd { break }200 digits[k] = 0201 }202 }203 return value(digits)204 }205206 static func double(_ s: String?) -> Double? { s.flatMap(Double.init) }207}208209// MARK: display of the server's decimal strings210211enum Fx {212 static let minus = "−"213214 /** Every digit kept, grouped for reading; a negative value keeps its sign in the text. */215 static func exact(_ s: String?) -> String {216 guard let s, !s.isEmpty else { return "—" }217 return s.hasPrefix("-") ? minus + Money.exact(String(s.dropFirst())) : Money.exact(s)218 }219220 /** Cut (towards zero, never rounded up) to `dp` decimals — lists and tiles only, never an approval. */221 static func brief(_ s: String?, dp: Int = 2) -> String {222 guard let s, let d = VenueDecimal(s) else { return s.map { exact($0) } ?? "—" }223 return exact(d.truncated(toDecimals: dp).description)224 }225226 static func usd(_ s: String?, exact full: Bool = false, signed: Bool = false) -> String {227 guard let s, let d = VenueDecimal(s) else { return s ?? "—" }228 let body = full ? exact(d.description) : brief(d.description, dp: 2)229 return (signed && d.isPositive ? "+" : "") + body + " $"230 }231232 /** An ESTIMATE of the server in USD: at most six decimals, cut (never rounded up) and marked « … » when digits are dropped. Never for an approved amount. */233 static func estimate(_ s: String?) -> String {234 guard let s, VenueDecimal(s) != nil else { return s ?? "—" }235 return (s.hasPrefix("-") ? minus + Money.brief(String(s.dropFirst())) : Money.brief(s)) + " $"236 }237238 /** A fraction as a percentage (0.0123 → « 1,23 % »), cut to `dp` decimals. */239 static func percent(fraction s: String?, dp: Int = 2, signed: Bool = true) -> String? {240 guard let s, let d = VenueDecimal(s), let hundred = VenueDecimal("100") else { return nil }241 let p = d.multiplied(by: hundred).truncated(toDecimals: dp)242 return (signed && p.isPositive ? "+" : "") + exact(p.description) + " %"243 }244245 static func sign(_ s: String?) -> Int {246 guard let s, let d = VenueDecimal(s) else { return 0 }247 return d.isZero ? 0 : d.isNegative ? -1 : 1248 }249250 /** Read-only compact figure (volume, open interest): nothing is acted on with it. */251 static func compactUSD(_ v: Double?) -> String {252 guard let v else { return "—" }253 return v.formatted(.number.notation(.compactName).precision(.fractionLength(0...2))) + " $"254 }255256 /** Open interest is served in BASE units: its USD value is that size at the served mark (exact product, shown compact). */257 static func openInterestUSD(_ oi: String?, mark: String?) -> String {258 guard let oi, let mark, let a = VenueDecimal(oi), let b = VenueDecimal(mark) else { return "—" }259 return compactUSD(Double(a.multiplied(by: b).description))260 }261262 static func leverage(_ s: String?) -> String { s.map { exact($0) + "×" } ?? "—" }263264 static func interval(seconds: Int) -> String {265 seconds % 3600 == 0 ? String(localized: "\(seconds / 3600) h") : String(localized: "\(seconds / 60) min")266 }267}268269// MARK: paper and live never share a type270271enum TradingMode: String, CaseIterable, Identifiable, Sendable {272 case paper, live273 var id: String { rawValue }274 /** The word shown on every screen of the terminal. */275 var badge: String { self == .paper ? String(localized: "PAPIER") : String(localized: "RÉEL") }276 var explanation: String {277 self == .paper ? String(localized: "Simulation : aucun fonds réel, aucun ordre envoyé à une plateforme.")278 : String(localized: "Compte réel sur la plateforme : chaque ordre demande ta clé d’accès.")279 }280}281282/** The account an order form trades on. A paper id can never reach a live route, and the reverse (distinct Core types). */283enum FuturesAccountRef: Hashable, Sendable {284 case paper(PaperAccountID)285 case live(LiveAccountID, network: String)286287 var mode: TradingMode { if case .paper = self { .paper } else { .live } }288 /** PAPIER, or RÉEL with the network (MAINNET / TESTNET) — never one without the other. */289 var badge: String {290 switch self {291 case .paper: TradingMode.paper.badge292 case .live(_, let network): TradingMode.live.badge + " · " + Self.networkBadge(network)293 }294 }295 static func networkBadge(_ network: String) -> String { network == "testnet" ? "TESTNET" : network == "mainnet" ? "MAINNET" : network.uppercased() }296}297298// MARK: the order form299300/** A leverage setting as it was served (« réglage actuel »): the paper account's for an instrument, or the venue's. */301struct CurrentLeverage: Equatable, Sendable {302 let leverage: String303 /** Empty when the source states none. */304 let marginMode: String305}306307struct FuturesOrderForm: Equatable, Sendable {308 enum Kind: String, CaseIterable, Sendable {309 case market, limit, stop, takeProfit310 var types: (market: DerivOrderType, limit: DerivOrderType) {311 switch self {312 case .market: (.market, .market)313 case .limit: (.limit, .limit)314 case .stop: (.stopMarket, .stopLimit)315 case .takeProfit: (.takeProfitMarket, .takeProfitLimit)316 }317 }318 var isTrigger: Bool { self == .stop || self == .takeProfit }319 var label: String {320 switch self {321 case .market: String(localized: "Marché")322 case .limit: String(localized: "Limite")323 case .stop: String(localized: "Stop")324 case .takeProfit: String(localized: "Prise de profit")325 }326 }327 /** The kinds a venue supports, from the `orderTypes` it serves; with nothing served only market and limit are offered. */328 static func supported(by orderTypes: [String]?) -> [Kind] {329 guard let t = orderTypes else { return [.limit, .market] }330 return [Kind.limit, .market, .stop, .takeProfit].filter { k in331 switch k {332 case .market: t.contains("market")333 case .limit: t.contains("limit")334 case .stop: t.contains("stop_limit")335 case .takeProfit: t.contains("take_profit_limit")336 }337 }338 }339 }340 enum Unit: String, CaseIterable, Sendable { case contracts, usd }341342 /** Nothing is chosen at the start. `keepCurrent` is the owner explicitly keeping the setting that was displayed to him. */343 enum LeverageChoice: Equatable, Sendable {344 case none345 case keepCurrent(String)346 case set(Int)347 var multiple: VenueDecimal? {348 switch self {349 case .none: nil350 case .keepCurrent(let s): VenueDecimal(s)351 case .set(let n): VenueDecimal(String(n))352 }353 }354 var text: String? { multiple.map { $0.description + "×" } }355 }356357 /** From this multiple on, the owner confirms once more, in front of the liquidation information the server gave. */358 static let highLeverageThreshold = 5359360 var side: DerivOrderSide?361 var kind: Kind = .limit362 var unit: Unit = .contracts363 var sizeText = ""364 var priceText = ""365 var triggerText = ""366 /** Market orders: the bound, in basis points from the book, typed by the owner. */367 var slippageText = ""368 var reduceOnly = false369 var tif: DerivTimeInForce = .gtc370 var leverage: LeverageChoice = .none371372 enum Problem: Equatable, Sendable {373 case sideMissing, sizeMissing, sizeInvalid, sizeAmbiguous, sizeZero, sizeNotOnLot(lot: String), belowMinimumSize(min: String)374 case usdUnavailable, noReferencePrice375 case priceMissing, priceInvalid, priceAmbiguous, priceNotOnTick(tick: String)376 case triggerMissing, triggerInvalid, triggerNotOnTick(tick: String)377 case slippageMissing, slippageInvalid378 case leverageMissing, leverageAboveMaximum(max: Int)379 case instrumentNotTradable(status: String)380381 var isMissingField: Bool {382 switch self { case .sideMissing, .sizeMissing, .priceMissing, .triggerMissing, .slippageMissing, .leverageMissing: true; default: false }383 }384 var text: String {385 switch self {386 case .sideMissing: String(localized: "Choisis le sens : Long ou Short.")387 case .sizeMissing: String(localized: "Saisis la taille.")388 case .sizeInvalid: String(localized: "Taille invalide.")389 case .sizeAmbiguous: String(localized: "Taille ambiguë (mille ou un ?) : écris-la sans séparateur de milliers.")390 case .sizeZero: String(localized: "La taille est nulle une fois ramenée au pas de lot.")391 case .sizeNotOnLot(let lot): String(localized: "La taille doit être un multiple du pas de lot (\(Fx.exact(lot))).")392 case .belowMinimumSize(let min): String(localized: "Taille inférieure au minimum de l’instrument (\(Fx.exact(min))).")393 case .usdUnavailable: String(localized: "La saisie en USD n’est pas possible pour le pas de lot de cet instrument : saisis des contrats.")394 case .noReferencePrice: String(localized: "Aucun prix de référence servi pour convertir un montant en USD.")395 case .priceMissing: String(localized: "Saisis le prix limite.")396 case .priceInvalid: String(localized: "Prix invalide.")397 case .priceAmbiguous: String(localized: "Prix ambigu (mille ou un ?) : écris-le sans séparateur de milliers.")398 case .priceNotOnTick(let tick): String(localized: "Le prix doit être un multiple du pas de cotation (\(Fx.exact(tick))).")399 case .triggerMissing: String(localized: "Saisis le prix de déclenchement.")400 case .triggerInvalid: String(localized: "Prix de déclenchement invalide.")401 case .triggerNotOnTick(let tick): String(localized: "Le prix de déclenchement doit être un multiple du pas de cotation (\(Fx.exact(tick))).")402 case .slippageMissing: String(localized: "Saisis l’écart maximal accepté par rapport au carnet, en points de base.")403 case .slippageInvalid: String(localized: "Écart maximal invalide (nombre entier de points de base, 1 à 1000).")404 case .leverageMissing: String(localized: "Choisis le levier : rien n’est présélectionné.")405 case .leverageAboveMaximum(let max): String(localized: "Levier au-dessus du maximum permis (\(max)×).")406 case .instrumentNotTradable(let status): String(localized: "Instrument non négociable pour le moment (\(status)).")407 }408 }409 }410411 /** A valid order: exact decimals, ready to become a paper OR a live request — two different types. */412 struct Built: Equatable, Sendable {413 let instrument: String414 let side: DerivOrderSide415 let type: DerivOrderType416 let size: VenueDecimal417 let price: VenueDecimal?418 let trigger: VenueDecimal?419 let reduceOnly: Bool420 let tif: DerivTimeInForce421 let slippageBps: Int?422 let leverage: LeverageChoice423 /** size × the reference price below (exact). An indication; the server's preview is the figure that counts. */424 let notional: VenueDecimal?425 let referencePrice: VenueDecimal?426 let referenceIsMark: Bool427428 /** The leverage travels with a PAPER order (nil keeps the paper account's setting, which the owner chose to keep). */429 var paperRequest: PaperOrderRequest {430 var lev: String?431 if case .set(let n) = leverage { lev = String(n) }432 return PaperOrderRequest(instrument: instrument, side: side, type: type, size: size.description, price: price?.description, triggerPrice: trigger?.description,433 reduceOnly: reduceOnly, tif: tif, leverage: lev, slippageBps: slippageBps)434 }435 /** A LIVE order carries no leverage: on a venue it is a setting, changed by its own passkey-approved object. */436 var liveRequest: LiveOrderRequest {437 LiveOrderRequest(instrument: instrument, side: side, type: type, size: size.description, price: price?.description, triggerPrice: trigger?.description,438 reduceOnly: reduceOnly, tif: tif, slippageBps: slippageBps)439 }440 var needsHighLeverageConfirmation: Bool {441 guard !reduceOnly, let m = leverage.multiple, let t = VenueDecimal(String(FuturesOrderForm.highLeverageThreshold)) else { return false }442 return m >= t443 }444 }445446 /**447 - Parameters:448 - mark: the served mark (reference of a market order and of a USD size); nil when none is served.449 - maxLeverage: the lowest of the instrument's, the account policy's and the authorization's maxima.450 - leverageRequired: false when the leverage is chosen elsewhere (live: after the preview has read the venue's setting).451 */452 func build(instrument: DerivInstrument, mark: String?, maxLeverage: Int, leverageRequired: Bool = true, decimalSeparator: String = Locale.current.decimalSeparator ?? ".") -> (order: Built?, problems: [Problem]) {453 var problems: [Problem] = []454 if instrument.status == "halted" || (instrument.status == "reduce_only" && !reduceOnly) { problems.append(.instrumentNotTradable(status: instrument.status)) }455 if side == nil { problems.append(.sideMissing) }456457 func read(_ text: String, missing: Problem, invalid: Problem, ambiguous: Problem) -> VenueDecimal? {458 switch DecimalInput.parse(text, decimalSeparator: decimalSeparator) {459 case .success(let v): if v.isPositive { return v }; problems.append(invalid); return nil460 case .failure(.empty): problems.append(missing); return nil461 case .failure(.ambiguous): problems.append(ambiguous); return nil462 case .failure(.invalid): problems.append(invalid); return nil463 }464 }465 var price: VenueDecimal?, trigger: VenueDecimal?466 if kind.isTrigger {467 trigger = read(triggerText, missing: .triggerMissing, invalid: .triggerInvalid, ambiguous: .triggerInvalid)468 if let t = trigger, FuturesMath.isOnStep(t, step: instrument.tickSize) == false { problems.append(.triggerNotOnTick(tick: instrument.tickSize)); trigger = nil }469 }470 if kind != .market {471 price = read(priceText, missing: .priceMissing, invalid: .priceInvalid, ambiguous: .priceAmbiguous)472 if let p = price, FuturesMath.isOnStep(p, step: instrument.tickSize) == false { problems.append(.priceNotOnTick(tick: instrument.tickSize)); price = nil }473 }474 var slippage: Int?475 if kind == .market {476 if slippageText.trimmingCharacters(in: .whitespaces).isEmpty { problems.append(.slippageMissing) }477 else if let n = DecimalInput.wholeNumber(slippageText), n <= 1000 { slippage = n } else { problems.append(.slippageInvalid) }478 }479480 let markDec = mark.flatMap(VenueDecimal.init).flatMap { $0.isPositive ? $0 : nil }481 let reference = price ?? (kind == .market ? markDec : nil)482 var size: VenueDecimal?483 if let typed = read(sizeText, missing: .sizeMissing, invalid: .sizeInvalid, ambiguous: .sizeAmbiguous) {484 switch unit {485 case .contracts:486 if FuturesMath.isOnStep(typed, step: instrument.lotSize) == false { problems.append(.sizeNotOnLot(lot: instrument.lotSize)) } else { size = typed }487 case .usd:488 if let d = FuturesMath.decimals(ofStep: instrument.lotSize) {489 if let ref = reference { size = FuturesMath.size(forUSD: typed, price: ref, lotDecimals: d); if size?.isZero != false { size = nil; problems.append(.sizeZero) } }490 else if kind == .market { problems.append(.noReferencePrice) }491 // a limit order without a valid price: the price problem is already listed492 } else { problems.append(.usdUnavailable) }493 }494 }495 if let s = size, let min = instrument.minOrderSize, let m = VenueDecimal(min), s < m { problems.append(.belowMinimumSize(min: min)); size = nil }496497 if !reduceOnly {498 switch leverage {499 case .none: if leverageRequired { problems.append(.leverageMissing) }500 case .set(let n): if n > maxLeverage { problems.append(.leverageAboveMaximum(max: maxLeverage)) }501 case .keepCurrent: break502 }503 }504 guard problems.isEmpty, let side, let size else { return (nil, problems) }505 let types = kind.types506 let order = Built(instrument: instrument.id, side: side, type: kind == .market ? types.market : types.limit, size: size, price: price, trigger: trigger,507 reduceOnly: reduceOnly, tif: kind == .market ? .ioc : tif, slippageBps: slippage, leverage: reduceOnly ? .none : leverage,508 notional: reference.map { size.multiplied(by: $0) }, referencePrice: reference, referenceIsMark: price == nil)509 return (order, [])510 }511}512513/** What still stands between a built order and the button that places (paper) or proposes (live) it. */514enum OrderGate {515 enum Blocker: Equatable, Sendable {516 case offline, formIncomplete, leverageNotChosen, previewMissing, previewOutdated, refusedByRisk, highLeverageNotConfirmed, busy517 var text: String {518 switch self {519 case .offline: String(localized: "Hors ligne : aucun ordre n’est possible.")520 case .formIncomplete: String(localized: "Le formulaire est incomplet.")521 case .leverageNotChosen: String(localized: "Choisis le levier : rien n’est présélectionné.")522 case .previewMissing: String(localized: "Demande d’abord l’aperçu du serveur.")523 case .previewOutdated: String(localized: "Le formulaire a changé : redemande l’aperçu.")524 case .refusedByRisk: String(localized: "Refusé par le contrôle de risque du serveur.")525 case .highLeverageNotConfirmed: String(localized: "Confirme le levier élevé.")526 case .busy: String(localized: "Opération en cours.")527 }528 }529 }530531 /** The server's preview relative to the form as it is NOW. */532 enum PreviewState: Equatable, Sendable {533 case missing534 /** A preview exists, but for another request than the one the form builds now. */535 case outdated536 case current(riskAccepted: Bool)537 }538539 static func blockers(order: FuturesOrderForm.Built?, leverageChosen: Bool, preview: PreviewState, highLeverageConfirmed: Bool, canOperate: Bool, busy: Bool) -> [Blocker] {540 var b: [Blocker] = []541 if !canOperate { b.append(.offline) }542 if order?.reduceOnly != true, !leverageChosen { b.append(.leverageNotChosen) }543 guard let order else { b.append(.formIncomplete); return b }544 switch preview {545 case .missing: b.append(.previewMissing)546 case .outdated: b.append(.previewOutdated)547 case .current(let ok): if !ok { b.append(.refusedByRisk) }548 }549 if order.needsHighLeverageConfirmation, !highLeverageConfirmed { b.append(.highLeverageNotConfirmed) }550 if busy { b.append(.busy) }551 return b552 }553}554555/** One key per distinct request: retrying the same request after a lost answer answers the same order instead of a second one. */556struct AttemptKey<Request: Equatable & Sendable>: Sendable {557 private var last: (key: String, request: Request)?558 mutating func key(for request: Request) -> String {559 if let l = last, l.request == request { return l.key }560 let k = APIClient.newIdempotencyKey()561 last = (k, request)562 return k563 }564 /** After the server has answered the attempt for good (placed, refused, withdrawn): the next order is a new one. */565 mutating func finish() { last = nil }566}567568// MARK: liquidation price provenance569570/** Where a liquidation price comes from. The app never computes one. */571enum LiquidationProvenance: Equatable, Sendable {572 /** The venue's own figure for an existing position. */573 case venueReported574 /** An estimate of the wallet's server (paper engine, or a preview), with the method it stated. */575 case serverEstimate(method: String?)576577 var label: String {578 switch self {579 case .venueReported: String(localized: "rapporté par la plateforme")580 case .serverEstimate: String(localized: "estimation du serveur")581 }582 }583 var tone: Tone { self == .venueReported ? .info : .warn }584585 /** nil: no liquidation price was served — nothing is shown in its place. */586 static func of(_ p: DerivPosition) -> LiquidationProvenance? {587 guard p.liquidationPrice != nil else { return nil }588 return p.liquidationPriceIsVenueReported ? .venueReported : .serverEstimate(method: nil)589 }590 static func of(_ e: DerivEstimatedValue?) -> LiquidationProvenance? {591 guard let e, e.value != nil else { return nil }592 return .serverEstimate(method: e.method)593 }594}595596// MARK: order states (a submitted order is not a filled order)597598struct OrderStateView: Equatable, Sendable {599 let label: String600 let tone: Tone601 let symbol: String602 /** True only when the venue (or the paper engine) reported a complete fill. */603 let isFilled: Bool604 /** Nothing more will happen to it. */605 let isFinal: Bool606 /** Sent or about to be, and the venue has confirmed nothing: never shown as done. */607 let isInFlight: Bool608609 private init(_ label: String, _ tone: Tone, _ symbol: String, filled: Bool = false, final: Bool = false, inFlight: Bool = false) {610 self.label = label; self.tone = tone; self.symbol = symbol; isFilled = filled; isFinal = final; isInFlight = inFlight611 }612613 /** States of a paper order or of an order as a venue lists it (`DerivOrder.status`). */614 static func of(status: String) -> OrderStateView {615 switch status {616 case "pending": return OrderStateView(String(localized: "En attente"), .info, "clock", inFlight: true)617 case "open": return OrderStateView(String(localized: "Au carnet, non exécuté"), .info, "tray.full")618 case "triggered": return OrderStateView(String(localized: "Déclenché, non exécuté"), .info, "bolt")619 case "partially_filled": return OrderStateView(String(localized: "Partiellement exécuté"), .warn, "circle.lefthalf.filled")620 case "filled": return OrderStateView(String(localized: "Exécuté"), .ok, "checkmark.circle.fill", filled: true, final: true)621 case "cancelled": return OrderStateView(String(localized: "Annulé"), .neutral, "xmark.circle", final: true)622 case "rejected": return OrderStateView(String(localized: "Rejeté"), .danger, "xmark.octagon.fill", final: true)623 default: return OrderStateView(status, .neutral, "questionmark.circle")624 }625 }626627 /** States of a LIVE order (`proposed → risk_checked → authorized → signed → submitted → open | … | unknown`). */628 static func of(live state: LiveOrderState, final: Bool) -> OrderStateView {629 switch state.rawValue {630 case "proposed", "risk_checked": return OrderStateView(String(localized: "Proposé, en attente de ta clé d’accès"), .info, "person.badge.key")631 case "authorized": return OrderStateView(String(localized: "Approuvé, signature en cours"), .info, "clock.arrow.2.circlepath", inFlight: true)632 case "signed": return OrderStateView(String(localized: "Signé, pas encore envoyé"), .info, "clock.arrow.2.circlepath", inFlight: true)633 case "submitted": return OrderStateView(String(localized: "Envoyé à la plateforme, pas encore confirmé"), .info, "paperplane", inFlight: true)634 case "unknown": return OrderStateView(String(localized: "État inconnu : la plateforme n’a rien confirmé"), .warn, "questionmark.circle.fill", inFlight: true)635 case "expired": return OrderStateView(String(localized: "Expiré avant approbation"), .neutral, "clock.badge.xmark", final: true)636 default:637 let v = of(status: state.rawValue)638 return OrderStateView(v.label, v.tone, v.symbol, filled: v.isFilled, final: final || v.isFinal, inFlight: v.isInFlight)639 }640 }641}642643// MARK: sides and small labels644645enum FuturesText {646 static func side(order s: String) -> String { s == "buy" ? String(localized: "Achat (long)") : s == "sell" ? String(localized: "Vente (short)") : s }647 static func side(position s: String) -> String { s == "long" ? "Long" : s == "short" ? "Short" : s }648 static func sideTone(_ s: String) -> Tone { s == "buy" || s == "long" ? .ok : s == "sell" || s == "short" ? .danger : .neutral }649 static func type(_ t: String) -> String {650 switch t {651 case "market": String(localized: "Marché")652 case "limit": String(localized: "Limite")653 case "stop_market": String(localized: "Stop au marché")654 case "stop_limit": String(localized: "Stop limite")655 case "take_profit_market": String(localized: "Prise de profit au marché")656 case "take_profit_limit": String(localized: "Prise de profit limite")657 default: t658 }659 }660 static func tif(_ t: String) -> String {661 switch t {662 case "gtc": String(localized: "Valable jusqu’à annulation (GTC)")663 case "ioc": String(localized: "Immédiat ou annulé (IOC)")664 case "alo": String(localized: "Ajout de liquidité seulement (post-only)")665 default: t666 }667 }668 static func marginMode(_ m: String) -> String { m == "cross" ? String(localized: "croisée") : m == "isolated" ? String(localized: "isolée") : m }669 static func accountMode(_ m: String) -> String {670 switch m {671 case "READ_ONLY": String(localized: "LECTURE SEULE")672 case "PAPER": String(localized: "PAPIER")673 case "MANUAL_LIVE": String(localized: "RÉEL MANUEL")674 case "MANDATE_LIVE": String(localized: "MANDAT RÉEL")675 default: m676 }677 }678 static var locale: String { Locale.current.language.languageCode?.identifier == "en" ? "en" : "fr" }679}680