SPB Git

Repository Public

FuturesFlowTests.swift 20.2 KB 298 lines swift

1// SP Wallet iOS2// File: Tests/FuturesFlowTests.swift3// Description: Unit tests of the perp terminal's logic: typed numbers are never guessed, sizes and notionals are exact, the4//              order form has no default leverage and asks an extra confirmation from 5×, paper and live requests are distinct5//              types (a live order carries no leverage), a liquidation price is labelled by its provenance and never invented,6//              and an order that was sent is not an order that was filled.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Testing12import SPWalletCore13@testable import SPWallet1415private func decode<T: Decodable>(_ json: String, as: T.Type = T.self) throws -> T { try APICoding.decoder().decode(T.self, from: Data(json.utf8)) }1617private func instrument(tick: String = "1", lot: String = "0.00001", min: String? = nil, maxLeverage: String = "40", status: String = "active") throws -> DerivInstrument {18    try decode("""19    {"venue":"hyperliquid","symbol":"BTC","id":"hyperliquid:BTC","base":"BTC","quote":"USD","kind":"perp","collateral":"USDC","settlement":"USDC",20     "tickSize":"\(tick)","lotSize":"\(lot)","minOrderSize":\(min.map { "\"\($0)\"" } ?? "null"),"minNotional":"10","maxLeverage":"\(maxLeverage)","marginModes":["cross","isolated"],21     "fundingIntervalSec":3600,"markPriceMethod":"oracle","status":"\(status)"}22    """)23}2425private func position(source: String, liquidation: String?) throws -> DerivPosition {26    try decode("""27    {"instrument":"hyperliquid:BTC","side":"long","size":"0.01","entryPrice":"100000","markPrice":"100500","liquidationPrice":\(liquidation.map { "\"\($0)\"" } ?? "null"),28     "leverage":"5","marginMode":"cross","margin":"200","unrealizedPnl":"5","source":"\(source)"}29    """)30}3132@Suite struct FuturesDecimalInputTests {33    @Test func bothSeparatorsAreReadWithoutGuessing() {34        #expect(try! DecimalInput.parse("0,01", decimalSeparator: ",").get().description == "0.01")35        #expect(try! DecimalInput.parse("0.01", decimalSeparator: ",").get().description == "0.01")36        #expect(try! DecimalInput.parse("1 234,5", decimalSeparator: ",").get().description == "1234.5")37        #expect(try! DecimalInput.parse("1,234.5", decimalSeparator: ".").get().description == "1234.5")38        #expect(try! DecimalInput.parse("1,000,000", decimalSeparator: ".").get().description == "1000000")39        #expect(try! DecimalInput.parse(".5", decimalSeparator: ".").get().description == "0.5")40        #expect(try! DecimalInput.parse("007", decimalSeparator: ".").get().description == "7")41    }42    @Test func anAmbiguousThousandIsRefusedNotGuessed() {43        #expect(DecimalInput.parse("1.000", decimalSeparator: ",") == .failure(.ambiguous))44        #expect(DecimalInput.parse("12,345", decimalSeparator: ".") == .failure(.ambiguous))45        // the screen's own decimal separator is a decimal separator: « 1,000 » in French is one46        #expect(try! DecimalInput.parse("1,000", decimalSeparator: ",").get().description == "1")47        #expect(try! DecimalInput.parse("0.001", decimalSeparator: ",").get().description == "0.001")48    }49    @Test func signsExponentsAndLettersAreInvalid() {50        for bad in ["-1", "1e3", "abc", "1,2,3", "1.2.3.4x", ","] { #expect(DecimalInput.parse(bad, decimalSeparator: ".") == .failure(.invalid), "\(bad)") }51        #expect(DecimalInput.parse("  ", decimalSeparator: ".") == .failure(.empty))52        #expect(DecimalInput.wholeNumber("5") == 5)53        #expect(DecimalInput.wholeNumber("0") == nil)54        #expect(DecimalInput.wholeNumber("5.0") == nil)55        #expect(DecimalInput.wholeNumber("") == nil)56    }57}5859@Suite struct FuturesMathTests {60    @Test func stepsAreCheckedExactly() {61        #expect(FuturesMath.decimals(ofStep: "0.001") == 3)62        #expect(FuturesMath.decimals(ofStep: "1") == 0)63        #expect(FuturesMath.decimals(ofStep: "0.5") == nil)64        #expect(FuturesMath.isOnStep(VenueDecimal("0.0012")!, step: "0.001") == false)65        #expect(FuturesMath.isOnStep(VenueDecimal("0.012")!, step: "0.001") == true)66        #expect(FuturesMath.isOnStep(VenueDecimal("100.5")!, step: "0.5") == true)67        #expect(FuturesMath.isOnStep(VenueDecimal("100.3")!, step: "0.5") == false)68        #expect(FuturesMath.isOnStep(VenueDecimal("30")!, step: "10") == true)69        #expect(FuturesMath.isOnStep(VenueDecimal("35")!, step: "10") == false)70    }71    @Test func aUSDAmountBecomesTheGreatestSizeThatDoesNotExceedIt() {72        // 1000 / 97 123.5 = 0.010296…  → 0.01029 on a 0.00001 lot (never rounded up)73        let s = FuturesMath.size(forUSD: VenueDecimal("1000")!, price: VenueDecimal("97123.5")!, lotDecimals: 5)!74        #expect(s.description == "0.01029")75        #expect(s.multiplied(by: VenueDecimal("97123.5")!) <= VenueDecimal("1000")!)76        #expect(VenueDecimal("0.0103")!.multiplied(by: VenueDecimal("97123.5")!) > VenueDecimal("1000")!)77        // a cheap contract: more units than dollars78        #expect(FuturesMath.size(forUSD: VenueDecimal("50")!, price: VenueDecimal("0.00002")!, lotDecimals: 0)!.description == "2500000")79        // less than one lot: zero, never one lot80        #expect(FuturesMath.size(forUSD: VenueDecimal("1")!, price: VenueDecimal("97123.5")!, lotDecimals: 2)!.isZero)81        #expect(FuturesMath.size(forUSD: VenueDecimal("100")!, price: VenueDecimal("25")!, lotDecimals: 2)!.description == "4")82    }83    @Test func displayKeepsEveryDigitAndTheSign() {84        #expect(Fx.exact("-12.50").hasPrefix("−"))85        #expect(Fx.percent(fraction: "0.0123", dp: 2)?.replacingOccurrences(of: ",", with: ".") == "+1.23 %")86        #expect(Fx.percent(fraction: "-0.000125", dp: 4)?.replacingOccurrences(of: ",", with: ".") == "−0.0125 %")87        #expect(Fx.percent(fraction: nil) == nil)88        #expect(Fx.exact(nil) == "—")89    }90}9192@Suite struct FuturesOrderFormTests {93    private func filled(_ change: (inout FuturesOrderForm) -> Void = { _ in }) -> FuturesOrderForm {94        var f = FuturesOrderForm()95        f.side = .buy; f.kind = .limit; f.sizeText = "0.01"; f.priceText = "100000"; f.leverage = .set(3)96        change(&f)97        return f98    }99100    @Test func nothingIsPreselected() throws {101        let f = FuturesOrderForm()102        #expect(f.side == nil)103        #expect(f.leverage == .none)104        #expect(f.sizeText.isEmpty && f.priceText.isEmpty && f.slippageText.isEmpty)105        #expect(!f.reduceOnly)106        let r = f.build(instrument: try instrument(), mark: "100000", maxLeverage: 40, decimalSeparator: ".")107        #expect(r.order == nil)108        #expect(r.problems.contains(.sideMissing) && r.problems.contains(.leverageMissing) && r.problems.contains(.sizeMissing))109    }110111    @Test func thereIsNoDefaultLeverage() throws {112        let i = try instrument()113        let without = filled { $0.leverage = .none }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".")114        #expect(without.order == nil)115        #expect(without.problems == [.leverageMissing])116        // the gate keeps the order button disabled until a leverage is chosen, whatever else is true117        #expect(OrderGate.blockers(order: nil, leverageChosen: false, preview: .current(riskAccepted: true), highLeverageConfirmed: true, canOperate: true, busy: false).contains(.leverageNotChosen))118        let with = filled().build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".")119        #expect(with.order?.leverage == .set(3))120        #expect(with.order?.paperRequest.leverage == "3")121        // explicitly keeping the displayed setting is a choice; the paper request then leaves the account's setting alone122        let kept = filled { $0.leverage = .keepCurrent("7") }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".")123        #expect(kept.order?.paperRequest.leverage == nil)124        #expect(kept.order?.needsHighLeverageConfirmation == true)125        // above what the instrument, the policy or the authorization allow126        #expect(filled { $0.leverage = .set(50) }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").problems == [.leverageAboveMaximum(max: 40)])127        // a reduce-only order opens no risk: it needs no leverage128        #expect(filled { $0.leverage = .none; $0.reduceOnly = true }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").order != nil)129    }130131    @Test func fromFiveTimesAnExtraConfirmationIsRequired() throws {132        let i = try instrument()133        let low = filled { $0.leverage = .set(4) }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!134        let high = filled { $0.leverage = .set(5) }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!135        #expect(!low.needsHighLeverageConfirmation)136        #expect(high.needsHighLeverageConfirmation)137        let ok = OrderGate.PreviewState.current(riskAccepted: true)138        #expect(OrderGate.blockers(order: low, leverageChosen: true, preview: ok, highLeverageConfirmed: false, canOperate: true, busy: false).isEmpty)139        #expect(OrderGate.blockers(order: high, leverageChosen: true, preview: ok, highLeverageConfirmed: false, canOperate: true, busy: false) == [.highLeverageNotConfirmed])140        #expect(OrderGate.blockers(order: high, leverageChosen: true, preview: ok, highLeverageConfirmed: true, canOperate: true, busy: false).isEmpty)141    }142143    @Test func theGateNeedsAFreshAcceptedPreviewAndAConnection() throws {144        let o = filled().build(instrument: try instrument(), mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!145        #expect(OrderGate.blockers(order: o, leverageChosen: true, preview: .missing, highLeverageConfirmed: false, canOperate: true, busy: false) == [.previewMissing])146        #expect(OrderGate.blockers(order: o, leverageChosen: true, preview: .outdated, highLeverageConfirmed: false, canOperate: true, busy: false) == [.previewOutdated])147        #expect(OrderGate.blockers(order: o, leverageChosen: true, preview: .current(riskAccepted: false), highLeverageConfirmed: false, canOperate: true, busy: false) == [.refusedByRisk])148        #expect(OrderGate.blockers(order: o, leverageChosen: true, preview: .current(riskAccepted: true), highLeverageConfirmed: false, canOperate: false, busy: false) == [.offline])149        #expect(OrderGate.blockers(order: nil, leverageChosen: true, preview: .missing, highLeverageConfirmed: false, canOperate: true, busy: false) == [.formIncomplete])150    }151152    @Test func sizeAndNotionalAreExact() throws {153        let i = try instrument(tick: "0.1", lot: "0.00001", min: "0.0001")154        let o = filled { $0.sizeText = "0.01234"; $0.priceText = "97123.5" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ".").order!155        #expect(o.size.description == "0.01234")156        #expect(o.notional?.description == "1198.50399")       // 0.01234 × 97123.5, every digit157        #expect(o.referenceIsMark == false)158        // USD size: cut down to the lot, never up159        let usd = filled { $0.unit = .usd; $0.sizeText = "1000"; $0.priceText = "97123.5" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ".").order!160        #expect(usd.size.description == "0.01029")161        #expect(usd.notional! <= VenueDecimal("1000")!)162        // off the lot / off the tick / below the minimum: refused, not rounded163        #expect(filled { $0.sizeText = "0.000001" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ".").problems == [.sizeNotOnLot(lot: "0.00001")])164        #expect(filled { $0.priceText = "97123.55" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ".").problems == [.priceNotOnTick(tick: "0.1")])165        #expect(filled { $0.sizeText = "0.00005" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ".").problems == [.belowMinimumSize(min: "0.0001")])166        #expect(filled { $0.sizeText = "1.000" }.build(instrument: i, mark: "97000", maxLeverage: 40, decimalSeparator: ",").problems == [.sizeAmbiguous])167    }168169    @Test func aMarketOrderNeedsATypedBoundAndUsesTheServedMarkOnlyAsAnIndication() throws {170        let i = try instrument()171        let noBound = filled { $0.kind = .market; $0.priceText = "" }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".")172        #expect(noBound.problems == [.slippageMissing])173        let o = filled { $0.kind = .market; $0.priceText = ""; $0.slippageText = "30" }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!174        #expect(o.type == .market && o.tif == .ioc && o.price == nil && o.slippageBps == 30)175        #expect(o.referenceIsMark && o.notional?.description == "1000")176        // no mark served: no notional is made up; a USD size cannot be converted177        let blind = filled { $0.kind = .market; $0.priceText = ""; $0.slippageText = "30" }.build(instrument: i, mark: nil, maxLeverage: 40, decimalSeparator: ".").order!178        #expect(blind.notional == nil)179        #expect(filled { $0.kind = .market; $0.priceText = ""; $0.slippageText = "30"; $0.unit = .usd; $0.sizeText = "500" }.build(instrument: i, mark: nil, maxLeverage: 40, decimalSeparator: ".").problems == [.noReferencePrice])180        // a trigger order carries the owner's own limit price181        let stop = filled { $0.kind = .stop; $0.triggerText = "95000"; $0.priceText = "94900" }.build(instrument: i, mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!182        #expect(stop.type == .stopLimit && stop.trigger?.description == "95000" && stop.price?.description == "94900")183    }184185    @Test func aHaltedInstrumentIsNotTradable() throws {186        #expect(filled().build(instrument: try instrument(status: "halted"), mark: "1", maxLeverage: 40, decimalSeparator: ".").problems.contains(.instrumentNotTradable(status: "halted")))187        #expect(filled { $0.reduceOnly = true }.build(instrument: try instrument(status: "reduce_only"), mark: "1", maxLeverage: 40, decimalSeparator: ".").order != nil)188    }189190    @Test func supportedKindsFollowWhatTheVenueServes() {191        #expect(FuturesOrderForm.Kind.supported(by: ["limit", "market"]) == [.limit, .market])192        #expect(FuturesOrderForm.Kind.supported(by: ["limit", "market", "stop_limit", "take_profit_limit"]) == [.limit, .market, .stop, .takeProfit])193        #expect(FuturesOrderForm.Kind.supported(by: nil) == [.limit, .market])194    }195}196197@Suite struct FuturesPaperLiveSeparationTests {198    @Test func aLiveRequestCarriesNoLeverageAndAPaperRequestDoes() throws {199        var f = FuturesOrderForm()200        f.side = .sell; f.kind = .limit; f.sizeText = "0.01"; f.priceText = "100000"; f.leverage = .set(3)201        let o = f.build(instrument: try instrument(), mark: "100000", maxLeverage: 40, decimalSeparator: ".").order!202        let paper = try JSONValue.from(o.paperRequest), live = try JSONValue.from(o.liveRequest)203        #expect(paper["leverage"]?.stringValue == "3")204        #expect(live["leverage"] == nil)205        #expect(live["size"]?.stringValue == "0.01" && live["side"]?.stringValue == "sell" && live["price"]?.stringValue == "100000")206        // the two requests are different Swift types: a paper order cannot be handed to a live route (it would not compile)207        #expect(type(of: o.paperRequest) == PaperOrderRequest.self)208        #expect(type(of: o.liveRequest) == LiveOrderRequest.self)209    }210211    @Test func theAccountReferenceSaysPaperOrRealWithItsNetwork() {212        let paper = FuturesAccountRef.paper(PaperAccountID(rawValue: "p1"))213        let main = FuturesAccountRef.live(LiveAccountID(rawValue: "l1"), network: "mainnet"), test = FuturesAccountRef.live(LiveAccountID(rawValue: "l2"), network: "testnet")214        #expect(paper.mode == .paper && paper.badge == "PAPIER")215        #expect(main.mode == .live && main.badge.contains("MAINNET") && main.badge.contains("RÉEL"))216        #expect(test.badge.contains("TESTNET"))217        #expect(paper != main)218    }219220    @Test func oneKeyPerAttemptAndANewOneAfterItIsSettled() {221        var keys = AttemptKey<String>()222        let a = keys.key(for: "order A")223        #expect(keys.key(for: "order A") == a)          // a retry of the same request reuses the key224        #expect(keys.key(for: "order B") != a)          // another request is another attempt225        let b = keys.key(for: "order B")226        keys.finish()227        #expect(keys.key(for: "order B") != b)          // once settled, the same order placed again is a new order228    }229230    @Test func onlyHyperliquidIsOffered() {231        #expect(OfferedVenues.ids == ["hyperliquid"])232        #expect(OfferedVenues.offers(instrument: "hyperliquid:BTC"))233        #expect(!OfferedVenues.offers(instrument: "gmx:BTC-USD") && !OfferedVenues.offers("dydx") && !OfferedVenues.offers("edgex"))234        #expect(OfferedVenues.symbol(of: "hyperliquid:BTC") == "BTC")235    }236}237238@Suite struct FuturesLiquidationProvenanceTests {239    @Test func aVenuePriceAndAServerEstimateAreLabelledApart() throws {240        let venue = try position(source: "venue", liquidation: "81000"), paper = try position(source: "paper", liquidation: "80500")241        #expect(LiquidationProvenance.of(venue) == .venueReported)242        #expect(LiquidationProvenance.of(venue)?.label == "rapporté par la plateforme")243        #expect(LiquidationProvenance.of(paper) == .serverEstimate(method: nil))244        #expect(LiquidationProvenance.of(paper)?.label == "estimation du serveur")245    }246247    @Test func noLiquidationPriceIsEverMadeUp() throws {248        #expect(LiquidationProvenance.of(try position(source: "venue", liquidation: nil)) == nil)249        #expect(LiquidationProvenance.of(try position(source: "paper", liquidation: nil)) == nil)250        #expect(LiquidationProvenance.of(DerivEstimatedValue?.none) == nil)251        let none: DerivEstimatedValue = try decode(#"{"value":null,"source":"estimate","method":"cross"}"#)252        #expect(LiquidationProvenance.of(none) == nil)253        let some: DerivEstimatedValue = try decode(#"{"value":"80500","source":"estimate","method":"cross, single-position approximation"}"#)254        #expect(LiquidationProvenance.of(some) == .serverEstimate(method: "cross, single-position approximation"))255    }256}257258@Suite struct FuturesOrderStateTests {259    @Test func aSubmittedOrderIsNotAFilledOrder() {260        for raw in ["proposed", "risk_checked", "authorized", "signed", "submitted", "unknown", "open", "partially_filled", "cancelled", "rejected", "expired"] {261            #expect(!OrderStateView.of(live: LiveOrderState(rawValue: raw), final: false).isFilled, "\(raw)")262        }263        let submitted = OrderStateView.of(live: LiveOrderState(rawValue: "submitted"), final: false)264        #expect(submitted.isInFlight && !submitted.isFinal && submitted.tone != .ok)265        let filled = OrderStateView.of(live: LiveOrderState(rawValue: "filled"), final: true)266        #expect(filled.isFilled && filled.isFinal && filled.tone == .ok)267        #expect(submitted.label != filled.label)268    }269270    @Test func anUnknownStateIsShownAsUnknownNeverAsDone() {271        let u = OrderStateView.of(live: .unknown, final: false)272        #expect(u.isInFlight && !u.isFilled && u.tone == .warn)273        let odd = OrderStateView.of(status: "some_new_state")274        #expect(odd.label == "some_new_state" && !odd.isFilled && !odd.isFinal)275    }276277    @Test func paperStatesMapTheSameWay() {278        #expect(OrderStateView.of(status: "filled").isFilled)279        #expect(!OrderStateView.of(status: "open").isFilled && !OrderStateView.of(status: "open").isFinal)280        #expect(!OrderStateView.of(status: "partially_filled").isFilled)281        #expect(OrderStateView.of(status: "rejected").isFinal && OrderStateView.of(status: "rejected").tone == .danger)282    }283}284285@Suite struct FuturesPolicyDraftTests {286    @Test func aPolicyRoundTripsExactlyAndRefusesANonNumber() throws {287        let p = DerivRiskPolicy(mode: "PAPER", allowedInstruments: ["hyperliquid:BTC"], halt: nil, maxDataAgeMs: 15000, maxDeviationBps: "100", maxMarkIndexBps: "150", maxLeverage: "5",288                                maxOrderNotional: "25000", maxGrossExposure: "50000", maxPositionNotional: "25000", minFreeCollateral: "0", minLiquidationDistanceBps: "500",289                                maxDailyLoss: "1000", maxTotalLoss: "5000", maxOrdersPerMinute: 30, maxOrdersPerDay: 500)290        var d = PolicyDraft(p)291        #expect(d.build(decimalSeparator: ".") == p)292        d.maxLeverage = "3"293        #expect(d.build(decimalSeparator: ".")?.maxLeverage == "3")294        d.maxOrderNotional = "beaucoup"295        #expect(d.build(decimalSeparator: ".") == nil)296    }297}298
Files main
Menu

Theme