SPB Git

Repository Public

ChartSync.swift 12.6 KB 216 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartSync.swift3// Description: Persistence of a chart in the synced `chart` object of its symbol (`sym-<SYMBOL>`, the id the web and iOS clients use): reading it, following changes made on other devices, saving edits with a debounce while keeping every key this app does not know.4import SwiftUI5import VQuantCore6import VQuantKit78/// The mapping between the synced object and what this app charts. Pure functions over the kit's typed value.9enum ChartObject {10    /// Id of the object that holds a symbol's working chart (`sym-<SYMBOL>`, derived like the web client: see `ChartObjectID`).11    static func id(for symbol: String) -> String { ChartObjectID.working(symbol) }1213    /// A NAMED saved layout (web: `layout: true` + `name`) is a different object from the per-symbol chart.14    static func isLayout(_ d: VQChart) -> Bool { d.bool("layout") == true }1516    private static let smaPeriods: [(WritableKeyPath<IndicatorSet, Bool>, Double)] = [(\.sma20, 20), (\.sma50, 50), (\.sma200, 200)]1718    private static func period(_ i: VQChart.Indicator, default d: Double) -> Double { i.params["period"]?.doubleValue ?? d }19    /// Which of this app's indicators an entry of the object is (nil = one this app keeps but does not draw).20    private static func keyPath(_ i: VQChart.Indicator) -> WritableKeyPath<IndicatorSet, Bool>? {21        switch i.type {22        case "sma": return smaPeriods.first { $0.1 == period(i, default: 50) }?.023        case "ema": return period(i, default: 20) == 20 ? \.ema20 : nil24        case "bollinger": return period(i, default: 20) == 20 && (i.params["k"]?.doubleValue ?? 2) == 2 ? \.bollinger : nil25        case "rsi": return period(i, default: 14) == 14 ? \.rsi : nil26        case "macd": return (i.params["fast"]?.doubleValue ?? 12) == 12 && (i.params["slow"]?.doubleValue ?? 26) == 26 && (i.params["signal"]?.doubleValue ?? 9) == 9 ? \.macd : nil27        default: return nil28        }29    }30    private static func entry(_ kp: WritableKeyPath<IndicatorSet, Bool>) -> VQChart.Indicator {31        switch kp {32        case \.sma20: VQChart.Indicator(type: "sma", params: ["period": 20], pane: "price")33        case \.sma50: VQChart.Indicator(type: "sma", params: ["period": 50], pane: "price")34        case \.sma200: VQChart.Indicator(type: "sma", params: ["period": 200], pane: "price")35        case \.ema20: VQChart.Indicator(type: "ema", params: ["period": 20], pane: "price")36        case \.bollinger: VQChart.Indicator(type: "bollinger", params: ["period": 20, "k": 2], pane: "price")37        case \.rsi: VQChart.Indicator(type: "rsi", params: ["period": 14], pane: "own")38        default: VQChart.Indicator(type: "macd", params: ["fast": 12, "slow": 26, "signal": 9], pane: "own")39        }40    }41    private static let drawn: [WritableKeyPath<IndicatorSet, Bool>] = [\.sma20, \.sma50, \.sma200, \.ema20, \.bollinger, \.rsi, \.macd]4243    /// What the object says, completed by `fallback` (the chart as it is) where the object is silent or odd.44    static func config(from d: VQChart, symbol: String, fallback: ChartConfig) -> (config: ChartConfig, foreignIndicators: Int, foreignDrawings: Int) {45        var c = fallback46        if let i = BarInterval(v2: d.interval) { c.interval = i }47        if let r = d.range.flatMap({ ChartRange(rawValue: $0.uppercased()) }), ChartRange.available(for: c.interval).contains(r) { c.range = r }48        else if !ChartRange.available(for: c.interval).contains(c.range) { c.range = c.interval.isIntraday ? .d5 : .y1 }49        if let s = ChartStyle(rawValue: d.chartType.rawValue) { c.style = s }50        c.logScale = d.logScale51        // another client may have stored a boolean here: false = not adjusted52        if d.raw["adjust"] == .bool(false) { c.adjust = "none" } else if let a = d.adjust, ChartModel.adjustments.contains(a) { c.adjust = a } else { c.adjust = "split_div" }53        var set = IndicatorSet(sma20: false, sma50: false, sma200: false, ema20: false, bollinger: false, volume: d.bool("volume") ?? true, rsi: false, macd: false)54        var foreign = 055        for i in d.indicators { if let kp = keyPath(i) { set[keyPath: kp] = true } else { foreign += 1 } }56        c.indicators = set57        c.compare = Array(d.compare.filter { !$0.isEmpty && $0.count <= 24 && $0 != symbol }.prefix(ChartModel.maxCompare))58        var drawings: [ChartDrawing] = []; var odd = 059        for x in d.drawings {60            let pts = x.points.filter { $0.raw["t"]?.doubleValue?.isFinite == true && $0.raw["p"]?.doubleValue?.isFinite == true }61            guard !x.id.isEmpty, let kind = DrawingKind(rawValue: x.type), pts.count >= kind.pointsNeeded else { odd += 1; continue }62            drawings.append(ChartDrawing(id: x.id, kind: kind, points: pts.prefix(2).map { DrawingPoint(t: $0.t, p: $0.p) }, color: max(0, x.style["color"]?.intValue ?? 0), text: x.text))63        }64        c.drawings = drawings65        return (c, foreign, odd)66    }6768    /// Writes the chart into the object by editing its typed properties: keys this app does not know (at any69    /// depth), indicators it does not draw and drawings it cannot read are left exactly as they were.70    static func write(_ c: ChartConfig, symbol: String, into d: inout VQChart) {71        if d.symbol != symbol { d.symbol = symbol }72        if d.interval != c.interval.v2 || d.raw["interval"] == nil { d.interval = c.interval.v2 }73        if d.range?.uppercased() != c.range.rawValue { d.range = c.range.rawValue }74        if d.chartType.rawValue != c.style.rawValue || d.raw["chartType"] == nil { d.chartType = VQOpen(c.style.rawValue) }75        if d.logScale != c.logScale || d.raw["logScale"] == nil { d.logScale = c.logScale }76        if d.adjust != c.adjust { d.adjust = c.adjust }77        if d.bool("volume") != c.indicators.volume { d.set("volume", c.indicators.volume) }78        // indicators: entries this app draws are added or removed; the others stay where they are79        var list = d.indicators.filter { i in keyPath(i).map { c.indicators[keyPath: $0] } ?? true }80        for kp in drawn where c.indicators[keyPath: kp] && !list.contains(where: { keyPath($0) == kp }) { list.append(entry(kp)) }81        if list != d.indicators || d.raw["indicators"] == nil { d.indicators = list }82        if d.compare != c.compare || d.raw["compare"] == nil { d.compare = c.compare }83        // drawings: edited in place by id (their unknown keys survive), new ones appended, removed ones dropped;84        // an entry this app cannot read was never shown, so it cannot have been deleted here: it stays85        var out: [VQChart.Drawing] = []86        var seen = Set<String>()87        for x in d.drawings {88            if let mine = c.drawings.first(where: { $0.id == x.id }) { var e = x; apply(mine, to: &e); out.append(e); seen.insert(x.id) }89            else if DrawingKind(rawValue: x.type) == nil || x.id.isEmpty { out.append(x) }90        }91        for mine in c.drawings where !seen.contains(mine.id) {92            var e = VQChart.Drawing(id: mine.id, type: mine.kind.rawValue, points: [])93            apply(mine, to: &e); out.append(e)94        }95        if out != d.drawings || d.raw["drawings"] == nil { d.drawings = out }96    }9798    private static func apply(_ m: ChartDrawing, to e: inout VQChart.Drawing) {99        if e.type != m.kind.rawValue { e.type = m.kind.rawValue }100        let old = e.points101        if old.count != m.points.count || zip(old, m.points).contains(where: { $0.t != $1.t || $0.p != $1.p }) {102            e.points = m.points.enumerated().map { i, p in103                var q = i < old.count ? old[i] : VQChart.Drawing.Point(t: p.t, p: p.p)104                q.t = p.t; q.p = p.p105                return q106            }107        }108        if e.style["color"]?.intValue != m.color { var s = e.style; s["color"] = .number(Double(m.color)); e.style = s }109        if e.text != m.text { e.text = m.text }110    }111}112113/// Binds one `ChartModel` to the synced object of its symbol.114@Observable final class ChartSync {115    let app: AppEnvironment116    let chart: ChartModel117    /// The object exists on the account (false = this symbol has never been changed: nothing was created).118    private(set) var hasObject = false119    private(set) var saving = false120121    @ObservationIgnored private var symbol: String122    /// The object's data as last applied to, or written from, the chart: an identical value coming back is an echo.123    @ObservationIgnored private var known: VQChart?124    @ObservationIgnored private var dirty = false125    @ObservationIgnored private var saveTask: Task<Void, Never>?126    /// Drawings shown before the pending edit (so a drawing deleted here is not resurrected by a merge).127    @ObservationIgnored private var shownIDs = Set<String>()128    static let debounce: Duration = .milliseconds(700)129130    init(app: AppEnvironment, chart: ChartModel) {131        self.app = app; self.chart = chart; symbol = chart.symbol132        chart.onUserChange = { [weak self] in self?.changed() }133        chart.onSymbolWillChange = { [weak self] in self?.flush() }134    }135136    private var collection: VQSyncedCollection<VQChart>? { app.sync.active?.charts }137    var objectID: String { ChartObject.id(for: symbol) }138139    /// Named layouts saved by any client, newest first.140    var layouts: [VQObject<VQChart>] { (collection?.items ?? []).filter { ChartObject.isLayout($0.data) && ($0.data.string("name") ?? "").isEmpty == false } }141142    /// Applies a named layout's settings to this chart (its drawings only when it was saved on the same symbol).143    /// This is a change made by the person: it is saved in the symbol's own object.144    func applyLayout(_ o: VQObject<VQChart>) {145        var c = ChartObject.config(from: o.data, symbol: symbol, fallback: chart.config).config146        if o.data.symbol.uppercased() != symbol.uppercased() { c.drawings = chart.drawings }147        chart.apply(c)148        changed()149    }150151    /// Called when the collection changed (another device, the first pull, the echo of a save) or the symbol did.152    func refresh() {153        if chart.symbol != symbol {154            // (a pending edit of the previous symbol was written by `onSymbolWillChange`)155            // a symbol without an object keeps the view settings in use (1.0.1 behaviour); drawings never carry over156            symbol = chart.symbol; known = nil; hasObject = false; shownIDs = []; dirty = false; saveTask?.cancel()157        }158        guard let object = collection?[objectID], !ChartObject.isLayout(object.data) else {159            if hasObject, !dirty { hasObject = false; known = nil; var c = chart.config; c.drawings = []; chart.apply(c); chart.foreignIndicators = 0; chart.foreignDrawings = 0 }160            return161        }162        hasObject = true163        guard object.data != known else { return }164        let read = ChartObject.config(from: object.data, symbol: symbol, fallback: chart.config)165        var config = read.config166        let foreignI = read.foreignIndicators, foreignD = read.foreignDrawings167        if dirty {168            // an edit is waiting to be saved: it wins field by field; drawings from the other device are added169            let mine = chart.config170            let added = config.drawings.filter { d in !mine.drawings.contains { $0.id == d.id } && !shownIDs.contains(d.id) }171            config = mine; config.drawings += added172        }173        known = object.data174        chart.apply(config)175        chart.foreignIndicators = foreignI; chart.foreignDrawings = foreignD176        if !dirty { shownIDs = Set(config.drawings.map(\.id)) }177    }178179    private func changed() {180        guard app.sync.active != nil else { return }181        dirty = true182        saveTask?.cancel()183        saveTask = Task { [weak self] in184            try? await Task.sleep(for: Self.debounce)185            if Task.isCancelled { return }186            await self?.save()187        }188    }189190    /// Saves a pending edit now (symbol change, window closing).191    func flush() {192        guard dirty else { return }193        saveTask?.cancel(); saveTask = nil194        let (id, data) = prepare()195        if let c = collection { Task { await c.save(data, id: id) } }196    }197198    private func prepare() -> (String, VQChart) {199        // start from what the account holds now, so nothing another client wrote is lost200        var data = collection?[objectID]?.data ?? known ?? VQChart(raw: [:])201        ChartObject.write(chart.config, symbol: symbol, into: &data)202        dirty = false; known = data; hasObject = true203        shownIDs = Set(chart.drawings.map(\.id))204        return (objectID, data)205    }206207    private func save() async {208        guard dirty, let c = collection else { return }209        let (id, data) = prepare()210        saving = true211        await c.save(data, id: id)212        saving = false213        if let e = c.lastError { app.toasts.show("The chart could not be saved: \(e.userMessage)", error: true) }214    }215}216
Files main
Menu

Theme