Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/OrdersModels.swift3// Description: The unified orders of V11 as the owner's session reads them under /api/v1/trading (services/api/src/trading-api/4// spec.ts `OrderRow`, `R.preview`, `R.placed`, `R.cancelled`, `R.command`; services/api/src/orders/service.ts `view`):5// the twelve states of the single state machine (packages/trading/src/orders/state.ts), orders, fills, transitions,6// positions, the preview with every check, and the canonical order `SPW-ORDER-INTENT-v1` whose hash names an order.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import CryptoKit1213/**14 The unified order state machine:15 CREATED → VALIDATED → AWAITING_APPROVAL → APPROVED → SUBMITTING → SUBMITTED → PARTIALLY_FILLED → FILLED, with16 SUBMITTING → UNKNOWN → (reconciliation). Terminal: FILLED, CANCELLED, REJECTED, FAILED.17 `unknown` is a REAL state of the server ("the outcome at the venue is not known yet"): not final, not a failure.18 A state this version has never heard of is `unrecognized` and is shown verbatim — also not final, not a failure, not a success.19 */20public enum OrderState: Sendable, Hashable, Codable {21 case created, validated, awaitingApproval, approved, submitting, submitted, partiallyFilled, filled, cancelled, rejected, failed, unknown22 case unrecognized(String)2324 public static let all: [OrderState] = [.created, .validated, .awaitingApproval, .approved, .submitting, .submitted, .partiallyFilled, .filled, .cancelled, .rejected, .failed, .unknown]25 private static let names: [(OrderState, String)] = [(.created, "CREATED"), (.validated, "VALIDATED"), (.awaitingApproval, "AWAITING_APPROVAL"), (.approved, "APPROVED"), (.submitting, "SUBMITTING"),26 (.submitted, "SUBMITTED"), (.partiallyFilled, "PARTIALLY_FILLED"), (.filled, "FILLED"), (.cancelled, "CANCELLED"), (.rejected, "REJECTED"),27 (.failed, "FAILED"), (.unknown, "UNKNOWN")]28 public init(rawValue: String) { self = Self.names.first { $0.1 == rawValue }?.0 ?? .unrecognized(rawValue) }29 public var rawValue: String { if case .unrecognized(let s) = self { return s }; return Self.names.first { $0.0 == self }!.1 }30 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }31 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }3233 /** FILLED, CANCELLED, REJECTED, FAILED: no outgoing transition. */34 public var isTerminal: Bool { [.filled, .cancelled, .rejected, .failed].contains(self) }35 /** Only FILLED is a success. SUBMITTED and PARTIALLY_FILLED are not. */36 public var isSuccess: Bool { self == .filled }37 /** REJECTED (a refusal with a business cause) or FAILED (a technical failure after which it is proven that no order exists). */38 public var isFailure: Bool { self == .rejected || self == .failed }39 /** The venue may hold (or may have held) the order. */40 public var isAtVenue: Bool { [.submitting, .submitted, .partiallyFilled, .unknown].contains(self) }41 /** The order waits for the owner's passkey in the venue's own approval flow. */42 public var awaitsOwner: Bool { self == .awaitingApproval }43 /** The outcome is being verified with the venue: keep reading; never present it as done or as failed. */44 public var isBeingVerified: Bool { if case .unrecognized = self { return true }; return self == .unknown }45}4647/** One order, whatever placed it (the app, an API key, an agent) and wherever (paper, a venue, GMX, a spot swap). Sizes and prices are decimal strings. */48public struct UnifiedOrder: Codable, Sendable, Hashable, Identifiable {49 /** the id every order operation takes */50 public let id: String51 public let orderId: String?52 /** `paper` or `live`: never merged in one figure */53 public let mode: String54 public let venue: String55 public let network: String56 public let accountId: String?57 public let instrument: String?58 public let side: String?59 public let type: String60 public let status: OrderState61 /** the executing engine's own word for the same moment; informative — decide on `status` */62 public let engineStatus: String?63 /** the server's statement that `status` is terminal; nil when it does not say */64 public let final: Bool?65 public let size: String?66 public let price: String?67 public let triggerPrice: String?68 public let reduceOnly: Bool?69 public let tif: String?70 /** cumulative filled size, base units */71 public let filled: String?72 public let avgFillPrice: String?73 /** closed reason code of the current state (REASON_CODES of the state machine), verbatim */74 public let reasonCode: String?75 /** the sentence for people, verbatim */76 public let reason: String?77 /** API error code of the refusal, when the order was refused */78 public let rejectCode: String?79 public let clientId: String?80 public let clientOrderId: String?81 public let venueOrderId: String?82 public let origin: String?83 public let principal: RiskActor?84 public let mandateId: String?85 public let engine: String?86 /** hash of the canonical order (hex) */87 public let hash: String?88 public let notionalUsd: String?89 /** unix ms */90 public let createdAt: Int91 public let updatedAt: Int92 /** detail only: the canonical order as stored */93 public let canonical: JSONValue?94 /** spot orders: the steps of the swap and what it gives and takes */95 public let execution: JSONValue?96 public let spot: JSONValue?9798 /** Terminal by the state machine. When the server's `final` disagrees with the state, the order is NOT treated as terminal. */99 public var isFinal: Bool { status.isTerminal && final != false }100 public var isOpen: Bool { !isFinal }101 public var created: Date { Date(timeIntervalSince1970: TimeInterval(createdAt) / 1000) }102 public var updated: Date { Date(timeIntervalSince1970: TimeInterval(updatedAt) / 1000) }103}104105public struct OrderFill: Codable, Sendable, Hashable, Identifiable {106 public let id: String107 public let instrument: String?108 public let side: String?109 public let price: String110 public let size: String111 public let fee: String?112 public let feeAsset: String?113 public let closedPnl: String?114 public let liquidation: Bool?115 public let ts: Int116}117118/** One transition of an order, oldest first in a history. `reason` is a member of the closed reason codes; `detail` is free text. */119public struct OrderTransition: Codable, Sendable, Hashable {120 public let seq: Int121 public let from: OrderState122 public let to: OrderState123 public let event: String124 public let reason: String125 public let detail: String?126 public let at: Int127}128129public struct OrderDetail: Decodable, Sendable, Equatable {130 public let order: UnifiedOrder131 public let fills: [OrderFill]132 /** absent for `agent:` rows */133 public let history: [OrderTransition]?134}135136public struct OrderPage: Decodable, Sendable, Equatable {137 public let orders: [UnifiedOrder]138 /** pass it as `cursor` with the same filters to read the next (older) page; nil at the end */139 public let nextCursor: String?140 public let ts: Int141}142143public struct OrderFilter: Sendable, Equatable {144 public var mode: RiskMode?145 public var venue: String?146 /** true: only orders that are not final; false: only final orders; nil: all */147 public var open: Bool?148 public var limit: Int149 public var cursor: String?150 public init(mode: RiskMode? = nil, venue: String? = nil, open: Bool? = nil, limit: Int = 100, cursor: String? = nil) { self.mode = mode; self.venue = venue; self.open = open; self.limit = limit; self.cursor = cursor }151}152153public struct UnifiedPosition: Codable, Sendable, Hashable, Identifiable {154 /** what close / reduce take; it contains colons */155 public let id: String156 public let mode: String157 public let venue: String158 public let accountId: String159 public let instrument: String?160 public let side: String161 public let size: String162 public let entryPrice: String163 public let markPrice: String?164 public let unrealizedPnl: String?165 public let source: String?166}167public struct SourceError: Codable, Sendable, Hashable { public let source: String; public let message: String }168public struct PositionList: Decodable, Sendable, Equatable {169 public let positions: [UnifiedPosition]170 /** sources that could not be read: the list is then partial, and the screen says so */171 public let errors: [SourceError]172 public let ts: Int173}174175/** POST /trading/orders and /orders/preview (`OrderRequestSchema`). Exactly one of `size` and `notional`. */176public struct OrderRequest: Encodable, Sendable, Equatable {177 public enum Quantity: Sendable, Equatable {178 /** quantity of the base asset */179 case size(String)180 /** value in the quote currency; the SERVER turns it into a size and answers the size it used */181 case notional(String)182 }183 public let mode: RiskMode184 public let accountId: String?185 /** `venue:symbol` */186 public let instrument: String187 /** `buy` or `sell` */188 public let side: String189 /** `limit`, `market`, `stop_market`, `stop_limit`, `take_profit_market`, `take_profit_limit` */190 public let type: String191 public let size: String?192 public let notional: String?193 public let price: String?194 public let triggerPrice: String?195 public let reduceOnly: Bool196 /** `gtc`, `ioc`, `alo` */197 public let tif: String198 public let slippageBps: Int?199 /** paper only */200 public let leverage: String?201 public let maxFeeUsd: String?202203 public init(mode: RiskMode, accountId: String?, instrument: String, side: String, type: String, quantity: Quantity, price: String? = nil, triggerPrice: String? = nil,204 reduceOnly: Bool, tif: String, slippageBps: Int? = nil, leverage: String? = nil, maxFeeUsd: String? = nil) {205 self.mode = mode; self.accountId = accountId; self.instrument = instrument; self.side = side; self.type = type206 switch quantity { case .size(let s): size = s; notional = nil; case .notional(let n): size = nil; notional = n }207 self.price = price; self.triggerPrice = triggerPrice; self.reduceOnly = reduceOnly; self.tif = tif; self.slippageBps = slippageBps; self.leverage = leverage; self.maxFeeUsd = maxFeeUsd208 }209}210211/**212 The canonical order `SPW-ORDER-INTENT-v1` (packages/trading/src/orders/canonical.ts): what is hashed, checked by the mandate and213 by the risk engine, and handed to the engine. Its hash IDENTIFIES an order; it is never a passkey challenge (a live order is214 approved in the venue's own flow), so this type deliberately does not conform to `PasskeyApprovable`.215 */216public struct CanonicalOrder: Decodable, Sendable, Equatable {217 public static let domain = "SPW-ORDER-INTENT-v1"218 public let v: Int219 public let venue, network, instrument, marketKind, side, type: String220 public let size, notional, limitPrice, triggerPrice: String?221 public let reduceOnly: Bool222 public let tif: String223 public let maxSlippageBps: Int224 public let maxFeeUsd: String225 public let leverage: String?226 public let marginMode: String?227 public let clientOrderId: String228 public let mode: String229 public let principal: RiskActor230 public let mandateId: String?231 public let createdAt, expiresAt: Int232233 public func canonicalBytes() throws -> Data {234 guard v == 1 else { throw ApprovalError.unsupported("canonical order version \(v)") }235 func d(_ x: String?) throws -> String { try x.map(ExecutionDecimal.canon) ?? "" }236 var w = CanonicalWriter(domain: Self.domain)237 w.field("v", "1"); w.field("venue", venue); w.field("network", network); w.field("instrument", instrument); w.field("marketKind", marketKind); w.field("side", side); w.field("type", type)238 w.field("size", try d(size)); w.field("notional", try d(notional)); w.field("limitPrice", try d(limitPrice)); w.field("triggerPrice", try d(triggerPrice))239 w.field("reduceOnly", reduceOnly); w.field("tif", tif); w.field("maxSlippageBps", maxSlippageBps); w.field("maxFeeUsd", try ExecutionDecimal.canon(maxFeeUsd))240 w.field("leverage", try d(leverage)); w.field("marginMode", marginMode ?? "")241 w.field("mode", mode); w.field("principal.kind", principal.kind); w.field("principal.id", principal.id); w.field("mandateId", mandateId ?? "")242 w.field("clientOrderId", clientOrderId); w.field("createdAt", createdAt); w.field("expiresAt", expiresAt)243 return w.data244 }245 public func hashHex() throws -> String { Data(SHA256.hash(data: try canonicalBytes())).hex }246}247248/** What a preview says would stop the order, stage by stage. Messages are the server's, verbatim. */249public struct OrderPreviewRefusal: Codable, Sendable, Hashable {250 /** `key`, `lock`, `mandate`, `risk`, `engine` */251 public let stage: String252 public let code: String253 public let message: String254 public let reasons: [String]?255}256257/** POST /trading/orders/preview: the order as it would be placed, every check it would meet, and an ESTIMATE. Nothing is created. */258public struct OrderPreview: Decodable, Sendable, Equatable {259 public struct Resolved: Decodable, Sendable, Equatable { public let size: String?; public let worstPrice: String?; public let notionalUsd: String? }260 public struct Approval: Decodable, Sendable, Equatable {261 public let required: Bool262 /** `owner_passkey`, `mandate`, `none` */263 public let by: String264 public let note: String?265 }266 public struct Risk: Decodable, Sendable, Equatable {267 public let decision: String268 public let reducing: Bool269 public let checks: [RiskCheck]270 public let derived: JSONValue?271 public var failures: [RiskCheckFailure] { checks.filter { $0.exempt != true }.compactMap(\.failure) }272 }273 public struct Mandate: Decodable, Sendable, Equatable { public let id: String; public let decision: String; public let reasons: [String] }274 public struct Engine: Decodable, Sendable, Equatable { public let name: String; public let risk: JSONValue?; public let estimate: JSONValue? }275 public struct Account: Decodable, Sendable, Equatable { public let id: String?; public let venue: String; public let network: String; public let equity: String?; public let freeCollateral: String?; public let withheld: Bool? }276277 public let order: CanonicalOrder278 /** SHA-256 of the canonical bytes of `order` (hex) — recomputed and compared by `OrdersAPI.preview` */279 public let hash: String280 public let resolved: Resolved?281 /** the server's statement; true exactly when `refusals` is empty */282 public let wouldExecute: Bool283 public let refusals: [OrderPreviewRefusal]284 public let approval: Approval285 public let risk: Risk286 public let mandate: Mandate?287 public let engine: Engine288 public let account: Account289 public let ts: Int290}291292/** Where the owner approves an order that waits AWAITING_APPROVAL: the venue engine's own route (derivatives domain), with the passkey. */293public struct OrderApprovalPointer: Decodable, Sendable, Equatable {294 public struct Route: Decodable, Sendable, Equatable { public let method: String; public let path: String }295 public let by: String?296 public let engine: String?297 public let accountId: String?298 public let clientId: String?299 public let hash: String?300 public let expiresAt: Int?301 public let approve: Route?302}303304/**305 POST /trading/orders, /positions/:id/close, /positions/:id/reduce. The answer of the call is NOT a fill and not even a306 submission: read `order.status`. A live owner order comes back AWAITING_APPROVAL with `approval` — nothing is signed until the307 owner approves it with the passkey in the venue's flow.308 */309public struct PlacedOrder: Decodable, Sendable, Equatable {310 public let order: UnifiedOrder311 /** true: this Idempotency-Key already placed this order; nothing was sent again */312 public let idempotent: Bool?313 public let approval: OrderApprovalPointer?314}315316public struct CancelledOrder: Decodable, Sendable, Equatable {317 public let order: UnifiedOrder318 /** true: a cancel request went to a venue (the order is cancelled only when its status says so) */319 public let sent: Bool320 /** false: the order was already final */321 public let changed: Bool322 public let approval: JSONValue?323}324325/** POST /trading/commands: one line of the command grammar. Four shapes, told apart by `kind` and `executed`; kept as served. */326public struct CommandAnswer: Decodable, Sendable, Equatable {327 /** `query`, `control`, `order` */328 public let kind: String329 public let command: String330 public let mode: String331 public let dryRun: Bool332 public let executed: Bool?333 /** dry run of an order command: the canonical order it resolves to */334 public let canonicalOrder: CanonicalOrder?335 /** executed order command: the order that was placed */336 public let placedOrder: UnifiedOrder?337 public let hash: String?338 public let idempotent: Bool?339 /** the whole answer, for the shapes this version does not model (query data, control results, attached protections) */340 public let raw: JSONValue341342 public init(from decoder: Decoder) throws {343 let j = try JSONValue(from: decoder)344 guard let kind = j["kind"]?.stringValue, let command = j["command"]?.stringValue, let mode = j["mode"]?.stringValue, let dryRun = j["dryRun"]?.boolValue else {345 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "command answer without kind, command, mode or dryRun"))346 }347 self.kind = kind; self.command = command; self.mode = mode; self.dryRun = dryRun; executed = j["executed"]?.boolValue348 hash = j["hash"]?.stringValue; idempotent = j["idempotent"]?.boolValue; raw = j349 if kind == "order", executed == true { placedOrder = try j["order"]?.decode(UnifiedOrder.self); canonicalOrder = try j["canonical"]?.decode(CanonicalOrder.self) }350 else if kind == "order" { canonicalOrder = try j["order"]?.decode(CanonicalOrder.self); placedOrder = nil }351 else { canonicalOrder = nil; placedOrder = nil }352 }353}354355/** The owner's defaults of the command line and of spot orders (`CommandDefaultsSchema`). Absent members are absent. */356public struct CommandDefaults: Codable, Sendable, Equatable {357 public var spotNetwork: String?358 public var spotVenueByNetwork: [String: String]?359 public var spotQuote: String?360 public var usdQuotes: [String]?361 public var perpVenue: String?362 public var perpNetworkByVenue: [String: String]?363 public var perpLeverage: String?364 public var perpMarginMode: String?365 public var maxFeeBps: Int?366 public var maxSlippageBps: Int?367 public var orderTtlMs: Int?368 public init() {}369}370371/** GET /trading/risk: what can stop an order, in one read. `engine` are the global switches; `signer` is the signer's emergency halt (another thing). */372public struct TradingRiskOverview: Decodable, Sendable, Equatable {373 public struct SignerHalt: Decodable, Sendable, Equatable { public let signerReachable: Bool; public let signerHalted: Bool?; public let note: String? }374 public struct Engine: Decodable, Sendable, Equatable { public let killSwitch: RiskSwitch; public let readOnly: RiskSwitch; public let note: String? }375 public struct Account: Decodable, Sendable, Equatable { public let mode: String; public let venue: String; public let accountId: String; public let policy: JSONValue?; public let halted: Bool? }376 public let signer: SignerHalt377 public let signerPolicy: JSONValue?378 public let capabilityLocks: [ExecutionLock]379 public let accounts: [Account]380 public let errors: [SourceError]381 public let ts: Int382 public let engine: Engine383 enum CodingKeys: String, CodingKey { case signer = "killSwitch", signerPolicy, capabilityLocks, accounts, errors, ts, engine }384}385