Strategy · Pine Script v6 · On the chart

Estrategia Donchian Breakout

by JoelPasapera

Calculates upper and lower Donchian Channel bands over a customizable lookback length and plots them on the main price chart.

View on GitHub

GitHub stars11on the repository
Pine versionv6current
Lines of code94
Settings4inputs
LicenceApache-2.0
Last update5 months ago23 May 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

94 lines of Pine Script v6 from Donchian Breakout Strate/Estrategia Donchian Breakout.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

Estrategia Donchian Breakout.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JJPP_Joel - Joel Pasapera
// funciona bien para forex (EURUSD: 30m y 1h, GBPUSD: 30m y 1h), pero puedes probar en otros mercados...

//@version=6
strategy("Estrategia Donchian Breakout", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, default_qty_value=1)

// ==========================================
// ⚙️ CONFIGURACIÓN Y ENTRADAS
// ==========================================

// Configuración del Indicador
donchianLen = input.int(25, "Longitud Canal Donchian", minval=1, group="Indicador")

// Configuración de Tiempo y Reglas
targetHour  = input.int(17, "Hora de Colocación de Orden (Hora del Exchange)", minval=0, maxval=23, group="Reglas de Estrategia")
validHours  = input.int(60, "Horas de validez de la orden", minval=1, group="Reglas de Estrategia")

// configuracion de gestion de riesgo
lot_size = input.int(900, "Volumen de posición", minval=1, group="Riesgo")

// ==========================================
// 📐 CÁLCULOS DEL INDICADOR
// ==========================================

// Calculamos el Canal de Donchian. 
// Usamos [1] para referirnos al máximo de las 51 velas *cerradas* anteriores.
// Esto es crucial para definir el nivel de ruptura (Breakout).
upperBand = ta.highest(high, donchianLen)[1]
lowerBand = ta.lowest(low, donchianLen)[1]

// Plot del canal para visualización
plot(upperBand, "Donchian Superior", color=color.green, linewidth=2)
plot(lowerBand, "Donchian Inferior", color=color.red, linewidth=1)

// ==========================================
// 🕒 LÓGICA DE TIEMPO
// ==========================================

// Detectar si es la hora objetivo (ej: 16:00) y si estamos en el minuto 0 de esa hora
isTargetTime = (hour == targetHour) and (minute == 0)

// Variables para guardar el estado de la orden pendiente
var float pendingPrice = na
var int entryBarIndex = 0

// ==========================================
// 🚀 EJECUCIÓN DE LA ORDEN (BUY STOP)
// ==========================================

// 1. Colocar la orden a las 16:00
if isTargetTime
    // Guardamos el precio del nivel superior actual
    pendingPrice := upperBand
    entryBarIndex := bar_index
    
    // Colocamos una orden "STOP". Esto significa que solo se comprará si el precio sube y toca este nivel.
    strategy.entry("Long Breakout", strategy.long, stop=pendingPrice, comment="cruze de vela",qty = lot_size)

// 2. Cancelación de la orden tras 7 horas
// Si la orden no se ha llenado (no tenemos posición) y han pasado más de 'validHours' barras:
barsPassed = bar_index - entryBarIndex

if (strategy.opentrades == 0) and (barsPassed >= validHours)
    strategy.cancel("Long Breakout")
    pendingPrice := na // Reseteamos el precio para limpieza visual

// ==========================================
// 🚪 SALIDA (EXIT STRATEGY)
// ==========================================

// NOTA: Tu descripción no especificaba cuándo VENDER. 
// Para que la estrategia sea funcional y rentable en el backtest, he añadido
// una salida clásica de Donchian: Vender si el precio toca la banda inferior.
if strategy.opentrades > 0
    strategy.exit("Exit Long", "Long Breakout", stop=lowerBand, comment="Salida Banda Inf")

// ==========================================
// 🎨 VISUALIZACIÓN
// ==========================================

// Colorear el fondo a las 16:00 para identificar visualmente el momento
bgcolor(isTargetTime ? color.new(color.blue, 80) : na, title="Hora Objetivo")

esHoraObjetivo = hour(time) == targetHour

// Dibuja una forma (triángulo) en la barra que comienza a las 16:00
plotshape(esHoraObjetivo ? high : na, 
     title="Marca 16:00", 
     location=location.abovebar, // Ubicación: sobre la barra de precios (utiliza 'high' como coordenada)
     color=color.green, // Color de la flecha
     style=shape.triangledown, // ¡Forma de triángulo hacia abajo! (También puedes probar shape.triangleup, shape.arrowup o shape.arrowdown)
     text="Buy\nStop", // ¡Aquí se añade el texto para la orden pendiente! 
     size=size.tiny) // Tamaño pequeño

Overview

At a specified exchange hour, the strategy places a long buy stop order at the upper Donchian Channel level. Unfilled pending orders automatically expire after a configurable number of bars. Open long positions exit via a trailing stop order pegged to the lower Donchian Channel band.

Details

Published by

JoelPasapera on GitHub

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Breakout, Support & resistance, Trend, Volatility & bands

Markets

Forex

Timeframes

M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

botpinescriptstrategytradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Longitud Canal Donchianint25donchianLen
Hora de Colocación de Orden (Hora del Exchange)int17targetHour
Horas de validez de la ordenint60validHours
Volumen de posiciónint900lot_size
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
16 stars

This strategy trades Donchian breakouts measured on weekly bars while orders execute on the chart timeframe. It allows long and short entries when price breaks the prior weekly channel and exits against the shorter weekly channel. Position size risks a set per

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 4: Weekly Donchian

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated today · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers