SPB Git

Repository Public

ChartCanvas.swift 28.0 KB 434 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartCanvas.swift3// Description: The chart renderer (Core Graphics through SwiftUI Canvas): price, volume, RSI and MACD panels, indicators, overlays, drawings, crosshair. One mark per ~2.5 points whatever the series length, from reductions cached per zoom level.4import SwiftUI5import VQuantCore6import VQuantUI78/// Geometry shared by drawing and hit-testing so both agree on which bar is under the pointer.9struct ChartLayout {10    static let axisWidth: CGFloat = 6411    static let timeAxisHeight: CGFloat = 2012    var size: CGSize13    var showVolume: Bool, showRSI: Bool, showMACD: Bool1415    var plotWidth: CGFloat { max(1, size.width - Self.axisWidth) }16    var plotHeight: CGFloat { max(1, size.height - Self.timeAxisHeight) }17    private var subCount: CGFloat { (showVolume ? 1 : 0) + (showRSI ? 1 : 0) + (showMACD ? 1 : 0) }18    private var subHeight: CGFloat { min(plotHeight * 0.17, 110) }19    var price: CGRect { CGRect(x: 0, y: 0, width: plotWidth, height: plotHeight - subCount * subHeight) }20    func sub(_ n: Int) -> CGRect { CGRect(x: 0, y: price.maxY + CGFloat(n) * subHeight, width: plotWidth, height: subHeight) }21    var volume: CGRect? { showVolume ? sub(0) : nil }22    var rsi: CGRect? { showRSI ? sub(showVolume ? 1 : 0) : nil }23    var macd: CGRect? { showMACD ? sub((showVolume ? 1 : 0) + (showRSI ? 1 : 0)) : nil }24}2526/// Colours of the chart, all from the design tokens (data palette for series, ink and lines for the frame).27enum ChartColors {28    static let grid = VQTokens.Palette.line.opacity(0.7)29    static let frame = VQTokens.Palette.lineStrong30    static let axisText = VQTokens.Palette.text331    static let background = VQTokens.Palette.ink132    static let series = VQTokens.DataPalette.categorical33    static let price = series[0]34    static let sma20 = series[3], sma50 = series[0], sma200 = series[4], ema20 = series[2], bollinger = series[6], rsi = series[6], macd = series[0], signal = series[1]35    static func drawing(_ i: Int) -> Color { series[((i % series.count) + series.count) % series.count] }36    static func compare(_ n: Int) -> Color { series[n % series.count] }37}3839struct ChartCanvas: View {40    let model: ChartModel41    let settings: SettingsStore42    /// false when rendering for export: no crosshair, no hover state, no selection handles43    var interactive = true4445    var body: some View {46        Canvas(opaque: false, rendersAsynchronously: false) { ctx, size in47            draw(&ctx, size)48        }49        .accessibilityElement()50        .accessibilityLabel(accessibilitySummary)51        .accessibilityValue("\(model.drawings.count) drawing\(model.drawings.count == 1 ? "" : "s")")52        .accessibilityIdentifier("chart.canvas")53    }5455    private var accessibilitySummary: String {56        guard let last = model.bars.last else { return "Chart of \(model.symbol): no data" }57        return "Chart of \(model.symbol), \(model.interval.label) bars, \(model.bars.count) bars, last close \(Fmt.price(last.close)) on \(model.dateText(last.time))"58    }5960    // MARK: Drawing6162    private func draw(_ ctx: inout GraphicsContext, _ size: CGSize) {63        #if DEBUG64        let perfStart = ChartPerf.samples == nil ? 0 : CACurrentMediaTime()65        defer { if ChartPerf.samples != nil { ChartPerf.samples?.append(CACurrentMediaTime() - perfStart) } }66        #endif67        let L = ChartLayout(size: size, showVolume: model.indicators.volume, showRSI: model.indicators.rsi, showMACD: model.indicators.macd)68        let bars = model.bars69        let grid = ChartColors.grid, axisText = ChartColors.axisText70        guard !bars.isEmpty else { return }71        let vis = model.visibleRange72        guard !vis.isEmpty else { return }73        let start = model.start74        let step = L.plotWidth / CGFloat(model.count)75        func x(_ i: Double) -> CGFloat { CGFloat(i - start) * step + step / 2 }7677        // Visual reduction only: when bars are narrower than 2.5 pt, consecutive bars are merged into OHLC marks that78        // keep every extreme. The marks are aligned on the series and cached per zoom level (ChartModel.buckets), so a79        // pan redraws from the same list. The source series is untouched (see the footer and the CSV export).80        let per = Downsampler.per(visible: vis.count, maxBuckets: max(20, Int(L.plotWidth / 2.5)))81        let all = per > 1 ? model.buckets(per: per) : []82        let br = per > 1 ? Downsampler.bucketRange(vis, per: per, total: all.count) : 0..<083        let markCount = per > 1 ? br.count : vis.count84        /// Calls `body` with each visible mark: its OHLCV, the index of its centre, its first source index.85        func forEachMark(_ body: (Bar, Double) -> Void) {86            if per > 1 { for k in br { let b = all[k]; body(b.bar, Double(b.firstIndex) + Double(b.count - 1) / 2) } }87            else { for i in vis { body(bars[i], Double(i)) } }88        }89        /// The visible part of a line series as a path: one point per bar, or first → low → high → last per mark.90        func linePath(_ name: String, _ s: [Double?], _ y: (Double) -> CGFloat) -> Path {91            var p = Path(); var on = false92            if per > 1 {93                let env = model.envelope(name, s, per: per)94                for k in br where k < env.count {95                    guard let e = env[k] else { on = false; continue }96                    let xx = x(Double(k * per) + Double(min(per, s.count - k * per) - 1) / 2)97                    if on { p.addLine(to: CGPoint(x: xx, y: y(e.first))) } else { p.move(to: CGPoint(x: xx, y: y(e.first))); on = true }98                    if e.lo != e.hi { p.addLine(to: CGPoint(x: xx, y: y(e.lo))); p.addLine(to: CGPoint(x: xx, y: y(e.hi))); p.addLine(to: CGPoint(x: xx, y: y(e.last))) }99                }100            } else {101                for i in vis where i < s.count {102                    if let v = s[i] { let pt = CGPoint(x: x(Double(i)), y: y(v)); if on { p.addLine(to: pt) } else { p.move(to: pt); on = true } } else { on = false }103                }104            }105            return p106        }107        let comparing = !model.compareOrder.isEmpty108109        // ── price scale110        var lo = Double.infinity, hi = -Double.infinity111        var base: Double = 1112        var compareBase: [String: Double] = [:]113        if comparing {114            base = bars[vis.lowerBound].close115            for i in vis { let p = (bars[i].close / base - 1) * 100; if p < lo { lo = p }; if p > hi { hi = p } }116            for s in model.compareOrder {117                guard let m = model.compare[s], let b0 = firstValue(m, vis) else { continue }118                compareBase[s] = b0119                for i in vis where i < m.count { if let c = m[i] { let p = (c / b0 - 1) * 100; if p < lo { lo = p }; if p > hi { hi = p } } }120            }121        } else {122            forEachMark { b, _ in if b.low < lo { lo = b.low }; if b.high > hi { hi = b.high } }123            if model.indicators.bollinger {124                if per > 1 {125                    let u = model.envelope("bbu", model.bands.upper, per: per), l = model.envelope("bbl", model.bands.lower, per: per)126                    for k in br { if k < u.count, let e = u[k], e.hi > hi { hi = e.hi }; if k < l.count, let e = l[k], e.lo < lo { lo = e.lo } }127                } else {128                    for i in vis { if let u = model.bands.upper[i], let l = model.bands.lower[i] { if u > hi { hi = u }; if l < lo { lo = l } } }129                }130            }131        }132        guard lo.isFinite, hi.isFinite else { return }133        if hi == lo { hi += 1; lo -= 1 }134        let useLog = model.logScale && !comparing && lo > 0135        let pad = (hi - lo) * 0.06136        let top = useLog ? hi * 1.02 : hi + pad, bottom = useLog ? lo / 1.02 : lo - pad137        let pr = L.price138        let scale = ChartScale(top: top, bottom: bottom, log: useLog, minY: pr.minY, maxY: pr.maxY, base: comparing ? base : nil)139        func y(_ v: Double) -> CGFloat { scale.y(v) }140        // the pointer handler reads the scale that was actually drawn141        model.scale = scale142143        // ── grid and price axis144        var gridPath = Path()145        for t in ticks(bottom, top, target: max(3, Int(pr.height / 56))) {146            let yy = y(t)147            guard yy > pr.minY + 4, yy < pr.maxY - 2 else { continue }148            gridPath.move(to: CGPoint(x: 0, y: yy)); gridPath.addLine(to: CGPoint(x: L.plotWidth, y: yy))149            ctx.draw(Text(comparing ? Fmt.percent(t, digits: 1) : Fmt.price(t)).font(.system(size: 10, design: .monospaced)).foregroundStyle(axisText), at: CGPoint(x: L.plotWidth + 5, y: yy), anchor: .leading)150        }151        // ── time axis152        drawTimeAxis(&ctx, L, bars: bars, vis: vis, x: x, grid: &gridPath, text: axisText)153        ctx.stroke(gridPath, with: .color(grid), lineWidth: 1)154155        let up = settings.upColor, down = settings.downColor156        var axisTags: [(String, CGFloat, Color)] = []157        ctx.drawLayer { layer in158            layer.clip(to: Path(pr))159            if comparing {160                layer.stroke(linePath("cmp-own", model.closeLine) { y(($0 / base - 1) * 100) }, with: .color(ChartColors.compare(0)), lineWidth: 1.6)161                for (n, s) in model.compareOrder.enumerated() {162                    guard let m = model.compare[s], let b0 = compareBase[s] else { continue }163                    layer.stroke(linePath("cmp-\(s)", m) { y(($0 / b0 - 1) * 100) }, with: .color(ChartColors.compare(n + 1)), lineWidth: 1.4)164                }165            } else {166                let w = max(1, L.plotWidth / CGFloat(max(markCount, 1)) * 0.72)167                switch model.style {168                case .candles, .ohlc:169                    var upBody = Path(), downBody = Path(), upWick = Path(), downWick = Path()170                    let candles = model.style == .candles171                    forEachMark { b, centre in172                        let cx = x(centre)173                        let rising = b.close >= b.open174                        let o = y(b.open), c = y(b.close), h = y(b.high), l = y(b.low)175                        if candles {176                            if rising { upWick.move(to: CGPoint(x: cx, y: h)); upWick.addLine(to: CGPoint(x: cx, y: l)); upBody.addRect(CGRect(x: cx - w / 2, y: min(o, c), width: w, height: max(1, abs(c - o)))) }177                            else { downWick.move(to: CGPoint(x: cx, y: h)); downWick.addLine(to: CGPoint(x: cx, y: l)); downBody.addRect(CGRect(x: cx - w / 2, y: min(o, c), width: w, height: max(1, abs(c - o)))) }178                        } else if rising {179                            upWick.move(to: CGPoint(x: cx, y: h)); upWick.addLine(to: CGPoint(x: cx, y: l)); upWick.move(to: CGPoint(x: cx - w / 2, y: o)); upWick.addLine(to: CGPoint(x: cx, y: o)); upWick.move(to: CGPoint(x: cx, y: c)); upWick.addLine(to: CGPoint(x: cx + w / 2, y: c))180                        } else {181                            downWick.move(to: CGPoint(x: cx, y: h)); downWick.addLine(to: CGPoint(x: cx, y: l)); downWick.move(to: CGPoint(x: cx - w / 2, y: o)); downWick.addLine(to: CGPoint(x: cx, y: o)); downWick.move(to: CGPoint(x: cx, y: c)); downWick.addLine(to: CGPoint(x: cx + w / 2, y: c))182                        }183                    }184                    layer.stroke(upWick, with: .color(up), lineWidth: 1); layer.stroke(downWick, with: .color(down), lineWidth: 1)185                    layer.fill(upBody, with: .color(up)); layer.fill(downBody, with: .color(down))186                case .line, .area:187                    var p = Path(); var started = false188                    var firstX: CGFloat = 0, lastX: CGFloat = 0189                    forEachMark { b, centre in190                        let pt = CGPoint(x: x(centre), y: y(b.close))191                        if started { p.addLine(to: pt) } else { p.move(to: pt); started = true; firstX = pt.x }192                        lastX = pt.x193                    }194                    if model.style == .area, started {195                        var a = p196                        a.addLine(to: CGPoint(x: lastX, y: pr.maxY)); a.addLine(to: CGPoint(x: firstX, y: pr.maxY)); a.closeSubpath()197                        layer.fill(a, with: .linearGradient(Gradient(colors: [ChartColors.price.opacity(0.26), ChartColors.price.opacity(0.02)]), startPoint: CGPoint(x: 0, y: pr.minY), endPoint: CGPoint(x: 0, y: pr.maxY)))198                    }199                    layer.stroke(p, with: .color(ChartColors.price), lineWidth: 1.6)200                }201                if model.indicators.bollinger {202                    layer.stroke(linePath("bbu", model.bands.upper) { y($0) }, with: .color(ChartColors.bollinger.opacity(0.8)), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round, dash: [3, 3])); layer.stroke(linePath("bbl", model.bands.lower) { y($0) }, with: .color(ChartColors.bollinger.opacity(0.8)), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round, dash: [3, 3]))203                    layer.stroke(linePath("bbm", model.bands.middle) { y($0) }, with: .color(ChartColors.bollinger.opacity(0.5)), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round))204                }205                if model.indicators.sma20 { layer.stroke(linePath("sma20", model.sma20) { y($0) }, with: .color(ChartColors.sma20), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round)) }206                if model.indicators.sma50 { layer.stroke(linePath("sma50", model.sma50) { y($0) }, with: .color(ChartColors.sma50), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round)) }207                if model.indicators.sma200 { layer.stroke(linePath("sma200", model.sma200) { y($0) }, with: .color(ChartColors.sma200), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round)) }208                if model.indicators.ema20 { layer.stroke(linePath("ema20", model.ema20) { y($0) }, with: .color(ChartColors.ema20), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round)) }209                // last close210                if let last = bars.last {211                    let yy = y(last.close)212                    layer.stroke(Path { $0.move(to: CGPoint(x: 0, y: yy)); $0.addLine(to: CGPoint(x: L.plotWidth, y: yy)) }, with: .color(axisText.opacity(0.7)), style: StrokeStyle(lineWidth: 0.8, dash: [2, 3]))213                }214            }215            // ── drawings (anchored in time and price; see ChartDrawingRender)216            if !model.drawings.isEmpty || model.draft != nil {217                let proj = ChartProjection(start: start, step: step, times: model.times, stepSeconds: model.stepSeconds, scale: scale)218                for d in model.drawings {219                    let selected = interactive && model.selection == d.id220                    if let tag = ChartDrawingRender.draw(d, in: &layer, proj: proj, plot: pr, selected: selected, draft: false, editing: model.editingText == d.id, model: model) { axisTags.append(tag) }221                }222                if interactive, let d = model.draft { _ = ChartDrawingRender.draw(d, in: &layer, proj: proj, plot: pr, selected: true, draft: true, editing: false, model: model) }223            }224        }225        for (text, yy, color) in axisTags where yy > pr.minY && yy < pr.maxY { tag(&ctx, text, at: CGPoint(x: L.plotWidth + 2, y: yy), fill: color) }226        if !comparing, let last = bars.last, y(last.close) > pr.minY, y(last.close) < pr.maxY {227            tag(&ctx, Fmt.price(last.close), at: CGPoint(x: L.plotWidth + 2, y: y(last.close)), fill: last.close >= last.open ? up : down)228        }229230        // ── sub-panels231        if let r = L.volume {232            hairline(&ctx, r.minY, L.plotWidth)233            var vmax = 0.0234            forEachMark { b, _ in if b.volume > vmax { vmax = b.volume } }235            if vmax > 0 {236                let w = max(1, L.plotWidth / CGFloat(max(markCount, 1)) * 0.72)237                var upPath = Path(), downPath = Path()238                forEachMark { b, centre in239                    let h = CGFloat(b.volume / vmax) * (r.height - 14)240                    let rect = CGRect(x: x(centre) - w / 2, y: r.maxY - h, width: w, height: h)241                    if b.close >= b.open { upPath.addRect(rect) } else { downPath.addRect(rect) }242                }243                ctx.fill(upPath, with: .color(up.opacity(0.55))); ctx.fill(downPath, with: .color(down.opacity(0.55)))244                ctx.draw(Text("Vol " + Fmt.compact(vmax)).font(.system(size: 9)).foregroundStyle(axisText), at: CGPoint(x: L.plotWidth + 5, y: r.minY + 8), anchor: .leading)245            }246        }247        if let r = L.rsi {248            hairline(&ctx, r.minY, L.plotWidth)249            func ry(_ v: Double) -> CGFloat { r.maxY - 3 - CGFloat(v / 100) * (r.height - 6) }250            for level in [30.0, 70.0] {251                ctx.stroke(Path { $0.move(to: CGPoint(x: 0, y: ry(level))); $0.addLine(to: CGPoint(x: L.plotWidth, y: ry(level))) }, with: .color(grid), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))252                ctx.draw(Text("\(Int(level))").font(.system(size: 9)).foregroundStyle(axisText), at: CGPoint(x: L.plotWidth + 5, y: ry(level)), anchor: .leading)253            }254            let p = linePath("rsi", model.rsi) { ry($0) }255            ctx.drawLayer { l in l.clip(to: Path(r)); l.stroke(p, with: .color(ChartColors.rsi), lineWidth: 1.2) }256            ctx.draw(Text("RSI 14").font(.system(size: 9, weight: .medium)).foregroundStyle(axisText), at: CGPoint(x: 6, y: r.minY + 8), anchor: .leading)257        }258        if let r = L.macd {259            hairline(&ctx, r.minY, L.plotWidth)260            var m = 0.0261            let hist = model.macd.histogram, ml = model.macd.macd, sg = model.macd.signal262            let he = per > 1 ? model.envelope("macdh", hist, per: per) : []263            if per > 1 {264                let a = model.envelope("macd", ml, per: per), b = model.envelope("macds", sg, per: per)265                for k in br { for e in [k < a.count ? a[k] : nil, k < b.count ? b[k] : nil, k < he.count ? he[k] : nil] { if let e { m = max(m, abs(e.lo), abs(e.hi)) } } }266            } else {267                for i in vis where i < ml.count { if let v = ml[i], abs(v) > m { m = abs(v) }; if let v = sg[i], abs(v) > m { m = abs(v) }; if let v = hist[i], abs(v) > m { m = abs(v) } }268            }269            if m > 0 {270                func my(_ v: Double) -> CGFloat { r.midY - CGFloat(v / m) * (r.height / 2 - 4) }271                ctx.drawLayer { l in272                    l.clip(to: Path(r))273                    var upPath = Path(), downPath = Path()274                    let w = max(1, L.plotWidth / CGFloat(max(markCount, 1)) * 0.6)275                    if per > 1 {276                        // a mark shows the largest swing of its bars, on its own side of zero277                        for k in br where k < he.count {278                            guard let e = he[k] else { continue }279                            let v = abs(e.hi) >= abs(e.lo) ? e.hi : e.lo280                            let cx = x(Double(k * per) + Double(min(per, hist.count - k * per) - 1) / 2)281                            let rect = CGRect(x: cx - w / 2, y: min(my(v), r.midY), width: w, height: abs(my(v) - r.midY))282                            if v >= 0 { upPath.addRect(rect) } else { downPath.addRect(rect) }283                        }284                    } else {285                        for i in vis where i < hist.count {286                            guard let h = hist[i] else { continue }287                            let rect = CGRect(x: x(Double(i)) - w / 2, y: min(my(h), r.midY), width: w, height: abs(my(h) - r.midY))288                            if h >= 0 { upPath.addRect(rect) } else { downPath.addRect(rect) }289                        }290                    }291                    l.fill(upPath, with: .color(up.opacity(0.5))); l.fill(downPath, with: .color(down.opacity(0.5)))292                    l.stroke(linePath("macd", ml) { my($0) }, with: .color(ChartColors.macd), lineWidth: 1.1)293                    l.stroke(linePath("macds", sg) { my($0) }, with: .color(ChartColors.signal), lineWidth: 1.1)294                }295                ctx.draw(Text("MACD 12 26 9").font(.system(size: 9, weight: .medium)).foregroundStyle(axisText), at: CGPoint(x: 6, y: r.minY + 8), anchor: .leading)296            }297        }298        ctx.stroke(Path { $0.move(to: CGPoint(x: L.plotWidth, y: 0)); $0.addLine(to: CGPoint(x: L.plotWidth, y: L.plotHeight)); $0.move(to: CGPoint(x: 0, y: L.plotHeight)); $0.addLine(to: CGPoint(x: L.plotWidth, y: L.plotHeight)) }, with: .color(ChartColors.frame), lineWidth: 1)299300        if per > 1 {301            ctx.draw(Text("Display: 1 mark = \(per) bars (extremes kept)").font(.system(size: 9)).foregroundStyle(axisText), at: CGPoint(x: 6, y: pr.maxY - 8), anchor: .leading)302        }303304        // ── crosshair305        guard interactive else { return }306        var idx = model.hover?.index307        var linkedOnly = false308        if idx == nil, model.linked, ChartLink.shared.source != model.id, let t = ChartLink.shared.time { idx = nearest(t, in: bars); linkedOnly = true }309        if let i = idx, vis.contains(i) {310            let xx = x(Double(i))311            let cross = VQTokens.Palette.text2.opacity(0.55), tagFill = VQTokens.Palette.text2312            ctx.stroke(Path { $0.move(to: CGPoint(x: xx, y: 0)); $0.addLine(to: CGPoint(x: xx, y: L.plotHeight)) }, with: .color(cross), style: StrokeStyle(lineWidth: 0.8, dash: [4, 3]))313            tag(&ctx, model.dateText(bars[i].time), at: CGPoint(x: min(max(xx, 60), L.plotWidth - 60), y: L.plotHeight + ChartLayout.timeAxisHeight / 2), fill: tagFill, anchor: .center)314            if !linkedOnly, let p = model.hover?.price, p.isFinite {315                let yy = y(p)316                if yy >= pr.minY, yy <= pr.maxY {317                    ctx.stroke(Path { $0.move(to: CGPoint(x: 0, y: yy)); $0.addLine(to: CGPoint(x: L.plotWidth, y: yy)) }, with: .color(cross), style: StrokeStyle(lineWidth: 0.8, dash: [4, 3]))318                    tag(&ctx, comparing ? Fmt.percent(p, digits: 2) : Fmt.price(p), at: CGPoint(x: L.plotWidth + 2, y: yy), fill: tagFill)319                }320            }321        }322    }323324    private func hairline(_ ctx: inout GraphicsContext, _ y: CGFloat, _ width: CGFloat) {325        ctx.stroke(Path { $0.move(to: CGPoint(x: 0, y: y)); $0.addLine(to: CGPoint(x: width, y: y)) }, with: .color(ChartColors.frame), lineWidth: 1)326    }327    private func firstValue(_ m: [Double?], _ vis: Range<Int>) -> Double? { for i in vis where i < m.count { if let v = m[i] { return v } }; return nil }328    private func nearest(_ t: Date, in bars: [Bar]) -> Int? {329        var lo = 0, hi = bars.count - 1330        guard hi >= 0 else { return nil }331        while lo < hi { let mid = (lo + hi) / 2; if bars[mid].time < t { lo = mid + 1 } else { hi = mid } }332        return lo333    }334335    private func tag(_ ctx: inout GraphicsContext, _ s: String, at p: CGPoint, fill: Color, anchor: UnitPoint = .leading) {336        let t = ctx.resolve(Text(s).font(.system(size: 10, weight: .medium, design: .monospaced)).foregroundStyle(VQTokens.Palette.ink1))337        let sz = t.measure(in: CGSize(width: 240, height: 40))338        let origin = anchor == .leading ? CGPoint(x: p.x, y: p.y - sz.height / 2 - 2) : CGPoint(x: p.x - sz.width / 2 - 4, y: p.y - sz.height / 2 - 2)339        let r = CGRect(origin: origin, size: CGSize(width: sz.width + 8, height: sz.height + 4))340        ctx.fill(Path(roundedRect: r, cornerRadius: 3), with: .color(fill))341        ctx.draw(t, at: CGPoint(x: r.midX, y: r.midY), anchor: .center)342    }343344    private func drawTimeAxis(_ ctx: inout GraphicsContext, _ L: ChartLayout, bars: [Bar], vis: Range<Int>, x: (Double) -> CGFloat, grid: inout Path, text: Color) {345        let boundaries = model.axisBoundaries346        let perLabel = max(1, Int((Double(vis.count) / Double(max(2, Int(L.plotWidth / 110)))).rounded()))347        var lastLabelX: CGFloat = -200348        var style = Date.FormatStyle(); style.timeZone = model.displayZone349        let intraday = model.isIntraday350        // candidates, in order: where the unit changes (day for intraday, month for daily) and every `perLabel` bars as351        // a fallback — found by search in the precomputed boundaries, not by scanning the visible bars352        var lo = 0, hi = boundaries.count353        while lo < hi { let mid = (lo + hi) / 2; if boundaries[mid] < vis.lowerBound { lo = mid + 1 } else { hi = mid } }354        var b = lo355        var m = ((vis.lowerBound + perLabel - 1) / perLabel) * perLabel356        while true {357            let nextB = b < boundaries.count && boundaries[b] < vis.upperBound ? boundaries[b] : Int.max358            let nextM = m < vis.upperBound ? m : Int.max359            let i = min(nextB, nextM)360            if i == Int.max { break }361            let boundary = i == nextB362            if i == nextB { b += 1 }363            if i == nextM { m += perLabel }364            let xx = x(Double(i))365            guard xx - lastLabelX > 74, xx > 20, xx < L.plotWidth - 20 else { continue }366            lastLabelX = xx367            grid.move(to: CGPoint(x: xx, y: 0)); grid.addLine(to: CGPoint(x: xx, y: L.plotHeight))368            let t = bars[i].time369            let label: String370            if intraday { label = boundary ? t.formatted(style.month(.abbreviated).day()) : t.formatted(style.hour(.twoDigits(amPM: .omitted)).minute()) }371            else if vis.count > 400 { label = t.formatted(style.year().month(.abbreviated)) }372            else { label = t.formatted(style.month(.abbreviated).day()) }373            ctx.draw(Text(label).font(.system(size: 10)).foregroundStyle(text), at: CGPoint(x: xx, y: L.plotHeight + ChartLayout.timeAxisHeight / 2), anchor: .center)374        }375    }376377    /// "Nice" axis values (1, 2, 5 × 10ⁿ) covering the range.378    private func ticks(_ lo: Double, _ hi: Double, target: Int) -> [Double] {379        let span = hi - lo380        guard span > 0, target > 0 else { return [] }381        let raw = span / Double(target), mag = pow(10, floor(log10(raw)))382        let n = raw / mag383        let stepv = (n < 1.5 ? 1 : n < 3 ? 2 : n < 7 ? 5 : 10) * mag384        var out: [Double] = []; var v = (lo / stepv).rounded(.up) * stepv385        while v <= hi, out.count < 40 { out.append(v); v += stepv }386        return out387    }388}389390/// The vertical scale of the price panel as last drawn.391struct ChartScale {392    var top: Double, bottom: Double, log: Bool393    var minY: CGFloat, maxY: CGFloat394    /// In comparison mode the scale is in percent change from this close; prices are converted through it.395    var base: Double?396397    /// The scale's own value under the pointer (a price, or a percentage when comparing); nil outside the panel.398    func value(atY y: CGFloat) -> Double? {399        guard y >= minY, y <= maxY, maxY > minY else { return nil }400        return raw(atY: y)401    }402    private func raw(atY y: CGFloat) -> Double {403        let t = Double((maxY - y) / max(maxY - minY, 1))404        return log ? exp(Foundation.log(bottom) + t * (Foundation.log(top) - Foundation.log(bottom))) : bottom + t * (top - bottom)405    }406    func y(_ v: Double) -> CGFloat {407        let t = log ? (Foundation.log(max(v, bottom * 1e-6)) - Foundation.log(bottom)) / (Foundation.log(top) - Foundation.log(bottom)) : (v - bottom) / (top - bottom)408        return maxY - CGFloat(t) * (maxY - minY)409    }410    /// Where a price sits (drawings are stored in prices, whatever the scale shows).411    func y(price p: Double) -> CGFloat { y(base.map { $0 > 0 ? (p / $0 - 1) * 100 : p } ?? p) }412    /// The price at a height, also outside the panel (a drawing may be dragged past its edge).413    func price(atY y: CGFloat) -> Double { let v = raw(atY: y); return base.map { $0 * (1 + v / 100) } ?? v }414}415416/// Data space ↔ screen for drawings: time → bar (snapped) → x, price → y.417struct ChartProjection {418    var start: Double419    var step: CGFloat420    var times: [Double]421    var stepSeconds: Double422    var scale: ChartScale423424    func x(index i: Double) -> CGFloat { CGFloat(i - start) * step + step / 2 }425    func index(of t: Double) -> Double { DrawingMath.snappedIndex(of: t, in: times, step: stepSeconds) }426    func point(_ p: DrawingPoint) -> CGPoint { CGPoint(x: x(index: index(of: p.t)), y: scale.y(price: p.p)) }427    func index(atX x: CGFloat) -> Double { start + Double(x / step) - 0.5 }428    /// The anchor a click at `pt` creates: on the nearest bar, at the pointer's price.429    func dataPoint(at pt: CGPoint) -> DrawingPoint {430        DrawingPoint(t: DrawingMath.snappedTime(at: index(atX: pt.x), in: times, step: stepSeconds), p: scale.price(atY: pt.y))431    }432    func screen(_ d: ChartDrawing) -> [ScreenPoint] { d.points.map { let p = point($0); return ScreenPoint(x: Double(p.x), y: Double(p.y)) } }433}434
Files main
Menu

Theme