Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartModel.swift3// Description: State of one chart: source bars from the server's data layer with their provenance, the visible window (zoom and pan), indicators, overlays, drawings (with undo), crosshair, periodic refresh.4import SwiftUI5import VQuantCore6import VQuantKit78enum ChartRange: String, CaseIterable, Identifiable, Codable {9 case d1 = "1D", d5 = "5D", m1 = "1M", m3 = "3M", m6 = "6M", ytd = "YTD", y1 = "1Y", y2 = "2Y", y5 = "5Y", max = "MAX"10 var id: String { rawValue }11 func start(from now: Date) -> Date {12 let c = Calendar.current13 switch self {14 case .d1: return c.date(byAdding: .day, value: -4, to: now)! // covers a weekend; the view opens on the last session15 case .d5: return c.date(byAdding: .day, value: -8, to: now)!16 case .m1: return c.date(byAdding: .month, value: -1, to: now)!17 case .m3: return c.date(byAdding: .month, value: -3, to: now)!18 case .m6: return c.date(byAdding: .month, value: -6, to: now)!19 case .ytd: return c.date(from: c.dateComponents([.year], from: now))!20 case .y1: return c.date(byAdding: .year, value: -1, to: now)!21 case .y2: return c.date(byAdding: .year, value: -2, to: now)!22 case .y5: return c.date(byAdding: .year, value: -5, to: now)!23 case .max: return c.date(byAdding: .year, value: -30, to: now)!24 }25 }26 /// Ranges offered for an interval (the provider keeps limited intraday history at fine resolutions).27 static func available(for i: BarInterval) -> [ChartRange] {28 switch i {29 case .m1: [.d1, .d5]30 case .m5, .m15: [.d1, .d5, .m1]31 case .m30, .h1, .h4: [.d5, .m1, .m3]32 case .d1: [.m1, .m3, .m6, .ytd, .y1, .y2, .y5, .max]33 }34 }35}3637struct IndicatorSet: Equatable, Codable {38 var sma20 = false, sma50 = true, sma200 = false, ema20 = false, bollinger = false39 var volume = true, rsi = false, macd = false40}4142/// Shared crosshair time for charts whose "Link" toggle is on: moving over one chart marks the same instant on the others.43@Observable final class ChartLink {44 static let shared = ChartLink()45 var time: Date?46 var source: UUID?47}4849/// Everything about a chart that is saved in the synced `chart` object (and nothing that is not: the visible window50/// and the crosshair stay on this Mac).51struct ChartConfig: Equatable {52 var interval: BarInterval53 var range: ChartRange54 var style: ChartStyle55 var logScale: Bool56 var adjust: String57 var indicators: IndicatorSet58 var compare: [String]59 var drawings: [ChartDrawing]60}6162extension BarInterval {63 /// The interval as the v2 data layer and the synced chart object name it: `1m|5m|15m|30m|1h|4h|1d`.64 var v2: String { label.lowercased() }65 init?(v2: String) { guard let i = BarInterval.allCases.first(where: { $0.v2 == v2.lowercased() }) else { return nil }; self = i }66}6768@Observable final class ChartModel {69 static let adjustments = ["split_div", "split", "none"]70 static let maxCompare = 671 static func newDrawingID() -> String { "d_" + UUID().uuidString.lowercased().replacingOccurrences(of: "-", with: "").prefix(16) }7273 let id = UUID()74 private(set) var symbol: String75 private(set) var interval: BarInterval76 private(set) var range: ChartRange77 var style: ChartStyle { didSet { if style != oldValue { userChanged() } } }78 var logScale: Bool { didSet { if logScale != oldValue { userChanged() } } }79 var indicators = IndicatorSet() { didSet { if indicators != oldValue { userChanged() } } }80 /// The adjustment asked from the data layer (`split_div` | `split` | `none`); the provenance says what was applied.81 private(set) var adjust = "split_div"82 var linked = true8384 /// The bars as received from the server. Exports and statistics always use these.85 private(set) var bars: [Bar] = []86 /// Epoch seconds of each bar (drawing anchors are positioned against these).87 private(set) var times: [Double] = []88 private(set) var provenance: ChartProvenance?89 private(set) var dropped = 090 private(set) var fetchedAt: Date?91 private(set) var fromCache = false92 private(set) var loading = false93 private(set) var error: String?94 /// Other symbols drawn as percentage change against the first visible bar: closes aligned on this chart's bars.95 private(set) var compare: [String: [Double?]] = [:]96 private(set) var compareOrder: [String] = []9798 // drawings99 private(set) var drawings: [ChartDrawing] = []100 /// The tool the next click uses (nil = the pointer: select, move, pan).101 var tool: DrawingKind?102 var selection: String?103 /// The drawing being created (second anchor follows the pointer).104 var draft: ChartDrawing?105 /// Palette index (design tokens, categorical data palette) given to new drawings.106 var drawingColor = 0107 /// The text note whose words are being typed.108 var editingText: String?109 /// Indicators and drawings another client stored that this app keeps but does not draw (set by ChartSync).110 var foreignIndicators = 0111 var foreignDrawings = 0112113 // visible window, in bar-index units (fractional while zooming and panning)114 private(set) var start: Double = 0115 private(set) var count: Double = 120116 /// Index of the bar under the pointer and the pointer's price, when it is over the chart.117 var hover: (index: Int, price: Double?)?118 /// Written by the renderer, read by the pointer handler (not observed: it changes on every frame).119 @ObservationIgnored var scale: ChartScale?120121 // derived series, recomputed when bars change122 private(set) var closes: [Double] = []123 /// The closes as a line series (comparison mode draws them like any other line).124 @ObservationIgnored private(set) var closeLine: [Double?] = []125 private(set) var sma20: [Double?] = []126 private(set) var sma50: [Double?] = []127 private(set) var sma200: [Double?] = []128 private(set) var ema20: [Double?] = []129 private(set) var bands = Indicators.Bands(middle: [], upper: [], lower: [])130 private(set) var rsi: [Double?] = []131 private(set) var macd = Indicators.MACD(macd: [], signal: [], histogram: [])132 /// Per bar, a number that changes where the time axis puts a label: the day (intraday) or the month (daily).133 @ObservationIgnored private(set) var axisKeys: [Int32] = []134 /// Indices of the bars that open a new day (intraday) or month (daily), ascending.135 @ObservationIgnored private(set) var axisBoundaries: [Int] = []136137 // per-zoom-level caches of the visual reduction (cleared when the series changes)138 @ObservationIgnored private var bucketCache: [Int: [Downsampler.Bucket]] = [:]139 @ObservationIgnored private var envelopeCache: [String: [Downsampler.Envelope?]] = [:]140141 /// Called after a change made by the person that belongs in the synced chart object (never for pan, zoom or data).142 @ObservationIgnored var onUserChange: (() -> Void)?143 /// Called before the symbol changes, while the chart still shows the old one (a pending save is written then).144 @ObservationIgnored var onSymbolWillChange: (() -> Void)?145 @ObservationIgnored private var applying = false146 @ObservationIgnored private var editSnapshot: [ChartDrawing]?147148 @ObservationIgnored private let api: VQuantAPI149 @ObservationIgnored private let vq: VQNextAPI150 @ObservationIgnored private let cache: DiskCache151 @ObservationIgnored private let settings: SettingsStore152 @ObservationIgnored private var loadTask: Task<Void, Never>?153 @ObservationIgnored private var refreshLoop: Task<Void, Never>?154 @ObservationIgnored private var loadedKey = ""155156 init(app: AppEnvironment, symbol: String, interval: BarInterval? = nil, range: ChartRange? = nil) {157 api = app.api; vq = app.vq; cache = app.cache; settings = app.settings158 self.symbol = symbol159 let i = interval ?? app.settings.chartInterval160 self.interval = i161 self.range = range ?? (i.isIntraday ? .d5 : .y1)162 style = app.settings.chartStyle; logScale = app.settings.chartLogScale163 indicators.volume = app.settings.chartVolume164 }165166 var isIntraday: Bool { interval.isIntraday }167 var visibleRange: Range<Int> {168 let a = max(0, Int(start.rounded(.down))), b = min(bars.count, Int((start + count).rounded(.up)))169 return a..<max(a, b)170 }171172 var freshness: Freshness {173 if let e = error, bars.isEmpty { return .unavailable(e) }174 if fromCache, let f = fetchedAt { return .cached(fetched: f) }175 return .historical(through: bars.last?.time)176 }177178 // MARK: time zone of the series179180 /// Daily bars are stamped 00:00 UTC of their session date; intraday bars are instants, shown in the market's181 /// zone when the server states it. Bars from the 1.x route keep its convention (exchange wall time read as UTC).182 var displayZone: TimeZone {183 guard isIntraday, provenance?.route == .v2, let z = provenance?.timezone.flatMap(TimeZone.init(identifier:)) else { return BarParser.calendar.timeZone }184 return z185 }186 func dateText(_ d: Date) -> String {187 var s = Date.FormatStyle(date: .abbreviated, time: isIntraday ? .shortened : .omitted)188 s.timeZone = displayZone189 return d.formatted(s)190 }191192 // MARK: settings changed by the person193194 private func userChanged() { if !applying { onUserChange?() } }195196 func setSymbol(_ s: String) {197 guard s != symbol else { return }198 onSymbolWillChange?()199 symbol = s; bars = []; provenance = nil; drawings = []; draft = nil; selection = nil; editingText = nil; foreignIndicators = 0; foreignDrawings = 0200 compareOrder.removeAll { $0 == s }; compare[s] = nil201 recompute(); reload()202 }203 func setInterval(_ i: BarInterval) {204 guard i != interval else { return }205 interval = i206 if !ChartRange.available(for: i).contains(range) { range = i.isIntraday ? .d5 : .y1 }207 userChanged(); reload()208 }209 func setRange(_ r: ChartRange) { guard r != range else { return }; range = r; userChanged(); reload() }210 func setAdjust(_ a: String) { guard a != adjust, Self.adjustments.contains(a) else { return }; adjust = a; userChanged(); reload() }211212 var config: ChartConfig {213 ChartConfig(interval: interval, range: range, style: style, logScale: logScale, adjust: adjust, indicators: indicators, compare: compareOrder, drawings: drawings)214 }215216 /// Applies settings that come from the synced object (another device, or the first read): no save is triggered.217 func apply(_ c: ChartConfig) {218 applying = true; defer { applying = false }219 let refetch = c.interval != interval || c.range != range || c.adjust != adjust220 interval = c.interval221 range = ChartRange.available(for: c.interval).contains(c.range) ? c.range : (c.interval.isIntraday ? .d5 : .y1)222 adjust = Self.adjustments.contains(c.adjust) ? c.adjust : "split_div"223 if style != c.style { style = c.style }224 if logScale != c.logScale { logScale = c.logScale }225 if indicators != c.indicators { indicators = c.indicators }226 if drawings != c.drawings {227 drawings = c.drawings228 if let s = selection, !drawings.contains(where: { $0.id == s }) { selection = nil }229 }230 let wanted = c.compare.filter { $0 != symbol }.prefix(Self.maxCompare)231 for s in compareOrder where !wanted.contains(s) { compareOrder.removeAll { $0 == s }; compare[s] = nil }232 let added = wanted.filter { !compareOrder.contains($0) }233 compareOrder = Array(wanted)234 if refetch { reload() } else { for s in added { Task { await loadCompare(s) } } }235 }236237 // MARK: loading238239 func reload(keepView: Bool = false) {240 loadTask?.cancel()241 loadTask = Task { await load(keepView: keepView) }242 }243244 private static let dayFormat: DateFormatter = { let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd"; return f }()245246 /// One series from `GET /api/v2/data/bars/:symbol`. The 1.x provider proxy is asked only when the data layer247 /// answers 404 or 502, and the provenance then says so. A network failure falls back to the encrypted cache248 /// (the result is marked as cached); any other refusal is an error.249 private func fetch(_ symbol: String) async throws -> Cached<ChartSeries> {250 let now = Date()251 let from = Self.dayFormat.string(from: range.start(from: now)), to = Self.dayFormat.string(from: now)252 let i = interval, adjust = adjust253 // the cache key names the series, not the dates: an offline reload returns the last series received for it254 return try await cache.fetch("bars2-\(symbol)-\(i.rawValue)-\(range.rawValue)-\(adjust)") { [api, vq] in255 do {256 return ChartSeries(try await vq.data.bars(symbol, interval: i.v2, from: from, to: to, adjust: adjust, limit: 50_000))257 } catch let e as VQError {258 if e.kind == .network { throw APIError(.network, e.message) }259 guard e.status == 404 || e.status == 502 else { throw APIError(e.status == 400 ? .rejected : .server, status: e.status, e.message) }260 let legacy = i.isIntraday ? try await api.intradayBars(symbol, interval: i, from: from, to: to) : try await api.dailyBars(symbol, from: from, to: to)261 guard !legacy.bars.isEmpty else { throw APIError(e.status == 404 ? .notFound : .server, status: e.status, e.message) }262 return ChartSeries(bars: legacy.bars, provenance: ChartProvenance(route: .legacy, routeReason: "the v2 data layer answered \(e.status)", provider: "fmp",263 observations: legacy.bars.count), dropped: legacy.dropped)264 }265 }266 }267268 private func load(keepView: Bool) async {269 let key = "\(symbol)|\(interval.rawValue)|\(range.rawValue)|\(adjust)"270 loading = true; defer { loading = false }271 do {272 let r = try await fetch(symbol)273 guard !Task.isCancelled else { return }274 let atEnd = start + count >= Double(bars.count) - 1275 let grew = r.value.bars.count - bars.count276 bars = r.value.bars; provenance = r.value.provenance; dropped = r.value.dropped277 fetchedAt = r.fetchedAt; fromCache = r.fromCache; error = bars.isEmpty ? "The provider returned no bars for \(symbol) at this interval and range." : nil278 recompute()279 if keepView, loadedKey == key { if atEnd, grew > 0 { start += Double(grew) }; clamp() } else { fit() }280 loadedKey = key281 for s in compareOrder { await loadCompare(s) }282 } catch is CancellationError {} catch {283 if !Task.isCancelled { self.error = error.localizedDescription; if loadedKey != key { bars = []; provenance = nil; recompute() } }284 }285 }286287 private func recompute() {288 closes = bars.map(\.close)289 closeLine = closes.map { Optional($0) }290 times = bars.map { $0.time.timeIntervalSince1970 }291 sma20 = Indicators.sma(closes, 20); sma50 = Indicators.sma(closes, 50); sma200 = Indicators.sma(closes, 200); ema20 = Indicators.ema(closes, 20)292 bands = Indicators.bollinger(closes, 20, k: 2)293 rsi = Indicators.rsi(closes, 14); macd = Indicators.macd(closes)294 bucketCache = [:]; envelopeCache = [:]295 // where the time axis changes unit: computed once per series, not per frame296 let zone = displayZone297 var cal = Calendar(identifier: .gregorian); cal.timeZone = zone298 if isIntraday {299 axisKeys = bars.map { Int32((($0.time.timeIntervalSince1970 + Double(zone.secondsFromGMT(for: $0.time))) / 86_400).rounded(.down)) }300 } else {301 axisKeys = bars.map { let c = cal.dateComponents([.year, .month], from: $0.time); return Int32((c.year ?? 0) * 12 + (c.month ?? 0)) }302 }303 axisBoundaries = axisKeys.indices.dropFirst().filter { axisKeys[$0] != axisKeys[$0 - 1] }304 }305306 func buckets(per: Int) -> [Downsampler.Bucket] {307 if let b = bucketCache[per] { return b }308 if bucketCache.count > 24 { bucketCache.removeAll() }309 let b = Downsampler.ohlcAligned(bars, per: per)310 bucketCache[per] = b311 return b312 }313 /// A line series reduced the same way, cached under `name`.314 func envelope(_ name: String, _ series: [Double?], per: Int) -> [Downsampler.Envelope?] {315 let key = "\(name)#\(per)"316 if let e = envelopeCache[key] { return e }317 if envelopeCache.count > 96 { envelopeCache.removeAll() }318 let e = Downsampler.envelope(series, per: per)319 envelopeCache[key] = e320 return e321 }322323 #if DEBUG324 /// Benchmark only (ChartBench): a synthetic series, never shown as data.325 func benchLoad(_ b: [Bar]) { bars = b; error = nil; recompute(); fit() }326 func benchWindow(start s: Double, count c: Double) { start = s; count = c }327 func benchDrawings(_ d: [ChartDrawing]) { drawings = d }328 #endif329330 // MARK: Compare331332 func addCompare(_ s: String) {333 guard s != symbol, !compareOrder.contains(s), compareOrder.count < Self.maxCompare else { return }334 compareOrder.append(s)335 userChanged()336 Task { await loadCompare(s) }337 }338 func removeCompare(_ s: String) { compareOrder.removeAll { $0 == s }; compare[s] = nil; envelopeCache = [:]; userChanged() }339 private func loadCompare(_ s: String) async {340 do {341 let r = try await fetch(s)342 guard compareOrder.contains(s) else { return }343 let m = Dictionary(r.value.bars.map { ($0.time, $0.close) }, uniquingKeysWith: { $1 })344 compare[s] = bars.map { m[$0.time] }345 envelopeCache = envelopeCache.filter { !$0.key.hasPrefix("cmp-\(s)#") }346 } catch { if !(error is CancellationError) { compareOrder.removeAll { $0 == s }; compare[s] = nil } }347 }348349 // MARK: Drawings350351 /// Replaces the drawings as one undoable step.352 func setDrawings(_ new: [ChartDrawing], undo: UndoManager?, action: String) {353 let old = drawings354 guard new != old else { return }355 drawings = new356 if let s = selection, !new.contains(where: { $0.id == s }) { selection = nil }357 if let e = editingText, !new.contains(where: { $0.id == e }) { editingText = nil }358 undo?.registerUndo(withTarget: self) { m in MainActor.assumeIsolated { m.setDrawings(old, undo: undo, action: action) } }359 undo?.setActionName(action)360 userChanged()361 }362 func add(_ d: ChartDrawing, undo: UndoManager?) { setDrawings(drawings + [d], undo: undo, action: "Add \(d.kind.title)"); selection = d.id }363 func delete(_ id: String, undo: UndoManager?) {364 guard let d = drawings.first(where: { $0.id == id }) else { return }365 setDrawings(drawings.filter { $0.id != id }, undo: undo, action: "Delete \(d.kind.title)")366 }367 func deleteAllDrawings(undo: UndoManager?) { setDrawings([], undo: undo, action: "Delete All Drawings") }368 func setColor(_ c: Int, of id: String, undo: UndoManager?) {369 var new = drawings370 guard let i = new.firstIndex(where: { $0.id == id }), new[i].color != c else { return }371 new[i].color = c372 setDrawings(new, undo: undo, action: "Change Colour")373 }374 /// Ends the typing of a note: an empty note is removed.375 func setText(_ text: String, of id: String, undo: UndoManager?) {376 editingText = nil377 let t = String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(200))378 var new = drawings379 guard let i = new.firstIndex(where: { $0.id == id }) else { return }380 if t.isEmpty { new.remove(at: i) } else { new[i].text = t }381 setDrawings(new, undo: undo, action: "Edit Note")382 }383384 /// A move or a resize in progress: the drawing follows the pointer without filling the undo stack; `endEdit`385 /// records the whole gesture as one step.386 func beginEdit() { editSnapshot = drawings }387 func updateDuringEdit(_ d: ChartDrawing) { if let i = drawings.firstIndex(where: { $0.id == d.id }), drawings[i] != d { drawings[i] = d } }388 func endEdit(undo: UndoManager?, action: String) {389 guard let old = editSnapshot else { return }390 editSnapshot = nil391 let new = drawings392 guard new != old else { return }393 drawings = old394 setDrawings(new, undo: undo, action: action)395 }396397 /// Seconds between two bars of this interval (extrapolates anchors outside the loaded series).398 var stepSeconds: Double { interval.seconds }399400 // MARK: View window401402 /// Shows the whole series (the last session only for the 1D range).403 func fit() {404 guard !bars.isEmpty else { start = 0; count = 120; return }405 if range == .d1, !axisKeys.isEmpty, isIntraday {406 let day = axisKeys[axisKeys.count - 1]407 let first = axisKeys.firstIndex(of: day) ?? 0408 start = Double(first); count = Double(bars.count - first)409 } else { start = 0; count = Double(bars.count) }410 count = max(count, 10); clamp()411 }412413 func pan(bars delta: Double) { start += delta; clamp() }414415 /// Zooms by `factor` (>1 shows fewer bars) keeping the bar under `anchor` (0…1 across the plot) in place.416 func zoom(factor: Double, anchor: Double) {417 let newCount = min(max(count / factor, 10), max(Double(bars.count) * 1.1, 10))418 let pivot = start + count * anchor419 start = pivot - newCount * anchor420 count = newCount421 clamp()422 }423424 private func clamp() {425 let n = Double(bars.count)426 count = min(max(count, 10), max(n * 1.1, 10))427 // a little empty space is allowed on the right so the last bar is not glued to the axis428 start = min(max(start, -count * 0.1), max(n - count * 0.9, 0))429 }430431 // MARK: Refresh432433 /// While a chart is on screen its series is fetched again at the quote cadence (intraday) or every five minutes (daily).434 func startRefreshing() {435 refreshLoop?.cancel()436 refreshLoop = Task { [weak self] in437 while !Task.isCancelled {438 guard let self else { return }439 let every = self.isIntraday ? max(self.settings.quoteRefresh, 15) : 300440 try? await Task.sleep(for: .seconds(self.settings.quoteRefresh == 0 ? 3600 : every))441 if Task.isCancelled { return }442 if NSApp.isActive, !self.loading { await self.load(keepView: true) }443 }444 }445 }446 func stopRefreshing() { refreshLoop?.cancel(); refreshLoop = nil; loadTask?.cancel() }447}448449extension ChartSeries {450 /// The kit's series as this app charts and caches it. A row without a close is dropped and counted.451 nonisolated init(_ s: VQBarSeries) {452 var out: [Bar] = []; out.reserveCapacity(s.bars.count)453 var dropped = 0454 for b in s.bars {455 guard let c = b.close, c.isFinite else { dropped += 1; continue }456 let o = b.open ?? c457 out.append(Bar(time: b.date, open: o, high: b.high ?? max(o, c), low: b.low ?? min(o, c), close: c, volume: b.volume ?? 0))458 }459 let p = s.provenance460 let prov = ChartProvenance(route: .v2, provider: p.provider, fallbackFrom: p.fallbackFrom, fallbackReason: p.fallbackReason, retrievedAt: p.retrievedAt,461 adjust: p.adjust, adjustRequested: p.adjustRequested, assetClass: p.assetClass, exchange: p.exchange, timezone: p.timezone, currency: p.currency,462 freshnessKind: p.freshness?.kind.rawValue, asOf: p.freshness?.asOf, observations: p.observations, firstDate: p.firstDate, lastDate: p.lastDate,463 truncated: p.truncated,464 gaps: p.gaps.map { .init(missingSessions: $0.missingSessions, missingDates: $0.missingDates, unexpectedSessions: $0.unexpectedSessions, unexpectedDates: $0.unexpectedDates,465 calendar: $0.calendar, checkedFrom: $0.checkedFrom, checkedTo: $0.checkedTo, note: $0.note) },466 notes: p.notes)467 self.init(bars: out, provenance: prov, dropped: dropped)468 }469}470