Backtesting

Strategies Completas en Pine Script v5

Indicator vs Strategy. EMA Crossover con SL/TP basado en ATR. RSI Mean Reversion con filtro ADX. Como leer Strategy Tester. Ajuste fino sin sobre-ajuste. Flujo completo backtest a real.

📚 12 min lectura 📊 Dificultad: Medio 🇲🇽 Codigo listo para copiar

Indicator vs Strategy

En Pine Script, hay 2 tipos de scripts:

  • Indicator: solo visualiza informacion. No simula trades.
  • Strategy: simula trades de compra/venta. Backtest completo con metricas.

La diferencia clave en el codigo: indicator(...) vs strategy(...). Los strategy tienen funciones adicionales como strategy.entry(), strategy.exit(), strategy.close().

Strategy 1: EMA Crossover

La strategy mas clasica — cruce de EMA rapida sobre lenta:

// PrimeTraderAI – EMA Crossover Strategy MX //@version=5 strategy(«EMA Cross PT», overlay=true, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.cash_per_order, commission_value=7, slippage=2, pyramiding=0) // Inputs fastLen = input.int(20, «EMA Rapida») slowLen = input.int(50, «EMA Lenta») slMultiplier = input.float(1.5, «SL ATR multiplier») tpMultiplier = input.float(3.0, «TP ATR multiplier») // Indicadores emaFast = ta.ema(close, fastLen) emaSlow = ta.ema(close, slowLen) atr = ta.atr(14) // Condiciones de entrada longCondition = ta.crossover(emaFast, emaSlow) shortCondition = ta.crossunder(emaFast, emaSlow) // Entradas if longCondition sl = close – atr * slMultiplier tp = close + atr * tpMultiplier strategy.entry(«Long», strategy.long) strategy.exit(«Exit Long», «Long», stop=sl, limit=tp) if shortCondition sl = close + atr * slMultiplier tp = close – atr * tpMultiplier strategy.entry(«Short», strategy.short) strategy.exit(«Exit Short», «Short», stop=sl, limit=tp) // Plot EMAs plot(emaFast, «EMA Fast», color=color.new(#b8893d, 0)) plot(emaSlow, «EMA Slow», color=color.blue)

Despues de pegar codigo y «Add to chart», abre tab «Strategy Tester» y veras:

  • Net profit
  • Max drawdown
  • Win rate
  • Profit factor
  • Lista de cada trade

Strategy 2: RSI Mean Reversion

Para mercados laterales — comprar en sobrevendido, vender en sobrecomprado:

// PrimeTraderAI – RSI Mean Reversion MX //@version=5 strategy(«RSI Mean Reversion PT», overlay=true, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=5, commission_value=7, slippage=2) // Inputs rsiLen = input.int(14, «RSI Period») overbought = input.int(75, «Sobrecomprado») oversold = input.int(25, «Sobrevendido») adxLen = input.int(14, «ADX Period») adxMax = input.int(25, «Max ADX (filtro)») // Indicadores rsi = ta.rsi(close, rsiLen) [diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen) // Filtro: solo en mercados laterales (ADX bajo) inRange = adx < adxMax // Condiciones longCondition = rsi < oversold and inRange and strategy.position_size == 0 shortCondition = rsi > overbought and inRange and strategy.position_size == 0 exitLong = rsi > 50 exitShort = rsi < 50 // Entradas if longCondition strategy.entry(«Long», strategy.long) if shortCondition strategy.entry(«Short», strategy.short) // Salidas (cuando RSI cruza 50) if exitLong strategy.close(«Long») if exitShort strategy.close(«Short») // Plots plot(rsi, «RSI», color=#b8893d, display=display.none) plot(adx, «ADX», color=color.purple, display=display.none)

Esta strategy:

  • Solo opera cuando ADX < 25 (mercado lateral)
  • Compra en RSI < 25, vende en RSI > 75
  • Cierra cuando RSI vuelve a 50
  • Mejor para pares ordenados (EUR/CHF, EUR/GBP)

Como leer los resultados

Despues de «Add to chart», el Strategy Tester muestra varios tabs:

Overview (lo mas importante)

  • Net Profit: ganancia/perdida total en %
  • Total Closed Trades: cantidad de trades
  • Percent Profitable: win rate
  • Profit Factor: ganancia bruta / perdida bruta (>1.5 es bueno)
  • Max Drawdown: caida maxima desde peak (<25% ideal)

Performance Summary

  • Average trade (promedio ganancia por trade)
  • Largest win / largest loss
  • Number of winning vs losing trades
  • Average bars in trade

List of trades

Cada trade individual con fecha, precio entrada/salida, profit. Util para identificar si la strategy gana de pocos trades grandes (peligroso) o muchos pequeños (mejor).

Ajuste fino (con cuidado)

Despues del primer backtest, querras optimizar parametros. Cuidado con sobre-ajuste:

Como optimizar bien

  1. Usa parametros estandar primero (EMA 50/200, RSI 14)
  2. Cambia un solo parametro a la vez
  3. Documenta cada cambio y su impacto
  4. Out-of-sample test: usa primeros 80% datos para optimizar, ultimos 20% para validar
  5. Walk forward: optimiza por periodos rolling, no sobre todo el historico
  6. Verifica robustez: si parametro X=20 funciona, prueba con X=18, 19, 21, 22. Si solo funciona con X=20, esta sobre-ajustado.
⚠️ La trampa del sobre-ajuste

Si tu strategy tiene 50% net profit con un combo magico de parametros, casi siempre esta sobre-ajustada. En vivo va a fallar.

Una strategy con 20% net profit pero robusta (funciona con parametros variados) es mucho mejor que una con 100% net profit que solo funciona con un combo especifico.

Limitaciones del Strategy Tester

El Strategy Tester de TradingView tiene limitaciones que importa conocer:

  • Solo un activo: no permite testear portfolio diversificado
  • Datos limitados: tipicamente solo ultimos 5-10 años en cuenta gratis
  • No simula slippage real: solo aproximacion
  • No simula spread variable: usa spread fijo
  • No simula swap overnight: ignora costo de hold > 1 dia
  • No simula gaps de fin de semana realistas

Para backtest mas profesional, usar Python (Backtrader, Vectorbt) o servicios como QuantConnect.

El flujo completo Pine Script Strategy

  1. Idea: defines reglas de trading
  2. Pseudocodigo: escribelas en español
  3. Pine Script v5: convertir con AI o manualmente
  4. Backtest inicial: ver si tiene sentido
  5. Refinar: ajustar parametros con cuidado
  6. Out-of-sample test: validar con datos no vistos
  7. Forward test: papel/demo 60+ dias
  8. Cuenta real pequeña: si todo lo anterior funciona
  9. Scale up gradual: nunca de golpe

Saltarse pasos = perder dinero. Cada paso filtra strategies que no funcionan en vivo.

Practica el codigo en demo

Backtest no es real. Demo 60+ dias antes de capital real. Pine Script es herramienta, no garantia.

Brokers con TradingView Mas Pine Script
Aviso de Riesgo
El codigo Pine Script es educativo. NO garantiza rentabilidad. 70-89% de los traders retail pierden varo (ESMA, FCA, CFTC). Backtest no predice futuro. SAPTEL: 55 5259-8121.