SPB Git

Repository Public

RiskLogic.swift 20.5 KB 295 lines swift

1// SP Wallet iOS2// File: Features/Security/RiskLogic.swift3// Description: Pure logic of the Risk screens: the catalogue of every limit of the unified risk engine (name, unit, explanation),4//              the reading of what the owner TYPED into a limit set (an empty field is an absent limit, never a default), the5//              from → to rows of a change with what the server found loosened, and the words of the engine's states.6//              Nothing here talks to the network; the server alone decides what is a loosening.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPWalletCore1213/** Reading of numbers typed by the owner. Text that cannot be read is refused — never guessed, never replaced by a default. */14enum RiskInput {15    /**16     A non-negative decimal as the server takes it (`123.45`). Accepts the locale's decimal comma and grouping spaces; a text with17     both a comma and a point is ambiguous and refused.18     */19    static func decimal(_ raw: String) -> String? {20        var s = raw.trimmingCharacters(in: .whitespacesAndNewlines)21        for sep in [" ", "\u{00a0}", "\u{202f}", "’", "'"] { s = s.replacingOccurrences(of: sep, with: "") }22        if s.contains(","), s.contains(".") { return nil }23        s = s.replacingOccurrences(of: ",", with: ".")24        guard s.range(of: "^[0-9]{1,30}(\\.[0-9]{1,18})?$", options: .regularExpression) != nil else { return nil }25        // canonical text: no leading zeros, no trailing zeros of the fraction26        var parts = s.split(separator: ".", maxSplits: 1).map(String.init)27        parts[0] = String(parts[0].drop { $0 == "0" }); if parts[0].isEmpty { parts[0] = "0" }28        if parts.count == 2 { while parts[1].last == "0" { parts[1].removeLast() } }29        return parts.count == 2 && !parts[1].isEmpty ? parts[0] + "." + parts[1] : parts[0]30    }31    static func positiveDecimal(_ raw: String) -> String? { decimal(raw).flatMap { ExecutionDecimal.isPositive($0) ? $0 : nil } }32    static func integer(_ raw: String) -> Int? {33        let s = raw.trimmingCharacters(in: .whitespacesAndNewlines)34        guard s.range(of: "^[0-9]{1,12}$", options: .regularExpression) != nil else { return nil }35        return Int(s)36    }37    /** Identifiers separated by commas, spaces or line breaks; duplicates removed, order kept. */38    static func list(_ raw: String) -> [String] {39        var seen = Set<String>(), out: [String] = []40        for p in raw.split(whereSeparator: { ",; \n\t".contains($0) }).map(String.init) where !p.isEmpty && seen.insert(p).inserted { out.append(p) }41        return out42    }43}4445struct RiskLimitField: Identifiable, Hashable {46    enum Kind { case decimal, integer, list, keyed, keyedAge, liquidity }47    let key: String48    let kind: Kind49    /** `usd`, `bps`, `x`, `ms` or empty */50    let unit: String51    let title: String52    let explanation: String53    var id: String { key }54}5556struct RiskLimitGroup: Identifiable { let id: String; let title: String; let fields: [RiskLimitField] }5758/** Every member of `RiskLimitsSchema`, grouped as the web Risk screen groups them, each with its name and what it does. */59enum RiskLimitCatalog {60    static let groups: [RiskLimitGroup] = [61        RiskLimitGroup(id: "scope", title: String(localized: "Périmètre"), fields: [62            f("allowedVenues", .list, "", String(localized: "Plateformes autorisées"), String(localized: "Seules ces plateformes peuvent recevoir un ordre qui ajoute du risque. Absente en mode réel : tout nouvel ordre à risque est refusé.")),63            f("allowedInstruments", .list, "", String(localized: "Marchés autorisés"), String(localized: "Identifiants « plateforme:symbole ». Un ordre sur un marché hors de cette liste est refusé.")),64        ]),65        RiskLimitGroup(id: "size", title: String(localized: "Taille des ordres"), fields: [66            f("maxOrderNotional", .decimal, "usd", String(localized: "Notionnel maximal par ordre"), String(localized: "Valeur maximale d’un seul ordre, en USD.")),67            f("maxDailyNotional", .decimal, "usd", String(localized: "Notionnel maximal par jour"), String(localized: "Somme maximale des ordres acceptés sur une journée (UTC), en USD.")),68            f("maxPositionNotional", .keyed, "usd", String(localized: "Position maximale par marché"), String(localized: "Valeur maximale d’une position, par marché, avec une valeur générale facultative.")),69            f("maxOrderLeverage", .decimal, "x", String(localized: "Levier maximal d’un ordre"), String(localized: "Un ordre demandant un levier supérieur est refusé.")),70            f("maxAccountLeverage", .decimal, "x", String(localized: "Levier maximal du compte"), String(localized: "Exposition brute divisée par les fonds propres du compte, après l’ordre.")),71        ]),72        RiskLimitGroup(id: "exposure", title: String(localized: "Exposition"), fields: [73            f("maxGrossExposure", .decimal, "usd", String(localized: "Exposition brute maximale"), String(localized: "Somme des positions longues et courtes du livre, en USD.")),74            f("maxNetExposure", .decimal, "usd", String(localized: "Exposition nette maximale"), String(localized: "Longues moins courtes, en valeur absolue, en USD.")),75            f("maxAssetExposure", .keyed, "usd", String(localized: "Exposition maximale par actif"), String(localized: "Exposition nette sur un même actif, toutes plateformes confondues.")),76            f("maxVenueExposure", .keyed, "usd", String(localized: "Exposition maximale par plateforme"), String(localized: "Exposition brute portée par une même plateforme.")),77            f("maxVenueCollateralShareBps", .decimal, "bps", String(localized: "Part maximale du collatéral sur une plateforme"), String(localized: "En points de base du collatéral total (10 000 = 100 %).")),78        ]),79        RiskLimitGroup(id: "loss", title: String(localized: "Pertes"), fields: [80            f("maxDailyLoss", .decimal, "usd", String(localized: "Perte maximale par jour"), String(localized: "Une fois la perte du jour atteinte, plus aucun nouveau risque. Appliquée par l’API, pas par le signataire.")),81            f("maxTotalLoss", .decimal, "usd", String(localized: "Perte totale maximale"), String(localized: "Perte cumulée depuis l’origine du livre au-delà de laquelle tout nouveau risque est refusé.")),82            f("maxDrawdownBps", .decimal, "bps", String(localized: "Repli maximal depuis le sommet"), String(localized: "Baisse des fonds propres depuis leur plus haut, en points de base.")),83            f("minLiquidationDistanceBps", .decimal, "bps", String(localized: "Distance minimale à la liquidation"), String(localized: "Un ordre qui laisserait la position plus près de sa liquidation est refusé. Baisser cette valeur est un assouplissement.")),84        ]),85        RiskLimitGroup(id: "quality", title: String(localized: "Qualité des prix"), fields: [86            f("maxSlippageBps", .decimal, "bps", String(localized: "Glissement maximal"), String(localized: "Écart maximal accepté entre le prix de référence et le prix d’exécution estimé.")),87            f("minLiquidity", .liquidity, "", String(localized: "Liquidité minimale du carnet"), String(localized: "La profondeur à moins de N points de base du milieu doit valoir au moins M fois la taille de l’ordre.")),88            f("maxPriceAgeMs", .keyedAge, "ms", String(localized: "Âge maximal d’un prix"), String(localized: "Par source, en millisecondes. Un prix plus vieux fait refuser l’ordre.")),89            f("maxBookAgeMs", .integer, "ms", String(localized: "Âge maximal du carnet"), String(localized: "En millisecondes.")),90            f("minPriceSources", .integer, "", String(localized: "Nombre minimal de sources de prix"), String(localized: "Au moins 1. Baisser cette valeur est un assouplissement.")),91            f("maxSourceDeviationBps", .decimal, "bps", String(localized: "Écart maximal entre sources"), String(localized: "Au-delà, les sources divergent et l’ordre est refusé.")),92        ]),93        RiskLimitGroup(id: "rate", title: String(localized: "Cadence"), fields: [94            f("maxOrdersPerMinute", .integer, "", String(localized: "Ordres par minute"), String(localized: "Nombre maximal d’ordres acceptés par minute.")),95            f("maxOrdersPerHour", .integer, "", String(localized: "Ordres par heure"), String(localized: "Nombre maximal d’ordres acceptés par heure.")),96            f("maxOrdersPerDay", .integer, "", String(localized: "Ordres par jour"), String(localized: "Nombre maximal d’ordres acceptés par jour.")),97        ]),98    ]99    static let fields: [RiskLimitField] = groups.flatMap(\.fields)100    static func field(_ key: String) -> RiskLimitField? { fields.first { $0.key == key } }101    /** The title of a limit, or its server name verbatim when this version does not know it. */102    static func title(_ key: String) -> String { field(key)?.title ?? key }103    private static func f(_ k: String, _ kind: RiskLimitField.Kind, _ unit: String, _ t: String, _ e: String) -> RiskLimitField { RiskLimitField(key: k, kind: kind, unit: unit, title: t, explanation: e) }104105    static func unitLabel(_ unit: String) -> String {106        switch unit { case "usd": "USD"; case "bps": String(localized: "pb"); case "x": "×"; case "ms": "ms"; default: "" }107    }108}109110/** How one limit value reads for a person (never JSON). nil/absent reads as nil: the caller says « absente ». */111enum RiskLimitText {112    static func text(_ v: JSONValue?) -> String? {113        guard let v, !v.isNull else { return nil }114        if let a = v.arrayValue { return a.isEmpty ? "∅" : a.map(scalar).joined(separator: ", ") }115        if let o = v.objectValue {116            if let w = o["withinBps"], let m = o["multiple"] { return "\(scalar(m))× ≤ \(scalar(w)) pb" }117            var parts: [String] = []118            if let d = o["default"], !d.isNull { parts.append(String(localized: "général : \(scalar(d))")) }119            if let per = o["per"]?.objectValue { for k in per.keys.sorted() { parts.append("\(k) : \(scalar(per[k]!))") } }120            return parts.isEmpty ? nil : parts.joined(separator: " · ")121        }122        return scalar(v)123    }124    static func scalar(_ v: JSONValue) -> String {125        switch v { case .string(let s): s; case .int(let i): String(i); case .double(let d): String(d); case .bool(let b): b ? "true" : "false"; default: "" }126    }127    static func value(_ limits: EngineRiskLimits, _ key: String) -> JSONValue? { (try? JSONValue.from(limits))?[key] }128    static func text(_ limits: EngineRiskLimits, _ key: String) -> String? { text(value(limits, key)) }129}130131/** What the owner is typing in the limits editor. Starts from what HE stored (never from the server's defaults). */132struct RiskLimitsDraft: Equatable {133    struct Keyed: Equatable { var fallback = ""; var per: [Row] = [] }134    struct Row: Equatable, Identifiable { let id: UUID; var key: String; var value: String135        init(key: String = "", value: String = "") { id = UUID(); self.key = key; self.value = value }136        static func == (a: Row, b: Row) -> Bool { a.key == b.key && a.value == b.value }137    }138    var text: [String: String] = [:]139    var keyed: [String: Keyed] = [:]140    var withinBps = ""141    var multiple = ""142143    init() {}144    init(stored: EngineRiskLimits) {145        let o = (try? JSONValue.from(stored))?.objectValue ?? [:]146        for f in RiskLimitCatalog.fields {147            guard let v = o[f.key], !v.isNull else { continue }148            switch f.kind {149            case .decimal, .integer: text[f.key] = RiskLimitText.scalar(v)150            case .list: text[f.key] = (v.arrayValue ?? []).map(RiskLimitText.scalar).joined(separator: ", ")151            case .keyed, .keyedAge:152                var k = Keyed()153                if let d = v["default"], !d.isNull { k.fallback = RiskLimitText.scalar(d) }154                if let per = v["per"]?.objectValue { k.per = per.keys.sorted().map { Row(key: $0, value: RiskLimitText.scalar(per[$0]!)) } }155                keyed[f.key] = k156            case .liquidity:157                withinBps = v["withinBps"].map(RiskLimitText.scalar) ?? ""; multiple = v["multiple"].map(RiskLimitText.scalar) ?? ""158            }159        }160    }161162    struct Built: Equatable {163        let limits: EngineRiskLimits164        /** keys of the fields whose text cannot be read */165        let bad: [String]166    }167168    /** The limit set exactly as typed: an empty field is ABSENT from the set. `bad` names what cannot be read (nothing is then sent). */169    func build() -> Built {170        var out: [String: JSONValue] = [:], bad: [String] = []171        for f in RiskLimitCatalog.fields {172            switch f.kind {173            case .decimal:174                let t = (text[f.key] ?? "").trimmingCharacters(in: .whitespaces); if t.isEmpty { continue }175                let positive = f.key == "maxOrderLeverage" || f.key == "maxAccountLeverage"176                if let d = positive ? RiskInput.positiveDecimal(t) : RiskInput.decimal(t) { out[f.key] = .string(d) } else { bad.append(f.key) }177            case .integer:178                let t = (text[f.key] ?? "").trimmingCharacters(in: .whitespaces); if t.isEmpty { continue }179                if let n = RiskInput.integer(t), f.key != "minPriceSources" || n >= 1 { out[f.key] = .int(Int64(n)) } else { bad.append(f.key) }180            case .list:181                let l = RiskInput.list(text[f.key] ?? ""); if !l.isEmpty { out[f.key] = .array(l.map { .string($0) }) }182            case .keyed, .keyedAge:183                guard let k = keyed[f.key] else { continue }184                func one(_ s: String) -> JSONValue? { f.kind == .keyedAge ? RiskInput.integer(s).map { .int(Int64($0)) } : RiskInput.decimal(s).map { .string($0) } }185                var per: [String: JSONValue] = [:], any = false, wrong = false186                for r in k.per {187                    let name = r.key.trimmingCharacters(in: .whitespaces), val = r.value.trimmingCharacters(in: .whitespaces)188                    if name.isEmpty && val.isEmpty { continue }189                    guard !name.isEmpty, per[name] == nil, let v = one(val) else { wrong = true; continue }190                    per[name] = v; any = true191                }192                var obj: [String: JSONValue] = [:]193                let d = k.fallback.trimmingCharacters(in: .whitespaces)194                if !d.isEmpty { if let v = one(d) { obj["default"] = v; any = true } else { wrong = true } }195                if wrong { bad.append(f.key); continue }196                if any { obj["per"] = .object(per); out[f.key] = .object(obj) }197            case .liquidity:198                let w = withinBps.trimmingCharacters(in: .whitespaces), m = multiple.trimmingCharacters(in: .whitespaces)199                if w.isEmpty && m.isEmpty { continue }200                if let a = RiskInput.decimal(w), let b = RiskInput.positiveDecimal(m) { out[f.key] = .object(["withinBps": .string(a), "multiple": .string(b)]) } else { bad.append(f.key) }201            }202        }203        guard let limits = try? JSONValue.object(out).decode(EngineRiskLimits.self), (try? limits.validate()) != nil else {204            return Built(limits: EngineRiskLimits(), bad: bad.isEmpty ? ["limits"] : bad)205        }206        return Built(limits: limits, bad: bad)207    }208}209210/** One row of the review of a limit change: the limit, what is stored now, what will be stored, and the SERVER's verdict. */211struct RiskLimitChange: Identifiable, Equatable {212    let key: String213    /** nil: no value stored by the owner (the mode's default applies, when there is one) */214    let from: String?215    let to: String?216    /** the mode's default for this limit, shown next to an absent value */217    let fallback: String?218    /** true when the server listed this limit as loosened */219    let loosened: Bool220    var id: String { key }221    var title: String { RiskLimitCatalog.title(key) }222}223224enum RiskLimitChanges {225    /**226     Every limit whose stored value differs between `stored` and `next`, plus every limit the server named as loosened (even one227     this version sees as unchanged — the server's list is shown in full, never filtered). Loosened rows first.228     */229    static func rows(stored: EngineRiskLimits, next: EngineRiskLimits, defaults: EngineRiskLimits, loosened: [String]) -> [RiskLimitChange] {230        let a = (try? JSONValue.from(stored))?.objectValue ?? [:], b = (try? JSONValue.from(next))?.objectValue ?? [:], d = (try? JSONValue.from(defaults))?.objectValue ?? [:]231        var keys = EngineRiskLimits.fieldNames.filter { a[$0] != b[$0] || loosened.contains($0) }232        for l in loosened where !keys.contains(l) { keys.append(l) }233        let rows = keys.map { RiskLimitChange(key: $0, from: RiskLimitText.text(a[$0]), to: RiskLimitText.text(b[$0]), fallback: RiskLimitText.text(d[$0]), loosened: loosened.contains($0)) }234        return rows.filter(\.loosened) + rows.filter { !$0.loosened }235    }236    static func describe(_ value: String?, fallback: String?) -> String {237        if let value { return value }238        if let fallback { return String(localized: "absente (défaut du mode : \(fallback))") }239        return String(localized: "absente")240    }241}242243/** Words for what the engine serves as codes. An unknown code is shown verbatim. */244enum RiskWords {245    static func mode(_ m: String) -> String { m == "paper" ? String(localized: "PAPIER") : m == "live" ? String(localized: "RÉEL") : m.uppercased() }246    static func modeTone(_ m: String) -> Tone { m == "live" ? .danger : m == "paper" ? .info : .neutral }247    static func modeIcon(_ m: String) -> String { m == "live" ? "bolt.fill" : m == "paper" ? "doc.plaintext" : "questionmark" }248    static func book(_ b: String) -> String {249        switch b { case "paper": String(localized: "Livre papier (simulation)"); case "live-mainnet": String(localized: "Livre réel · mainnet"); case "live-testnet": String(localized: "Livre réel · testnet"); default: b }250    }251    static func switchTitle(_ k: RiskSwitchKind) -> String { k == .killSwitch ? String(localized: "Arrêt du trading (kill switch)") : String(localized: "Mode lecture seule") }252    static func switchEffect(_ k: RiskSwitchKind) -> String {253        k == .killSwitch ? String(localized: "Aucun nouveau risque, pour personne, sur toutes les plateformes et dans tous les modes. Les annulations et les ordres strictement réducteurs passent encore.")254            : String(localized: "Seules les annulations passent. Aucun ordre, même réducteur.")255    }256    static func actor(_ a: RiskActor?) -> String {257        guard let a else { return String(localized: "inconnu") }258        switch a.kind {259        case "owner": return String(localized: "le propriétaire")260        case "system": return String(localized: "le système (\(a.id))")261        case "api_key": return String(localized: "la clé d’API \(a.id)")262        case "agent": return String(localized: "l’agent \(a.id)")263        default: return a.label264        }265    }266    static func autoTitle(_ key: String) -> String {267        switch key {268        case "totalLoss": String(localized: "Arrêt automatique sur perte totale")269        case "drawdown": String(localized: "Arrêt automatique sur repli")270        case "dailyLoss": String(localized: "Arrêt automatique sur perte du jour")271        default: key272        }273    }274    static func autoExplanation(_ key: String) -> String {275        switch key {276        case "totalLoss": String(localized: "Engage l’arrêt du trading quand la perte totale du livre réel atteint la limite « perte totale maximale ».")277        case "drawdown": String(localized: "Engage l’arrêt du trading quand le repli du livre réel atteint la limite « repli maximal ».")278        case "dailyLoss": String(localized: "Engage l’arrêt du trading quand la perte du jour du livre réel atteint la limite « perte maximale par jour ».")279        default: ""280        }281    }282    static func date(ms: Int?) -> String? { ms.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000).formatted(date: .abbreviated, time: .standard) } }283    static func date(seconds: Int?) -> String? { seconds.map { Date(timeIntervalSince1970: TimeInterval($0)).formatted(date: .abbreviated, time: .shortened) } }284}285286extension AutoKillSettings {287    static let keys = ["totalLoss", "drawdown", "dailyLoss"]288    func value(_ key: String) -> Bool { key == "totalLoss" ? totalLoss : key == "drawdown" ? drawdown : dailyLoss }289    func setting(_ key: String, _ on: Bool) -> AutoKillSettings {290        AutoKillSettings(totalLoss: key == "totalLoss" ? on : totalLoss, drawdown: key == "drawdown" ? on : drawdown, dailyLoss: key == "dailyLoss" ? on : dailyLoss)291    }292    /** Stops that this change switches OFF (what the server calls a loosening). Display only: the server's own list decides. */293    func switchedOff(from current: AutoKillSettings) -> [String] { Self.keys.filter { current.value($0) && !value($0) } }294}295
Files main
Menu

Theme