Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Analytics/ChartDrawings.swift3// Description: Drawing tools of the chart, as pure maths: drawings anchored in data space (time, price), time ↔ bar index, snapping, Fibonacci levels, the measure tool, hit-testing and moves. No UI.4import Foundation56/// The tools. Raw values are the `type` strings of the synced `chart` object (shared with the web and iOS clients).7public enum DrawingKind: String, Sendable, CaseIterable, Codable {8 case trend, hline, ray, rect, fib, text, measure910 /// Anchors a drawing of this kind needs before it is complete.11 public var pointsNeeded: Int {12 switch self { case .hline, .text: 1; case .trend, .ray, .rect, .fib, .measure: 2 }13 }14 public var title: String {15 switch self {16 case .trend: "Trend line"; case .hline: "Horizontal line"; case .ray: "Ray"; case .rect: "Rectangle"17 case .fib: "Fibonacci retracement"; case .text: "Text note"; case .measure: "Measure"18 }19 }20}2122/// One anchor: `t` = epoch seconds of the bar, `p` = price. Never pixels.23public struct DrawingPoint: Sendable, Equatable, Codable {24 public var t: Double25 public var p: Double26 public init(t: Double, p: Double) { self.t = t; self.p = p }27}2829public struct ChartDrawing: Sendable, Equatable, Identifiable, Codable {30 public var id: String31 public var kind: DrawingKind32 public var points: [DrawingPoint]33 /// Index in the categorical data palette of the design tokens (`style.color` of the synced object).34 public var color: Int35 public var text: String?36 public init(id: String, kind: DrawingKind, points: [DrawingPoint], color: Int = 0, text: String? = nil) {37 self.id = id; self.kind = kind; self.points = points; self.color = color; self.text = text38 }39 public var isComplete: Bool { points.count >= kind.pointsNeeded }40}4142public struct ScreenPoint: Sendable, Equatable {43 public var x: Double, y: Double44 public init(x: Double, y: Double) { self.x = x; self.y = y }45}4647public enum DrawingMath {48 // MARK: time ↔ bar index4950 /// Fractional index of time `t` on ascending bar times. Inside the series it is interpolated between the two51 /// neighbouring bars; outside it is extrapolated at one bar per `step` seconds, so a drawing that reaches past the52 /// loaded history stays where it was put.53 public static func index(of t: Double, in times: [Double], step: Double) -> Double {54 let n = times.count55 guard n > 0, step > 0 else { return 0 }56 if t <= times[0] { return (t - times[0]) / step }57 if t >= times[n - 1] { return Double(n - 1) + (t - times[n - 1]) / step }58 var lo = 0, hi = n - 159 while hi - lo > 1 { let mid = (lo + hi) / 2; if times[mid] <= t { lo = mid } else { hi = mid } }60 let span = times[hi] - times[lo]61 return Double(lo) + (span > 0 ? (t - times[lo]) / span : 0)62 }6364 /// Inverse of `index(of:in:step:)`.65 public static func time(at index: Double, in times: [Double], step: Double) -> Double {66 let n = times.count67 guard n > 0 else { return 0 }68 if index <= 0 { return times[0] + index * step }69 if index >= Double(n - 1) { return times[n - 1] + (index - Double(n - 1)) * step }70 let lo = Int(index.rounded(.down))71 return times[lo] + (index - Double(lo)) * (times[lo + 1] - times[lo])72 }7374 /// Where an anchor is drawn: on a bar, never between two. The bar is the one whose period contains `t`; when `t`75 /// falls in a gap (a night, a weekend, or a daily anchor seen on an intraday chart) it is the first bar after it.76 /// Outside the series the position is extrapolated in whole bars. This is display only: the stored `t` never77 /// changes because the interval did.78 public static func snappedIndex(of t: Double, in times: [Double], step: Double) -> Double {79 let n = times.count80 guard n > 0, step > 0 else { return 0 }81 if t <= times[0] { return ((t - times[0]) / step).rounded() }82 if t >= times[n - 1] { return Double(n - 1) + ((t - times[n - 1]) / step).rounded(.down) }83 var lo = 0, hi = n - 184 while hi - lo > 1 { let mid = (lo + hi) / 2; if times[mid] <= t { lo = mid } else { hi = mid } }85 return t - times[lo] < step ? Double(lo) : Double(hi)86 }8788 /// Time stored for an anchor put at a fractional index: the time of the nearest bar, or the extrapolated time89 /// (whole bars) outside the series.90 public static func snappedTime(at index: Double, in times: [Double], step: Double) -> Double {91 let r = index.rounded()92 if r >= 0, r < Double(times.count) { return times[Int(r)] }93 return time(at: r, in: times, step: step).rounded()94 }9596 // MARK: Fibonacci9798 public static let fibRatios: [Double] = [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]99100 /// Retracement of the move from A (first anchor) to B (second anchor): ratio 0 is at B, the end of the move,101 /// ratio 1 at A; a level r is the price after giving back r of the move: B + (A − B) × r.102 public static func fibLevels(from a: Double, to b: Double) -> [(ratio: Double, price: Double)] {103 fibRatios.map { ($0, b + (a - b) * $0) }104 }105106 // MARK: measure107108 public struct Measure: Sendable, Equatable {109 public var deltaPrice: Double110 /// A fraction (0.05 = +5 %); nil when the starting price is not positive.111 public var deltaFraction: Double?112 /// Signed number of bars between the two anchors, as displayed (snapped).113 public var bars: Int114 public var seconds: Double115 }116117 public static func measure(_ a: DrawingPoint, _ b: DrawingPoint, times: [Double], step: Double) -> Measure {118 Measure(deltaPrice: b.p - a.p, deltaFraction: a.p > 0 ? b.p / a.p - 1 : nil,119 bars: Int(snappedIndex(of: b.t, in: times, step: step) - snappedIndex(of: a.t, in: times, step: step)),120 seconds: b.t - a.t)121 }122123 /// "3 d 4 h", "45 min", "2 y 14 d" — the elapsed time of a measure, sign dropped.124 public static func durationText(_ seconds: Double) -> String {125 let s = Int(abs(seconds).rounded())126 let d = s / 86400, h = (s % 86400) / 3600, m = (s % 3600) / 60127 if d >= 365 { return "\(d / 365) y \(d % 365) d" }128 if d > 0 { return h > 0 ? "\(d) d \(h) h" : "\(d) d" }129 if h > 0 { return m > 0 ? "\(h) h \(m) min" : "\(h) h" }130 return "\(m) min"131 }132133 // MARK: edits134135 /// Moves a drawing by a whole number of bars and a price offset; bar distances between anchors are kept.136 public static func translate(_ d: ChartDrawing, bars deltaBars: Double, price deltaPrice: Double, times: [Double], step: Double) -> ChartDrawing {137 var out = d138 out.points = d.points.map {139 DrawingPoint(t: snappedTime(at: snappedIndex(of: $0.t, in: times, step: step) + deltaBars.rounded(), in: times, step: step), p: $0.p + deltaPrice)140 }141 return out142 }143144 /// Same, on a logarithmic scale: the price move is a ratio, so the drawing keeps its shape on screen.145 public static func translate(_ d: ChartDrawing, bars deltaBars: Double, priceRatio: Double, times: [Double], step: Double) -> ChartDrawing {146 var out = translate(d, bars: deltaBars, price: 0, times: times, step: step)147 for i in out.points.indices { out.points[i].p *= priceRatio }148 return out149 }150151 // MARK: screen geometry152153 public static func distance(_ p: ScreenPoint, toSegment a: ScreenPoint, _ b: ScreenPoint) -> Double {154 let dx = b.x - a.x, dy = b.y - a.y155 let len2 = dx * dx + dy * dy156 let u = len2 == 0 ? 0 : max(0, min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))157 return hypot(p.x - (a.x + u * dx), p.y - (a.y + u * dy))158 }159160 /// End of the ray that starts at A and passes through B, clipped to [0, width] × [0, height].161 public static func rayEnd(_ a: ScreenPoint, _ b: ScreenPoint, width: Double, height: Double) -> ScreenPoint {162 let dx = b.x - a.x, dy = b.y - a.y163 if dx == 0, dy == 0 { return b }164 var u = Double.infinity165 if dx > 0 { u = min(u, (width - a.x) / dx) } else if dx < 0 { u = min(u, (0 - a.x) / dx) }166 if dy > 0 { u = min(u, (height - a.y) / dy) } else if dy < 0 { u = min(u, (0 - a.y) / dy) }167 if !u.isFinite || u < 1 { u = 1 }168 return ScreenPoint(x: a.x + dx * u, y: a.y + dy * u)169 }170171 /// Is the pointer on this drawing? `pts` are its anchors projected to the screen. Lines are hit within `tolerance`172 /// points; rectangles on their border; Fibonacci zones on a level; a note on its label (`textWidth` wide).173 public static func hit(_ kind: DrawingKind, _ pts: [ScreenPoint], _ p: ScreenPoint, width: Double, height: Double, tolerance: Double = 6, textWidth: Double = 140) -> Bool {174 guard let a = pts.first else { return false }175 let b = pts.count > 1 ? pts[1] : nil176 switch kind {177 case .hline: return abs(p.y - a.y) <= tolerance178 case .text: return p.x >= a.x - tolerance && p.x <= a.x + textWidth && abs(p.y - a.y) <= 12179 case .trend, .measure: return b.map { distance(p, toSegment: a, $0) <= tolerance } ?? false180 case .ray: return b.map { distance(p, toSegment: a, rayEnd(a, $0, width: width, height: height)) <= tolerance } ?? false181 case .rect:182 guard let b else { return false }183 let x0 = min(a.x, b.x), x1 = max(a.x, b.x), y0 = min(a.y, b.y), y1 = max(a.y, b.y)184 let inside = p.x >= x0 - tolerance && p.x <= x1 + tolerance && p.y >= y0 - tolerance && p.y <= y1 + tolerance185 let deep = p.x > x0 + tolerance && p.x < x1 - tolerance && p.y > y0 + tolerance && p.y < y1 - tolerance186 return inside && !deep187 case .fib:188 guard let b else { return false }189 if p.x < min(a.x, b.x) - tolerance || p.x > max(a.x, b.x) + tolerance { return false }190 return fibRatios.contains { abs(p.y - (b.y + (a.y - b.y) * $0)) <= tolerance }191 }192 }193194 /// Index of the anchor handle under the pointer, if any.195 public static func handle(_ pts: [ScreenPoint], at p: ScreenPoint, radius: Double = 7) -> Int? {196 pts.firstIndex { hypot($0.x - p.x, $0.y - p.y) <= radius }197 }198}199200/// Id of the synced `chart` object that holds a symbol's working chart — the same derivation as the web client201/// (`chartObjectId` in client/src/lib/charting/data.ts), so every device opens the same object: upper-cased, every202/// UTF-16 unit outside `[A-Z0-9]` replaced by `_` and its code in lower-case hexadecimal, prefixed `sym-`, cut at 64203/// characters. `AAPL` → `sym-AAPL`, `^GSPC` → `sym-_5eGSPC`, `BRK.B` → `sym-BRK_2eB`, `EURUSD=X` → `sym-EURUSD_3dX`.204public enum ChartObjectID {205 public static func working(_ symbol: String) -> String {206 var out = "sym-"207 for u in symbol.uppercased().utf16 {208 if (u >= 65 && u <= 90) || (u >= 48 && u <= 57) { out.unicodeScalars.append(Unicode.Scalar(UInt8(u))) }209 else { out += "_" + String(u, radix: 16) }210 }211 return String(out.prefix(64))212 }213}214