Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/RiskModels.swift3// Description: What the Risk screen reads (services/api/src/orders/index.ts `executionRoutes`, services/api/src/risk/service.ts):4// the two global switches, the limits of each mode with what is missing, exposure per book, the log of the risk5// engine's decisions, the server locks — and the typed form of a refusal of the execution layer, kept verbatim.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011public struct RiskActor: Codable, Sendable, Hashable {12 /** `owner`, `api_key`, `agent`, `system` */13 public let kind: String14 public let id: String15 /** the form the release intent names: `<kind>:<id>` */16 public var label: String { "\(kind):\(id)" }17}1819/** One global switch. `on` blocks; `at`/`by`/`reason` describe the engagement that is in force. */20public struct RiskSwitch: Codable, Sendable, Hashable {21 public let on: Bool22 /** unix ms */23 public let at: Int?24 public let by: RiskActor?25 public let reason: String?26 public var engagedAt: Date? { at.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } }27}2829/**30 `killSwitch.on`: no new risk for anybody, on every venue, in every mode — cancels and strictly reducing orders still pass.31 `readOnly.on`: only cancels pass. Engaging either is free; releasing needs the owner's passkey.32 This is NOT the signer's emergency halt (WalletAPI.emergencyHalt), which is lifted on the signer machine only.33 */34public struct RiskSwitches: Codable, Sendable, Hashable {35 public let killSwitch: RiskSwitch36 public let readOnly: RiskSwitch37 public func state(of kind: RiskSwitchKind) -> RiskSwitch { kind == .killSwitch ? killSwitch : readOnly }38}3940/** GET /risk/limits/:mode. `effective` is what an API key or an agent is judged on; `effectiveOwner` what the owner's own orders are. */41public struct RiskLimitsView: Decodable, Sendable, Equatable {42 public struct Seed: Decodable, Sendable, Equatable {43 public struct Source: Decodable, Sendable, Equatable { public let field: String; public let from: String; public let accounts: [String] }44 public struct Account: Decodable, Sendable, Equatable { public let id: String; public let venue: String; public let network: String }45 /** unix ms */46 public let at: Int?47 public let limits: EngineRiskLimits48 public let sources: [Source]49 public let notSeeded: [String]50 public let accounts: [Account]?51 }52 public let mode: RiskMode53 /** what the owner stored himself */54 public let stored: EngineRiskLimits55 /** the same object as served: it may carry a limit this version does not know (see `storedUnknownFields`) */56 public let storedRaw: JSONValue57 public let defaults: EngineRiskLimits58 public let effective: EngineRiskLimits59 public let effectiveOwner: EngineRiskLimits?60 /** live: the limits the owner had approved before V11, applied under his OWN orders only */61 public let seed: Seed?62 /** capital limits absent for the owner's own orders: while not empty, his real orders that add risk are refused */63 public let missing: [String]64 public let missingForAutomation: [String]?65 public let ownerOrdersRefused: Bool?66 public let automationOrdersRefused: Bool?6768 /** Limits stored on the server that this version cannot show or edit. Sending a new set would REMOVE them: the screen must say so. */69 public var storedUnknownFields: [String] { Set(storedRaw.objectValue?.keys.map { $0 } ?? []).subtracting(EngineRiskLimits.fieldNames).sorted() }7071 enum CodingKeys: String, CodingKey { case mode, stored, defaults, effective, effectiveOwner, seed, missing, missingForAutomation, ownerOrdersRefused, automationOrdersRefused }72 public init(from decoder: Decoder) throws {73 let c = try decoder.container(keyedBy: CodingKeys.self)74 mode = try c.decode(RiskMode.self, forKey: .mode)75 stored = try c.decode(EngineRiskLimits.self, forKey: .stored); storedRaw = try c.decode(JSONValue.self, forKey: .stored)76 defaults = try c.decode(EngineRiskLimits.self, forKey: .defaults); effective = try c.decode(EngineRiskLimits.self, forKey: .effective)77 effectiveOwner = try c.decodeIfPresent(EngineRiskLimits.self, forKey: .effectiveOwner); seed = try c.decodeIfPresent(Seed.self, forKey: .seed)78 missing = try c.decode([String].self, forKey: .missing); missingForAutomation = try c.decodeIfPresent([String].self, forKey: .missingForAutomation)79 ownerOrdersRefused = try c.decodeIfPresent(Bool.self, forKey: .ownerOrdersRefused); automationOrdersRefused = try c.decodeIfPresent(Bool.self, forKey: .automationOrdersRefused)80 }81}8283public enum RiskBook: String, Codable, Sendable, CaseIterable { case paper, liveMainnet = "live-mainnet", liveTestnet = "live-testnet" }8485/** Exposure of ONE book (paper, live mainnet, live testnet are never merged). When the book could not be read, only `book` and `error` are set. */86public struct RiskExposure: Decodable, Sendable, Equatable {87 public struct Asset: Decodable, Sendable, Equatable { public let asset: String; public let long, short, net: String }88 public struct Venue: Decodable, Sendable, Equatable { public let venue: String; public let gross: String }89 public struct Collateral: Decodable, Sendable, Equatable {90 public let venue: String; public let accountId: String91 public let equity, collateral, freeCollateral, marginUsed: String?92 public let shareBps: String?93 }94 public struct Position: Decodable, Sendable, Equatable {95 public let venue: String; public let accountId: String; public let asset: String; public let instrument: String96 public let side: String; public let size: String; public let markPrice: String; public let notional: String97 public let leverage: String?; public let liquidationPrice: String?; public let liquidationDistanceBps: String?; public let unrealizedPnl: String?; public let source: String?98 }99 public let book: String100 public let error: String?101 /** unix ms */102 public let ts: Int?103 public let equity: String?104 public let peakEquity: String?105 public let grossExposure: String?106 /** gross exposure / equity; nil when the equity is not positive */107 public let leverage: String?108 public let byAsset: [Asset]?109 public let byVenue: [Venue]?110 public let collateral: [Collateral]?111 public let positions: [Position]?112 /** sources of the book that could not be read: the figures above are then partial */113 public let errors: [String]?114 /** realised result and funding of the book's accounts (today, total), as the server computes them */115 public let pnl: JSONValue?116 public var isReadable: Bool { error == nil && equity != nil }117}118119/** One failed check of the risk engine: WHICH limit (`id`), the value observed, the threshold, and the engine's sentence — all verbatim. */120public struct RiskCheckFailure: Codable, Sendable, Hashable {121 /** the check's id = the limit's name (`order_notional`, `daily_loss`, `kill_switch`, …; RISK_CHECK_IDS of trading-api/spec.ts) */122 public let id: String123 public let observed: String?124 public let limit: String?125 public let detail: String126}127128/** One check of a preview or of a refusal. */129public struct RiskCheck: Codable, Sendable, Hashable {130 public let id: String131 public let ok: Bool132 public let observed: String?133 public let limit: String?134 public let detail: String135 /** true: the check does not apply to this order (a strictly reducing order is exempt from the exposure limits) */136 public let exempt: Bool?137 public var failure: RiskCheckFailure? { ok ? nil : RiskCheckFailure(id: id, observed: observed, limit: limit, detail: detail) }138}139140/** One row of the risk engine's log (`risk_decisions`): every evaluation, previews included, allowed or denied. */141public struct RiskDecision: Decodable, Sendable, Equatable, Identifiable {142 public let id: Int143 /** unix ms */144 public let at: Int145 public let orderId: String?146 public let clientOrderId: String?147 /** what was evaluated (`order`, `cancel`, …), as the server names it */148 public let kind: String149 /** true: an evaluation of a preview — nothing was placed on its strength */150 public let preview: Bool151 public let principal: RiskActor152 public let mode: String153 public let venue: String154 public let instrument: String?155 /** `allow` or `deny`, verbatim */156 public let decision: String157 public let reducing: Bool158 /** ids of the failed checks */159 public let failed: [String]?160 public let failing: [RiskCheckFailure]161 public var date: Date { Date(timeIntervalSince1970: TimeInterval(at) / 1000) }162 public var denied: Bool { decision == "deny" }163}164165/** A server lock of execution (an environment setting): `on == false` means that path is closed, and `why` says so in the server's words. */166public struct ExecutionLock: Codable, Sendable, Hashable, Identifiable {167 public let id: String168 public let on: Bool169 public let why: String?170}171172/** GET /risk/state: everything the Risk screen shows, in one read. */173public struct RiskState: Decodable, Sendable, Equatable {174 public struct Limits: Decodable, Sendable, Equatable { public let paper: RiskLimitsView; public let live: RiskLimitsView }175 public struct Exposure: Decodable, Sendable, Equatable { public let paper: RiskExposure; public let live: RiskExposure; public let liveTestnet: RiskExposure }176 public let switches: RiskSwitches177 public let auto: AutoKillSettings178 public let limits: Limits179 public let exposure: Exposure180 public let decisions: [RiskDecision]181 public let locks: [ExecutionLock]182 /** unix ms */183 public let ts: Int184}185186/**187 A refusal of the execution layer, read from the error answer WITHOUT rewording: the server's code and sentence, the failed188 checks of the risk engine (limit name, observed value, threshold), the mandate's deny codes, and the order the refusal is about189 when one exists (it is then REJECTED or FAILED and visible in the order list).190 */191public struct ExecutionRefusal: Sendable, Equatable {192 public enum Stage: String, Sendable { case risk, mandate, other }193 public let status: Int194 /** `risk_denied`, `kill_switch_active`, `read_only_mode`, `mandate_denied`, `execution_disabled`, … */195 public let code: String196 public let message: String197 public let stage: Stage198 /** ids of the failed risk checks */199 public let failed: [String]200 public let checks: [RiskCheckFailure]201 /** `mandate_denied`: the mandate's deny codes (MANDATE_DENY_REASONS of trading-api/spec.ts) */202 public let reasons: [String]203 public let decisionId: Int?204 public let order: UnifiedOrder?205206 public static let riskCodes: Set<String> = ["risk_denied", "kill_switch_active", "read_only_mode"]207208 /** nil when the error carries no refusal detail (a transport error, a validation error…). */209 public init?(_ e: APIError) {210 guard e.status >= 400, e.status < 500 else { return nil }211 let d = e.data212 let checks: [RiskCheck] = (d?["checks"]).flatMap { try? $0.decode([RiskCheck].self) } ?? []213 let failed = d?["failed"]?.arrayValue?.compactMap(\.stringValue) ?? []214 let reasons = d?["reasons"]?.arrayValue?.compactMap(\.stringValue) ?? []215 let known = Self.riskCodes.contains(e.code) || e.code == "mandate_denied"216 guard known || !checks.isEmpty || !failed.isEmpty || !reasons.isEmpty else { return nil }217 status = e.status; code = e.code; message = e.message218 stage = Self.riskCodes.contains(e.code) ? .risk : e.code == "mandate_denied" ? .mandate : .other219 self.failed = failed; self.reasons = reasons220 self.checks = checks.compactMap(\.failure)221 decisionId = d?["decisionId"]?.intValue.map(Int.init)222 order = (d?["order"]).flatMap { try? $0.decode(UnifiedOrder.self) }223 }224}225