### Quick Example: Session Detector Indicator Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/session.md This example demonstrates how to use session flags to mark the start and end of trading days and to control strategy entries. It requires importing `close`, `session`, `bar_index`, `label`, and `strategy` from `pynecore.lib`. ```python from pynecore.lib import close, session, bar_index, label, strategy @script.indicator(title="Session Detector", overlay=True) def main(): # Mark the first bar of each day's session if session.isfirstbar_regular: label.new(bar_index, close, "Day start", textcolor="color.green") # Mark the last bar of regular trading hours if session.islastbar_regular: label.new(bar_index, close, "Regular close", textcolor="color.red") # Trade only during market hours if session.ismarket: strategy.entry("Long", strategy.long) ``` -------------------------------- ### Install PyneCore with all features and development dependencies Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore with all features and development dependencies. This is the most complete installation, suitable for active development. ```bash pip install "pynesys-pynecore[all,dev]" ``` -------------------------------- ### Install PyneCore from source in development mode Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore from its source repository for development purposes. This includes cloning the repo, setting up a virtual environment, and installing with all dependencies. ```bash git clone https://github.com/PyneSys/pynecore.git cd pynecore python -m venv venv # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate pip install -e ".[all,dev]" ``` -------------------------------- ### Install PyneCore with all features Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore with all available features, excluding development dependencies. This provides a comprehensive installation for general use. ```bash pip install "pynesys-pynecore[all]" ``` -------------------------------- ### Complete Risk Management Strategy Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_risk.md A full PyneCore script demonstrating the setup and usage of various strategy.risk functions for comprehensive risk management. ```python from pynecore.lib import ( close, strategy, ta, script ) @script.strategy(title="Risk Management Strategy", overlay=True) def main(): # Configure risk rules strategy.risk.max_position_size(10) strategy.risk.max_drawdown(10, strategy.percent_of_equity) strategy.risk.max_intraday_loss(5000, strategy.cash) strategy.risk.max_cons_loss_days(3) strategy.risk.max_intraday_filled_orders(5) strategy.risk.allow_entry_in(strategy.direction.long) # Trading logic sma20: float = ta.sma(close, 20) if close > sma20: strategy.entry("long", strategy.long, qty=1) ``` -------------------------------- ### Install PyneCore packages Source: https://github.com/pynesys/pynecore/blob/main/README.md Use pip to install the core library, CLI tools, or full feature set. ```bash # Basic installation pip install pynesys-pynecore # With CLI tools (recommended) pip install pynesys-pynecore[cli] # With all features including data providers pip install pynesys-pynecore[all] ``` -------------------------------- ### Verify Development Setup with Pytest Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Run the test suite to confirm that your development environment is correctly configured and all dependencies are installed properly. ```bash python -m pytest ``` -------------------------------- ### Quick Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/currency.md Demonstrates how to use currency constants in a strategy definition. ```APIDOC ## Quick Example ```python from pynecore.lib import close, script, strategy, currency @script.strategy(title="Currency Example", currency=currency.USD) def main(): if close > 100: strategy.entry("Long", strategy.long) ``` ``` -------------------------------- ### Quick Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/font.md Demonstrates how to use font constants in a script. ```APIDOC ## Quick Example ```python from pynecore.lib import script, label, font, bar_index, high, close, ta @script.indicator(title="Font Example", overlay=True) def main(): if ta.crossover(close, ta.sma(close, 20)): label.new( bar_index, high, text="Cross", text_font_family=font.family_monospace ) ``` ``` -------------------------------- ### Minimal PyneCore Script Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/script-format.md A basic example demonstrating the required structure of a PyneCore script. ```APIDOC ## Minimal PyneCore Script Example ```python """@pyne""" from pynecore.lib import script, close @script.indicator("My Indicator") def main(): return {"close": close} ``` ``` -------------------------------- ### Install PyneCore for development Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore with development dependencies. This is useful for developers contributing to the project. ```bash pip install "pynesys-pynecore[dev]" ``` -------------------------------- ### Install PyneCore with CLI Support Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/basics.md Install PyneCore including the necessary dependencies for CLI functionality. ```bash pip install "pynesys-pynecore[cli]" ``` -------------------------------- ### Quick Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/text.md Demonstrates how to use text alignment constants in a label. ```APIDOC ## Quick Example ### Description This example shows how to create a label with centered text using `text.align_center`. ### Code ```python 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 ) ``` ``` -------------------------------- ### Run a PyneCore script Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Execute a PyneCore script after installation and data setup. This command runs the specified script with the provided data file. ```bash pyne run test.py data/your-downloaded-data.ohlcv ``` -------------------------------- ### Install PyneCore with provider dependencies Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore with built-in data provider capabilities. This enables PyneCore to interact with various data sources. ```bash pip install "pynesys-pynecore[providers]" ``` -------------------------------- ### Install PyneCore with specific provider support Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install PyneCore with support for specific data providers like CCXT or CapitalCom. Choose the provider you intend to use. ```bash pip install "pynesys-pynecore[ccxt]" ``` ```bash pip install "pynesys-pynecore[capitalcom]" ``` -------------------------------- ### PyneCore Version Examples Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/versioning.md Illustrative examples of PyneCore versioning, showing stable releases tied to Pine Script versions and subsequent bug fixes or feature additions. ```text 6.0.0 – First stable release supporting Pine v6 ``` ```text 6.0.4 – Bugfix release, still Pine v6 ``` ```text 6.1.0 – Adds new Pine v6 features (e.g., support for `bar_index.new`) ``` ```text 7.0.0 – First version to support Pine v7 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Install all necessary dependencies for development, including testing and linting tools. This command installs PyneCore in editable mode. ```bash pip install -e ".[all,dev]" ``` -------------------------------- ### Install PyneCore with pip Source: https://github.com/pynesys/pynecore/blob/main/docs/faq.md Install PyneCore using pip. Use optional dependencies for additional features like the CLI or data providers. ```bash pip install pynesys-pynecore[cli] # With user-friendly CLI ``` ```bash pip install "pynesys-pynecore[cli,providers]" # With data providers ``` ```bash pip install "pynesys-pynecore[all]" # With all features ``` -------------------------------- ### Complete Pyne Code Transformation Example Source: https://github.com/pynesys/pynecore/blob/main/docs/advanced/ast-transformations.md Demonstrates the combined effect of AST transformers on a full Pyne code example, converting it to equivalent Python with PyneCore's runtime system. ```python """ @pyne """ from pynecore import Series, Persistent from pynecore.lib.ta import sma from pynecore.lib import close, open_, high, low, plot def main(): # Persistent counter count: Persistent[int] = 0 count += 1 # Moving average calculation ma: Series[float] = sma(close, 14) # Safe division that could cause division by zero range_ratio = (close - open_) / (high - low) # Plot results plot(ma, "MA", color=lib.color.blue) plot(count, "Count", color=lib.color.red) plot(range_ratio, "Range Ratio", color=lib.color.green) ``` ```python """ @pyne """ from pynecore import lib import pynecore.lib.ta from pynecore.core.series import SeriesImpl from pynecore.core.function_isolation import isolate_function from pynecore.core import safe_convert # Global variables and scope ID __scope_id__ = "8af7c21e_example.py" __persistent_main·count__ = 0 __series_main·ma__ = SeriesImpl() __series_main·range_ratio__ = SeriesImpl() # Function and variable registries __persistent_function_vars__ = {'main': ['__persistent_main·count__']} __series_function_vars__ = {'main': ['__series_main·ma__', '__series_main·range_ratio__']} def main(): global __scope_id__ global __persistent_main·count__ # Library Series declarations __lib·close: Series = lib.close __lib·open_: Series = lib.open_ __lib·high: Series = lib.high __lib·low: Series = lib.low # Persistent counter __persistent_main·count__ += 1 # Moving average calculation ma = __series_main·ma__.add(isolate_function(lib.ta.sma, "main|lib.ta.sma|0", __scope_id__)(__lib·close, 14)) # Safe division that could cause division by zero range_ratio = __series_main·range_ratio__.add(safe_convert.safe_div(__lib·close - __lib·open_, __lib·high - __lib·low)) # Plot results lib.plot(ma, "MA", color=lib.color.blue) lib.plot(__persistent_main·count__, "Count", color=lib.color.red) lib.plot(range_ratio, "Range Ratio", color=lib.color.green) ``` -------------------------------- ### Install PyneCore with pip Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Install the base PyneCore package without any optional dependencies. This is suitable for minimal CLI usage. ```bash pip install pynesys-pynecore ``` -------------------------------- ### Pynecore Map Usage Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/types.md Shows how to use the pynecore map type for key-value storage. This example demonstrates creating a map, adding a key-value pair, and retrieving a value by its key. ```python from pynecore.types import Persistent from pynecore.lib import script, close, map @script.indicator("Map Example") def main(): prices: Persistent[map] = map.new(str, float) map.put(prices, "last_close", close) val = map.get(prices, "last_close") ``` -------------------------------- ### Verify PyneCore installation Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/installation.md Run this command in your terminal to verify that PyneCore has been installed correctly. A successful verification will display the PyneCore logo and CLI help information. ```bash pyne -h ``` -------------------------------- ### PyneCore Strategy Example (Simple Crossover) Source: https://github.com/pynesys/pynecore/blob/main/docs/lib/reference.md An example of a trading strategy implemented with PyneCore. It uses SMAs to detect crossovers and enters long or short positions accordingly. ```python """ @pyne """ from pynecore.lib import script, ta, close, high, low from pynecore.lib import strategy @script.strategy("Simple Crossover Strategy") def main(): fast_ma = ta.sma(close, 9) slow_ma = ta.sma(close, 21) if ta.crossover(fast_ma, slow_ma): strategy.entry("Long", strategy.long) if ta.crossunder(fast_ma, slow_ma): strategy.entry("Short", strategy.short) ``` -------------------------------- ### Install Shell Completion Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/basics.md Enable command-line completion for PyneCore commands in your current shell. ```bash pyne --install-completion ``` -------------------------------- ### Plotshape Quick Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/shape.md A practical example demonstrating the usage of shape constants with the plotshape() function. ```APIDOC ## Plotshape Quick Example ### Description This example illustrates how to use different shape constants from the `shape` namespace along with the `plotshape()` function to visually represent crossover events on a chart. ### Code ```python from pynecore.lib import script, plotshape, ta, close, high, low, shape, color @script.indicator(title="Shape Demo", overlay=True) def main(): cross_up = ta.crossover(close, ta.sma(close, 20)) cross_down = ta.crossunder(close, ta.sma(close, 20)) plotshape(cross_up, style=shape.triangleup, location="belowbar", color=color.green, size="small") plotshape(cross_down, style=shape.triangledown, location="abovebar", color=color.red, size="small") ``` ### Explanation - The code defines an indicator that plots shapes based on price crossovers with a 20-period Simple Moving Average. - `shape.triangleup` is used for upward crossovers, plotted below the bar in green. - `shape.triangledown` is used for downward crossovers, plotted above the bar in red. ``` -------------------------------- ### PyneCore Pre-release Versions Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/versioning.md Examples of pre-release versions for PyneCore, used during the integration and testing of new Pine Script versions. These require explicit installation using the `--pre` flag with pip. ```text 7.0.0a1 – Alpha release ``` ```text 7.0.0b1 – Beta release ``` ```text 7.0.0rc1 – Release candidate ``` -------------------------------- ### Simple Compilation Example Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/compile.md Compiles a specified Pine Script file located in the current or scripts directory. ```bash # Compile a Pine Script file pyne compile my_strategy.pine ``` -------------------------------- ### Example Python Code with Type Hints and Docstrings Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Illustrates adherence to PEP 8, type hinting, and Sphinx-style docstrings for functions. This example calculates a simple moving average. ```python def calculate_moving_average(values: Series[float], length: int) -> Series[float]: """ Calculate a simple moving average of a series. :param values: Input series of values :param length: Window length for the moving average :return: New series containing the moving average values """ if length <= 0: raise ValueError("Length must be positive") # Implementation logic result = values.rolling_sum(length) / length return result ``` -------------------------------- ### API Configuration File Setup Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/compile.md Define the API key in the TOML configuration file located at workdir/config/api.toml. ```toml [api] api_key = "your-api-key-here" ``` -------------------------------- ### Pyne Script Indicator Test Example Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Demonstrates how to write tests in PyneCore using Pyne Script syntax for indicators. This example defines a simple SMA indicator. ```python """ @pyne """ from pynecore.lib import script, ta, close, plot @script.indicator(title="Test Indicator") def main(): my_value = ta.sma(close, 10) plot(my_value, "My SMA") ``` -------------------------------- ### Complete RSI Mean Reversion Strategy Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/script-format.md A full example of a strategy script that calculates RSI, enters long trades on oversold conditions, closes trades on overbought conditions, and plots the RSI. It uses `Persistent` for trade count and defines input parameters for RSI length and levels. ```python """@pyne""" from pynecore.types import Series, Persistent from pynecore.lib import script, input, close, ta, strategy, plot, color @script.strategy( "RSI Mean Reversion", overlay=True, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1, ) def main( rsi_length: int = input.int(14, title="RSI Length", minval=1), oversold: int = input.int(30, title="Oversold Level"), overbought: int = input.int(70, title="Overbought Level"), ): rsi: Series[float] = ta.rsi(close, rsi_length) trade_count: Persistent[int] = 0 if ta.crossover(rsi, oversold): strategy.entry("Long", strategy.long) trade_count += 1 if ta.crossunder(rsi, overbought): strategy.close("Long") plot(rsi, "RSI", color=color.purple) return { "Overbought": overbought, "Oversold": oversold, } ``` -------------------------------- ### Get Help Information Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/basics.md Display help messages for the PyneCore CLI. Use for general help or specific commands/subcommands. ```bash pyne --help ``` ```bash pyne run --help ``` ```bash pyne data download --help ``` -------------------------------- ### Get Exchange Prefix of Symbol Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves the exchange prefix for the current symbol. For example, 'NASDAQ' for 'NASDAQ:AAPL'. ```python exch: str | NA[str] = syminfo.prefix # "NASDAQ" ``` -------------------------------- ### Example Bar Data Source: https://github.com/pynesys/pynecore/blob/main/docs/advanced/bar-magnifier.md A sample representation of a 1-hour bar containing both take-profit and stop-loss levels. ```text Open=100, High=112, Low=88, Close=100 ``` -------------------------------- ### Script Configuration Example Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/configuration.md Demonstrates a TOML file for configuring script-specific settings and input parameters. This allows modification of script behavior without altering the code itself. ```toml # Indicator / Strategy / Library Settings [script] overlay = false behind_chart = true # Many more script settings... # Input Settings [inputs.maxIdLossPcnt] # Input metadata, cannot be modified # title: "Max Intraday Loss(%)" # inline: false # confirm: false # Change here to modify the input value #value = ``` -------------------------------- ### Get Symbol Industry Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves the industry classification for stocks. Returns `na` if not available. Examples include 'Internet Software/Services' or 'Packaged Software'. ```python ind: str | NA[str] = syminfo.industry # "Internet Software/Services" ``` -------------------------------- ### Get Symbol Sector Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves the sector classification for stocks. Returns `na` if not available. Examples include 'Electronic Technology' or 'Energy Minerals'. ```python sec: str | NA[str] = syminfo.sector # "Electronic Technology" ``` -------------------------------- ### Get Chart Period Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves the period or resolution of the chart data. Examples include '60' for minute bars, 'D' for daily, 'W' for weekly, or 'M' for monthly. ```python p: str | NA[str] = syminfo.period # "60", "D", "W" ``` -------------------------------- ### Get Timeframe Multiplier Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/timeframe.md Retrieves the numeric multiplier for the current timeframe resolution. For example, on a '60' minute chart, this returns 60; on a 'D' chart, it returns 1. ```python mult: int = timeframe.multiplier ``` -------------------------------- ### Pynecore Matrix Initialization and Access Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/types.md Demonstrates how to create and manipulate a 2D matrix using pynecore. This example shows matrix creation with specified dimensions and types, setting a value, and retrieving it. ```python from pynecore.types import Persistent from pynecore.lib import script, matrix @script.indicator("Matrix Example") def main(): m: Persistent[matrix] = matrix.new(float, 3, 3, 0.0) matrix.set(m, 0, 0, 1.0) val = matrix.get(m, 0, 0) ``` -------------------------------- ### Python Function Isolation Example Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/what-is-pynecore.md Demonstrates how each function call in PyneCore gets its own isolated state for persistent and series variables. Ensure correct type hinting for variables. ```python def my_indicator(input_series, length): # Each call to this function has its own state sum: Persistent[float] = 0 sum += input_series - input_series[length] return sum / length ``` -------------------------------- ### Run Strategy with Bar Magnifier Source: https://github.com/pynesys/pynecore/blob/main/docs/advanced/bar-magnifier.md Command line examples for running a strategy with lower-timeframe data provided via the --timeframe option. ```bash # Data file contains 10-minute candles, strategy runs on 1-hour chart pyne run my_strategy.py EURUSD_10m.ohlcv --timeframe 60 # Data file contains 1-minute candles, strategy runs on 5-minute chart pyne run my_strategy.py BTCUSDT_1m.ohlcv --timeframe 5 ``` -------------------------------- ### Symbol Configuration Example Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/configuration.md Shows a TOML file for configuring symbol-specific details like currency, tick size, and trading hours. This is crucial for accurate calculations and backtesting. ```toml [symbol] prefix = "CAPITALCOM" description = "EUR/USD" ticker = "EURUSD" currency = "USD" basecurrency = "EUR" period = "15" type = "forex" mintick = 0.00001000 pricescale = 100000 minmove = 1.00000000 pointvalue = 1 timezone = "US/Eastern" volumetype = "base" avg_spread = 0.00007430 # Opening hours [[opening_hours]] day = 0 start = "00:00:00" end = "16:59:50" # Many more opening hours entries... # Session starts [[session_starts]] day = 0 time = "17:05:00" # More session entries... ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Clone the PyneCore repository and change into the project directory. This is the first step for setting up your development environment. ```bash git clone https://github.com/PyneSys/pynecore.git cd pynecore ``` -------------------------------- ### Strategy with Currency Configuration Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/currency.md Example of how to define a trading strategy and specify a currency using the `currency.USD` constant. Ensure necessary imports are included. ```python from pynecore.lib import close, script, strategy, currency @script.strategy(title="Currency Example", currency=currency.USD) def main(): if close > 100: strategy.entry("Long", strategy.long) ``` -------------------------------- ### Map Usage Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/map.md Demonstrates basic map operations including creation, insertion, retrieval, existence checks, iteration, and clearing. ```python from pynecore.lib import close, strategy, script, ta, map @script.strategy(title="Map Usage Example", overlay=False) def main(): # Create a new map to store moving averages ma_values: dict = map.new() # Add moving averages to the map map.put(ma_values, "sma20", ta.sma(close, 20)) map.put(ma_values, "sma50", ta.sma(close, 50)) # Retrieve a value sma20: float = map.get(ma_values, "sma20") # Check if a key exists has_sma20: bool = map.contains(ma_values, "sma20") # Iterate over keys and values all_keys: list = map.keys(ma_values) all_values: list = map.values(ma_values) # Get the number of pairs pair_count: int = map.size(ma_values) # Clear the map map.clear(ma_values) ``` -------------------------------- ### Monitor Open Trades Strategy Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_opentrades.md This example demonstrates how to monitor open trades, display their metrics, and exit based on drawdown. It requires the pynecore library and uses the @script.strategy decorator. ```python from pynecore.lib import close, strategy, label, bar_index, script @script.strategy(title="Monitor Open Trades") def main(): # Enter a trade on every close above 100 if close > 100: strategy.entry("long", strategy.long, qty=1) # Monitor first open trade if strategy.opentrades.size(0) != 0: entry_price: float = strategy.opentrades.entry_price(0) current_profit: float = strategy.opentrades.profit(0) profit_pct: float = strategy.opentrades.profit_percent(0) max_dd: float = strategy.opentrades.max_drawdown(0) # Label showing trade metrics label.new(bar_index, close, f"P&L: {current_profit:.2f} ({profit_pct:.1f}%) | DD: {max_dd:.2f}") # Exit if drawdown exceeds 5% if strategy.opentrades.max_drawdown_percent(0) < -5.0: strategy.close("long") ``` -------------------------------- ### Run a script with default options Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/run.md Executes a strategy script using default settings. ```bash pyne run my_strategy.py eurusd_data.ohlcv ``` -------------------------------- ### Detect New Day Start Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/timeframe.md Returns True at the start of each new day on the current chart. Ensure the specified timeframe ('D') is equal to or larger than the chart's timeframe. ```python if timeframe.change("D"): label.new(bar_index, high, "New Day") ``` -------------------------------- ### Initialize performance-tuned CSVWriter Source: https://github.com/pynesys/pynecore/blob/main/docs/advanced/csv-reader-writer.md Provides the boilerplate for setting up a CSVWriter instance. ```python from pynecore.core.csv_file import CSVWriter from pathlib import Path ``` -------------------------------- ### Compilation with API Key Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/compile.md Provides the API key directly via the command line. ```bash # Compile with API key provided via command line pyne compile my_strategy.pine --api-key "your-api-key" ``` -------------------------------- ### PyneCore Technical Indicator Example (SMA and EMA) Source: https://github.com/pynesys/pynecore/blob/main/docs/lib/reference.md An example of creating a technical indicator using PyneCore. It calculates and plots Simple Moving Average (SMA) and Exponential Moving Average (EMA) for comparison. ```python """ @pyne """ from pynecore.lib import script, ta, close, plot @script.indicator(title="SMA and EMA Comparison") def main(): sma_val = ta.sma(close, 20) ema_val = ta.ema(close, 20) plot(sma_val, "SMA 20") plot(ema_val, "EMA 20") ``` -------------------------------- ### Minimal PyneCore Script Example Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/script-format.md A basic PyneCore script demonstrating the essential components: magic comment, imports, and a decorated main function. ```python """@pyne""" from pynecore.lib import script, close @script.indicator("My Indicator") def main(): return {"close": close} ``` -------------------------------- ### Trade Size Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_closedtrades.md Get the size of a closed trade. ```APIDOC ## size() ### Description Returns the trade size. Positive values indicate a long position, negative values indicate a short position. ### Method GET (simulated) ### Endpoint strategy.closedtrades.size(trade_num) ### Parameters #### Path Parameters - **trade_num** (int) - Required - Trade number (first trade is 0) ### Response #### Success Response (200) - **sz** (float) - The trade size. Positive for long, negative for short. ### Response Example { "sz": 1.0 } ``` -------------------------------- ### Create and Analyze a 3x3 Matrix Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/matrix.md Demonstrates creating a matrix, setting diagonal values, and analyzing its properties like being diagonal, trace, and average value. Requires the 'pynecore.lib.matrix' and 'pynecore.lib.script' modules. ```python from pynecore.lib import matrix, script @script.indicator(title="Matrix Analysis", overlay=False) def main(): # Create a 3x3 matrix m = matrix.new(3, 3, 0.0) # Set diagonal values matrix.set(m, 0, 0, 10.0) matrix.set(m, 1, 1, 20.0) matrix.set(m, 2, 2, 30.0) # Analyze matrix properties is_diag: bool = matrix.is_diagonal(m) trace_val: float = matrix.trace(m) # Sum of diagonal avg_val: float = matrix.avg(m) ``` -------------------------------- ### Get map values Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/map.md Retrieves a list of all values in the map as a copy. ```python value_list: list = map.values(data) # [100.5, 1000, 1234567890] ``` -------------------------------- ### Create an on-chart table Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/table.md Initializes a table with specified dimensions and styling, then populates it with header and data rows. ```python from pynecore.lib import script, table, position, color, close, bar_index @script.indicator(title="Price Table", overlay=True) def main(): # Create a table at the top-left corner tbl: table.Table = table.new( position.top_left, columns=2, rows=3, bgcolor=color.gray, border_width=1 ) # Add header row table.cell(tbl, 0, 0, "Metric", text_color=color.white) table.cell(tbl, 1, 0, "Value", text_color=color.white) # Add data rows table.cell(tbl, 0, 1, "Close", text_color=color.white) table.cell(tbl, 1, 1, str(close), text_color=color.white) table.cell(tbl, 0, 2, "Bar", text_color=color.white) table.cell(tbl, 1, 2, str(bar_index), text_color=color.white) ``` -------------------------------- ### Get map keys Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/map.md Retrieves a list of all keys in the map as a copy. ```python key_list: list = map.keys(data) # ["price", "volume", "time"] ``` -------------------------------- ### Create and run a simple indicator Source: https://github.com/pynesys/pynecore/blob/main/README.md Demonstrates defining a basic moving average script and executing it via the CLI. ```python """ @pyne """ from pynecore.lib import script, close, plot @script.indicator("My First Indicator") def main(): # Calculate a simple moving average sma_value = (close + close[1] + close[2]) / 3 # Plot the result plot(sma_value, "Simple Moving Average") ``` ```bash # First, download some price data pyne data download ccxt --symbol "BYBIT:BTC/USDT:USDT" # Then run your script on the data pyne run my_script.py ccxt_BYBIT_BTC_USDT_USDT_1D.ohlcv ``` -------------------------------- ### Get map size Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/map.md Returns the total count of key-value pairs. ```python count: int = map.size(data) # 3 ``` -------------------------------- ### Array Size Operation Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/array.md Function to get the number of elements in an array. ```APIDOC ## `size(id)` ### Description Returns the number of elements in the array. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example `len: int = array.size(my_array) # 10` ### Response #### Success Response (200) - **Returns** (int) - Array size #### Response Example N/A ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/pynesys/pynecore/blob/main/docs/development/contributing.md Set up an isolated Python environment for PyneCore development. This prevents dependency conflicts with other projects. ```bash python -m venv venv # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate ``` -------------------------------- ### Optimize strategy parameters Source: https://github.com/pynesys/pynecore/blob/main/docs/programmatic/integration-patterns.md Use itertools.product to sweep through parameter combinations and evaluate performance based on P&L. ```python from itertools import product results = [] for length, confirm in product(range(5, 30, 5), range(1, 4)): runner = ScriptRunner( script_path=Path("sma_crossover.py"), ohlcv_iter=data, syminfo=syminfo, inputs={"Length": length, "Confirm bars": confirm}, ) trades = [] for _, _, new_trades in runner.run_iter(): trades.extend(new_trades) if trades: pnl = sum(t.profit for t in trades) results.append({"length": length, "confirm": confirm, "pnl": pnl, "trades": len(trades)}) # Find best combination best = max(results, key=lambda r: r["pnl"]) print(f"Best: Length={best['length']}, Confirm={best['confirm']} → P&L={best['pnl']:+.2f}") ``` -------------------------------- ### Get Exchange Timezone Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves the IANA timezone identifier for the exchange where the symbol is traded. ```python tz: str | NA[str] = syminfo.timezone # "America/New_York" ``` -------------------------------- ### GET /opentrades/max_drawdown Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_opentrades.md Retrieves the maximum unrealized loss during an open trade in account currency. ```APIDOC ## GET /opentrades/max_drawdown ### Description Returns the maximum unrealized loss during the open trade, expressed in the strategy's account currency. ### Parameters #### Path Parameters - **trade_num** (int) - Required - Trade number (zero-indexed) ### Response #### Success Response (200) - **float** - Maximum drawdown, or 0 if trade doesn't exist ### Request Example strategy.opentrades.max_drawdown(0) ``` -------------------------------- ### GET /opentrades/max_runup Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_opentrades.md Retrieves the maximum unrealized profit during an open trade in account currency. ```APIDOC ## GET /opentrades/max_runup ### Description Returns the maximum unrealized profit during the open trade, expressed in the strategy's account currency. ### Parameters #### Path Parameters - **trade_num** (int) - Required - Trade number (zero-indexed) ### Response #### Success Response (200) - **float** - Maximum runup, or 0 if trade doesn't exist ### Request Example strategy.opentrades.max_runup(0) ``` -------------------------------- ### Download EURUSD 1-Hour Data from Capital.com Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/data.md Downloads 1-hour OHLCV data for EURUSD from Capital.com for a specified date range. ```bash pyne data download capitalcom --symbol "EURUSD" --timeframe "60" --from "2023-01-01" --to "2023-12-31" ``` -------------------------------- ### Get Currency Rate Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/request.md Obtain the exchange rate between two currencies using `currency_rate()`. ```APIDOC ## POST /api/request/currency_rate ### Description Gets the exchange rate between two currencies at the current bar's timestamp. ### Method POST ### Endpoint /api/request/currency_rate ### Parameters #### Request Body - **from_currency** (str) - Required - Source currency code (e.g., "EUR", "GBP") - **to_currency** (str) - Required - Target currency code (e.g., "USD") ### Request Example ```json { "from_currency": "EUR", "to_currency": "USD" } ``` ### Response #### Success Response (200) - **rate** (float) - Exchange rate as float, or `na` if no data is available. #### Response Example ```json { "rate": 1.095 } ``` ``` -------------------------------- ### Continue Last Download Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/data.md Shows how to use the 'continue' keyword for the --from option to resume downloading from the last recorded point. ```bash --from "continue" ``` -------------------------------- ### Array Initialization and Manipulation Source: https://github.com/pynesys/pynecore/blob/main/docs/overview/differences.md Compares the functional Pine Script approach with PyneCore's array functions and the more Pythonic list manipulation for initializing, setting, and appending elements. ```python from pynecore.types.na import NA from pynecore.lib import array, na # (Note, type hints are optional here) a: list[float | NA[float]] = array.new_float(5) # Functional Pine Script way, `a` is just a python list b: list[float | NA[float]] = [na(float)] * 5 # Pythonic way, for the same result array.set(a, 0, 1.0) # Functional Pine Script way b[0] = 1.0 # Pythonic way for the same array.push(a, 2.0) # Functional Pine Script way b.append(2.0) # Pythonic way for the same ``` -------------------------------- ### line.get_y2() - Get the second Y coordinate Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/line.md Returns the price of the line's second point. ```APIDOC ## GET /api/lines/{id}/y2 ### Description Returns the price of the line's second point. ### Method GET ### Endpoint /api/lines/{id}/y2 ### Parameters #### Path Parameters - **id** (line.Line) - Required - The unique identifier of the line object. ### Response #### Success Response (200) - **y2** (float) - The price of the second point. #### Response Example ```json { "y2": 60.2 } ``` ``` -------------------------------- ### Implement a simple strategy Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy.md Use the @script.strategy decorator to initialize a strategy and manage entries and exits based on technical indicators. ```python from pynecore.lib import ( close, high, low, strategy, ta, bar_index, script ) from pynecore.types import Persistent @script.strategy(title="Simple Strategy", initial_capital=10000) def main(): sma20: Persistent[float] = ta.sma(close, 20) if bar_index == 20: strategy.entry("long", strategy.long, qty=1) if ta.crossunder(close, sma20): strategy.close("long", comment="Exit on cross below") # Check performance pnl: float = strategy.netprofit position: float = strategy.position_size ``` -------------------------------- ### line.get_y1() - Get the first Y coordinate Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/line.md Returns the price of the line's first point. ```APIDOC ## GET /api/lines/{id}/y1 ### Description Returns the price of the line's first point. ### Method GET ### Endpoint /api/lines/{id}/y1 ### Parameters #### Path Parameters - **id** (line.Line) - Required - The unique identifier of the line object. ### Response #### Success Response (200) - **y1** (float) - The price of the first point. #### Response Example ```json { "y1": 50.5 } ``` ``` -------------------------------- ### Download Data with Specific Date Range Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/data.md Demonstrates using ISO date formats for the --from and --to options to specify a precise date range for data download. ```bash --from "2023-01-01" --to "2023-12-31 23:59:59" ``` -------------------------------- ### Run script with date range Source: https://github.com/pynesys/pynecore/blob/main/docs/cli/run.md Limits the execution of a strategy to a specific start and end date. ```bash # Run a script for a specific date range pyne run my_strategy.py eurusd_data.ohlcv --from "2023-01-01" --to "2023-12-31" ``` -------------------------------- ### Get Symbol Description Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/syminfo.md Retrieves a descriptive text for the symbol, provided by the exchange or data source. ```python desc: str | NA[str] = syminfo.description # "Apple Inc." ``` -------------------------------- ### PyneCore Custom Functions Example Source: https://github.com/pynesys/pynecore/blob/main/docs/getting-started/first-script.md Demonstrates how to define and use custom functions within a PyneCore script for reusable logic. Supports both simple and more complex calculations. ```python """ @pyne """ from pynecore import Series from pynecore.lib import script, close, plot, color, math def average(a, b): return (a + b) / 2 def custom_ma(src, length): """A simple moving average implementation""" sum = 0.0 for i in range(length): sum += src[i] return sum / length @script.indicator("Custom Functions", overlay=True) def main(): # Use custom functions avg = average(close, close[1]) custom_average: Series[float] = custom_ma(close, 20) # Plot results plot(avg, "Bar Average", color=color.green) plot(custom_average, "Custom MA", color=color.purple) ``` -------------------------------- ### GET /opentrades/max_drawdown_percent Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_opentrades.md Retrieves the maximum unrealized loss during an open trade as a percentage of entry value. ```APIDOC ## GET /opentrades/max_drawdown_percent ### Description Returns the maximum unrealized loss during the open trade as a percentage of entry value. ### Parameters #### Path Parameters - **trade_num** (int) - Required - Trade number (zero-indexed) ### Response #### Success Response (200) - **float** - Maximum drawdown percentage, or 0 if trade doesn't exist ### Request Example strategy.opentrades.max_drawdown_percent(0) ``` -------------------------------- ### GET /opentrades/max_runup_percent Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_opentrades.md Retrieves the maximum unrealized profit during an open trade as a percentage of entry value. ```APIDOC ## GET /opentrades/max_runup_percent ### Description Returns the maximum unrealized profit during the open trade as a percentage of entry value. ### Parameters #### Path Parameters - **trade_num** (int) - Required - Trade number (zero-indexed) ### Response #### Success Response (200) - **float** - Maximum runup percentage, or 0 if trade doesn't exist ### Request Example strategy.opentrades.max_runup_percent(0) ``` -------------------------------- ### Accessing Closed Trade Information Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/strategy_closedtrades.md This example demonstrates how to access various details of a closed trade, such as entry and exit prices, profit, and profit percentage. Ensure a trade exists before accessing its properties. ```python from pynecore.lib import close, strategy, bar_index, script @script.strategy(title="Trade Analysis") def main(): # Entry logic if bar_index == 10: strategy.entry("buy", strategy.long, 1.0) # Exit logic if bar_index == 20: strategy.close("buy") # Access the first closed trade (if it exists) if strategy.closedtrades.size(0) != 0: entry_px: float = strategy.closedtrades.entry_price(0) # Entry price exit_px: float = strategy.closedtrades.exit_price(0) # Exit price profit: float = strategy.closedtrades.profit(0) # P/L in currency pct: float = strategy.closedtrades.profit_percent(0) # P/L as % ``` -------------------------------- ### Label Creation and Modification Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/label.md Demonstrates how to create a new label with initial properties and how to modify its text and color after creation. ```APIDOC ## Quick Example This example shows how to create a label at the current bar and then modify its text and color. ### Code ```python from pynecore.lib import ( close, high, low, bar_index, label, color, xloc, yloc ) from pynecore.types import Persistent @script.indicator(title="Label Example", overlay=True) def main(): # Create a label at current bar lbl: Persistent[label] = label.new( bar_index, high, text="Peak", color=color.red, style=label.style_label_up, textcolor=color.white ) # Modify label properties label.set_text(lbl, "New Text") label.set_color(lbl, color.blue) label.set_y(lbl, low) ``` ``` -------------------------------- ### Get Blue Color Component Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/color.md Retrieves the blue component (0-255) from a given color object. ```python blue_comp: int = color.b(color.aqua) # 212 ``` -------------------------------- ### Get Green Color Component Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/color.md Retrieves the green component (0-255) from a given color object. ```python green_comp: int = color.g(color.lime) # 230 ``` -------------------------------- ### Python Script Runner Setup for Security Data Source: https://github.com/pynesys/pynecore/blob/main/docs/lib/request-data.md Demonstrates how to configure `ScriptRunner` to include external security data, such as currency pairs, by mapping arbitrary keys to OHLCV data paths. The currency pair is detected from the TOML metadata. ```python from pathlib import Path from pynecore.core.script_runner import ScriptRunner from pynecore.core.ohlcv_file import OHLCVReader from pynecore.core.syminfo import SymInfo syminfo = SymInfo.load_toml("workdir/data/BTCUSDT_4h.toml") reader = OHLCVReader("workdir/data/BTCUSDT_4h") reader.open() runner = ScriptRunner( script_path=Path("workdir/scripts/portfolio.py"), ohlcv_iter=reader, syminfo=syminfo, security_data={ # Key names are arbitrary — currency pairs are detected from TOML "eurusd": "workdir/data/capitalcom_EURUSD_1D", "btcusd": "workdir/data/ccxt_BINANCE_BTC_USDT_1D", }, ) ``` -------------------------------- ### Calculate Array Statistics Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/array.md Demonstrates creating a float array, populating it with close prices, and calculating basic statistics. ```python from pynecore.lib import ( close, array, script ) @script.indicator(title="Array Statistics", overlay=False) def main(): # Create and populate an array of closes closes: list[float] = array.new_float() array.push(closes, close) if array.size(closes) > 20: avg: float = array.avg(closes) max_val: float = array.max(closes) min_val: float = array.min(closes) ``` -------------------------------- ### Get Red Color Component Source: https://github.com/pynesys/pynecore/blob/main/docs/reference/lib/color.md Retrieves the red component (0-255) from a given color object. ```python red_comp: int = color.r(color.blue) # 41 ```