2025-05-28 22:37:53 +08:00

782 lines
20 KiB
Markdown

# API Reference
This document provides a comprehensive API reference for the IncrementalTrader framework.
## Module Structure
```
IncrementalTrader/
├── strategies/ # Trading strategies and base classes
│ ├── base.py # Base strategy framework
│ ├── metatrend.py # MetaTrend strategy
│ ├── bbrs.py # BBRS strategy
│ ├── random.py # Random strategy
│ └── indicators/ # Technical indicators
├── trader/ # Trade execution
│ ├── trader.py # Main trader implementation
│ └── position.py # Position management
├── backtester/ # Backtesting framework
│ ├── backtester.py # Main backtesting engine
│ ├── config.py # Configuration classes
│ └── utils.py # Utilities and helpers
└── utils/ # General utilities
```
## Core Classes
### IncStrategySignal
Signal class for strategy outputs.
```python
class IncStrategySignal:
def __init__(self, signal_type: str, confidence: float = 1.0, metadata: dict = None)
```
**Parameters:**
- `signal_type` (str): Signal type ('BUY', 'SELL', 'HOLD')
- `confidence` (float): Signal confidence (0.0 to 1.0)
- `metadata` (dict): Additional signal information
**Factory Methods:**
```python
@classmethod
def BUY(cls, confidence: float = 1.0, metadata: dict = None) -> 'IncStrategySignal'
@classmethod
def SELL(cls, confidence: float = 1.0, metadata: dict = None) -> 'IncStrategySignal'
@classmethod
def HOLD(cls, metadata: dict = None) -> 'IncStrategySignal'
```
**Properties:**
- `signal_type` (str): The signal type
- `confidence` (float): Signal confidence level
- `metadata` (dict): Additional metadata
- `timestamp` (int): Signal generation timestamp
**Example:**
```python
# Create signals using factory methods
buy_signal = IncStrategySignal.BUY(confidence=0.8, metadata={'reason': 'golden_cross'})
sell_signal = IncStrategySignal.SELL(confidence=0.9)
hold_signal = IncStrategySignal.HOLD()
```
### TimeframeAggregator
Aggregates data points to different timeframes.
```python
class TimeframeAggregator:
def __init__(self, timeframe: str)
```
**Parameters:**
- `timeframe` (str): Target timeframe ('1min', '5min', '15min', '30min', '1h', '4h', '1d')
**Methods:**
```python
def add_data_point(self, timestamp: int, ohlcv: tuple) -> tuple | None
"""Add data point and return aggregated OHLCV if timeframe complete."""
def get_current_aggregated(self) -> tuple | None
"""Get current aggregated data without completing timeframe."""
def reset(self) -> None
"""Reset aggregator state."""
```
**Example:**
```python
aggregator = TimeframeAggregator("15min")
for timestamp, ohlcv in data_stream:
aggregated = aggregator.add_data_point(timestamp, ohlcv)
if aggregated:
timestamp_agg, ohlcv_agg = aggregated
# Process aggregated data
```
### IncStrategyBase
Base class for all trading strategies.
```python
class IncStrategyBase:
def __init__(self, name: str, params: dict = None)
```
**Parameters:**
- `name` (str): Strategy name
- `params` (dict): Strategy parameters
**Abstract Methods:**
```python
def _process_aggregated_data(self, timestamp: int, ohlcv: tuple) -> IncStrategySignal
"""Process aggregated data and return signal. Must be implemented by subclasses."""
```
**Public Methods:**
```python
def process_data_point(self, timestamp: int, ohlcv: tuple) -> IncStrategySignal
"""Process raw data point and return signal."""
def get_current_signal(self) -> IncStrategySignal
"""Get the most recent signal."""
def get_performance_metrics(self) -> dict
"""Get strategy performance metrics."""
def reset(self) -> None
"""Reset strategy state."""
```
**Properties:**
- `name` (str): Strategy name
- `params` (dict): Strategy parameters
- `logger` (Logger): Strategy logger
- `signal_history` (list): History of generated signals
**Example:**
```python
class MyStrategy(IncStrategyBase):
def __init__(self, name: str, params: dict = None):
super().__init__(name, params)
self.sma = MovingAverageState(period=20)
def _process_aggregated_data(self, timestamp: int, ohlcv: tuple) -> IncStrategySignal:
_, _, _, close, _ = ohlcv
self.sma.update(close)
if self.sma.is_ready():
return IncStrategySignal.BUY() if close > self.sma.get_value() else IncStrategySignal.SELL()
return IncStrategySignal.HOLD()
```
## Strategy Classes
### MetaTrendStrategy
Multi-Supertrend trend-following strategy.
```python
class MetaTrendStrategy(IncStrategyBase):
def __init__(self, name: str, params: dict = None)
```
**Default Parameters:**
```python
{
"timeframe": "15min",
"supertrend_periods": [10, 20, 30],
"supertrend_multipliers": [2.0, 3.0, 4.0],
"min_trend_agreement": 0.6
}
```
**Methods:**
- Inherits all methods from `IncStrategyBase`
- Uses `SupertrendCollection` for meta-trend analysis
**Example:**
```python
strategy = MetaTrendStrategy("metatrend", {
"timeframe": "15min",
"supertrend_periods": [10, 20, 30],
"min_trend_agreement": 0.7
})
```
### BBRSStrategy
Bollinger Bands + RSI strategy with market regime detection.
```python
class BBRSStrategy(IncStrategyBase):
def __init__(self, name: str, params: dict = None)
```
**Default Parameters:**
```python
{
"timeframe": "15min",
"bb_period": 20,
"bb_std": 2.0,
"rsi_period": 14,
"rsi_overbought": 70,
"rsi_oversold": 30,
"volume_ma_period": 20,
"volume_spike_threshold": 1.5
}
```
**Methods:**
- Inherits all methods from `IncStrategyBase`
- Implements market regime detection
- Uses volume analysis for signal confirmation
**Example:**
```python
strategy = BBRSStrategy("bbrs", {
"timeframe": "15min",
"bb_period": 20,
"rsi_period": 14
})
```
### RandomStrategy
Random signal generation for testing.
```python
class RandomStrategy(IncStrategyBase):
def __init__(self, name: str, params: dict = None)
```
**Default Parameters:**
```python
{
"timeframe": "15min",
"buy_probability": 0.1,
"sell_probability": 0.1,
"seed": None
}
```
**Example:**
```python
strategy = RandomStrategy("random", {
"buy_probability": 0.05,
"sell_probability": 0.05,
"seed": 42
})
```
## Indicator Classes
### Base Indicator Classes
#### IndicatorState
```python
class IndicatorState:
def __init__(self, period: int)
def update(self, value: float) -> None
def get_value(self) -> float
def is_ready(self) -> bool
def reset(self) -> None
```
#### SimpleIndicatorState
```python
class SimpleIndicatorState(IndicatorState):
def __init__(self)
```
#### OHLCIndicatorState
```python
class OHLCIndicatorState(IndicatorState):
def __init__(self, period: int)
def update_ohlc(self, high: float, low: float, close: float) -> None
```
### Moving Average Indicators
#### MovingAverageState
```python
class MovingAverageState(IndicatorState):
def __init__(self, period: int)
def update(self, value: float) -> None
def get_value(self) -> float
def is_ready(self) -> bool
```
#### ExponentialMovingAverageState
```python
class ExponentialMovingAverageState(IndicatorState):
def __init__(self, period: int, alpha: float = None)
def update(self, value: float) -> None
def get_value(self) -> float
def is_ready(self) -> bool
```
### Volatility Indicators
#### ATRState
```python
class ATRState(OHLCIndicatorState):
def __init__(self, period: int)
def update_ohlc(self, high: float, low: float, close: float) -> None
def get_value(self) -> float
def get_true_range(self) -> float
def is_ready(self) -> bool
```
#### SimpleATRState
```python
class SimpleATRState(IndicatorState):
def __init__(self, period: int)
def update_range(self, high: float, low: float) -> None
def get_value(self) -> float
def is_ready(self) -> bool
```
### Trend Indicators
#### SupertrendState
```python
class SupertrendState(OHLCIndicatorState):
def __init__(self, period: int, multiplier: float)
def update_ohlc(self, high: float, low: float, close: float) -> None
def get_value(self) -> float
def get_signal(self) -> str
def is_uptrend(self) -> bool
def get_upper_band(self) -> float
def get_lower_band(self) -> float
def is_ready(self) -> bool
```
#### SupertrendCollection
```python
class SupertrendCollection:
def __init__(self, periods: list, multipliers: list)
def update_ohlc(self, high: float, low: float, close: float) -> None
def get_signals(self) -> list
def get_meta_signal(self, min_agreement: float = 0.6) -> str
def get_agreement_ratio(self) -> float
def is_ready(self) -> bool
```
### Oscillator Indicators
#### RSIState
```python
class RSIState(IndicatorState):
def __init__(self, period: int)
def update(self, price: float) -> None
def get_value(self) -> float
def is_overbought(self, threshold: float = 70) -> bool
def is_oversold(self, threshold: float = 30) -> bool
def is_ready(self) -> bool
```
#### SimpleRSIState
```python
class SimpleRSIState(IndicatorState):
def __init__(self, period: int)
def update(self, price: float) -> None
def get_value(self) -> float
def is_ready(self) -> bool
```
### Bollinger Bands
#### BollingerBandsState
```python
class BollingerBandsState(IndicatorState):
def __init__(self, period: int, std_dev: float = 2.0)
def update(self, price: float) -> None
def get_bands(self) -> tuple # (upper, middle, lower)
def get_upper_band(self) -> float
def get_middle_band(self) -> float
def get_lower_band(self) -> float
def get_bandwidth(self) -> float
def get_percent_b(self, price: float) -> float
def is_squeeze(self, threshold: float = 0.1) -> bool
def is_ready(self) -> bool
```
#### BollingerBandsOHLCState
```python
class BollingerBandsOHLCState(OHLCIndicatorState):
def __init__(self, period: int, std_dev: float = 2.0)
def update_ohlc(self, high: float, low: float, close: float) -> None
def get_bands(self) -> tuple # (upper, middle, lower)
# ... same methods as BollingerBandsState
```
## Trading Classes
### IncTrader
Main trader class for executing strategies.
```python
class IncTrader:
def __init__(self, strategy: IncStrategyBase, initial_usd: float = 10000,
stop_loss_pct: float = None, take_profit_pct: float = None,
fee_pct: float = 0.001, slippage_pct: float = 0.0005)
```
**Parameters:**
- `strategy` (IncStrategyBase): Trading strategy instance
- `initial_usd` (float): Starting capital
- `stop_loss_pct` (float): Stop loss percentage
- `take_profit_pct` (float): Take profit percentage
- `fee_pct` (float): Trading fee percentage
- `slippage_pct` (float): Slippage percentage
**Methods:**
```python
def process_data_point(self, timestamp: int, ohlcv: tuple) -> None
"""Process new data point and execute trades."""
def get_results(self) -> dict
"""Get comprehensive trading results."""
def get_portfolio_value(self, current_price: float) -> float
"""Get current portfolio value."""
def get_position_info(self) -> dict
"""Get current position information."""
def reset(self) -> None
"""Reset trader state."""
```
**Example:**
```python
trader = IncTrader(
strategy=MetaTrendStrategy("metatrend"),
initial_usd=10000,
stop_loss_pct=0.03,
take_profit_pct=0.06
)
for timestamp, ohlcv in data_stream:
trader.process_data_point(timestamp, ohlcv)
results = trader.get_results()
```
### PositionManager
Manages trading positions and portfolio state.
```python
class PositionManager:
def __init__(self, initial_usd: float)
```
**Methods:**
```python
def execute_buy(self, price: float, timestamp: int, fee_pct: float = 0.001,
slippage_pct: float = 0.0005) -> TradeRecord | None
def execute_sell(self, price: float, timestamp: int, fee_pct: float = 0.001,
slippage_pct: float = 0.0005) -> TradeRecord | None
def get_portfolio_value(self, current_price: float) -> float
def get_position_info(self) -> dict
def reset(self) -> None
```
**Properties:**
- `usd_balance` (float): Current USD balance
- `coin_balance` (float): Current coin balance
- `position_type` (str): Current position ('LONG', 'SHORT', 'NONE')
- `entry_price` (float): Position entry price
- `entry_timestamp` (int): Position entry timestamp
### TradeRecord
Record of individual trades.
```python
class TradeRecord:
def __init__(self, side: str, price: float, quantity: float, timestamp: int,
fee: float = 0.0, slippage: float = 0.0, pnl: float = 0.0)
```
**Properties:**
- `side` (str): Trade side ('BUY', 'SELL')
- `price` (float): Execution price
- `quantity` (float): Trade quantity
- `timestamp` (int): Execution timestamp
- `fee` (float): Trading fee paid
- `slippage` (float): Slippage cost
- `pnl` (float): Profit/loss for the trade
## Backtesting Classes
### IncBacktester
Main backtesting engine.
```python
class IncBacktester:
def __init__(self)
```
**Methods:**
```python
def run_single_strategy(self, strategy_class: type, strategy_params: dict,
config: BacktestConfig, data_file: str) -> dict
"""Run backtest for single strategy."""
def optimize_strategy(self, strategy_class: type, optimization_config: OptimizationConfig,
data_file: str) -> dict
"""Optimize strategy parameters."""
```
**Example:**
```python
backtester = IncBacktester()
results = backtester.run_single_strategy(
strategy_class=MetaTrendStrategy,
strategy_params={"timeframe": "15min"},
config=BacktestConfig(initial_usd=10000),
data_file="data.csv"
)
```
### BacktestConfig
Configuration for backtesting.
```python
class BacktestConfig:
def __init__(self, initial_usd: float = 10000, stop_loss_pct: float = None,
take_profit_pct: float = None, start_date: str = None,
end_date: str = None, fee_pct: float = 0.001,
slippage_pct: float = 0.0005, output_dir: str = "backtest_results",
save_trades: bool = True, save_portfolio_history: bool = True,
risk_free_rate: float = 0.02)
```
**Properties:**
- `initial_usd` (float): Starting capital
- `stop_loss_pct` (float): Stop loss percentage
- `take_profit_pct` (float): Take profit percentage
- `start_date` (str): Start date (YYYY-MM-DD)
- `end_date` (str): End date (YYYY-MM-DD)
- `fee_pct` (float): Trading fee percentage
- `slippage_pct` (float): Slippage percentage
- `output_dir` (str): Output directory
- `save_trades` (bool): Save trade records
- `save_portfolio_history` (bool): Save portfolio history
- `risk_free_rate` (float): Risk-free rate for Sharpe ratio
### OptimizationConfig
Configuration for parameter optimization.
```python
class OptimizationConfig:
def __init__(self, base_config: BacktestConfig, param_ranges: dict,
max_workers: int = None, optimization_metric: str | callable = "sharpe_ratio",
save_all_results: bool = False)
```
**Properties:**
- `base_config` (BacktestConfig): Base configuration
- `param_ranges` (dict): Parameter ranges to test
- `max_workers` (int): Number of parallel workers
- `optimization_metric` (str | callable): Metric to optimize
- `save_all_results` (bool): Save all parameter combinations
## Utility Classes
### DataLoader
Loads and validates trading data.
```python
class DataLoader:
@staticmethod
def load_data(file_path: str, start_date: str = None, end_date: str = None) -> pd.DataFrame
"""Load and validate OHLCV data from CSV file."""
@staticmethod
def validate_data(data: pd.DataFrame) -> bool
"""Validate data format and consistency."""
```
### SystemUtils
System resource management utilities.
```python
class SystemUtils:
@staticmethod
def get_optimal_workers() -> int
"""Get optimal number of worker processes."""
@staticmethod
def get_memory_usage() -> dict
"""Get current memory usage statistics."""
```
### ResultsSaver
Save backtesting results to files.
```python
class ResultsSaver:
@staticmethod
def save_results(results: dict, output_dir: str) -> None
"""Save complete results to directory."""
@staticmethod
def save_performance_metrics(metrics: dict, file_path: str) -> None
"""Save performance metrics to JSON file."""
@staticmethod
def save_trades(trades: list, file_path: str) -> None
"""Save trade records to CSV file."""
@staticmethod
def save_portfolio_history(history: list, file_path: str) -> None
"""Save portfolio history to CSV file."""
```
### MarketFees
Trading fee calculation utilities.
```python
class MarketFees:
@staticmethod
def calculate_fee(trade_value: float, fee_pct: float) -> float
"""Calculate trading fee."""
@staticmethod
def calculate_slippage(trade_value: float, slippage_pct: float) -> float
"""Calculate slippage cost."""
@staticmethod
def get_binance_fees() -> dict
"""Get Binance fee structure."""
@staticmethod
def get_coinbase_fees() -> dict
"""Get Coinbase fee structure."""
```
## Performance Metrics
The framework calculates comprehensive performance metrics:
```python
performance_metrics = {
# Return metrics
'total_return_pct': float, # Total portfolio return percentage
'annualized_return_pct': float, # Annualized return percentage
'final_portfolio_value': float, # Final portfolio value
# Risk metrics
'volatility_pct': float, # Annualized volatility
'max_drawdown_pct': float, # Maximum drawdown percentage
'sharpe_ratio': float, # Sharpe ratio
'sortino_ratio': float, # Sortino ratio
'calmar_ratio': float, # Calmar ratio
# Trading metrics
'total_trades': int, # Total number of trades
'win_rate': float, # Percentage of winning trades
'profit_factor': float, # Gross profit / gross loss
'avg_trade_pct': float, # Average trade return percentage
'avg_win_pct': float, # Average winning trade percentage
'avg_loss_pct': float, # Average losing trade percentage
# Time metrics
'total_days': int, # Total trading days
'trades_per_day': float, # Average trades per day
# Additional metrics
'var_95': float, # Value at Risk (95%)
'es_95': float, # Expected Shortfall (95%)
'beta': float, # Beta vs benchmark
'alpha': float # Alpha vs benchmark
}
```
## Error Handling
The framework uses custom exceptions for better error handling:
```python
class IncrementalTraderError(Exception):
"""Base exception for IncrementalTrader."""
class StrategyError(IncrementalTraderError):
"""Strategy-related errors."""
class IndicatorError(IncrementalTraderError):
"""Indicator-related errors."""
class BacktestError(IncrementalTraderError):
"""Backtesting-related errors."""
class DataError(IncrementalTraderError):
"""Data-related errors."""
```
## Logging
The framework provides comprehensive logging:
```python
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Strategy logging
strategy = MetaTrendStrategy("metatrend")
strategy.logger.info("Strategy initialized")
# Trader logging
trader = IncTrader(strategy)
trader.logger.info("Trader initialized")
```
## Type Hints
The framework uses comprehensive type hints:
```python
from typing import Dict, List, Tuple, Optional, Union, Callable
from abc import ABC, abstractmethod
# Example type hints used throughout the framework
def process_data_point(self, timestamp: int, ohlcv: Tuple[float, float, float, float, float]) -> IncStrategySignal:
pass
def get_results(self) -> Dict[str, Union[float, int, List, Dict]]:
pass
```
This API reference provides comprehensive documentation for all public classes, methods, and functions in the IncrementalTrader framework. For detailed usage examples, see the other documentation files.