SPB Git

Repository Public

DerivativesAPI.swift 8.1 KB 131 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Derivatives/DerivativesAPI.swift3// Description: The read-only and paper routes of the derivatives module (services/api/src/derivatives/routes.ts, every route of4//              `derivativesRoutes`): venues, instruments, tickers, market, candles, funding, comparison, account watch, router5//              simulation, paper accounts. Nothing here can reach a venue's trading endpoint or the signer: live trading is6//              `DerivativesLiveAPI`, collateral `DerivativesCollateralAPI`, GMX `DerivativesGMXAPI`.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112public struct DerivativesAPI: Sendable {13    let client: APIClient14    public init(_ client: APIClient) { self.client = client }1516    private static let base = "/derivatives"17    private func paper(_ id: PaperAccountID) -> String { "\(Self.base)/accounts/\(APIClient.segment(id.rawValue))" }1819    // MARK: venues and market data2021    /** Venues with their capabilities, status and jurisdiction restriction (a restricted venue is market data only). */22    public func venues() async throws -> DerivVenuesAnswer { try await client.get("\(Self.base)/venues") }2324    /** All venues when `venue` is nil; a venue that cannot be read is in `errors`, the others are still listed. */25    public func instruments(venue: String? = nil, locale: String? = nil) async throws -> DerivInstrumentsAnswer {26        try await client.get("\(Self.base)/instruments", query: ["venue": venue, "locale": locale])27    }2829    public func tickers(venue: String? = nil) async throws -> DerivTickersAnswer { try await client.get("\(Self.base)/tickers", query: ["venue": venue]) }3031    /** Instrument (tick, lot, maximum leverage), ticker (mark, index, funding, open interest), book or GMX liquidity, recent trades. */32    public func market(instrument: String) async throws -> DerivMarket { try await client.get("\(Self.base)/market", query: ["instrument": instrument]) }3334    /** `limit`: 1…1000 bars. */35    public func candles(instrument: String, interval: DerivCandleInterval, limit: Int) async throws -> DerivCandlesAnswer {36        try await client.get("\(Self.base)/candles", query: ["instrument": instrument, "interval": interval.rawValue, "limit": String(limit)])37    }3839    /** Funding rates the venue applied over the last `hours` (1…480). */40    public func fundingHistory(instrument: String, hours: Int) async throws -> DerivFundingHistory {41        try await client.get("\(Self.base)/funding", query: ["instrument": instrument, "hours": String(hours)])42    }4344    /**45     Path and query of the server-sent events of one instrument (`status`, `ticker`, `book`, `trades`, `error`), below /api/v1.46     The API client has no event-stream transport yet: the apps open it with the session cookie (`APIClient.cookieHeader()`) and47     feed each event to `DerivStreamEvent.parse`.48     */49    public func marketStream(instrument: String) -> (path: String, query: [String: String]) { ("\(Self.base)/stream", ["instrument": instrument]) }5051    /** One row per instrument on `base` across the venues: facts and live figures, never a recommendation. */52    public func compare(base: String, locale: String? = nil) async throws -> DerivCompareAnswer {53        try await client.get("\(Self.base)/compare", query: ["base": base, "locale": locale])54    }5556    /** Read-only view of a public address on a venue that allows account reads (a restricted venue answers 403 `venue_restricted`). */57    public func watch(account: String, venue: String) async throws -> DerivWatch {58        try await client.get("\(Self.base)/watch", query: ["account": account, "venue": venue])59    }6061    // MARK: router — simulation only, nothing is placed6263    public func routeAssets() async throws -> DerivRouteAssetsAnswer { try await client.get("\(Self.base)/route/assets") }6465    public func route(_ request: DerivRouteRequest, locale: String? = nil) async throws -> DerivRouteAnswer {66        try await client.send(.post, "\(Self.base)/route", query: ["locale": locale], body: request)67    }6869    // MARK: paper accounts (simulated; no key, no venue, no real funds)7071    public func paperAccounts() async throws -> [PaperAccount] { try await client.get("\(Self.base)/accounts", as: PaperAccountsAnswer.self).accounts }7273    public func createPaperAccount(_ request: PaperAccountCreation) async throws -> PaperAccountDetail { try await client.post("\(Self.base)/accounts", body: request) }7475    public func paperAccount(_ id: PaperAccountID) async throws -> PaperAccountDetail { try await client.get(paper(id)) }7677    /** Replaces the whole risk policy of a paper account. */78    public func setPaperPolicy(_ id: PaperAccountID, policy: DerivRiskPolicy) async throws -> PaperAccountDetail { try await client.post("\(paper(id))/policy", body: policy) }7980    /** What the risk engine says and what the paper engine would do; nothing is stored. */81    public func previewPaperOrder(_ id: PaperAccountID, order: PaperOrderRequest) async throws -> PaperOrderPreview { try await client.post("\(paper(id))/orders/preview", body: order) }8283    /**84     Place a PAPER order. A risk refusal is HTTP 422 with the risk code (`DerivativesRefusal(error)`); a paper-engine rejection is85     an answered order with `status == "rejected"`. The key is the order's client id: a retry with the same key answers the same order.86     */87    public func placePaperOrder(_ id: PaperAccountID, order: PaperOrderRequest, idempotencyKey: String) async throws -> PaperPlacement {88        try await client.post("\(paper(id))/orders", body: order, idempotencyKey: idempotencyKey)89    }9091    public func cancelPaperOrder(_ id: PaperAccountID, clientId: String) async throws -> DerivOrder {92        try await client.post("\(paper(id))/orders/\(APIClient.segment(clientId))/cancel", as: PaperCancelAnswer.self).order93    }9495    /** A reduce-only market order on `fraction` (0 < f ≤ 1) of the paper position, bounded at `slippageBps` from the book. */96    public func closePaperPosition(_ id: PaperAccountID, instrument: String, fraction: String, slippageBps: Int, idempotencyKey: String) async throws -> PaperPlacement {97        struct Body: Encodable, Sendable { let instrument: String; let fraction: String; let slippageBps: Int }98        return try await client.post("\(paper(id))/close", body: Body(instrument: instrument, fraction: fraction, slippageBps: slippageBps), idempotencyKey: idempotencyKey)99    }100101    /** Back to the initial collateral: orders, fills, funding and equity history of the paper account are erased. */102    public func resetPaperAccount(_ id: PaperAccountID) async throws -> PaperAccountDetail { try await client.post("\(paper(id))/reset") }103}104105// MARK: shared by the approval flows of the live, collateral and GMX APIs106107enum DerivApproval {108    static func no(_ what: String) -> ApprovalError { .inconsistent(what) }109110    /** The hash the server displays must be the one recomputed here (the binding itself is `ApprovalBinding.verify`). */111    static func requireHash<T: PasskeyApprovable>(_ served: String?, of object: T) throws {112        guard let served else { return }113        guard served.lowercased() == (try object.approvalDigest()).hex else { throw no("hash") }114    }115116    static func sameAddress(_ a: String, _ b: String) -> Bool { a.lowercased() == b.lowercased() }117118    /** The acknowledgement displayed is the one the approved object commits to: same hash, and the hash of that very text. */119    static func requireAck(_ ack: JurisdictionAck, sha: String, venue: String, locale: String) throws {120        guard ack.venue == venue, ack.locale == locale else { throw no("acknowledgement venue or language") }121        guard ack.sha256 == sha, ack.textMatchesHash else { throw no("acknowledgement text") }122    }123124    static func assertion(_ options: PasskeyRequestOptions, _ client: APIClient, _ authenticator: PasskeyAuthenticator) async throws -> PasskeyAssertion {125        try await authenticator.assert(options, rpId: client.configuration.rpId)126    }127}128129struct DerivAssertionBody: Encodable, Sendable { let assertion: PasskeyAssertion }130struct AcknowledgedAssertionBody: Encodable, Sendable { let assertion: PasskeyAssertion; let acknowledged: Bool }131
Files main
Menu

Theme