PyneCore

repository·main·Indexed 41 days ago

https://github.com/pynesys/pynecore

A Python library and runtime that brings TradingView's Pine Script capabilities to the Python ecosystem. It uses AST transformations to enable bar-by-bar semantics, allowing developers to use Python's data science and ML libraries for trading logic. PyneCore includes a ScriptRunner API, a comprehensive technical analysis library (ta), and a CLI tool for downloading data and executing scripts. Version 6.10.2.

Tokens
163.9K
Snippets
499
Records
664
Agent score
54%

What's inside PyneCore

  1. What is PyneCore?

    main

    PyneCore is an open-source framework that implements the TradingView Pine Script bar-by-bar execution model natively in Python. It allows developers to write trading strategies and technical indicators using Python syntax while benefiting from Pine Script's intuitive semantics.

    Key characteristics include:

    • AST Transformation: Instead of using heavy object-oriented wrappers, PyneCore uses Python's Abstract Syntax Tree (AST) to transform regular Python code into Pine Script-like behavior.
    • High Compatibility: Aims for 0.001% precision tolerance compared to TradingView's Pine Script.
    • Zero Mandatory Dependencies: The core system is designed to operate without external libraries for maximum portability.
    • Pythonic Integration: Maintains Python's type hints, ecosystem, and syntax while providing specialized trading primitives.
  2. Overview of PyneCore Data Management CLI commands

    main

    The PyneCore CLI manages OHLCV (Open, High, Low, Close, Volume) data through the pyne data subcommand. It supports downloading historical data from various providers, converting between PyneCore's efficient binary .ohlcv format and common formats like CSV or JSON, and aggregating data across timeframes.

    Available commands under pyne data:

    • download: Fetch historical OHLCV data from a provider.
    • convert-to: Convert PyneCore .ohlcv files to CSV or JSON.
    • convert-from: Convert CSV or JSON files into PyneCore .ohlcv format.
    • aggregate: Aggregate data from a lower to a higher timeframe.
    pyne data [COMMAND] [OPTIONS] [ARGUMENTS]
  3. String manipulation with the str namespace

    main

    The str namespace (imported from pynecore.lib.string) provides functions for searching, formatting, transforming, and analyzing text values within PyneCore scripts. These functions are designed to be compatible with TradingView's Pine Script v6 string functions.

    from pynecore.lib import string as pstr, label, bar_index, high, close, script
    
    @script.indicator(title="String Operations Demo", overlay=True)
    def main():
        # Get price as formatted string
        price_text: str = pstr.tostring(close)
        
        # Format with custom precision
        formatted_price: str = pstr.format("{0}", close)
        
        # String transformations
        upper_text: str = pstr.upper(price_text)
        lower_text: str = pstr.lower(upper_text)
        
        # String analysis
        length_val: int = pstr.length(price_text)
        contains_val: bool = pstr.contains(price_text, ".")
        
        # Display result
        if bar_index % 10 == 0:
            label.new(bar_index, high, upper_text)
  4. Programmatic Usage of PyneCore

    main

    PyneCore can be used directly from Python code to embed Pine Script indicators and strategies into external applications. This allows for integration into trading bots, custom backtesting frameworks, data pipelines, and other automated systems, moving beyond the standalone CLI usage.

    Key programmatic capabilities include:

    • ScriptRunner API: Running scripts from Python and accessing the resulting indicator or strategy data.
    • Visual Output (Viz): Configuring plot styles and exporting drawing data as an opt-in NDJSON stream.
    • Data & SymInfo: Loading or creating OHLCV (Open, High, Low, Close, Volume) data and symbol information.
    • Integration Patterns: Implementing real-world workflows such as FreqTrade integration, live trading, or custom system builds.
  5. Use the text namespace for alignment, formatting, and wrapping

    main

    The pynecore.lib.text namespace provides constants used to control the visual presentation of text within drawing objects like labels, boxes, and table cells. You can use these constants to specify horizontal/vertical alignment, text styles (bold/italic), and wrapping behavior.

    from pynecore.lib import script, label, text, bar_index, high, low, close, ta
    
    @script.indicator(title="Signal Labels", overlay=True)
    def main():
        is_cross: bool = ta.crossover(close, ta.sma(close, 20))
        if is_cross:
            label.new(
                bar_index, high,
                text="BUY",
                textalign=text.align_center,
                style=label.style_label_up,
                text_formatting=text.format_bold
            )
  6. Use the math library for numerical operations

    main

    The pynecore.lib.math namespace provides mathematical functions and constants for use in indicators and strategies. All functions handle NA (not available) values gracefully: if any input is NA, the function returns NA.

    from pynecore.lib import math, close, script
    
    @script.indicator(title="Math Demo", overlay=True)
    def main():
        # Example usage
        val = math.abs(close - close[1])
  7. Understand the Pyne Ecosystem components

    main

    The Pyne ecosystem provides a complete solution for achieving TradingView Pine Script compatibility within a Python environment. It is composed of two primary pillars:

    1. PyneCore (Open Source): The foundational Python library that implements a Pine Script-like runtime. It provides the execution model, AST transformations for Pine-like syntax, technical indicators, series data structures, and backtesting capabilities.
    2. PyneComp (SaaS Service): A compiler/transpiler that converts existing Pine Script code into clean, readable PyneCore-compatible Python code. This allows for a smooth migration from TradingView to Python.

    PyneComp can be accessed via the PyneSys API, the pynesys.io web interface, or directly through the PyneCore CLI (requires an API key).

  8. Explore the PyneCore Reference Documentation

    main

    The PyneCore reference documentation is organized into four primary sections to help you understand the script structure, type system, input handling, and the core library:

    • Script Format: Explains the required anatomy of a @pyne script, including magic comments, imports, decorators, the main() function, and input parameters.
    • Types: Details the PyneCore type system, covering primitives, collections, drawing types, and specialized annotations like Series, Persistent, IBPersistent, @udt, and StrEnum.
    • Input Functions: Provides documentation for user-configurable script parameters (e.g., input.int(), input.float(), input.string()) and how to manage them via TOML-based configuration.
    • Library: A comprehensive reference for all library functions, variables, and constants, organized by namespaces such as ta, math, and strategy.
  9. Use the color namespace in PyneCore

    main

    The pynecore.lib.color namespace provides tools for creating, modifying, and inspecting colors used in visual elements like lines, labels, and plots. You can use predefined color constants, create custom colors via RGB or hex strings, apply transparency, and generate color gradients based on data ranges.

    from pynecore.lib import color, Color
    
    # Use predefined colors
    my_color: Color = color.green
    
    # Create custom color with transparency
    transparent_blue: Color = color.new(color.blue, transp=50)
    
    # Create color from RGB values
    custom_color: Color = color.rgb(255, 165, 0)
    
    # Create color gradient based on price position
    price_position: float = (close - low) / (high - low) if high != low else 0.5
    bar_color: Color = color.from_gradient(
        price_position, 0, 1, color.red, color.green
    )
  10. Use the `ta` namespace for technical analysis

    main

    The ta namespace provides Pine Script-compatible technical analysis indicators. It includes functions for calculating moving averages, momentum oscillators, volatility measures, trend indicators, and statistical functions. These functions are designed to work with series data from OHLCV bars (such as close, high, low, open, and volume).

    from pynecore.lib import (
        close, high, low, open, volume, bar_index, ta, plot, strategy, script
    )
    
    @script.indicator(title="RSI and MACD Analysis", overlay=False)
    def main():
        # Calculate RSI
        rsi_val: float = ta.rsi(close, 14)
        
        # Calculate MACD
        macd_line, signal_line, histogram = ta.macd(close, 12, 26, 9)
        
        # Calculate Bollinger Bands
        bb_middle, bb_upper, bb_lower = ta.bb(close, 20, 2.0)
        
        # Plot results
        plot(rsi_val, title="RSI(14)", color="blue")
        plot(macd_line, title="MACD", color="red")
  11. Explore PyneCore built-in library namespaces

    main

    PyneCore provides a comprehensive set of built-in namespaces for technical analysis, mathematical operations, data manipulation, and chart visualization. Use these namespaces to access functions, variables, and constants required for building trading strategies and indicators.

    Key functional areas include:

    • Analysis & Math: ta (Technical Analysis), math (Mathematical functions), array (Array operations), matrix (Matrix operations), and map (Key-value operations).
    • Data & Symbols: request (Cross-symbol/timeframe data), syminfo (Symbol information), timeframe (Timeframe utilities), ticker (Ticker identifiers), and session (Session information).
    • Strategy & Execution: strategy (Entry, exit, and order management), alert (Alert triggering), and barstate (Bar state flags).
    • Visualization: label (Chart labels), line (Chart lines), box (Chart boxes), table (Data tables), polyline (Multi-segment lines), linefill (Fill between lines), plot (Plotting), hline (Horizontal lines), and chart (Chart properties).
    • String & Color: str (String manipulation) and color (Color functions/constants).
    • System: log (Logging) and runtime (Error handling).
  12. Understand the PyneCore project structure

    main

    PyneCore is a modular system designed to emulate Pine Script (v6) behavior within Python. The architecture is divided into several key functional areas:

    • Core (core/): The execution engine. It contains the Series implementation (circular buffers for high-performance data handling), the Script Runner for bar-by-bar execution, and the Import Hook System that enables @pyne magic comments.
    • Transformers (transformers/): A suite of AST (Abstract Syntax Tree) transformers that convert standard Python syntax into Pine Script-compatible semantics (e.g., handling persistent variables, function isolation, and safe division).
    • Library (lib/): A comprehensive implementation of 134+ TradingView-compatible indicators (via ta.py), math functions, and a complete strategy backtesting subsystem.
    • Types (types/): Type definitions for Pine Script constructs like Series, na (Not Available) values, and OHLCV data.
    • CLI (cli/): The pyne command-line interface for running, compiling, and managing data.
    • Providers (providers/): Modules for fetching OHLCV data from TradingView, CCXT, and Capital.com.
    • PyneSys (pynesys/): The client for the cloud compilation service that converts Pine Script to Python code.