Turtle Trading Implementation
Relevant source files
The following files were used as context for generating this wiki page:
The Turtle Trading Implementation within this project refers to a modular, agentic framework designed for building and backtesting systematic trading strategies. The system leverages the backtrader engine to process market data and execute structured trade decisions such as "buy to open" or "sell to close". It focuses on decision explainability, position sizing, and risk management through technical indicators like Moving Averages, RSI, and ATR.
The implementation is part of an ongoing effort to slim down the original backtrader codebase, improving performance and modernizing syntax while maintaining core functionalities like live data feeds, multi-timeframe support, and comprehensive broker simulation.
Sources: README.md, PLAN.md:1-12, PLANNING.md:1-10
System Architecture
The architecture follows an agentic approach where modular components observe market data and reason over it to generate trade signals. The high-level data flow involves fetching historical or live data through specialized feeds (e.g., CSV, PostgreSQL, or Interactive Brokers), processing these via Cerebro, and applying strategy logic.
Core Components
| Component | Description |
|---|---|
| Agents | Specialized strategies (Long, Short, Breakout) that reason over market ticks. |
| Cerebro | The central engine that manages data feeds, strategies, brokers, and analyzers. |
| Data Feeds | Adapters for various sources including BacktraderCSVData, PandasData, and IBCSVData. |
| Analyzers | Tools for calculating performance metrics like Sharpe Ratio, Drawdown, and P&L. |
| Broker | Simulation layer that handles order execution, commissions, and slippage. |
Sources: PLAN.md:15-25, backtrader/feeds/btcsv.py:32-110, strategies/moving_average_crossover.py:348-360
Logic and Execution Flow
The system processes data sequentially through a strategy lifecycle. The next() method serves as the entry point for bar-by-bar logic, where indicators are evaluated to trigger entry or exit signals.
The diagram shows the standard flow from data ingestion to order execution and logging within the strategy lifecycle.
Sources: strategies/moving_average_crossover.py:270-330, strategies/rsi_divergence.py:460-580
Strategy Implementation Patterns
The "Turtle" philosophy of systematic, rule-based trading is evidenced across several strategy implementations within the repository. Key elements include trend identification, volatility-based sizing, and multi-step exit strategies.
Trend and Momentum Identification
Strategies use technical indicators to confirm market conditions before entry. For example, the MovingAverageCrossStrategy uses short-term and long-term MAs to identify "Golden Cross" or "Death Cross" events. The RSIDivergenceStrategy looks for momentum shifts where price and RSI diverge in overbought or oversold territories.
Sources: strategies/moving_average_crossover.py:43-65, strategies/rsi_divergence.py:43-55
Risk Management and Position Sizing
A critical part of the implementation is the dynamic calculation of position sizes based on portfolio risk. Strategies typically risk a fixed percentage (e.g., 1%) of total equity per trade, adjusted for volatility using the Average True Range (ATR).
# Example of dynamic position sizing logic
risk_amount = self.broker.getvalue() * (self.p.risk_percent / 100)
risk_per_share = abs(entry_price - stop_price)
size = int(risk_amount / risk_per_share)
Sources: strategies/rsi_divergence.py:410-445, strategies/fibonacci_retracement_pullback.py:263-280
Exit Strategies
The implementation supports multiple exit mechanisms:
- Stop Loss: Absolute price levels to limit downside, often ATR-based.
- Trailing Stop: Dynamic stops that "lock in" profits as price moves favorably.
- Technical Exits: Exits based on indicator thresholds, such as RSI reaching overbought/oversold levels.
Sources: strategies/cup_and_handle.py:284-315, strategies/rsi_divergence.py:370-405
Data Management
The system utilizes various data feed classes to handle different formats and sources. This includes standard CSV parsing and complex Interactive Brokers (IB) data integration.
Data Feed Classes
| Class | Purpose | Key Features |
|---|---|---|
BacktraderCSVData | Standard file parsing | Handles YYYY-MM-DD formats for testing. |
IBCSVData | IB specific data | Includes security types, exchanges, and contract details. |
StockPriceData | Database-backed data | Extends PandasData to pull from PostgreSQL. |
Sources: backtrader/feeds/btcsv.py:32-150, strategies/moving_average_crossover.py:127-138
Sequence of Data Ingestion
The interaction between the data store and the engine is essential for replaying historical data or processing live streams.
Sequence diagram illustrating the bar-by-bar data processing loop.
Sources: backtrader/feeds/btcsv.py:32-55, Tutorials/quickstart/strategy_tester.py:30-70
Conclusion
The Turtle Trading Implementation provides a robust framework for systematic trading. By combining modular strategy agents with backtrader's flexible engine, the system enables developers to test complex patterns—such as Fibonacci retracements, RSI divergences, and Moving Average crossovers—while maintaining strict risk controls through automated position sizing and multiple exit strategies.
Sources: PLAN.md:75-85, README.md:15-50