Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Derivatives/DerivativesModels.swift3// Description: Models of the read-only and paper part of the derivatives module (services/api/src/derivatives/routes.ts, data.ts,4// paper.ts, route.ts; packages/derivatives/src/models.ts, risk.ts, router.ts): venues, instruments, tickers, books,5// candles, funding, comparison, router simulation, paper accounts. Every price, size and amount is the server's6// decimal string. A liquidation price is only ever the one the server sent, with the source it stated.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112// MARK: identifiers that keep paper and live apart at compile time1314/** Id of a PAPER (simulated) account. A live route never accepts it. */15public struct PaperAccountID: RawRepresentable, Codable, Sendable, Hashable, CustomStringConvertible {16 public let rawValue: String17 public init(rawValue: String) { self.rawValue = rawValue }18 public var description: String { rawValue }19}2021/** Id of a LIVE venue account (real funds on mainnet). A paper route never accepts it. */22public struct LiveAccountID: RawRepresentable, Codable, Sendable, Hashable, CustomStringConvertible {23 public let rawValue: String24 public init(rawValue: String) { self.rawValue = rawValue }25 public var description: String { rawValue }26}2728// MARK: venues and market data2930/** `Capabilities` of packages/derivatives/src/venue.ts, as the registry narrows them for a restricted venue. */31public struct DerivVenueCapabilities: Codable, Sendable, Hashable {32 public let marketData: Bool?33 public let account: Bool?34 public let orders: Bool?35 public let orderTypes: [String]?36 public let tif: [String]?37 public let modify: Bool?38 public let leverage: Bool?39 public let marginModes: [String]?40 public let subaccounts: Bool?41 public let testnet: Bool?42 public let stream: Bool?43 public let notes: [String]?44}4546public struct DerivVenue: Codable, Sendable, Hashable, Identifiable {47 /** `hyperliquid`, `gmx`, `dydx`, `edgex`. Only Hyperliquid is offered by the web interface today (apps/web/src/venues.ts). */48 public let id: String49 public let name: String50 public let network: String51 public let capabilities: DerivVenueCapabilities?52 /** `ok`, `degraded`, `down`. */53 public let status: String54 public let lastOkAt: Date?55 /** Non-nil: market data only on this venue (jurisdiction). The text is the server's and is shown verbatim. */56 public let restriction: String?57 public let lastError: String?58 /** True when a paper account can exist on this venue. */59 public let paper: Bool?60 public let orderBook: Bool?61}6263public struct DerivVenuesAnswer: Codable, Sendable, Hashable {64 public let venues: [DerivVenue]65 /** Cache ages of each kind of data (`DATA_BOUNDS`), in milliseconds. */66 public let bounds: JSONValue?67 public let ts: Date?68}6970/** A venue that could not be read while the others were answered. */71public struct DerivVenueReadError: Codable, Sendable, Hashable {72 public let venue: String73 public let message: String74}7576public struct DerivInstrument: Codable, Sendable, Hashable, Identifiable {77 public let venue: String78 public let symbol: String79 /** `${venue}:${symbol}`. */80 public let id: String81 public let base: String82 public let quote: String83 public let kind: String84 public let collateral: String85 public let settlement: String86 public let tickSize: String87 public let lotSize: String88 public let minOrderSize: String?89 public let minNotional: String?90 public let maxLeverage: String91 public let marginModes: [String]92 public let fundingIntervalSec: Int93 public let markPriceMethod: String94 /** `active`, `reduce_only`, `halted`. */95 public let status: String96 public let category: String?97}9899public struct DerivInstrumentsAnswer: Codable, Sendable, Hashable {100 public let instruments: [DerivInstrument]101 public let ts: Date?102 public let errors: [DerivVenueReadError]?103}104105public struct DerivTicker: Codable, Sendable, Hashable {106 public let instrument: String107 public let mark: String108 /** The venue's index / oracle price; nil when it publishes none. */109 public let index: String?110 public let mid: String?111 /** Per funding interval of the instrument. */112 public let funding: String?113 public let openInterest: String?114 public let volume24h: String?115 public let change24h: String?116 public let ts: Date117 public let last: String?118 public let volumeBase24h: String?119 public let nextFundingTs: Date?120 public let source: String?121}122123public struct DerivTickersAnswer: Codable, Sendable, Hashable {124 public let tickers: [DerivTicker]125 public let ts: Date?126 public let source: String?127 public let errors: [DerivVenueReadError]?128}129130/** One `[price, size]` level of a book. */131public struct DerivBookLevel: Codable, Sendable, Hashable {132 public let price: String133 public let size: String134 public init(from decoder: Decoder) throws {135 var c = try decoder.unkeyedContainer()136 price = try c.decode(String.self); size = try c.decode(String.self)137 }138 public func encode(to encoder: Encoder) throws { var c = encoder.unkeyedContainer(); try c.encode(price); try c.encode(size) }139}140141public struct DerivBook: Codable, Sendable, Hashable {142 public let instrument: String143 /** Best (highest) first. */144 public let bids: [DerivBookLevel]145 /** Best (lowest) first. */146 public let asks: [DerivBookLevel]147 public let ts: Date148 public let source: String?149}150151public struct DerivPublicTrade: Codable, Sendable, Hashable {152 public let instrument: String153 public let price: String154 public let size: String155 public let side: String156 public let ts: Date157 public let id: String158}159160/** What GMX has instead of a book (`GmxLiquidity`); every figure optional: the panel shows what it gets. */161public struct DerivLiquidity: Codable, Sendable, Hashable {162 public struct PriceImpact: Codable, Sendable, Hashable {163 public let factorPositive, factorNegative, exponentPositive, exponentNegative, maxFactorPositive, maxFactorNegative, maxFactorForLiquidations: String?164 }165 public struct PositionFeeFactor: Codable, Sendable, Hashable { public let balanceImproved, balanceNotImproved: String? }166 public let instrument: String?167 public let market: String?168 public let openInterestLongUsd, openInterestShortUsd, maxOpenInterestLongUsd, maxOpenInterestShortUsd: String?169 public let availableLiquidityLongUsd, availableLiquidityShortUsd, capacityLongUsd, capacityShortUsd: String?170 /** Per hour, fraction; positive = the side RECEIVES, negative = the side PAYS. */171 public let fundingRateLongPerHour, fundingRateShortPerHour, borrowingRateLongPerHour, borrowingRateShortPerHour, netRateLongPerHour, netRateShortPerHour: String?172 public let priceImpact: PriceImpact?173 public let positionFeeFactor: PositionFeeFactor?174 public let oracleMin, oracleMax: String?175 public let ts: Date?176 public let source: String?177}178179/** `GET /derivatives/market`: the ticker is the minimum; book, liquidity and trades fail separately and say so in `errors`. */180public struct DerivMarket: Codable, Sendable, Hashable {181 public let instrument: DerivInstrument182 public let ticker: DerivTicker183 public let book: DerivBook?184 public let liquidity: DerivLiquidity?185 public let trades: [DerivPublicTrade]?186 /** `book`, `trades`, `liquidity` → why that part is missing. */187 public let errors: [String: String]?188 public let ts: Date?189 public let source: String?190}191192public struct DerivCandle: Codable, Sendable, Hashable {193 public let ts: Date194 public let open, high, low, close, volume: String195}196197public enum DerivCandleInterval: String, Codable, Sendable, CaseIterable { case m1 = "1m", m5 = "5m", m15 = "15m", h1 = "1h", h4 = "4h", d1 = "1d" }198199public struct DerivCandlesAnswer: Codable, Sendable, Hashable {200 public let instrument: String201 public let interval: String202 public let candles: [DerivCandle]203 public let ts: Date?204 public let source: String?205}206207public struct DerivFundingRate: Codable, Sendable, Hashable { public let ts: Date; public let rate: String }208209/** Funding rates the venue applied (market data — not the payments of an account). */210public struct DerivFundingHistory: Codable, Sendable, Hashable {211 public let instrument: String212 public let history: [DerivFundingRate]213 public let intervalSec: Int214 public let ts: Date?215 public let source: String?216}217218public struct DerivCompareRow: Codable, Sendable, Hashable {219 public struct VenueFunding: Codable, Sendable, Hashable { public let rate: String?; public let intervalSec: Int? }220 public let venue: String221 public let instrument: String222 public let mark: String223 public let index: String?224 /** Fraction of notional longs pay per HOUR (negative: longs receive). */225 public let funding: String?226 public let fundingVenue: VenueFunding?227 public let spreadBps, depthUsd1pct, depthBidUsd1pct, depthAskUsd1pct, takerFeeBps: String?228 public let maxLeverage: String229 public let collateral: String230 public let settlement: String231 public let restriction: String?232 public let notes: [String]?233 public let ts: Date?234 public let source: String?235}236237/** A table of facts and live figures — never a recommendation. */238public struct DerivCompareAnswer: Codable, Sendable, Hashable {239 public let base: String240 public let rows: [DerivCompareRow]241 public let errors: [DerivVenueReadError]?242 public let ts: Date?243}244245// MARK: account state as a venue or the paper engine reports it246247public struct DerivAccountState: Codable, Sendable, Hashable {248 public let venue: String249 public let account: String250 public let equity: String251 public let collateral: String252 public let freeCollateral: String253 public let marginUsed: String254 public let maintenanceMargin: String?255 public let withdrawable: String?256 public let ts: Date257 /** `venue` or `paper`. */258 public let source: String259}260261public struct DerivPosition: Codable, Sendable, Hashable {262 public let instrument: String263 /** `long` or `short`. */264 public let side: String265 /** Positive; the direction is `side`. */266 public let size: String267 public let entryPrice: String268 public let markPrice: String269 /**270 As SERVED. With `source == "venue"` it is the venue's own figure; with `source == "paper"` it is the paper engine's271 estimate (cross, single-position approximation). The client never computes one.272 */273 public let liquidationPrice: String?274 public let leverage: String275 public let marginMode: String276 public let margin: String277 public let unrealizedPnl: String278 public let realizedPnl: String?279 public let fundingPaid: String?280 public let source: String281 public var liquidationPriceIsVenueReported: Bool { source == "venue" && liquidationPrice != nil }282}283284/** An order in the venue-neutral form (`OrderSchema`): a paper order, or an order resting on a venue as the venue reports it. */285public struct DerivOrder: Codable, Sendable, Hashable {286 public let instrument: String287 public let side: String288 public let type: String289 public let size: String290 public let price: String?291 public let triggerPrice: String?292 public let reduceOnly: Bool293 public let tif: String294 public let clientId: String295 public let venueOrderId: String?296 /** `pending`, `open`, `filled`, `partially_filled`, `cancelled`, `rejected`, `triggered`. */297 public let status: String298 public let filled: String299 public let avgFillPrice: String?300 public let createdAt: Date?301 public let updatedAt: Date?302 public let rejectReason: String?303}304305public struct DerivFill: Codable, Sendable, Hashable, Identifiable {306 public let instrument: String307 public let orderId: String?308 public let clientId: String?309 public let side: String310 public let price: String311 public let size: String312 public let fee: String313 public let feeAsset: String314 public let closedPnl: String?315 public let ts: Date316 public let id: String317 public let liquidation: Bool318 public let source: String?319}320321/** A funding payment of an ACCOUNT (negative amount = paid). */322public struct DerivFundingPayment: Codable, Sendable, Hashable {323 public let instrument: String324 public let amount: String325 public let rate: String326 public let size: String327 public let ts: Date328 public let source: String?329}330331public struct DerivRiskEvent: Codable, Sendable, Hashable, Identifiable {332 public let id: Int333 public let ts: Date334 public let kind: String335 public let code: String?336 public let message: String337 public let data: JSONValue?338}339340public struct DerivEquityPoint: Codable, Sendable, Hashable {341 public let ts: Date342 public let equity: String343 public let collateral: String?344 public let marginUsed: String?345 public let unrealizedPnl: String?346 public let source: String?347}348349/** `GET /derivatives/watch`: read-only view of a public address on a venue that allows account reads. */350public struct DerivWatch: Codable, Sendable, Hashable {351 public let venue: String352 public let account: String353 public let state: DerivAccountState354 public let positions: [DerivPosition]355 public let openOrders: [DerivOrder]356 public let ts: Date?357 public let source: String?358}359360// MARK: risk policy and verdicts361362/** `RiskPolicySchema` (packages/derivatives/src/risk.ts), every field stated. Sent whole when it is replaced. */363public struct DerivRiskPolicy: Codable, Sendable, Hashable {364 /** `READ_ONLY`, `PAPER`, `MANUAL_LIVE`, `MANDATE_LIVE`. */365 public var mode: String366 public var allowedInstruments: [String]367 /** Circuit breaker: a non-nil reason refuses every order. */368 public var halt: String?369 public var maxDataAgeMs: Int370 public var maxDeviationBps: String371 public var maxMarkIndexBps: String372 public var maxLeverage: String373 public var maxOrderNotional: String374 public var maxGrossExposure: String375 public var maxPositionNotional: String376 public var minFreeCollateral: String377 public var minLiquidationDistanceBps: String378 public var maxDailyLoss: String379 public var maxTotalLoss: String380 public var maxOrdersPerMinute: Int381 public var maxOrdersPerDay: Int382383 public init(mode: String, allowedInstruments: [String], halt: String?, maxDataAgeMs: Int, maxDeviationBps: String, maxMarkIndexBps: String, maxLeverage: String,384 maxOrderNotional: String, maxGrossExposure: String, maxPositionNotional: String, minFreeCollateral: String, minLiquidationDistanceBps: String,385 maxDailyLoss: String, maxTotalLoss: String, maxOrdersPerMinute: Int, maxOrdersPerDay: Int) {386 self.mode = mode; self.allowedInstruments = allowedInstruments; self.halt = halt; self.maxDataAgeMs = maxDataAgeMs; self.maxDeviationBps = maxDeviationBps387 self.maxMarkIndexBps = maxMarkIndexBps; self.maxLeverage = maxLeverage; self.maxOrderNotional = maxOrderNotional; self.maxGrossExposure = maxGrossExposure388 self.maxPositionNotional = maxPositionNotional; self.minFreeCollateral = minFreeCollateral; self.minLiquidationDistanceBps = minLiquidationDistanceBps389 self.maxDailyLoss = maxDailyLoss; self.maxTotalLoss = maxTotalLoss; self.maxOrdersPerMinute = maxOrdersPerMinute; self.maxOrdersPerDay = maxOrdersPerDay390 }391392 /** `halt` is nullable but REQUIRED by the server's schema: it is written as `null`, never left out. */393 public func encode(to encoder: Encoder) throws {394 var c = encoder.container(keyedBy: CodingKeys.self)395 try c.encode(mode, forKey: .mode); try c.encode(allowedInstruments, forKey: .allowedInstruments)396 if let halt { try c.encode(halt, forKey: .halt) } else { try c.encodeNil(forKey: .halt) }397 try c.encode(maxDataAgeMs, forKey: .maxDataAgeMs); try c.encode(maxDeviationBps, forKey: .maxDeviationBps); try c.encode(maxMarkIndexBps, forKey: .maxMarkIndexBps)398 try c.encode(maxLeverage, forKey: .maxLeverage); try c.encode(maxOrderNotional, forKey: .maxOrderNotional); try c.encode(maxGrossExposure, forKey: .maxGrossExposure)399 try c.encode(maxPositionNotional, forKey: .maxPositionNotional); try c.encode(minFreeCollateral, forKey: .minFreeCollateral)400 try c.encode(minLiquidationDistanceBps, forKey: .minLiquidationDistanceBps); try c.encode(maxDailyLoss, forKey: .maxDailyLoss); try c.encode(maxTotalLoss, forKey: .maxTotalLoss)401 try c.encode(maxOrdersPerMinute, forKey: .maxOrdersPerMinute); try c.encode(maxOrdersPerDay, forKey: .maxOrdersPerDay)402 }403}404405/** `RiskResult`: accepted, or refused with the engine's code and sentence (shown verbatim). */406public struct DerivRiskVerdict: Codable, Sendable, Hashable {407 public let ok: Bool408 public let code: String?409 public let reason: String?410 public var refusal: DerivativesRefusal? { ok ? nil : DerivativesRefusal(code: code ?? "refused", reason: reason ?? "", status: 200) }411}412413/** A value the server marks as an estimate, with the method it used. Never presented as the venue's figure. */414public struct DerivEstimatedValue: Codable, Sendable, Hashable {415 public let value: String?416 public let source: String417 public let method: String418}419420// MARK: paper accounts421422public struct PaperSettings: Codable, Sendable, Hashable {423 public let leverage: String?424 public let leverageByInstrument: [String: String]?425 public let takerFeeRate, makerFeeRate, maintenanceMarginFraction: String?426 /** How the paper engine arrives at a liquidation price: an estimate, in the server's words. */427 public let liquidationPrice: String?428}429430public struct PaperTotals: Codable, Sendable, Hashable {431 public let realizedPnl, feesPaid, fundingNet: String?432 public let liquidations: Int?433}434435/** A simulated account: no key, no venue account, no real funds. */436public struct PaperAccount: Codable, Sendable, Hashable, Identifiable {437 public let id: PaperAccountID438 public let venue: String439 public let network: String440 /** Always `paper`. */441 public let kind: String442 public let mode: String443 public let label: String444 public let policy: DerivRiskPolicy445 public let state: DerivAccountState446 public let positions: [DerivPosition]447 public let openOrders: [DerivOrder]448 public let initialCollateral: String?449 public let settings: PaperSettings?450 public let totals: PaperTotals?451 public let createdAt: Date?452 public let updatedAt: Date?453}454455public struct PaperAccountsAnswer: Decodable, Sendable { public let accounts: [PaperAccount]; public let ts: Date? }456457/** `GET /derivatives/accounts/:id`: the account, flat, plus its history. */458public struct PaperAccountDetail: Decodable, Sendable {459 public let account: PaperAccount460 public let orders: [DerivOrder]461 public let fills: [DerivFill]462 public let funding: [DerivFundingPayment]463 public let riskEvents: [DerivRiskEvent]464 public let equity: [DerivEquityPoint]465 private enum Keys: String, CodingKey { case orders, fills, funding, riskEvents, equity }466 public init(from decoder: Decoder) throws {467 account = try PaperAccount(from: decoder)468 let c = try decoder.container(keyedBy: Keys.self)469 orders = try c.decodeIfPresent([DerivOrder].self, forKey: .orders) ?? []470 fills = try c.decodeIfPresent([DerivFill].self, forKey: .fills) ?? []471 funding = try c.decodeIfPresent([DerivFundingPayment].self, forKey: .funding) ?? []472 riskEvents = try c.decodeIfPresent([DerivRiskEvent].self, forKey: .riskEvents) ?? []473 equity = try c.decodeIfPresent([DerivEquityPoint].self, forKey: .equity) ?? []474 }475}476477public struct PaperAccountCreation: Encodable, Sendable {478 public let venue: String479 public let label: String480 /** Simulated collateral, between 10 and 1 000 000 000. */481 public let collateral: String482 public init(venue: String, label: String, collateral: String) { self.venue = venue; self.label = label; self.collateral = collateral }483}484485public enum DerivOrderSide: String, Codable, Sendable { case buy, sell }486public enum DerivOrderType: String, Codable, Sendable { case limit, market, stopMarket = "stop_market", stopLimit = "stop_limit", takeProfitMarket = "take_profit_market", takeProfitLimit = "take_profit_limit" }487public enum DerivTimeInForce: String, Codable, Sendable { case gtc, ioc, alo }488public enum DerivMarginMode: String, Codable, Sendable { case cross, isolated }489490/** Body of a PAPER order. It cannot be passed to a live function: live orders are `LiveOrderRequest`. */491public struct PaperOrderRequest: Encodable, Sendable, Equatable {492 public let instrument: String493 public let side: DerivOrderSide494 public let type: DerivOrderType495 public let size: String496 /** Limit price; for a market order the worst acceptable price, or nil with `slippageBps`. */497 public let price: String?498 public let triggerPrice: String?499 public let reduceOnly: Bool500 public let tif: DerivTimeInForce501 /** Leverage setting of this instrument on the paper account. Nil keeps the account's current setting; nothing is assumed here. */502 public let leverage: String?503 public let slippageBps: Int?504505 public init(instrument: String, side: DerivOrderSide, type: DerivOrderType, size: String, price: String?, triggerPrice: String?, reduceOnly: Bool, tif: DerivTimeInForce, leverage: String?, slippageBps: Int?) {506 self.instrument = instrument; self.side = side; self.type = type; self.size = size; self.price = price; self.triggerPrice = triggerPrice507 self.reduceOnly = reduceOnly; self.tif = tif; self.leverage = leverage; self.slippageBps = slippageBps508 }509 private enum Keys: String, CodingKey { case instrument, side, type, size, price, triggerPrice, reduceOnly, tif, leverage, slippageBps }510 public func encode(to encoder: Encoder) throws {511 var c = encoder.container(keyedBy: Keys.self)512 try c.encode(instrument, forKey: .instrument); try c.encode(side, forKey: .side); try c.encode(type, forKey: .type); try c.encode(size, forKey: .size)513 if let price { try c.encode(price, forKey: .price) } else { try c.encodeNil(forKey: .price) }514 if let triggerPrice { try c.encode(triggerPrice, forKey: .triggerPrice) } else { try c.encodeNil(forKey: .triggerPrice) }515 try c.encode(reduceOnly, forKey: .reduceOnly); try c.encode(tif, forKey: .tif)516 try c.encodeIfPresent(leverage, forKey: .leverage); try c.encodeIfPresent(slippageBps, forKey: .slippageBps)517 }518}519520/** The order as the engines take it (`OrderRequest`), returned by a preview. */521public struct DerivOrderRequestEcho: Codable, Sendable, Hashable {522 public let instrument: String523 public let side: String524 public let type: String525 public let size: String526 public let price: String?527 public let triggerPrice: String?528 public let reduceOnly: Bool529 public let tif: String530 public let clientId: String?531}532533/** What the paper engine would do. Everything here is `source: estimate`. */534public struct PaperOrderEstimate: Codable, Sendable, Hashable {535 public let notional: String536 public let initialMargin: String537 public let fee: String538 public let avgFillPrice: String?539 public let slippageBps: String?540 /** An ESTIMATE of the paper engine with its method — not a venue figure. */541 public let liquidationPrice: DerivEstimatedValue?542 public let freeCollateralAfter: String543 public let filledSize: String?544 public let restingSize: String?545 public let status: String?546 public let rejectReason: String?547 public let leverage: String?548 public let price: String?549 public let source: String?550}551552public struct PaperOrderPreview: Codable, Sendable, Hashable {553 public let risk: DerivRiskVerdict554 public let estimate: PaperOrderEstimate?555 public let request: DerivOrderRequestEcho?556 public let ts: Date?557}558559/** A placed paper order. A paper-engine rejection is `order.status == "rejected"` with `order.rejectReason`. */560public struct PaperPlacement: Codable, Sendable, Hashable {561 public let order: DerivOrder562 public let fills: [DerivFill]?563 public let idempotent: Bool?564 /** Close only: the worst price the server derived and the bound it used. */565 public let worstPrice: String?566 public let slippageBoundBps: Int?567}568569public struct PaperCancelAnswer: Codable, Sendable, Hashable { public let order: DerivOrder }570571// MARK: router (simulation only)572573public struct DerivRouteAsset: Codable, Sendable, Hashable {574 public struct Venue: Codable, Sendable, Hashable { public let venue: String; public let name: String; public let instruments: [String]; public let restriction: String? }575 public let base: String576 public let venues: [Venue]577 public let candidateVenues: Int578}579580public struct DerivRouteAssetsAnswer: Codable, Sendable, Hashable {581 public let assets: [DerivRouteAsset]582 public let errors: [DerivVenueReadError]?583 public let ts: Date?584}585586/** `OrderIntentSchema` of packages/derivatives/src/router.ts + the accounts whose policy is asked. Nothing is placed by the router. */587public struct DerivRouteRequest: Encodable, Sendable {588 public let base: String589 /** Side of the EXPOSURE: `long` or `short`. */590 public let side: String591 /** Exactly one of `sizeBase` and `notionalUsd`. */592 public let sizeBase: String?593 public let notionalUsd: String?594 public let leverage: String595 /** `market` or `limit`. */596 public let type: String597 public let price: String?598 public let reduceOnly: Bool599 public let horizonHours: String600 public let accountIds: [String]601 public init(base: String, side: String, sizeBase: String?, notionalUsd: String?, leverage: String, type: String, price: String?, reduceOnly: Bool, horizonHours: String, accountIds: [String]) {602 self.base = base; self.side = side; self.sizeBase = sizeBase; self.notionalUsd = notionalUsd; self.leverage = leverage; self.type = type; self.price = price603 self.reduceOnly = reduceOnly; self.horizonHours = horizonHours; self.accountIds = accountIds604 }605 private enum Keys: String, CodingKey { case base, side, sizeBase, notionalUsd, leverage, type, price, reduceOnly, horizonHours, accountIds }606 public func encode(to encoder: Encoder) throws {607 var c = encoder.container(keyedBy: Keys.self)608 try c.encode(base, forKey: .base); try c.encode(side, forKey: .side); try c.encodeIfPresent(sizeBase, forKey: .sizeBase); try c.encodeIfPresent(notionalUsd, forKey: .notionalUsd)609 try c.encode(leverage, forKey: .leverage); try c.encode(type, forKey: .type)610 if let price { try c.encode(price, forKey: .price) } else { try c.encodeNil(forKey: .price) }611 try c.encode(reduceOnly, forKey: .reduceOnly); try c.encode(horizonHours, forKey: .horizonHours); try c.encode(accountIds, forKey: .accountIds)612 }613}614615public struct DerivRouteReason: Codable, Sendable, Hashable { public let code: String; public let kind: String; public let message: String }616617public struct DerivRoutePolicyCheck: Codable, Sendable, Hashable {618 public let accountId: String619 public let label: String620 public let kind: String621 public let mode: String622 public let network: String623 /** Nil: the policy was not asked (the reason says why). */624 public let accepted: Bool?625 public let code: String?626 public let reason: String?627 public let source: String628}629630/** One candidate of the router (`ExecutionEstimate` + its risk part). Every figure is an estimate; the full object is kept in `raw`. */631public struct DerivRouteCandidate: Decodable, Sendable {632 public struct Eligibility: Codable, Sendable, Hashable { public let eligible: Bool; public let executableNow: Bool; public let executableAs: String?; public let reasons: [DerivRouteReason] }633 public struct VenueLimits: Codable, Sendable, Hashable { public let accepted: Bool; public let codes: [String]; public let note: String }634 public struct Risk: Codable, Sendable, Hashable { public let venue: VenueLimits; public let accounts: [DerivRoutePolicyCheck] }635 public let venue: String636 public let venueName: String?637 public let instrument: String638 public let symbol: String?639 public let eligibility: Eligibility640 public let risk: Risk?641 /** Costs, fill simulation, margin estimate, contract terms: as served (packages/derivatives/src/router.ts `ExecutionEstimate`). */642 public let raw: JSONValue643 private enum Keys: String, CodingKey { case venue, venueName, instrument, symbol, eligibility, risk }644 public init(from decoder: Decoder) throws {645 raw = try JSONValue(from: decoder)646 let c = try decoder.container(keyedBy: Keys.self)647 venue = try c.decode(String.self, forKey: .venue); venueName = try c.decodeIfPresent(String.self, forKey: .venueName)648 instrument = try c.decode(String.self, forKey: .instrument); symbol = try c.decodeIfPresent(String.self, forKey: .symbol)649 eligibility = try c.decode(Eligibility.self, forKey: .eligibility); risk = try c.decodeIfPresent(Risk.self, forKey: .risk)650 }651}652653public struct DerivRouteRankingRow: Codable, Sendable, Hashable {654 public let rank: Int655 public let instrument: String656 public let venue: String657 public let allInUsd: String658 public let allInBps: String659 public let uncertaintyUsd: String660 public let complete: Bool661 public let executableNow: Bool662 public let tiedWith: [String]?663 public let nearTieWith: [String]?664 public let roundTripUsd: String?665 public let roundTripRank: Int?666}667668public struct DerivRouteRanking: Codable, Sendable, Hashable {669 public struct Excluded: Codable, Sendable, Hashable { public let instrument: String; public let venue: String; public let reasons: [String] }670 public let rows: [DerivRouteRankingRow]671 public let basis: String?672 public let note: String?673 public let orderChangesWithExit: Bool?674 public let excluded: [Excluded]?675}676677/** `POST /derivatives/route`: a comparison in simulation. The ranking is information, never a selection. */678public struct DerivRouteAnswer: Decodable, Sendable {679 public let intent: JSONValue?680 public let candidates: [DerivRouteCandidate]681 public let ranking: DerivRouteRanking?682 public let differences: JSONValue?683 public let warnings: [String]?684 public let errors: [DerivVenueReadError]?685 public let chain: JSONValue?686 public let ts: Date?687 public let source: String?688}689690// MARK: server-sent events (market stream, live account stream)691692/** One event of `GET /derivatives/stream` or `GET /derivatives/live/accounts/:id/stream`, decoded from its `event:` and `data:` lines. */693public enum DerivStreamEvent: Sendable {694 case status(JSONValue)695 case ticker(DerivTicker)696 case book(DerivBook)697 case trades(instrument: String?, trades: [DerivPublicTrade])698 /** Live stream: the venue state after a reconciliation. */699 case account(JSONValue)700 case order(LiveOrder)701 case action(LiveAction)702 case risk(JSONValue)703 case error(message: String)704 case unknown(event: String, data: JSONValue)705706 public static func parse(event: String, data: Data) throws -> DerivStreamEvent {707 let d = APICoding.decoder(), json = try d.decode(JSONValue.self, from: data)708 switch event {709 case "status": return .status(json)710 case "ticker": return .ticker(try d.decode(DerivTicker.self, from: data))711 case "book": return .book(try d.decode(DerivBook.self, from: data))712 case "trades": return .trades(instrument: json["instrument"]?.stringValue, trades: try (json["trades"] ?? .array([])).decode([DerivPublicTrade].self))713 case "account": return .account(json)714 case "order": return .order(try d.decode(LiveOrder.self, from: data))715 case "action": return .action(try d.decode(LiveAction.self, from: data))716 case "risk": return .risk(json)717 case "error": return .error(message: json["message"]?.stringValue ?? "error")718 default: return .unknown(event: event, data: json)719 }720 }721}722723// MARK: refusals724725/**726 A refusal of the server, kept as its machine code and its own sentence so that the screen shows it verbatim: a risk limit, a727 server lock that is off, a jurisdiction restriction, a halt, an expired authorization, a signer or venue refusal.728 */729public struct DerivativesRefusal: Error, Sendable, Equatable, LocalizedError {730 public enum Kind: String, Sendable {731 /** One of the risk engine's codes (packages/derivatives/src/risk.ts `RISK_CODES`, or `risk_<code>` on GMX, `risk_denied`). */732 case risk733 /** A server setting keeps the feature closed: `mainnet_disabled` (SPW_DERIV_LIVE_MAINNET), `mandate_mainnet_disabled` (SPW_DERIV_MANDATE_MAINNET), `gmx_disabled` (SPW_DERIV_GMX_LIVE), `mandate_unavailable`. */734 case lock735 /** `halted`, `kill_switch_active`, `read_only_mode`: new risk is stopped. */736 case halted737 /** `venue_restricted`: the venue's terms exclude the owner's jurisdiction; market data only. */738 case jurisdiction739 /** The account or the authorization does not allow it: `mode_read_only`, `authorization_expired`, `not_authorized`, `passkey_required`, mandate states. */740 case authorization741 /** The isolated signer refused (`signer_*`). */742 case signer743 /** The venue or the chain: unreachable, stale, or it refused the request. */744 case venue745 /** The approval window closed: prepare again. */746 case expired747 case other748 }749 public let code: String750 public let reason: String751 public let status: Int752 public var kind: Kind { Self.kind(of: code) }753 public var errorDescription: String? { reason.isEmpty ? code : reason }754755 public init(code: String, reason: String, status: Int) { self.code = code; self.reason = reason; self.status = status }756757 /** The refusal carried by an API error; nil for a transport failure, a lost session or an answer that could not be read. */758 public init?(_ error: Error) {759 guard let e = error as? APIError, e.status >= 400, !e.isUnauthenticated else { return nil }760 self.init(code: e.code, reason: e.message == "error" ? "" : e.message, status: e.status)761 }762763 public static let riskCodes: Set<String> = [764 "bad_policy", "bad_order", "bad_input", "mode_read_only", "halted", "instrument_mismatch", "instrument_not_allowed", "instrument_halted", "instrument_reduce_only",765 "data_mismatch", "stale_ticker", "stale_book", "price_required", "trigger_required", "bad_mark", "price_deviation", "mark_index_divergence", "price_not_on_tick",766 "size_not_on_lot", "below_min_size", "below_min_notional", "reduce_only_would_increase", "reduce_only_would_flip", "leverage_exceeded", "order_notional_exceeded",767 "gross_exposure_exceeded", "position_notional_exceeded", "insufficient_collateral", "liquidation_too_close", "daily_loss_exceeded", "total_loss_exceeded",768 "order_rate_minute", "order_rate_day", "duplicate_client_id",769 ]770771 static func kind(of code: String) -> Kind {772 switch code {773 case "mainnet_disabled", "mandate_mainnet_disabled", "gmx_disabled", "mandate_unavailable", "gmx_setting_off", "mainnet_setting_off": return .lock774 case "halted", "kill_switch_active", "read_only_mode", "gmx_halted", "signer_halted": return .halted775 case "venue_restricted": return .jurisdiction776 case "mode_read_only", "authorization_expired", "authorization_revoked", "not_authorized", "passkey_required", "passkey_unavailable", "bad_approval", "authorization_orphaned",777 "authorization_unknown", "mandate_none", "mandate_mismatch", "mandate_wind_down", "mandate_floor_equity", "contracts_changed": return .authorization778 case "proposal_expired", "expired": return .expired779 case "venue_unavailable", "venue_rate_limited", "venue_rejected", "venue_timeout", "venue_unreadable", "stale_data", "no_liquidity", "asset_table_mismatch", "contract_changed",780 "bridge_paused", "route_not_proven", "chain_unreadable", "rpc_degraded", "venue_policy": return .venue781 case "risk_denied": return .risk782 default:783 if code.hasPrefix("signer_") { return .signer }784 if riskCodes.contains(code) || (code.hasPrefix("risk_") && riskCodes.contains(String(code.dropFirst(5)))) { return .risk }785 return .other786 }787 }788}789