Introduction to Turtle Trading and Pine Script
Overview of the Turtle Trading Strategy
The Turtle Trading system, popularized by Richard Dennis and William Eckhardt, is a trend-following strategy built on simple rules for entry, position sizing, stop-loss placement, and exit. It focuses on capturing significant price trends and managing risk effectively. The core principles involve using Average True Range (ATR) to normalize position sizes across different assets, entering on breakouts of Donchian channels, and applying strict stop-loss orders to control losses.
Introduction to TradingView and Pine Script
TradingView is a popular platform for charting and analyzing financial markets. Pine Script is TradingView’s proprietary scripting language, designed for creating custom indicators and trading strategies. Its syntax is relatively straightforward, allowing traders to translate their ideas into automated code. It provides built-in functions for accessing historical data, performing calculations, and generating visual signals on charts. Understanding Pine Script’s capabilities is essential for automating any trading strategy on TradingView.
Why Use Pine Script for Turtle Trading?
Pine Script offers a conducive environment for implementing the Turtle Trading system due to its ability to:
- Automate calculations: Calculations like ATR and Donchian channels, which are integral to the strategy, can be automated.
- Backtest strategy: Assess the historical performance of the strategy with TradingView’s backtesting engine.
- Visually display signals: Plot entry and exit points directly on the chart for easy monitoring.
- Customize the strategy: Adapt the Turtle Trading system to different markets and timeframes through parameter adjustments.
Core Components of the Turtle Trading System
Determining the Average True Range (ATR)
ATR is a volatility indicator used to normalize position size. It measures the average range of price movements over a specified period. A higher ATR indicates greater volatility, requiring a smaller position size, and vice versa. The typical period used is 20 days, but this can be optimized.
Calculating Position Size Based on Volatility (N)
‘N’ represents the dollar volatility of an asset. It’s calculated as the ATR multiplied by the dollar value of one point of the asset. Position size is then determined by dividing the total risk capital by the ‘N’ value. A key tenet is to risk a fixed percentage (e.g., 1% or 2%) of trading capital per trade.
Entry Rules: Channel Breakouts (Donchian Channels)
The Turtle Trading system uses Donchian channels to identify potential breakout entry points. A Donchian channel consists of the highest high and lowest low over a specified period (typically 20 or 55 periods). A buy signal is triggered when the price breaks above the upper channel boundary, while a sell signal occurs when the price breaks below the lower channel boundary.
Stop-Loss Placement and Risk Management
Stop-loss orders are crucial for limiting potential losses. In the Turtle Trading system, the initial stop-loss is typically placed a multiple of ‘N’ (usually 2N or 3N) away from the entry price, in the opposite direction of the trade. Risk management is further enhanced by limiting the number of units risked in a single market and across correlated markets.
Implementing the Turtle Trading Strategy in Pine Script
Coding the ATR Calculation in Pine Script
//@version=5
indicator(title="ATR", shorttitle="ATR", overlay=false)
length = input.int(20, title="ATR Length")
atrValue = ta.atr(length)
plot(atrValue, title="ATR")
This code calculates the ATR using the ta.atr() function. The length input allows users to adjust the ATR period. The calculated ATR value is plotted on a separate pane for visualization.
Implementing Donchian Channels for Entry Signals
//@version=5
indicator(title="Donchian Channels", overlay=true)
upperLength = input.int(20, title="Upper Channel Length")
lowerLength = input.int(10, title="Lower Channel Length")
upperChannel = ta.highest(high, upperLength)
lowerChannel = ta.lowest(low, lowerLength)
plot(upperChannel, color=color.green, title="Upper Channel")
plot(lowerChannel, color=color.red, title="Lower Channel")
longCondition = ta.crossover(close, upperChannel)
shortCondition = ta.crossunder(close, lowerChannel)
plotshape(longCondition, style=shape.triangleup, color=color.green, size=size.small, location=location.bottom)
plotshape(shortCondition, style=shape.triangledown, color=color.red, size=size.small, location=location.top)
This code implements Donchian channels using ta.highest() and ta.lowest() to find the highest high and lowest low over specified periods. ta.crossover and ta.crossunder functions are used to detect breakout signals. The plotshape function visualizes entry signals on the chart.
Coding Position Sizing Logic
//@version=5
indicator(title="Turtle Trading Position Size", overlay=false)
riskPercentage = input.float(1, title="Risk Percentage per Trade", step=0.1) / 100
accountSize = input.float(10000, title="Account Size")
atrLength = input.int(20, title="ATR Length")
atrValue = ta.atr(atrLength)
dollarValuePerPoint = syminfo.mintick * syminfo.pointvalue // Modify if not trading standard contracts (e.g., futures)
N = atrValue * dollarValuePerPoint
units = math.floor((accountSize * riskPercentage) / N)
plot(units, title="Position Size")
This code calculates the position size based on the risk percentage, account size, and ATR. syminfo.mintick and syminfo.pointvalue are used to determine the dollar value per point, which is then multiplied by the ATR to obtain ‘N’. The math.floor function ensures that the position size is an integer value.
Implementing Stop-Loss and Take-Profit Levels
//@version=5
strategy(title="Turtle Trading Strategy", overlay=true)
// Inputs
upperLength = input.int(20, title="Upper Channel Length")
lowerLength = input.int(10, title="Lower Channel Length")
atrLength = input.int(20, title="ATR Length")
riskMultiple = input.float(2, title="Stop-Loss Multiple of ATR")
// Calculations
upperChannel = ta.highest(high, upperLength)
lowerChannel = ta.lowest(low, lowerLength)
atrValue = ta.atr(atrLength)
// Entry Conditions
longCondition = ta.crossover(close, upperChannel)
shortCondition = ta.crossunder(close, lowerChannel)
// Stop-Loss and Take-Profit Levels
longStopLoss = close - riskMultiple * atrValue
shortStopLoss = close + riskMultiple * atrValue
// Strategy Execution
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop = longStopLoss)
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop = shortStopLoss)
This code implements the complete Turtle Trading strategy with entry, stop-loss, and take-profit levels. strategy.entry and strategy.exit functions are used to enter and exit trades based on the defined conditions. The stop-loss is placed at a multiple of the ATR away from the entry price.
Backtesting and Optimization
Setting Up a Backtesting Environment in TradingView
TradingView provides a built-in strategy tester that allows you to backtest your Pine Script strategies. To use the strategy tester, add your strategy to the chart and navigate to the “Strategy Tester” tab below the chart. Configure the backtesting period, initial capital, and commission fees to accurately assess the strategy’s performance.
Analyzing Backtesting Results
The strategy tester provides detailed performance metrics, including net profit, drawdown, win rate, and profit factor. Analyze these metrics to understand the strengths and weaknesses of your strategy. Pay close attention to the drawdown, which indicates the maximum loss experienced during the backtesting period.
Optimizing Parameters for Different Markets
The Turtle Trading system has parameters that can be optimized for different markets and timeframes, such as the ATR length, Donchian channel lengths, and risk multiple. Use TradingView’s strategy tester to identify the optimal parameter values for each market. Be cautious of overfitting your strategy to historical data, as this can lead to poor performance in live trading. Consider using walk-forward optimization to validate your results.
Advanced Considerations and Enhancements
Implementing Pyramiding Strategies
Pyramiding involves adding to a winning position as the price moves in your favor. This can potentially increase profits, but it also increases risk. In Pine Script, pyramiding can be implemented by adding additional entry orders after the initial entry is profitable. This requires careful consideration of position sizing and risk management.
Adding Filters Based on Market Conditions
The Turtle Trading system can be enhanced by adding filters based on market conditions, such as trend direction or volatility. For example, you might only take long trades when the market is in an uptrend or avoid trading during periods of high volatility. These filters can improve the strategy’s performance by reducing the number of false signals.
Alerts and Automated Trading (if applicable)
Pine Script allows you to set alerts based on specific conditions. These alerts can be used to notify you of potential trading opportunities. However, direct automated trading from TradingView is limited. You typically need to integrate with a broker using external tools and APIs to fully automate the strategy. Services like Webhooks can be used to trigger external trading platforms based on Pine Script alerts, effectively bridging the gap for automated execution.