Contributing
Set up a PyneCore development environment and prepare contributions. Read the project requirements and workflow for changing code and checking your implementation.
Introduction
Thank you for your interest in contributing to PyneCore! This document provides guidance for developers who want to contribute to this open-source project that brings TradingView Pine Script compatibility to Python.
PyneCore is designed with a focus on high performance, minimal external dependencies, and an intuitive Pine Script-like development experience in Python. We welcome contributions that enhance this vision.
Setting Up Your Development Environment
Prerequisites
- Python Version: 3.11 or newer (as specified in the project’s requirements)
- Git: For version control
- Virtual Environment: To isolate dependencies
Setup Steps
Clone the repository:
git clone https://github.com/PyneSys/pynecore.git cd pynecoreCreate and activate a virtual environment:
python -m venv venv # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activateInstall development dependencies:
# For development, install all dependencies including development tools pip install -e ".[all,dev]"Verify your setup:
# Run the test suite to ensure everything is working python -m pytestpytest.iniadds-x(stop at the first failure) and deselectslive-marked tests; run those with-m live.
Project Structure
PyneCore is organized as follows:
pynecore/
├── src/ # Source code
│ └── pynecore/ # Main package
│ ├── core/ # Core functionality and runtime components
│ │ ├── broker/ # Broker plugin runtime support
│ │ └── plugin/ # Plugin base classes, discovery and loading
│ ├── lib/ # Pine Script v6 function library
│ ├── transformers/ # AST transformers that give Pyne code its Pine Script semantics
│ ├── types/ # Type definitions and interfaces
│ ├── utils/ # Utility functions and helpers
│ ├── cli/ # Command-line interface
│ ├── providers/ # Built-in data providers
│ ├── pynesys/ # PyneSys API client (PyneComp compilation)
│ └── testing/ # Offline broker conformance testing (broker_lab)
├── tests/ # Test suite
├── broker_lab/ # Broker lab suites
├── docs/ # Component-specific documentation
└── scripts/ # Utility scriptsUnderstanding this structure is essential for effective contribution.
Development Guidelines
Code Style
PyneCore follows these coding standards:
- PEP 8 compliance: Try to keep line length around 100 characters, with a hard limit of 120 characters
- Type hints: Use for all function arguments and return values
- Docstrings: Use PyCharm’s default “Sphinx-style” reStructuredText format (
:param:,:return:, etc.) for docstrings - Naming conventions:
- Functions and variables:
snake_case - Classes:
PascalCase - Constants:
UPPER_CASE
- Functions and variables:
- Comments: Add explanatory comments for complex logic
Example Code Style
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")
return ta.sma(values, length)Clean Code Principles
- Single Responsibility: Functions and classes should do one thing well
- DRY (Don’t Repeat Yourself): Avoid code duplication
- KISS (Keep It Simple): Prefer simple solutions over complex ones
- Early Returns: Return early to reduce nesting and improve readability
Testing
PyneCore uses a comprehensive testing system where tests themselves are often Pyne code. This “dogfooding” approach ensures tests run in the same environment as real user code.
Running Tests
# Run the entire test suite
python -m pytest
# Run specific test files
python -m pytest tests/path/to/test_file.py
# Run tests with coverage report (requires `pip install pytest-cov`)
python -m pytest --cov=pynecoreWriting Tests
Tests in PyneCore follow a unique pattern where test files are also valid Pyne code. Test functions must be named
__test_<name>__: pytest is configured with python_functions = __test_*__, so plain test_* functions are not
collected. Test files are test_NNN_<topic>.py inside numbered category folders (e.g. tests/t01_lib/t20_ta/), with
reference data in a data/ subfolder. Helper functions used only by tests are named __test_helper_<name>.
"""
@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")
def __test_my_feature__(csv_reader, runner, dict_comparator, log):
""" Test Description """
with csv_reader('test_data.csv', subdir="data") as cr:
for i, (candle, plot) in enumerate(runner(cr).run_iter()):
dict_comparator(plot, candle.extra_fields)
if i > 100:
breakFor more details, refer to the Testing System Documentation.
Working with Core Components
AST Transformers
When modifying AST transformers in pynecore/transformers/:
- Understand the transformation pipeline and execution order
- Test with various edge cases
- Ensure backward compatibility
- Add comprehensive tests
Library Functions
When working with library functions in pynecore/lib/:
Match Pine Script behavior when possible (for compatibility)
Document any differences from Pine Script
Optimize for performance
Add appropriate type hints
Include examples in docstrings
Decide the call-site route of every new or renamed function a script can call, in the same change. A stateless function of a plain module (no per-call-site state, no
@overload, no__pyne_layout__, calls nothing stateful such asta.*orPersistent/Seriescode) goes intoNON_TRANSFORMABLE_FUNCTIONSintransformers/function_isolation.py; otherwise leave it out and say why in a comment next to the function. A missing entry is not an error, but every call site then pays for the state-binding machinery. Read the function body before adding it: a wrong entry silently drops state the function relies on.Regenerate the lib registry whenever you add, rename or remove a function, change whether a builtin keeps state, or touch an
@overloadgroup, a@module_property, a__pyne_shared_call_site__marker or a module’s__all__:python scripts/lib_type_collector.pyCommit the regenerated
transformers/lib_types.jsonwith the change.tests/t00_pynecore/ast/test_104_lib_types_registry.pyfails until it matches; without the regeneration, cached and freshly transformed scripts keep the old route.
See Function Isolation — Where the classification comes from for the details behind both steps.
Core Runtime
When modifying core runtime components in pynecore/core/:
- Be extra cautious - these changes affect all Pyne code
- Consider backward compatibility
- Document performance implications
- Add thorough tests
Documentation
All code should be well-documented:
- Every function should have a reStructuredText format docstring
- Complex code should have inline comments
- Major features should have documentation files
Docstring Format Example
def function_name(param1: type, param2: type) -> return_type:
"""
Brief description of the function.
Detailed description of the function, if needed.
:param param1: Description of param1
:param param2: Description of param2
:return: Description of return value
:raises ExceptionType: When and why this exception is raised
"""
# Function implementationThis is the PyCharm’s default Sphinx-style docstring format, not the full reStructuredText syntax used for comprehensive documentation.
Cross-References in Docstrings
PyCharm resolves every :class:, :meth:, :attr:, :data:, :mod: and :func: role in a
docstring, and reports a target it cannot find as an “Unresolved reference” warning. These roles
give Ctrl+click navigation and let rename-refactoring update the docstring too. Keep them
warning-free, so that a warning always means a stale reference (a renamed or deleted name).
Use the form that resolves:
- Class member (method, property, class attribute, or instance attribute set in
__init__):~Class.member, for example:attr:`~OrderSyncEngine._order_mapping`or:meth:`~BrokerPlugin.get_position`. A bare:attr:`_order_mapping`does not resolve for an instance attribute, and a full dotted path to a member is unreliable. The class does not need to be imported. - Class, function or constant that the module does not import: the full dotted path with
~, for example:class:`~pynecore.core.broker.exceptions.UnexpectedCancelError`. - Module: the full dotted path, for example
:mod:`~pynecore.core.broker.sync_engine`. - Method referenced from a module docstring: prefix it with its class, for example
:meth:`OrderSyncEngine.on_order_event`. - Nested function (defined inside another function): it cannot be referenced; write it as a
``literal``instead.
Do not add an import only to make a docstring reference resolve: PyCharm and type checkers report it as an unused import.
Contribution Workflow
Select or create an issue: Start by finding an existing issue to work on or create a new one
Create a branch:
git checkout -b feature/your-feature-nameMake your changes: Follow the coding standards and guidelines
Add tests: Ensure your changes are properly tested
Run tests locally:
python -m pytestCommit your changes:
git commit -m "Description of changes"Push your branch:
git push origin feature/your-feature-nameCreate a pull request: Provide a clear description of your changes
Pull Request Guidelines
When submitting a pull request, please:
- Reference issues: Link to any related issues
- Describe changes: Provide a clear description of what you’ve changed
- Document impact: Note any performance, compatibility, or API impacts
- Include tests: Add appropriate tests for your changes
- Update documentation: If applicable
License
By contributing to PyneCore, you agree that your contributions will be licensed under the project’s Apache License 2.0.
Additional Resources
- Project Structure
- Testing System Overview
- AST Module Documentation
- PyneCore Reference - Complete function and type reference
- TradingView Pine Script Documentation - The original Pine Script language documentation
Getting Help
If you have questions or need assistance, you can:
- Open an issue on GitHub
- Reach out to the maintainers
Thank you for contributing to PyneCore!