Files
crypto_trader/docs/developer/coding_standards.md

4.1 KiB

Coding Standards

This document outlines the coding standards and conventions for Crypto Trader.

Code Style

Python Style Guide

Follow PEP 8 with the following additions:

  • Line Length: Maximum 100 characters
  • Indentation: 4 spaces (no tabs)
  • Imports: Grouped and sorted (stdlib, third-party, local)
  • Naming:
    • Classes: PascalCase
    • Functions/Variables: snake_case
    • Constants: UPPER_SNAKE_CASE
    • Private: _leading_underscore

Code Formatting

Use black for automatic formatting:

black src/ tests/

Type Hints

Always use type hints for function signatures:

def calculate_position_size(
    capital: float,
    risk_percentage: float
) -> float:
    """Calculate position size."""
    return capital * risk_percentage

Docstrings

Use Google-style docstrings:

def fetch_balance(self) -> Dict[str, Any]:
    """Fetches the account balance.
    
    Args:
        None
        
    Returns:
        Dictionary containing balance information with keys:
        - 'free': Available balance
        - 'used': Used balance
        - 'total': Total balance
        
    Raises:
        ConnectionError: If exchange connection fails
        ValueError: If exchange credentials are invalid
    """
    pass

File Organization

Module Structure

"""Module docstring describing the module."""

# Standard library imports
import os
from typing import Dict, List

# Third-party imports
import pandas as pd
from sqlalchemy import Column

# Local imports
from ..core.logger import get_logger
from .base import BaseClass

# Constants
DEFAULT_VALUE = 100

# Module-level variables
logger = get_logger(__name__)

# Classes
class MyClass:
    """Class docstring."""
    pass

# Functions
def my_function():
    """Function docstring."""
    pass

Error Handling

Exception Handling

try:
    result = risky_operation()
except SpecificError as e:
    logger.error(f"Operation failed: {e}")
    raise
except Exception as e:
    logger.exception("Unexpected error")
    raise RuntimeError("Operation failed") from e

Logging

Use appropriate log levels:

  • DEBUG: Detailed information for debugging
  • INFO: General informational messages
  • WARNING: Warning messages
  • ERROR: Error messages
  • CRITICAL: Critical errors
logger.debug("Detailed debug information")
logger.info("Operation completed successfully")
logger.warning("Deprecated function used")
logger.error("Operation failed")
logger.critical("System failure")

Testing Standards

Test Naming

def test_function_name_should_do_something():
    """Test description."""
    pass

class TestClassName:
    """Test class description."""
    
    def test_method_should_handle_case(self):
        """Test method description."""
        pass

Test Organization

  • One test class per module
  • Test methods should be independent
  • Use fixtures for common setup
  • Mock external dependencies

Documentation Standards

Inline Comments

# Calculate position size using Kelly Criterion
# Formula: f = (bp - q) / b
fraction = (payout_ratio * win_prob - loss_prob) / payout_ratio

Function Documentation

Always document:

  • Purpose
  • Parameters
  • Return values
  • Exceptions
  • Examples (when helpful)

Git Commit Messages

Follow conventional commits:

type(scope): subject

body

footer

Types:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation
  • test: Tests
  • refactor: Code refactoring
  • chore: Maintenance

Example:

feat(trading): add trailing stop order support

Implemented trailing stop orders with configurable
trail percentage and activation price.

Closes #123

Code Review Guidelines

What to Review

  • Code correctness
  • Test coverage
  • Documentation
  • Performance
  • Security
  • Style compliance

Review Checklist

  • Code follows style guide
  • Tests are included
  • Documentation is updated
  • No security issues
  • Performance is acceptable
  • Error handling is appropriate