SPB Git

Repository Public

OrdersAPI.swift 9.2 KB 124 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/OrdersAPI.swift3// Description: The unified execution layer through the OWNER SESSION (cookie): the operations of /api/v1/trading that the web4//              Trade screen uses (apps/web/src/trade.ts) — orders, positions, preview, place, cancel, close, reduce, the command5//              line, the risk overview — and the owner's command defaults. There is no /api/v1/orders route: the owner and the API6//              keys share /api/v1/trading, told apart by the credential. Placing never signs: a live owner order waits7//              AWAITING_APPROVAL for the passkey in the venue's own flow (derivatives domain); a spot order becomes a swap proposal.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213public struct OrdersAPI: Sendable {14    let client: APIClient15    public init(_ client: APIClient) { self.client = client }1617    // MARK: reads1819    /** Every order of the wallet, newest first, in one stable order; keyset pagination (`nextCursor`). */20    public func orders(_ f: OrderFilter = OrderFilter()) async throws -> OrderPage {21        try await client.get("/trading/orders", query: ["mode": f.mode?.rawValue, "venue": f.venue, "open": f.open.map { $0 ? "true" : "false" }, "limit": String(min(max(f.limit, 1), 500)), "cursor": f.cursor])22    }2324    /** One order, its fills and every transition it went through. Poll it until `order.isFinal`; UNKNOWN is not final — keep reading. */25    public func order(_ id: String) async throws -> OrderDetail { try await client.get("/trading/orders/\(APIClient.segment(id))") }2627    public func positions(mode: RiskMode? = nil, venue: String? = nil) async throws -> PositionList {28        try await client.get("/trading/positions", query: ["mode": mode?.rawValue, "venue": venue])29    }3031    public func riskOverview() async throws -> TradingRiskOverview { try await client.get("/trading/risk") }3233    // MARK: orders3435    /**36     Every check the order would meet, and an estimate; nothing is created. The canonical order of the answer is compared with37     the request (mode, instrument, side, quantity, prices, reduce-only) and its hash is recomputed: what the screen shows under38     "this is the order" is then the order the hash names.39     */40    public func preview(_ r: OrderRequest, idempotencyKey: String) async throws -> OrderPreview {41        let p: OrderPreview = try await client.post("/trading/orders/preview", body: r, idempotencyKey: idempotencyKey)42        try Self.check(preview: p, against: r)43        return p44    }4546    /**47     Place an order. The key makes the call safe to repeat: the same key answers the same order (`idempotent: true`) and sends48     nothing again; after a lost answer REPEAT WITH THE SAME KEY, never with a new one. A refusal is an `APIError` whose detail49     `ExecutionRefusal` reads (risk checks, mandate reasons, the rejected order).50     */51    public func place(_ r: OrderRequest, idempotencyKey: String) async throws -> PlacedOrder {52        let p: PlacedOrder = try await client.post("/trading/orders", body: r, idempotencyKey: idempotencyKey)53        try Self.check(order: p.order, against: r)54        return p55    }5657    /** Ask for a cancel. `sent` says a request went to the venue; the order is cancelled only when its status says CANCELLED. */58    public func cancel(orderId: String, idempotencyKey: String) async throws -> CancelledOrder {59        try await client.send(.delete, "/trading/orders/\(APIClient.segment(orderId))", body: EmptyBody(), idempotencyKey: idempotencyKey)60    }6162    /** Close a position with a reduce-only market order (bounded by `slippageBps` when given). */63    public func closePosition(id: String, slippageBps: Int? = nil, idempotencyKey: String) async throws -> PlacedOrder {64        struct Body: Encodable, Sendable { let slippageBps: Int? }65        return try await client.post("/trading/positions/\(APIClient.segment(id))/close", body: Body(slippageBps: slippageBps), idempotencyKey: idempotencyKey)66    }6768    /** Reduce a position by `fraction` in (0, 1], a decimal string. */69    public func reducePosition(id: String, fraction: String, slippageBps: Int? = nil, idempotencyKey: String) async throws -> PlacedOrder {70        struct Body: Encodable, Sendable { let fraction: String; let slippageBps: Int? }71        guard fraction.range(of: "^(0(\\.\\d+)?|1(\\.0+)?)$", options: .regularExpression) != nil, ExecutionDecimal.isPositive(fraction) else {72            throw APIError(status: 0, code: "invalid_order", message: "the fraction must be a decimal in (0, 1]")73        }74        return try await client.post("/trading/positions/\(APIClient.segment(id))/reduce", body: Body(fraction: fraction, slippageBps: slippageBps), idempotencyKey: idempotencyKey)75    }7677    /** One line of the command grammar. With `dryRun` the answer is what the line resolves to and nothing is done. */78    public func command(text: String, mode: RiskMode, accountId: String? = nil, dryRun: Bool, idempotencyKey: String) async throws -> CommandAnswer {79        struct Body: Encodable, Sendable { let text: String; let mode: RiskMode; let dryRun: Bool; let accountId: String? }80        let a: CommandAnswer = try await client.post("/trading/commands", body: Body(text: text, mode: mode, dryRun: dryRun, accountId: accountId), idempotencyKey: idempotencyKey)81        guard a.mode == mode.rawValue, a.dryRun == dryRun else { throw ApprovalError.inconsistent("the command was answered for another mode or another dry-run setting") }82        if dryRun, a.executed == true { throw ApprovalError.inconsistent("a dry run answered as executed") }83        return a84    }8586    // MARK: command defaults (owner only, /api/v1/developer)8788    private struct Defaults: Codable, Sendable { let defaults: CommandDefaults }89    public func commandDefaults() async throws -> CommandDefaults { try await client.get("/developer/command-defaults", as: Defaults.self).defaults }90    public func setCommandDefaults(_ d: CommandDefaults) async throws -> CommandDefaults { try await client.put("/developer/command-defaults", body: Defaults(defaults: d), as: Defaults.self).defaults }9192    // MARK: checks9394    /** The canonical type of a requested order type: `stop_market`/`stop_limit` → `stop`, `take_profit_*` → `take_profit`. */95    static func canonicalType(_ t: String) -> String { t.hasPrefix("stop") ? "stop" : t.hasPrefix("take_profit") ? "take_profit" : t }96    private static func sameInstrument(_ served: String, _ asked: String) -> Bool { served == asked || (!asked.contains(":") && served.hasSuffix(":" + asked)) }9798    public static func check(preview p: OrderPreview, against r: OrderRequest) throws {99        let o = p.order100        guard try o.hashHex() == p.hash else { throw ApprovalError.inconsistent("the hash stated is not the hash of the order shown") }101        guard o.mode == r.mode.rawValue else { throw ApprovalError.inconsistent("mode") }102        guard o.side == r.side else { throw ApprovalError.inconsistent("side") }103        guard o.reduceOnly == r.reduceOnly else { throw ApprovalError.inconsistent("reduce-only") }104        guard o.type == canonicalType(r.type) else { throw ApprovalError.inconsistent("order type") }105        // a spot order is resolved to the venue that will swap it (`spot:ETH` → e.g. `kyberswap:ETH-USDC`): the instrument is then the server's106        if !r.instrument.hasPrefix("spot:") { guard sameInstrument(o.instrument, r.instrument) else { throw ApprovalError.inconsistent("instrument") } }107        if let s = r.size, let os = o.size { guard ExecutionDecimal.equal(s, os) else { throw ApprovalError.inconsistent("size") } }108        if let price = r.price, r.type.hasSuffix("limit") { guard let lp = o.limitPrice, ExecutionDecimal.equal(lp, price) else { throw ApprovalError.inconsistent("limit price") } }109        if r.type == "market" { guard o.limitPrice == nil else { throw ApprovalError.inconsistent("a market order carries a limit price") } }110        if let t = r.triggerPrice { guard let ot = o.triggerPrice, ExecutionDecimal.equal(ot, t) else { throw ApprovalError.inconsistent("trigger price") } }111        if let a = r.accountId, let pa = p.account.id { guard a.lowercased() == pa.lowercased() else { throw ApprovalError.inconsistent("account") } }112        guard p.wouldExecute == p.refusals.isEmpty else { throw ApprovalError.inconsistent("the preview says it would execute and lists refusals") }113    }114115    public static func check(order o: UnifiedOrder, against r: OrderRequest) throws {116        guard o.mode == r.mode.rawValue else { throw ApprovalError.inconsistent("mode") }117        if let side = o.side { guard side == r.side else { throw ApprovalError.inconsistent("side") } }118        if !r.instrument.hasPrefix("spot:"), let i = o.instrument { guard sameInstrument(i, r.instrument) else { throw ApprovalError.inconsistent("instrument") } }119        if let s = r.size, let os = o.size, !r.instrument.hasPrefix("spot:") { guard ExecutionDecimal.equal(s, os) else { throw ApprovalError.inconsistent("size") } }120        if let ro = o.reduceOnly { guard ro == r.reduceOnly else { throw ApprovalError.inconsistent("reduce-only") } }121        if let a = r.accountId, let oa = o.accountId { guard a.lowercased() == oa.lowercased() else { throw ApprovalError.inconsistent("account") } }122    }123}124
Files main
Menu

Theme