SPB Git

Repository Public

ChartViewport.swift 7.0 KB 159 lines swift

1//2//  VQuant iOS3//  File: Core/Quant/ChartViewport.swift4//  Description: Pure geometry of the price chart: the visible window over the bars (zoom, pan, clamping), the mapping5//               between bar indices and horizontal positions, the display aggregation factor, and "nice" axis ticks.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213/// The window of bars a chart shows: `length` bars starting at the (fractional) index `start`, over `count` bars14/// ordered oldest first. Every mutation keeps the window inside the data and between the minimum and the full length.15struct ChartViewport: Equatable, Sendable {16    /// Fewest bars a zoom can leave on screen (or all of them when there are fewer).17    static let minimumVisible = 1018    /// Bars shown when a chart opens on a long series: the most recent ones.19    static let defaultVisible = 2402021    private(set) var count: Int22    private(set) var start: Double23    private(set) var length: Double2425    /// Opening window: everything when it fits in `visible` bars, else the most recent `visible` bars.26    init(count: Int, visible: Int = ChartViewport.defaultVisible) {27        self.count = max(0, count)28        self.length = Double(min(self.count, max(1, visible)))29        self.start = Double(self.count) - self.length30        normalise()31    }3233    init(count: Int, start: Double, length: Double) {34        self.count = max(0, count)35        self.start = start36        self.length = length37        normalise()38    }3940    var end: Double { start + length }41    var isEmpty: Bool { count == 0 }42    var minimumLength: Double { Double(min(count, Self.minimumVisible)) }43    var showsEverything: Bool { count > 0 && length >= Double(count) }4445    /// Indices of the bars that are at least partly visible.46    var range: Range<Int> {47        guard count > 0 else { return 0..<0 }48        let lo = max(0, min(count - 1, Int(start.rounded(.down))))49        let hi = max(lo + 1, min(count, Int(end.rounded(.up))))50        return lo..<hi51    }5253    private mutating func normalise() {54        guard count > 0 else { start = 0; length = 0; return }55        if !length.isFinite { length = Double(count) }56        if !start.isFinite { start = 0 }57        length = min(max(length, minimumLength), Double(count))58        start = min(max(start, 0), Double(count) - length)59    }6061    /// Zoom by `scale` (> 1 zooms in) keeping the bar under `anchor` (0 = left edge, 1 = right edge) in place,62    /// as far as the clamping allows.63    func zoomed(by scale: Double, anchor: Double) -> ChartViewport {64        guard count > 0, scale.isFinite, scale > 0 else { return self }65        let a = min(max(anchor.isFinite ? anchor : 0.5, 0), 1)66        let pivot = start + a * length67        let newLength = min(max(length / scale, minimumLength), Double(count))68        return ChartViewport(count: count, start: pivot - a * newLength, length: newLength)69    }7071    /// Shift the window by `bars` (positive = towards more recent bars).72    func panned(byBars bars: Double) -> ChartViewport {73        guard count > 0, bars.isFinite else { return self }74        return ChartViewport(count: count, start: start + bars, length: length)75    }7677    func reset() -> ChartViewport { ChartViewport(count: count) }7879    /// Width of one bar slot for a plot `width` points wide.80    func slot(width: Double) -> Double { length > 0 && width > 0 ? width / length : 0 }8182    /// Horizontal centre of the bar at `index` (fractional indices allowed: the centre of a group of bars).83    func x(index: Double, width: Double) -> Double { (index + 0.5 - start) * slot(width: width) }8485    /// The bar under the horizontal position `x`, clamped to the visible bars. `nil` without data or width.86    func index(x: Double, width: Double) -> Int? {87        guard count > 0, width > 0, x.isFinite else { return nil }88        let raw = Int((start + x / width * length).rounded(.down))89        let r = range90        return min(max(raw, r.lowerBound), r.upperBound - 1)91    }9293    /// The visible range widened to whole groups of `factor` bars, groups being aligned on multiples of `factor`94    /// from the first bar so they do not shift while the window is panned.95    func alignedRange(factor: Int) -> Range<Int> {96        let f = max(1, factor)97        let r = range98        guard !r.isEmpty else { return r }99        let lo = (r.lowerBound / f) * f100        let hi = min(count, ((r.upperBound + f - 1) / f) * f)101        return lo..<hi102    }103}104105enum ChartMath {106    /// How many consecutive bars one drawn mark must stand for so that marks are at least `minimumSlot` points107    /// apart. 1 means every bar is drawn as it is.108    static func aggregationFactor(visibleBars: Int, width: Double, minimumSlot: Double) -> Int {109        guard visibleBars > 0, width > 0, minimumSlot > 0, width.isFinite else { return 1 }110        let marks = max(1, (width / minimumSlot).rounded(.down))111        return max(1, Int((Double(visibleBars) / marks).rounded(.up)))112    }113114    /// A step of the form 1, 2, 2.5 or 5 × 10ⁿ giving about `target` intervals over `span`.115    static func niceStep(span: Double, target: Int) -> Double {116        guard span.isFinite, span > 0, target > 0 else { return 0 }117        let raw = span / Double(target)118        let magnitude = pow(10, (log10(raw)).rounded(.down))119        let f = raw / magnitude120        let nice: Double = f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10121        return nice * magnitude122    }123124    /// Round tick values inside `[min, max]`, increasing. A flat range gives its single value.125    static func niceTicks(min a: Double, max b: Double, target: Int = 5) -> [Double] {126        guard a.isFinite, b.isFinite else { return [] }127        let lo = Swift.min(a, b), hi = Swift.max(a, b)128        guard hi > lo else { return [lo] }129        let step = niceStep(span: hi - lo, target: Swift.max(1, target))130        guard step > 0 else { return [lo] }131        let tolerance = step * 1e-9132        var k = ((lo - tolerance) / step).rounded(.up)133        var out: [Double] = []134        while out.count < 64 {135            let v = k * step136            if v > hi + tolerance { break }137            out.append(Swift.min(Swift.max(v, lo), hi))138            k += 1139        }140        return out141    }142143    /// The value range of a pane with breathing room. A flat series gets a small symmetric band so it can be drawn.144    static func paddedRange(low: Double, high: Double, padding: Double = 0.06) -> ClosedRange<Double> {145        guard low.isFinite, high.isFinite else { return 0...1 }146        let lo = Swift.min(low, high), hi = Swift.max(low, high)147        if hi > lo { let pad = (hi - lo) * Swift.max(0, padding); return (lo - pad)...(hi + pad) }148        let band = lo == 0 ? 1 : abs(lo) * 0.01149        return (lo - band)...(lo + band)150    }151152    /// Vertical position (0 = top) of `value` in a pane `height` points tall showing `range`.153    static func y(_ value: Double, in range: ClosedRange<Double>, height: Double) -> Double {154        let span = range.upperBound - range.lowerBound155        guard span > 0 else { return height / 2 }156        return (range.upperBound - value) / span * height157    }158}159
Files main
Menu

Theme