TradingView Lightweight Charts for iOS

repository·master·Indexed 41 days ago

https://github.com/tradingview/lightweightchartsios

A Swift wrapper for the TradingView Lightweight Charts library providing high-performance financial charting for iOS applications. Version 5.1.0+ requires iOS 15.0, Swift 6, and Xcode 16, utilizing an async/await-first API and Swift Package Manager for distribution. Features include a plugin system for series markers and watermarks, multi-pane management, and AsyncStream for event consumption.

Tokens
4.2K
Snippets
11
Records
18
Agent score
52%

What's inside Lightweight Charts

  1. Use async/await for JavaScript-backed reads

    master

    All JavaScript-backed read operations that previously used completion handlers are now async throws(JavaScriptBridgeError) APIs. You should wrap these calls in a Task { @MainActor in ... } block when interacting with the chart from a view controller to ensure UI safety and proper error handling.

    Task { @MainActor in
        do {
            let panes = try await chart.panes()
            let visibleRange = try await chart.timeScale().getVisibleRange()
            let formatted = try await series.priceFormatter().format(price: 42)
    
            print("Pane count:", panes.count)
            print(visibleRange.from)
            print(formatted)
        } catch let error as JavaScriptBridgeError {
            print("Bridge error:", error)
        } catch {
            print("Unexpected error:", error)
        }
    }
  2. How the Plugin System works

    master

    Version 5.0 introduced a plugin system for extended functionality. Plugins are created via factory methods on the LightweightCharts instance or specific series.

    Key plugins include:

    • Series Markers Plugin: Control series markers with lifecycle management.
    • Up/Down Markers Plugin: Directional price movement indicators.
    • Text Watermark Plugin: Multi-line text watermarks with per-line styling.
    • Image Watermark Plugin: Display images as watermarks on any pane.

    Plugins can be updated using applyOptions or updated with new data (e.g., setMarkers), and can be removed from the chart using detach().

  3. Perform mutating calls synchronously

    master

    Most mutating wrapper APIs remain synchronous from the caller's perspective. Even though they are submitted to the main-actor JavaScript bridge, they are processed in call order. You do not need to add artificial delays between consecutive mutating calls.

    let plugin = series.createMarkersPlugin(data: markers)
    plugin.applyOptions(options: SeriesMarkersOptions(active: false))
    series.setSeriesOrder(order: 2)
  4. Consume chart events using AsyncStream

    master

    While delegate-based subscriptions are still available, the idiomatic Swift 6 way to consume chart events is through AsyncStream properties. This allows you to iterate over events using a for await loop within a Task.

    private var crosshairTask: Task<Void, Never>?
    
    // Start observing events
    crosshairTask = Task { @MainActor [weak self] in
        guard let self else { return }
    
        for await event in self.chart.crosshairMoveEvents {
            self.handleCrosshairMove(event)
        }
    }
    
    // Supported streams:
    // - clickEvents
    // - doubleClickEvents
    // - crosshairMoveEvents
  5. Migrate from v4 to v5

    master

    If you are upgrading from v4, be aware of the following breaking changes:

    • Requirements: Minimum iOS version is now 15.0. Requires Swift 6 and Xcode 16+.
    • Watermarks: ChartOptions.watermark is deprecated. Use createTextWatermarkPlugin() instead.
    • Plugins: Use the new explicit plugin APIs for markers and watermarks.
    • Panes: New async and synchronous pane management APIs are available (await chart.panes(), removePane(index:), swapPanes(first:second:)).
    • Attribution: LayoutOptions.attributionLogo now controls visibility, and links open in Safari.
    • Async/Await: The API is moving toward an async-first model. Expect await for many operations like paneSize() and priceLines().
  6. Check Minimum iOS Version Requirements

    master

    LightweightChartsIOS (v5.1.0+) requires a minimum deployment target of iOS 15.0.

    This requirement exists because the library uses Swift 6 and an async/await-first API, which relies on modern WebKit and concurrency behaviors available in iOS 15 and later. If your app targets an iOS version earlier than 15.0, you cannot use version 5.1.0 or higher.

  7. Basic Usage: Create a chart and add a series

    master

    To use the library, import LightweightCharts. The LightweightCharts class is a subclass of UIView. You must create an instance, add it to your view hierarchy, add a series (like a Bar series), and then provide data to that series.

    Note: This version is designed for Swift 6 and uses async/await. Completion-handler compatibility is not supported in this major version.

    import LightweightCharts
    
    // 1. Initialize the chart view
    var chart: LightweightCharts!
    chart = LightweightCharts()
    view.addSubview(chart)
    
    // 2. Add a series and store a reference
    var series: BarSeries!
    series = chart.addBarSeries(options: nil)
    
    // 3. Provide data
    let data = [
        BarData(time: .string("2018-10-19"), open: 180.34, high: 180.99, low: 178.57, close: 179.85),
        BarData(time: .string("2018-10-22"), open: 180.82, high: 181.40, low: 177.56, close: 178.75)
    ]
    series.setData(data: data)
  8. Migrate to Swift 6 Async API

    master

    When moving from the older completion-handler-based wrapper to the current Swift 6 API, you must meet the following requirements:

    • Swift Version: Swift 6 is required.
    • Deployment Target: iOS 15.0 or newer is required.
    • API Pattern: Value-returning wrapper APIs are now async throws instead of using completion handlers.
    • Event Consumption: Use AsyncStream properties instead of delegate-based subscriptions.
    • Distribution: CocoaPods is no longer a supported distribution path for this release.
  9. Install LightweightCharts via Swift Package Manager

    master

    LightweightCharts is available through Swift Package Manager. CocoaPods is no longer supported in this release.

    To install via Package.swift:

    dependencies: [
        .package(url: "https://github.com/tradingview/LightweightChartsIOS.git", from: "5.1.0")
    ]

    Alternatively, in Xcode, go to File > Add Package Dependencies and enter the repository URL: https://github.com/tradingview/LightweightChartsIOS.git.

    dependencies: [
        .package(url: "https://github.com/tradingview/LightweightChartsIOS.git", from: "5.1.0")
    ]
  10. Migrate to LightweightChartsIOS v5.1.0+

    master

    If you are upgrading from version 4.x or are currently using CocoaPods, you must perform the following migrations to use version 5.1.0 or later:

    1. Update Deployment Target: Ensure your app targets iOS 15.0 or higher.
    2. Switch Distribution: Move from CocoaPods to Swift Package Manager.
    3. Update Language Baseline: Ensure your environment is compatible with Swift 6 and the async/await-first API patterns used in this release.
  11. Configure Attribution Logo visibility

    master

    You can control the visibility of the built-in TradingView attribution logo via LayoutOptions. Note that if you disable the logo, you must ensure your app still complies with TradingView's NOTICE and licensing obligations.

    When the logo is visible, tapping it opens the link in Safari.

    var layout = LayoutOptions()
    layout.attributionLogo = false
    
    let options = ChartOptions(layout: layout)
    let chart = LightweightCharts(options: options)