Repository Public
1//2// VQuant iOS3// File: VQuant/Charts/PriceChartScene.swift4// Description: One frame of the price chart: layout of the panes, the marks of the visible window (raw bars or exact5// OHLC aggregates), scales, and the Canvas drawing of prices, overlays, sub-panels, axes and crosshair.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI12import VQuantUI1314/// Where the panes are inside the chart's frame.15struct ChartLayout {16 var size: CGSize17 /// Price pane (marks area, without the price axis).18 var plot: CGRect19 var panels: [(panel: ChartPanel, rect: CGRect)]20 var axisWidth: CGFloat21 var xAxis: CGRect2223 init(size: CGSize, panels wanted: Set<ChartPanel>, axisWidth: CGFloat, xAxisHeight: CGFloat) {24 self.size = size25 self.axisWidth = min(axisWidth, max(0, size.width * 0.3))26 let ordered = ChartPanel.allCases.filter { wanted.contains($0) }27 let width = max(0, size.width - self.axisWidth)28 let available = max(0, size.height - xAxisHeight)29 let gap: CGFloat = 430 var panelHeight: CGFloat = 031 if !ordered.isEmpty {32 panelHeight = min(max(available * 0.17, 40), 96, available * 0.55 / CGFloat(ordered.count))33 }34 let priceHeight = max(0, available - (panelHeight + gap) * CGFloat(ordered.count))35 plot = CGRect(x: 0, y: 0, width: width, height: priceHeight)36 var y = priceHeight + gap37 var rects: [(ChartPanel, CGRect)] = []38 for p in ordered { rects.append((p, CGRect(x: 0, y: y, width: width, height: panelHeight))); y += panelHeight + gap }39 panels = rects.map { (panel: $0.0, rect: $0.1) }40 xAxis = CGRect(x: 0, y: max(0, size.height - xAxisHeight), width: width, height: xAxisHeight)41 }42}4344/// Everything needed to draw one frame. Built on each render from the bars, the cached indicators and the viewport.45struct PriceChartScene {46 /// What is drawn at one horizontal position: a bar as received (`first == last`) or the exact OHLCV aggregate47 /// of the bars `first...last`.48 struct Mark {49 var bar: Bar50 var first: Int51 var last: Int52 }5354 let bars: [Bar]55 let data: ChartData56 let configuration: ChartConfiguration57 let intraday: Bool58 let previousClose: Double?59 let viewport: ChartViewport60 let layout: ChartLayout61 /// Bars per mark. Above 1 the chart says so on screen.62 let factor: Int63 let marks: [Mark]64 let yRange: ClosedRange<Double>65 var crosshair: Int?6667 init(bars: [Bar], data: ChartData, configuration: ChartConfiguration, intraday: Bool, previousClose: Double?, viewport: ChartViewport, layout: ChartLayout, crosshair: Int?) {68 self.bars = bars; self.data = data; self.configuration = configuration; self.intraday = intraday69 self.previousClose = previousClose; self.viewport = viewport; self.layout = layout; self.crosshair = crosshair7071 let visible = viewport.range.count72 let f = ChartMath.aggregationFactor(visibleBars: visible, width: Double(layout.plot.width), minimumSlot: configuration.kind.minimumSlot)73 factor = f74 let r = viewport.alignedRange(factor: f)75 var built: [Mark] = []76 if !r.isEmpty, r.upperBound <= bars.count {77 if f == 1 {78 built = r.map { Mark(bar: bars[$0], first: $0, last: $0) }79 } else {80 let aggregated = Indicators.aggregate(Array(bars[r]), factor: f)81 built = aggregated.enumerated().map { k, b in82 let first = r.lowerBound + k * f83 return Mark(bar: b, first: first, last: min(first + f - 1, r.upperBound - 1))84 }85 }86 }87 marks = built8889 var lo = Double.infinity, hi = -Double.infinity90 let ohlc = configuration.kind == .candles || configuration.kind == .ohlc91 for m in built {92 lo = min(lo, ohlc ? m.bar.low : m.bar.close)93 hi = max(hi, ohlc ? m.bar.high : m.bar.close)94 for series in data.overlays.values {95 for line in series where m.last < line.count { if let v = line[m.last] { lo = min(lo, v); hi = max(hi, v) } }96 }97 }98 yRange = lo.isFinite && hi.isFinite ? ChartMath.paddedRange(low: lo, high: hi) : 0...199 }100101 // MARK: geometry102103 var plotWidth: Double { Double(layout.plot.width) }104 var markSlot: CGFloat { CGFloat(viewport.slot(width: plotWidth)) * CGFloat(factor) }105106 func x(_ m: Mark) -> CGFloat {107 layout.plot.minX + CGFloat(viewport.x(index: Double(m.first + m.last) / 2, width: plotWidth))108 }109 func y(_ value: Double) -> CGFloat {110 layout.plot.minY + CGFloat(ChartMath.y(value, in: yRange, height: Double(layout.plot.height)))111 }112 func mark(containing index: Int) -> Mark? { marks.first { $0.first <= index && index <= $0.last } }113 func markIndex(containing index: Int) -> Int? { marks.firstIndex { $0.first <= index && index <= $0.last } }114 func index(atX x: CGFloat) -> Int? { viewport.index(x: Double(x - layout.plot.minX), width: plotWidth) }115116 // MARK: drawing117118 private static let labelFont = Font.caption2.monospacedDigit()119120 func draw(in ctx: inout GraphicsContext) {121 guard !marks.isEmpty, layout.plot.width > 1, layout.plot.height > 1 else { return }122 drawGrid(&ctx)123 var clipped = ctx124 clipped.clip(to: Path(layout.plot))125 drawOverlays(&clipped, bandsOnly: true)126 drawPrice(&clipped)127 drawOverlays(&clipped, bandsOnly: false)128 drawReferenceLines(&ctx)129 for (panel, rect) in layout.panels where rect.height > 8 {130 switch panel {131 case .volume: drawVolume(&ctx, rect)132 case .rsi: drawRSI(&ctx, rect)133 case .macd: drawMACD(&ctx, rect)134 }135 }136 drawXAxis(&ctx)137 drawCrosshair(&ctx)138 }139140 private func label(_ s: String, color: Color = Theme.textSecondary) -> Text {141 Text(s).font(Self.labelFont).foregroundStyle(color)142 }143144 private func drawGrid(_ ctx: inout GraphicsContext) {145 let ticks = ChartMath.niceTicks(min: yRange.lowerBound, max: yRange.upperBound, target: 5)146 for t in ticks {147 let py = y(t)148 var line = Path(); line.move(to: CGPoint(x: layout.plot.minX, y: py)); line.addLine(to: CGPoint(x: layout.plot.maxX, y: py))149 ctx.stroke(line, with: .color(Theme.border.opacity(0.7)), lineWidth: 0.5)150 ctx.draw(label(Fmt.price(t)), at: CGPoint(x: layout.size.width - 2, y: py), anchor: .trailing)151 }152 }153154 private func drawPrice(_ ctx: inout GraphicsContext) {155 let slot = markSlot156 switch configuration.kind {157 case .candles:158 let body = max(1, min(slot * 0.72, 22))159 var upWicks = Path(), downWicks = Path(), upBodies = Path(), downBodies = Path()160 for m in marks {161 let px = x(m), up = m.bar.close >= m.bar.open162 let top = y(max(m.bar.open, m.bar.close)), bottom = y(min(m.bar.open, m.bar.close))163 let rect = CGRect(x: px - body / 2, y: top, width: body, height: max(1, bottom - top))164 if up {165 upWicks.move(to: CGPoint(x: px, y: y(m.bar.high))); upWicks.addLine(to: CGPoint(x: px, y: y(m.bar.low)))166 upBodies.addRect(rect)167 } else {168 downWicks.move(to: CGPoint(x: px, y: y(m.bar.high))); downWicks.addLine(to: CGPoint(x: px, y: y(m.bar.low)))169 downBodies.addRect(rect)170 }171 }172 ctx.stroke(upWicks, with: .color(Theme.up), lineWidth: 1)173 ctx.stroke(downWicks, with: .color(Theme.down), lineWidth: 1)174 ctx.fill(upBodies, with: .color(Theme.up))175 ctx.fill(downBodies, with: .color(Theme.down))176 case .ohlc:177 let arm = max(1, min(slot * 0.36, 10))178 var ups = Path(), downs = Path()179 for m in marks {180 let px = x(m)181 var p = Path()182 p.move(to: CGPoint(x: px, y: y(m.bar.high))); p.addLine(to: CGPoint(x: px, y: y(m.bar.low)))183 p.move(to: CGPoint(x: px - arm, y: y(m.bar.open))); p.addLine(to: CGPoint(x: px, y: y(m.bar.open)))184 p.move(to: CGPoint(x: px, y: y(m.bar.close))); p.addLine(to: CGPoint(x: px + arm, y: y(m.bar.close)))185 if m.bar.close >= m.bar.open { ups.addPath(p) } else { downs.addPath(p) }186 }187 ctx.stroke(ups, with: .color(Theme.up), lineWidth: 1.2)188 ctx.stroke(downs, with: .color(Theme.down), lineWidth: 1.2)189 case .line, .area:190 var line = Path()191 for (k, m) in marks.enumerated() {192 let p = CGPoint(x: x(m), y: y(m.bar.close))193 if k == 0 { line.move(to: p) } else { line.addLine(to: p) }194 }195 if configuration.kind == .area, let first = marks.first, let last = marks.last {196 var area = line197 area.addLine(to: CGPoint(x: x(last), y: layout.plot.maxY))198 area.addLine(to: CGPoint(x: x(first), y: layout.plot.maxY))199 area.closeSubpath()200 ctx.fill(area, with: .linearGradient(Gradient(colors: [Theme.orange.opacity(0.32), Theme.orange.opacity(0.02)]),201 startPoint: CGPoint(x: 0, y: layout.plot.minY), endPoint: CGPoint(x: 0, y: layout.plot.maxY)))202 }203 ctx.stroke(line, with: .color(Theme.orange), style: StrokeStyle(lineWidth: 1.6, lineJoin: .round))204 if marks.count == 1, let only = marks.first {205 ctx.fill(Path(ellipseIn: CGRect(x: x(only) - 2.5, y: y(only.bar.close) - 2.5, width: 5, height: 5)), with: .color(Theme.orange))206 }207 }208 }209210 /// A polyline through the values of `series` at the last bar of each mark, broken where the indicator is undefined.211 private func path(of series: [Double?], y: (Double) -> CGFloat) -> Path {212 var p = Path(); var pen = false213 for m in marks {214 guard m.last < series.count, let v = series[m.last] else { pen = false; continue }215 let pt = CGPoint(x: x(m), y: y(v))216 if pen { p.addLine(to: pt) } else { p.move(to: pt); pen = true }217 }218 return p219 }220221 private func drawOverlays(_ ctx: inout GraphicsContext, bandsOnly: Bool) {222 for o in ChartOverlay.allCases {223 guard let series = data.overlays[o] else { continue }224 if o == .bollinger, series.count == 3 {225 if bandsOnly {226 var upper: [CGPoint] = [], lower: [CGPoint] = []227 for m in marks where m.last < series[1].count {228 if let u = series[1][m.last], let l = series[2][m.last] { upper.append(CGPoint(x: x(m), y: y(u))); lower.append(CGPoint(x: x(m), y: y(l))) }229 }230 if upper.count > 1 {231 var band = Path(); band.addLines(upper + lower.reversed()); band.closeSubpath()232 ctx.fill(band, with: .color(o.color.opacity(0.10)))233 }234 } else {235 ctx.stroke(path(of: series[1], y: y), with: .color(o.color), lineWidth: 1)236 ctx.stroke(path(of: series[2], y: y), with: .color(o.color), lineWidth: 1)237 ctx.stroke(path(of: series[0], y: y), with: .color(o.color), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))238 }239 } else if !bandsOnly, let line = series.first {240 ctx.stroke(path(of: line, y: y), with: .color(o.color), style: StrokeStyle(lineWidth: 1.3, lineJoin: .round))241 }242 }243 }244245 private func drawReferenceLines(_ ctx: inout GraphicsContext) {246 if let pc = previousClose, yRange.contains(pc) {247 let py = y(pc)248 var line = Path(); line.move(to: CGPoint(x: layout.plot.minX, y: py)); line.addLine(to: CGPoint(x: layout.plot.maxX, y: py))249 ctx.stroke(line, with: .color(Theme.textSecondary), style: StrokeStyle(lineWidth: 0.8, dash: [4, 4]))250 }251 if let last = bars.last, yRange.contains(last.close) {252 let py = y(last.close)253 let up = last.close >= (previousClose ?? last.open)254 let color = up ? Theme.up : Theme.down255 var line = Path(); line.move(to: CGPoint(x: layout.plot.minX, y: py)); line.addLine(to: CGPoint(x: layout.plot.maxX, y: py))256 ctx.stroke(line, with: .color(color.opacity(0.55)), style: StrokeStyle(lineWidth: 0.6, dash: [2, 3]))257 priceTag(&ctx, Fmt.price(last.close), y: py, fill: color)258 }259 }260261 private func priceTag(_ ctx: inout GraphicsContext, _ text: String, y py: CGFloat, fill: Color) {262 let resolved = ctx.resolve(Text(text).font(Self.labelFont.weight(.semibold)).foregroundStyle(Theme.background))263 let size = resolved.measure(in: CGSize(width: layout.axisWidth, height: 40))264 let rect = CGRect(x: layout.size.width - size.width - 6, y: py - size.height / 2 - 1, width: size.width + 6, height: size.height + 2)265 ctx.fill(Path(roundedRect: rect, cornerRadius: 3), with: .color(fill))266 ctx.draw(resolved, at: CGPoint(x: rect.midX, y: rect.midY), anchor: .center)267 }268269 private func panelFrame(_ ctx: inout GraphicsContext, _ rect: CGRect, title: String) {270 var top = Path(); top.move(to: CGPoint(x: rect.minX, y: rect.minY)); top.addLine(to: CGPoint(x: layout.size.width, y: rect.minY))271 ctx.stroke(top, with: .color(Theme.border), lineWidth: 0.5)272 ctx.draw(label(title), at: CGPoint(x: rect.minX + 4, y: rect.minY + 2), anchor: .topLeading)273 }274275 private func drawVolume(_ ctx: inout GraphicsContext, _ rect: CGRect) {276 panelFrame(&ctx, rect, title: ChartPanel.volume.label)277 let peak = marks.compactMap(\.bar.volume).max() ?? 0278 guard peak > 0 else {279 ctx.draw(label("Volume non fourni"), at: CGPoint(x: rect.midX, y: rect.midY), anchor: .center)280 return281 }282 let width = max(1, min(markSlot * 0.72, 22))283 let usable = rect.height - 14284 var ups = Path(), downs = Path()285 for m in marks {286 guard let v = m.bar.volume, v > 0 else { continue }287 let h = max(1, CGFloat(v / peak) * usable)288 let r = CGRect(x: x(m) - width / 2, y: rect.maxY - h, width: width, height: h)289 if m.bar.close >= m.bar.open { ups.addRect(r) } else { downs.addRect(r) }290 }291 var c = ctx; c.clip(to: Path(rect))292 c.fill(ups, with: .color(Theme.up.opacity(0.75)))293 c.fill(downs, with: .color(Theme.down.opacity(0.75)))294 ctx.draw(label(Fmt.compact(peak)), at: CGPoint(x: layout.size.width - 2, y: rect.minY + 2), anchor: .topTrailing)295 }296297 private func drawRSI(_ ctx: inout GraphicsContext, _ rect: CGRect) {298 panelFrame(&ctx, rect, title: ChartPanel.rsi.label)299 let range = 0.0...100.0300 let py: (Double) -> CGFloat = { rect.minY + CGFloat(ChartMath.y($0, in: range, height: Double(rect.height))) }301 for guide in [30.0, 70.0] {302 var g = Path(); g.move(to: CGPoint(x: rect.minX, y: py(guide))); g.addLine(to: CGPoint(x: rect.maxX, y: py(guide)))303 ctx.stroke(g, with: .color(Theme.textSecondary.opacity(0.7)), style: StrokeStyle(lineWidth: 0.6, dash: [3, 3]))304 ctx.draw(label(String(Int(guide))), at: CGPoint(x: layout.size.width - 2, y: py(guide)), anchor: .trailing)305 }306 var c = ctx; c.clip(to: Path(rect))307 c.stroke(path(of: data.rsi, y: py), with: .color(VQTokens.DataPalette.categorical[6]), style: StrokeStyle(lineWidth: 1.3, lineJoin: .round))308 }309310 private func drawMACD(_ ctx: inout GraphicsContext, _ rect: CGRect) {311 panelFrame(&ctx, rect, title: ChartPanel.macd.label)312 guard let macd = data.macd else { return }313 var peak = 0.0314 for m in marks {315 for s in [macd.macd, macd.signal, macd.histogram] where m.last < s.count { if let v = s[m.last] { peak = max(peak, abs(v)) } }316 }317 guard peak > 0 else { return }318 let range = (-peak * 1.1)...(peak * 1.1)319 let py: (Double) -> CGFloat = { rect.minY + CGFloat(ChartMath.y($0, in: range, height: Double(rect.height))) }320 var zero = Path(); zero.move(to: CGPoint(x: rect.minX, y: py(0))); zero.addLine(to: CGPoint(x: rect.maxX, y: py(0)))321 ctx.stroke(zero, with: .color(Theme.border), lineWidth: 0.6)322 var c = ctx; c.clip(to: Path(rect))323 let width = max(1, min(markSlot * 0.6, 14))324 var pos = Path(), neg = Path()325 for m in marks where m.last < macd.histogram.count {326 guard let h = macd.histogram[m.last] else { continue }327 let a = py(max(h, 0)), b = py(min(h, 0))328 let r = CGRect(x: x(m) - width / 2, y: a, width: width, height: max(0.5, b - a))329 if h >= 0 { pos.addRect(r) } else { neg.addRect(r) }330 }331 c.fill(pos, with: .color(Theme.up.opacity(0.6)))332 c.fill(neg, with: .color(Theme.down.opacity(0.6)))333 c.stroke(path(of: macd.macd, y: py), with: .color(VQTokens.DataPalette.categorical[0]), lineWidth: 1.2)334 c.stroke(path(of: macd.signal, y: py), with: .color(VQTokens.DataPalette.categorical[3]), lineWidth: 1.2)335 }336337 private func drawXAxis(_ ctx: inout GraphicsContext) {338 guard let first = marks.first?.bar.date, let last = marks.last?.bar.date else { return }339 let wanted = max(2, Int(layout.plot.width / 84))340 var previous = ""341 var lastRight: CGFloat = -.infinity342 for j in 0..<wanted {343 let k = min(marks.count - 1, Int((Double(j) + 0.5) / Double(wanted) * Double(marks.count)))344 let m = marks[k]345 let text = ChartDates.axisLabel(m.bar.date, first: first, last: last, intraday: intraday)346 guard text != previous else { continue }347 let resolved = ctx.resolve(label(text))348 let w = resolved.measure(in: CGSize(width: 200, height: 40)).width349 let cx = min(max(x(m), layout.plot.minX + w / 2), layout.plot.maxX - w / 2)350 guard cx - w / 2 > lastRight + 6 else { continue }351 ctx.draw(resolved, at: CGPoint(x: cx, y: layout.xAxis.midY), anchor: .center)352 previous = text; lastRight = cx + w / 2353 }354 }355356 private func drawCrosshair(_ ctx: inout GraphicsContext) {357 guard let index = crosshair, let m = mark(containing: index) else { return }358 let px = x(m)359 let bottom = layout.panels.last?.rect.maxY ?? layout.plot.maxY360 var v = Path(); v.move(to: CGPoint(x: px, y: layout.plot.minY)); v.addLine(to: CGPoint(x: px, y: bottom))361 ctx.stroke(v, with: .color(Theme.textSecondary), lineWidth: 0.8)362 guard yRange.contains(m.bar.close) else { return }363 let py = y(m.bar.close)364 var h = Path(); h.move(to: CGPoint(x: layout.plot.minX, y: py)); h.addLine(to: CGPoint(x: layout.plot.maxX, y: py))365 ctx.stroke(h, with: .color(Theme.textSecondary), lineWidth: 0.8)366 ctx.fill(Path(ellipseIn: CGRect(x: px - 3.5, y: py - 3.5, width: 7, height: 7)), with: .color(Theme.orange))367 priceTag(&ctx, Fmt.price(m.bar.close), y: py, fill: VQTokens.Palette.text2)368 }369}370