lightweight-charts-indicators

repository·main·Indexed 41 days ago

https://github.com/deepentropy/lightweight-charts-indicators

A library providing 446 technical analysis indicators for TradingView's lightweight-charts, including standard, community, and candlestick patterns with PineScript v6 compatibility. Version 0.5.0 features a wide range of moving averages, oscillators, momentum, trend, volatility, and volume indicators, utilizing a .calculate() method that integrates with oakscriptjs and lightweight-charts.

Tokens
253.6K
Snippets
882
Records
1.1K
Agent score
6%

What's inside lightweight-charts-indicators

  1. Review the OakScriptJS Community Indicator Inventory

    main

    The INDICATOR_INVENTORY_COMMUNITY.md file provides a status report of community-contributed indicators for the OakScriptJS ecosystem. It tracks which indicators are currently Implemented, Implementable (planned), Blocked (due to technical limitations), or Duplicate (already available in the standard library).

    Status Definitions

    • Implemented: The indicator is available and ready for use.
    • Implementable: The indicator is planned and can be built, often categorized by difficulty (Easy, Medium, Hard).
    • Blocked: The indicator cannot be implemented currently due to specific technical blockers.
    • Duplicate: The indicator is already covered by an existing standard or community indicator.

    Common Blockers

    If an indicator is marked as Blocked, it is typically due to one of the following requirements that the current engine may not support:

    • MTF: Multi-Timeframe support.
    • Drawing: Requires drawing shapes or lines on the chart.
    • Table: Requires rendering data tables.
    • Strategy: Requires a backtesting or trading strategy engine.
    • Session: Requires specific session-based logic.
    • Screener: Requires a screener interface.
  2. Understand the OakScriptJS Community Indicator Implementation Status

    main

    The INDICATOR_INVENTORY_COMMUNITY.md document tracks the feasibility of porting TradingView PineScript indicators to OakScriptJS. It categorizes indicators based on whether they can be implemented and what technical limitations (blockers) prevent certain features from being replicated.

    Implementation Feasibility

    • Implementable (Easy/Medium/Hard): Indicators that can be ported. 'Hard' indicators typically involve complex logic (>200 lines) and may require skipping non-essential features like tables or drawings.
    • Blocked: Indicators that cannot be fully replicated due to missing engine capabilities. While the core calculation logic might be portable, the full feature set is unavailable.
    • Duplicate: Indicators that provide functionality already covered by existing standard or community indicators.
    • N/A: Indicators that are fundamentally incompatible or have missing data requirements.
  3. Important considerations for strategies

    main

    When developing strategies, keep the following limitations and behaviors in mind:

    • Repainting: Using calc_on_every_tick = true can cause the strategy to calculate differently on historical vs. real-time bars, leading to repainting.
    • Chart Types: Strategies use the chart's prices for entries and exits. Using non-standard charts like Heikin Ashi or Renko will produce misleading results because their prices are synthetic. Backtesting on these is not recommended.
    • Order Limits: Unless using Deep Backtesting mode, a strategy is limited to 9,000 orders. If this limit is exceeded, the oldest order information is removed. When this happens, strategy.closedtrades.*() functions will return na for those removed trades.
    • Execution: Strategy-specific labels for entries and exits will always be displayed over the main chart, regardless of the overlay setting.
  4. Understand the TradingView Indicator Catalog structure

    main

    The project maintains a catalog of indicators derived from TradingView, categorized into built-in and community-contributed scripts.

    Built-in Catalog

    Built-in indicators are categorized by their source filter:

    • standard: Includes 121 studies, 23 strategies, and 1 library (found in the "Technicals" tab).
    • candlestick: Includes 45 built-in candlestick patterns.
    • all: The full set of account-accessible indicators (built-ins plus partner/invite-only).

    Community Library

    The community library contains a large volume of unique published scripts, which can be of type study, strategy, or library. Access levels include open-source, protected, and invite-only.

    Note: The full community catalog is stored in official/catalog/community-catalog.json but is git-ignored due to its size (~16.5 MB).

  5. Implementation of AI/ML Indicators

    main

    The library includes specialized indicators that utilize Machine Learning algorithms for prediction and clustering. These are implemented using TypeScript and can output data to charts via the setTable() method.

    Key ML algorithms supported:

    • kNN (k-Nearest Neighbors): Used for classification and regression, often employing inverse-distance weighting for smoother predictions and Euclidean distance on normalized features.
    • k-means Clustering: Used for volatility clustering, typically utilizing a 10-iteration convergence approach.
    • Gaussian Kernel Regression: Used in specialized moving averages to provide kernel-weighted smoothing.

    Some indicators, such as ML Adaptive SuperTrend, ML RSI, and SuperTrend AI Clustering, are designed to output data tables directly onto the chart.

  6. Understand the timeframe.main_period variable

    main

    The timeframe.main_period variable is a simple string representing the script's main timeframe.

    Behavioral Nuances:

    • Indicator Declaration: If an indicator specifies a timeframe value in its declaration statement, timeframe.main_period holds that specific value. Otherwise, it defaults to the chart's current timeframe.
    • Request Functions: Unlike timeframe.period, the value of timeframe.main_period remains constant when used inside the expression argument of a request.*() function call.

    String Format: The format follows "<quantity>[<unit>]".

    Supported Units:

    • T: Ticks
    • S: Seconds
    • D: Days
    • W: Weeks
    • M: Months
    • (No unit): Minutes
    • Note on Hours: There is no specific unit for hours; hourly timeframes must be expressed in minutes (e.g., 4 hours is "240").
    "10S" // 10 seconds
    "30"   // 30 minutes
    "240"  // 4 hours (expressed in minutes)
    "1D"   // 1 day
    "2W"   // 2 weeks
    "3M"   // 3 months
  7. Use the var keyword to maintain state in indicators

    main

    The var keyword is used for assigning and one-time initializing a variable.

    Unlike standard variable assignment (which overwrites the value with every data update), variables initialized with var "keep their state" across updates. The value remains unchanged unless it is explicitly modified using the reassignment operator (:=) within conditional blocks (like if expressions).

    Syntax

    var variable_name = expression
    • variable_name: Any valid name (Latin characters, numbers, and underscores; cannot start with a number).
    • expression: An arithmetic expression that is calculated and assigned to the variable exactly once during the first execution.
    //@version=6  
    indicator("Var keyword example")  
    var a = close  
    var b = 0.0  
    var c = 0.0  
    var green_bars_count = 0  
    
    if close > open  
        var x = close  
        b := x  
        green_bars_count := green_bars_count + 1  
        if green_bars_count >= 10  
            var y = close  
            c := y  
    
    plot(a)
    plot(b)
    plot(c)
  8. Understand indicator display features: Markers, Fills, and Hlines

    main

    The library supports several visual display features for indicators to enhance chart readability. These are implemented using framework primitives:

    • Markers: Used for signals like trend flips or crossovers (e.g., AlphaTrend, HalfTrend, UTBot). They use the lightweight-charts v5 SeriesMarker<Time> API and include fields like position, shape, color, and text.
    • Fills: Used to create visual areas between two lines (e.g., Hull Suite, CDC Action Zone, Zero Lag MACD). These are implemented using FillData.
    • Hlines (Horizontal Lines): Used for constant levels, such as the zero line in QQE MOD or specific thresholds in Premier RSI. These use HLineData.

    Note: Dynamic per-bar coloring (e.g., changing a line color based on a condition) and barcolor are currently not supported by the framework.

  9. Configure indicator display elements (plots, markers, and fills)

    main

    Indicators in this library are designed to match PineScript display fidelity. When consuming an indicator, be aware that it may provide several types of visual outputs:

    • Plots: Standard data lines or histograms (e.g., macd1Line, macd1Hist).
    • Markers: Visual shapes like triangles or divergence labels (e.g., Bear R, Bull O, macdUp, macdDn).
    • Fills: Shaded areas between two plots or levels (e.g., BB-to-ATR outer channels in cog-channel, or Fibonacci zone fills).
    • Hlines: Horizontal lines representing constant levels (e.g., RSI 50 midline, Murrey Math quadrant levels, or OB/OS levels in ehlers-stochastic-cg).
    • BarColors/PlotCandles: Logic that changes the color of the price bars or candles based on indicator state.
    • BgColors: Background coloring for specific chart zones (e.g., atlas/choppiness bgcolor in double-macd).
  10. Understand the OakScriptJS Indicator Inventory

    main

    The OakScriptJS Indicator Inventory tracks the implementation status of PineScript indicators (from TradingView's standard library) within the OakScriptJS environment. It categorizes indicators by their implementation status (Implemented vs Pending) and assigns a complexity score based on the technical features they require.

    Implementation Status

    • Implemented: The indicator is available for use in OakScriptJS. Many implemented indicators have passed regression testing (marked with ✅ Pass).
    • Pending: The indicator is planned but not yet fully implemented.

    Complexity Scoring

    Complexity is used to prioritize development and is calculated using the following weights:

    • Strategy functions: +20 points
    • Drawing functions: +10 points
    • request.security usage: +5 points
    • Table operations: +5 points
    • Array/Matrix operations: +5 points
    • Number of unique TA functions used: (Base score)
  11. Identify and use drawing-based indicator outputs

    main

    Some community indicators in this library provide LineDrawingData[] as an output. This allows the indicator to render drawing objects (like dashed lines or horizontal levels) that persist from a specific bar forward, matching the behavior of PineScript's line.new calls.

    Examples of indicators using this feature:

    • consolidation-zones: Outputs dashed zone boundary lines drawn from the current bar back to the start of consolidation.
    • false-breakout: Outputs horizontal breakout level lines drawn from the breakout origin bar to the current bar.
  12. Understanding the `series` type qualifier

    main

    The series keyword is a type qualifier used to declare variables or function parameters that can change throughout a script's execution. In the type qualifier hierarchy, series is the strongest qualifier:

    const < input < simple < series

    Key Behaviors

    • Automatic Inference: The compiler usually detects if a parameter is compatible with series or simple automatically. For exported library functions, parameters are treated as series by default whenever possible.
    • Variable Declarations: The compiler can typically infer the qualifier based on the assigned value and can automatically upgrade a variable to a stronger qualifier (e.g., from simple to series) if needed.
    • Restriction: Explicitly declaring a variable as series restricts it. A series variable cannot be passed to any function or assigned to any variable that requires a weaker qualifier (such as const, input, or simple).
    • Requirement: When using series as a qualifier, you must also provide a type keyword (e.g., float, int, bool).
    //@version=6  
    //@description A library with custom functions.  
    library("CustomFunctions", overlay = true)  
      
    //@function Finds the highest `source` value over `length` bars, filtered by the `cond` condition.  
    export conditionalHighest(series float source, series bool cond, series int length) =>  
        //@variable The highest `source` value from when the `cond` was `true` over `length` bars.  
        series float result = na  
        // Loop to find the highest value.  
        for i = 0 to length - 1  
            if cond[i]  
                value   = source[i]  
                result := math.max(nz(result, value), value)  
        // Return the `result`.  
        result  
      
    //@variable Is `true` once every five bars.  
    series bool condition = bar_index % 5 == 0  
      
    //@variable The highest `close` value from every fifth bar over the last 100 bars.  
    series float hiValue = conditionalHighest(close, condition, 100)  
    
    plot(hiValue)  
    bgcolor(condition ? color.new(color.teal, 80) : na)