Indicator · Pine Script v5 · On the chart

MNQ Fondeo Agent v5

by fundedtradersclub-code

MNQ Fondeo Agent v5 calculates trade entries and dynamic contract sizing tailored for Micro E-mini Nasdaq-100 futures funded accounts.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code237
Settings23inputs
LicenceMIT
Last update6 days ago18 Nov 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

237 lines of Pine Script v5 from mnq-fondeo-agent.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

mnq-fondeo-agent.pine
//@version=5
indicator("MNQ Fondeo Agent v5", shorttitle="MNQ Fondeo v5", overlay=true, max_labels_count=200)

// Indicador de apoyo para operar futuros MNQ en cuentas de fondeo (25K / 50K).
// No es asesoría financiera ni garantiza pasar una evaluación. Sin relación con ninguna
// firma de fondeo: verifica siempre las reglas vigentes de tu cuenta en su panel.
// Licencia MIT · https://github.com/fundedtradersclub-code/mnq-fondeo-agent

// ═══════════════════════ CUENTA DE FONDEO ═══════════════════════
gCuenta       = "Cuenta de fondeo"
tamanoCuenta  = input.string("25K", "Tamaño de cuenta", options=["25K", "50K"], group=gCuenta)
ddManual      = input.float(0, "Trailing drawdown ($) · 0 = valor típico (25K: 1500 / 50K: 2500)", minval=0, step=50, group=gCuenta)
saldoActual   = input.float(25000, "Saldo actual ($) · actualízalo antes de operar", step=50, group=gCuenta)
saldoMaximo   = input.float(25000, "Saldo máximo alcanzado ($) · del panel de tu cuenta", step=50, group=gCuenta)
colchonMin    = input.float(300, "Colchón mínimo sobre el límite ($)", minval=0, step=50, group=gCuenta)

// ═══════════════════════ RIESGO POR OPERACIÓN ═══════════════════════
gRiesgo       = "Riesgo por operación"
riskDollars   = input.float(150, "Riesgo máximo por operación ($)", minval=25, maxval=1000, step=10, group=gRiesgo)
maxContratos  = input.int(3, "Máximo de contratos", minval=1, maxval=50, group=gRiesgo)
maxTradesDay  = input.int(3, "Máximo de operaciones por día", minval=1, maxval=10, group=gRiesgo)
perdidaDiaMax = input.float(300, "Pérdida diaria máxima ($, simulada) · 0 = sin límite", minval=0, step=50, group=gRiesgo)
atrLength     = input.int(14, "ATR Length", minval=1, group=gRiesgo)
atrMultiplier = input.float(1.4, "ATR multiplicador (stop)", minval=0.5, maxval=4, step=0.1, group=gRiesgo)
stopMinPts    = input.float(8, "Stop mínimo (puntos)", minval=1, step=1, group=gRiesgo)
objetivoR     = input.float(1.5, "Objetivo (R)", minval=0.5, maxval=5, step=0.1, group=gRiesgo)
breakevenR    = input.float(1.0, "Mover el stop a breakeven al llegar a (R) · 0 = no", minval=0, maxval=5, step=0.1, group=gRiesgo)

// ═══════════════════════ HORARIOS (HORA DE NUEVA YORK) ═══════════════════════
gSesion        = "Horarios (hora de Nueva York)"
sesionEntradas = input.session("0930-1145", "Horario para abrir operaciones", group=gSesion)
sesionGestion  = input.session("0930-1600", "Horario máximo con operación abierta", group=gSesion)
sesionNocturna = input.session("1800-0930", "Sesión nocturna (rango ON)", group=gSesion)
volLength      = input.int(20, "Volumen promedio Length", minval=1, group=gSesion)

// ═══════════════════════ NOTICIAS ═══════════════════════
gNoticias       = "Noticias (hora de Nueva York)"
useNewsFilter   = input.bool(true, "Activar filtro de noticias", group=gNoticias)
newsBlackoutMin = input.int(20, "Minutos de bloqueo antes y después", minval=5, maxval=90, group=gNoticias)
// -05:00 = hora de Nueva York en invierno (noviembre a marzo); en verano usa -04:00.
news1 = input.time(timestamp("2026-11-10T08:30:00-05:00"), "Noticia 1", group=gNoticias)
news2 = input.time(timestamp("2026-12-04T08:30:00-05:00"), "Noticia 2", group=gNoticias)
news3 = input.time(timestamp("2026-12-09T14:00:00-05:00"), "Noticia 3", group=gNoticias)

// ═══════════════════════ DATOS BASE ═══════════════════════
tz         = "America/New_York"
// Valor de un punto del contrato del gráfico (MNQ = 2 USD; NQ = 20 USD).
puntoValor = na(syminfo.pointvalue) or syminfo.pointvalue <= 0 ? 2.0 : syminfo.pointvalue

enEntradas = not na(time(timeframe.period, sesionEntradas, tz))
enGestion  = not na(time(timeframe.period, sesionGestion, tz))
enNocturna = not na(time(timeframe.period, sesionNocturna, tz))
nuevoDia   = nz(ta.change(time("D")), 1) != 0

atr    = ta.atr(atrLength)
vwap   = ta.vwap(hlc3)
volAvg = ta.sma(volume, volLength)

// Rango nocturno real: máximo y mínimo entre las 18:00 y las 09:30. Se fija al terminar la sesión
// nocturna, así que no cambia durante el día (v4 usaba el rango del día anterior completo).
var float onAlto      = na
var float onBajo      = na
var float onAltoFinal = na
var float onBajoFinal = na
if enNocturna and not enNocturna[1]
    onAlto := high
    onBajo := low
else if enNocturna
    onAlto := na(onAlto) ? high : math.max(onAlto, high)
    onBajo := na(onBajo) ? low : math.min(onBajo, low)
if not enNocturna and enNocturna[1]
    onAltoFinal := onAlto
    onBajoFinal := onBajo

// Máximo y mínimo del día anterior, sin repintar.
maxAnterior = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
minAnterior = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)

// Filtro de noticias: las fechas se interpretan en hora de Nueva York.
msBloqueo = newsBlackoutMin * 60 * 1000
cercaDe(t) => not na(t) and math.abs(time - t) <= msBloqueo
enNoticia = useNewsFilter and (cercaDe(news1) or cercaDe(news2) or cercaDe(news3))

// ═══════════════════════ CUENTA Y TAMAÑO DE POSICIÓN ═══════════════════════
ddLimite = ddManual > 0 ? ddManual : (tamanoCuenta == "25K" ? 1500.0 : 2500.0)
umbralDD = saldoMaximo - ddLimite          // nivel de saldo que no se puede tocar
margenDD = saldoActual - umbralDD          // dinero que queda antes de perder la cuenta

// Stop por ATR (con un mínimo) y contratos para no pasar del riesgo elegido.
// En v4 el riesgo actuaba como MÍNIMO del stop y no se calculaban contratos.
stopDist     = math.max(atr * atrMultiplier, stopMinPts)
riesgoPorCto = stopDist * puntoValor
ctosCalc     = math.min(maxContratos, math.floor(riskDollars / riesgoPorCto))
riesgoTotal  = ctosCalc * riesgoPorCto
tamanoOk     = ctosCalc >= 1
margenOk     = margenDD - riesgoTotal >= colchonMin

// ═══════════════════════ ESTADO DE LA OPERACIÓN SIMULADA ═══════════════════════
var int   tradesHoy   = 0
var float pnlHoy      = 0.0
var int   pos         = 0          // 1 = largo, -1 = corto, 0 = sin operación
var float precioEnt   = na
var float stopIni     = na
var float stopAct     = na
var float objetivo    = na
var int   contratos   = 0
var bool  enBreakeven = false

if nuevoDia
    tradesHoy := 0
    pnlHoy    := 0.0

// Gestión de la operación abierta: solo con la vela cerrada, para no repintar.
// Si en la misma vela se tocan el stop y el objetivo, se asume el stop (lo conservador).
if barstate.isconfirmed and pos != 0
    cerrada      = false
    motivo       = ""
    precioSalida = close
    if pos == 1
        if low <= stopAct
            cerrada      := true
            precioSalida := stopAct
            motivo       := enBreakeven ? "Breakeven" : "Stop"
        else if high >= objetivo
            cerrada      := true
            precioSalida := objetivo
            motivo       := "Objetivo"
    else
        if high >= stopAct
            cerrada      := true
            precioSalida := stopAct
            motivo       := enBreakeven ? "Breakeven" : "Stop"
        else if low <= objetivo
            cerrada      := true
            precioSalida := objetivo
            motivo       := "Objetivo"
    if not cerrada and not enGestion
        cerrada      := true
        precioSalida := close
        motivo       := "Fin de horario"
    if cerrada
        resultado = (precioSalida - precioEnt) * pos * contratos * puntoValor
        pnlHoy += resultado
        textoSalida = motivo + "\n" + (resultado >= 0 ? "+$" : "-$") + str.tostring(math.abs(resultado), "#")
        label.new(bar_index, pos == 1 ? high : low, textoSalida, style=pos == 1 ? label.style_label_down : label.style_label_up, color=resultado > 0 ? color.new(color.green, 30) : resultado < 0 ? color.new(color.red, 30) : color.new(color.gray, 30), textcolor=color.white, size=size.small)
        alert("Salida (" + motivo + "): " + (resultado >= 0 ? "+$" : "-$") + str.tostring(math.abs(resultado), "#") + " · P&L simulado del día: " + (pnlHoy >= 0 ? "+$" : "-$") + str.tostring(math.abs(pnlHoy), "#"), alert.freq_once_per_bar)
        pos         := 0
        enBreakeven := false
    else if breakevenR > 0 and not enBreakeven
        r = math.abs(precioEnt - stopIni)
        if (pos == 1 and high >= precioEnt + r * breakevenR) or (pos == -1 and low <= precioEnt - r * breakevenR)
            stopAct     := precioEnt
            enBreakeven := true
            label.new(bar_index, pos == 1 ? high : low, "Stop a breakeven", style=pos == 1 ? label.style_label_down : label.style_label_up, color=color.new(color.blue, 30), textcolor=color.white, size=size.tiny)
            alert("Mueve el stop a breakeven: " + str.tostring(precioEnt, format.mintick), alert.freq_once_per_bar)

// ═══════════════════════ SEÑALES ═══════════════════════
sesgoLargo = close > vwap and not na(onAltoFinal) and close > onAltoFinal
sesgoCorto = close < vwap and not na(onBajoFinal) and close < onBajoFinal
confLargo  = close > open and close > high[1] and volume > volAvg
confCorto  = close < open and close < low[1] and volume > volAvg

limiteDiario = perdidaDiaMax > 0 and pnlHoy <= -perdidaDiaMax
puedeOperar  = enEntradas and not enNoticia and tradesHoy < maxTradesDay and not limiteDiario and pos == 0

senalLargo = barstate.isconfirmed and puedeOperar and sesgoLargo and confLargo and tamanoOk and margenOk
senalCorto = barstate.isconfirmed and puedeOperar and sesgoCorto and confCorto and tamanoOk and margenOk

// Señal que se habría dado, pero no cabe en el riesgo o en el margen de la cuenta.
senalBloqueada = barstate.isconfirmed and puedeOperar and ((sesgoLargo and confLargo) or (sesgoCorto and confCorto)) and not (tamanoOk and margenOk)

setupLargo = barstate.isconfirmed and puedeOperar and sesgoLargo and close > open and close > high[1] * 0.999 and volume > volAvg * 0.9 and not confLargo
setupCorto = barstate.isconfirmed and puedeOperar and sesgoCorto and close < open and close < low[1] * 1.001 and volume > volAvg * 0.9 and not confCorto

if senalLargo or senalCorto
    pos         := senalLargo ? 1 : -1
    precioEnt   := close
    stopIni     := close - pos * stopDist
    stopAct     := stopIni
    objetivo    := close + pos * stopDist * objetivoR
    contratos   := ctosCalc
    enBreakeven := false
    tradesHoy   += 1
    textoEnt = (pos == 1 ? "LARGO" : "CORTO") + " #" + str.tostring(tradesHoy) + " · " + str.tostring(contratos) + " cto" + "\nStop: " + str.tostring(stopIni, format.mintick) + "\nObjetivo: " + str.tostring(objetivo, format.mintick) + "\nRiesgo: $" + str.tostring(contratos * riesgoPorCto, "#")
    label.new(bar_index, pos == 1 ? low : high, textoEnt, style=pos == 1 ? label.style_label_up : label.style_label_down, color=pos == 1 ? color.green : color.red, textcolor=color.white, size=size.normal)
    alert("Entrada " + textoEnt, alert.freq_once_per_bar)

if senalBloqueada
    label.new(bar_index, close, not tamanoOk ? "Sin entrada:\nstop muy amplio\npara tu riesgo" : "Sin entrada:\npoco margen\nhasta el límite", style=label.style_label_left, color=color.new(color.gray, 40), textcolor=color.white, size=size.tiny)

if setupLargo
    label.new(bar_index, low, "Setup largo\ncasi confirmado", style=label.style_label_up, color=color.new(color.teal, 20), textcolor=color.white, size=size.small)
if setupCorto
    label.new(bar_index, high, "Setup corto\ncasi confirmado", style=label.style_label_down, color=color.new(color.orange, 20), textcolor=color.white, size=size.small)

// ═══════════════════════ GRÁFICO ═══════════════════════
plot(vwap, "VWAP", color=color.yellow, linewidth=2)
plot(onAltoFinal, "Máximo nocturno (ON High)", color=color.new(color.green, 20), style=plot.style_linebr, linewidth=2)
plot(onBajoFinal, "Mínimo nocturno (ON Low)", color=color.new(color.red, 20), style=plot.style_linebr, linewidth=2)
plot(maxAnterior, "Máximo del día anterior", color=color.new(color.green, 70), style=plot.style_linebr)
plot(minAnterior, "Mínimo del día anterior", color=color.new(color.red, 70), style=plot.style_linebr)
plot(pos != 0 ? precioEnt : na, "Entrada", color=color.gray, style=plot.style_linebr)
plot(pos != 0 ? stopAct : na, "Stop", color=color.red, style=plot.style_linebr, linewidth=2)
plot(pos != 0 ? objetivo : na, "Objetivo", color=color.lime, style=plot.style_linebr, linewidth=2)

bgcolor(enEntradas ? color.new(color.blue, 94) : na)
bgcolor(enNoticia ? color.new(color.orange, 80) : na)
bgcolor(limiteDiario or tradesHoy >= maxTradesDay ? color.new(color.red, 92) : na)

// ═══════════════════════ TABLA DE CONTROL ═══════════════════════
var table info = table.new(position.top_right, 2, 10, bgcolor=color.new(#0d0d0d, 15), border_width=1, border_color=color.gray)
fila(n, nombre, valor, col) =>
    table.cell(info, 0, n, nombre, text_color=color.white, text_size=size.small)
    table.cell(info, 1, n, valor, text_color=col, text_size=size.small)

if barstate.islast
    listo = puedeOperar and tamanoOk and margenOk
    fila(0, "Cuenta " + tamanoCuenta, "Límite: $" + str.tostring(umbralDD, "#,###"), #ffd700)
    fila(1, "Margen al límite", "$" + str.tostring(margenDD, "#,###"), margenOk ? color.lime : color.red)
    fila(2, "Operaciones hoy", str.tostring(tradesHoy) + " / " + str.tostring(maxTradesDay), tradesHoy >= maxTradesDay ? color.red : color.lime)
    fila(3, "Tamaño", tamanoOk ? str.tostring(ctosCalc) + " cto · riesgo $" + str.tostring(riesgoTotal, "#") : "Stop muy amplio", tamanoOk ? color.yellow : color.red)
    fila(4, "P&L simulado hoy", (pnlHoy >= 0 ? "+$" : "-$") + str.tostring(math.abs(pnlHoy), "#"), limiteDiario ? color.red : pnlHoy >= 0 ? color.lime : color.orange)
    fila(5, "Horario de entradas", enEntradas ? "ABIERTO" : "CERRADO", enEntradas ? color.lime : color.gray)
    fila(6, "Noticias", enNoticia ? "BLOQUEO" : "OK", enNoticia ? color.orange : color.lime)
    fila(7, "Puede operar", listo ? "SÍ" : "NO", listo ? color.lime : color.red)
    fila(8, "Operación", pos == 1 ? "LARGO" : pos == -1 ? "CORTO" : setupLargo ? "Setup L" : setupCorto ? "Setup C" : "—", pos == 1 ? color.lime : pos == -1 ? color.red : color.gray)
    fila(9, "Stop actual", pos != 0 ? str.tostring(stopAct, format.mintick) + (enBreakeven ? " (BE)" : "") : "—", color.white)

// ═══════════════════════ ALERTAS ═══════════════════════
alertcondition(setupLargo, title="Setup largo (casi)", message="Setup largo muy cerca de confirmar")
alertcondition(setupCorto, title="Setup corto (casi)", message="Setup corto muy cerca de confirmar")
alertcondition(senalLargo, title="Entrada larga", message="Entrada larga confirmada")
alertcondition(senalCorto, title="Entrada corta", message="Entrada corta confirmada")
alertcondition(tradesHoy >= maxTradesDay, title="Máximo de operaciones", message="Máximo de operaciones del día alcanzado")
alertcondition(limiteDiario, title="Pérdida diaria alcanzada", message="Se alcanzó la pérdida diaria máxima: no abrir más operaciones hoy")
alertcondition(enNoticia, title="Bloqueo por noticias", message="Zona de noticia: no abrir operaciones")
alertcondition(not margenOk, title="Poco margen al límite", message="El margen hasta el límite de la cuenta es menor que el riesgo más el colchón")

Overview

MNQ Fondeo Agent v5 evaluates market bias using VWAP and overnight trading ranges alongside volume-confirmed impulse breakouts. Position size is calculated using specified dollar risk, ATR stop distance, and account trailing drawdown constraints. The indicator draws trade entry labels, stop loss levels, target prices, and breakeven thresholds directly on the price chart. It also incorporates custom trading session windows and scheduled news blackout filters. All calculations use closed bars to avoid repainting.

Details

Published by

fundedtradersclub-code on GitHub

Draws

On the price chart

Markets

Indices

Timeframes

M15-H1, M1-M5

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

futuresmnqnasdaqpine-scriptprop-firmrisk-managementtradingview

Settings

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

SettingTypeDefaultVariable
Tamaño de cuentastring25KtamanoCuenta
Trailing drawdown ($) · 0 = valor típico (25K: 1500 / 50K: 2500)float0ddManual
Saldo actual ($) · actualízalo antes de operarfloat25000saldoActual
Saldo máximo alcanzado ($) · del panel de tu cuentafloat25000saldoMaximo
Colchón mínimo sobre el límite ($)float300colchonMin
Riesgo máximo por operación ($)float150riskDollars
Máximo de contratosint3maxContratos
Máximo de operaciones por díaint3maxTradesDay
Pérdida diaria máxima ($, simulada) · 0 = sin límitefloat300perdidaDiaMax
ATR Lengthint14atrLength
ATR multiplicador (stop)float1.4atrMultiplier
Stop mínimo (puntos)float8stopMinPts
Show all 23 settings
SettingTypeDefaultVariable
Objetivo (R)float1.5objetivoR
Mover el stop a breakeven al llegar a (R) · 0 = nofloat1.0breakevenR
Horario para abrir operacionessession0930-1145sesionEntradas
Horario máximo con operación abiertasession0930-1600sesionGestion
Sesión nocturna (rango ON)session1800-0930sesionNocturna
Volumen promedio Lengthint20volLength
Activar filtro de noticiasbooltrueuseNewsFilter
Minutos de bloqueo antes y despuésint20newsBlackoutMin
Noticia 1timetimestamp("2026-11-10T08:30:00-05:00")news1
Noticia 2timetimestamp("2026-12-04T08:30:00-05:00")news2
Noticia 3timetimestamp("2026-12-09T14:00:00-05:00")news3
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

114 stars

This indicator adapts Michael Chalek's Dual Thrust trading concept to plot breakout levels and overlay bands directly on the price chart. It calculates lookback ranges based on historical price action and provides two algorithmic variations along with multiple

Indicator v4 TrendBreakout Repaints
Updated 2 years ago · None stated GitHub repository of Dual Thrust Trading Algorithm
98 stars

This indicator classifies the market into gamma regime types (negative gamma trend, positive gamma mean-reversion, or transition) by calculating a composite score based on daily ATR ratios, session VWAP crossover frequencies, and opening range displacement. It

Indicator v5 Volatility & bandsTrend
Updated 2 months ago · Custom licence GitHub repository of Moon Dev GEX Regime & Trap

The Mathematical Indicator calculates session bias by evaluating previous daily and 4-hour closed candles. It draws timeframe support and resistance levels using candle bodies, highlights clean trading zones, and identifies setup patterns involving consolidati

Indicator v6 TrendSupport & resistance Repaints
Updated 3 days ago · MIT GitHub repository of The Mathematical Indicator · 2-Candle Bias
34 stars

Adaptive Ehlers Filtered Percentile is a technical indicator that calculates a volatility-adaptive moving average smoothed by a nonlinear Ehlers filter. It plots dynamic upper and lower volatility bands around the baseline based on historical percentile price

Indicator v6 Moving averagesVolatility & bands
Updated 2 weeks ago · MIT GitHub repository of Adaptive Ehlers Filtered Percentile

The Market Tradability Engine calculates multi-factor tradability, balance, compression, and direction scores to evaluate market regime quality. It classifies market conditions into eight distinct states, including Balance, Compression, Ready, Breakout, Trend,

Indicator v6 TrendVolatility & bands
Updated 4 weeks ago · MIT GitHub repository of Market Tradability Engine [WavesUnchained]

GainzAlgo V2 Alpha

by Bakomebandias
8 stars

This overlay indicator scores breakouts of recent highs and lows against failed-breakout checks, EMA trend alignment, RSI momentum, and an ATR volatility band. It plots green buy and red sell labels when conditions pass a minimum score, and it prints ATR-based

Indicator v6 TrendOscillators & momentum
Updated 6 months ago · None stated GitHub repository of GainzAlgo V2 Alpha

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers