本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("NexTrade Strategy 1.1 - Backtest", overlay=true, max_boxes_count=250, max_labels_count=300,
initial_capital=10000, default_qty_type=strategy.fixed, default_qty_value=1,
commission_type=strategy.commission.cash_per_contract, commission_value=1.25,
slippage=1, process_orders_on_close=true, pyramiding=0, calc_on_every_tick=false)
// Version estrategia del indicador NexTrade Strategy 1.1: misma logica de zonas y senales, con entradas y salidas para el Strategy Tester.
// Va sobre el precio (overlay) para que las marcas de operaciones queden junto a las velas; el estocastico se ve en el indicador.
// Comision, deslizamiento, capital y contratos se ajustan en Configuracion -> Propiedades.
// ---------------- Inputs ----------------
gStrat = "Strategy"
tradeWith = input.bool(true, "Trade with-trend signals", group=gStrat)
tradeAgainst = input.bool(false, "Trade countertrend signals", group=gStrat)
exitMode = input.string("ATR", "Exit mode", options=["ATR", "Estructura", "Señal contraria"], group=gStrat,
tooltip="ATR: stop y objetivo fijos en ATR. Estructura: stop bajo/sobre el ultimo pivote, objetivo por ratio R. Señal contraria: cierra/invierte con la senal opuesta, stop ATR de seguridad.")
slAtr = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1, group=gStrat)
rr = input.float(2.0, "Take profit (R multiple)", minval=0.1, step=0.1, group=gStrat)
slBuffer = input.float(0.2, "Structural stop buffer (x ATR)", minval=0.0, step=0.1, group=gStrat)
maxRiskAtr = input.float(4.0, "Max structural risk (x ATR), else use ATR stop", minval=0.5, step=0.5, group=gStrat)
startDate = input.time(timestamp("2024-01-01T00:00:00"), "Backtest start", group=gStrat)
endDate = input.time(timestamp("2030-12-31T00:00:00"), "Backtest end", group=gStrat)
gTrend = "Trend and structure"
pivotLen = input.int(5, "Pivot bars", minval=2, maxval=20, group=gTrend)
gZones = "Zones"
showOB = input.bool(true, "Show 1H order blocks", group=gZones)
showFVG = input.bool(false, "Show FVG", group=gZones)
maxZones = input.int(12, "Max zones per type", minval=1, maxval=40, group=gZones)
obAtr = input.float(0.8, "OB displacement ATR", minval=0.1, step=0.1, group=gZones)
gTech = "Technical confirmation"
rsiLen = input.int(5, "RSI length", minval=2, group=gTech)
stochLen = input.int(5, "Stochastic length", minval=2, group=gTech)
stochSmooth = input.int(3, "Stochastic K smoothing", minval=1, group=gTech)
stochD = input.int(3, "Stochastic D smoothing", minval=1, group=gTech)
bbLen = input.int(20, "Bollinger length", minval=2, group=gTech)
bbDev = input.float(2.0, "Bollinger deviation", minval=0.1, group=gTech)
gSig = "Signals"
scoreWith = input.int(2, "Technical confirmations with trend", minval=0, maxval=3, group=gSig)
scoreAgainst = input.int(3, "Technical confirmations against trend", minval=0, maxval=3, group=gSig)
// ---------------- Indicadores base ----------------
atr = ta.atr(14)
rsi = ta.rsi(close, rsiLen)
k = ta.sma(ta.stoch(close, high, low, stochLen), stochSmooth)
d = ta.sma(k, stochD)
basis = ta.sma(close, bbLen)
dev = bbDev * ta.stdev(close, bbLen)
upper = basis + dev
lower = basis - dev
plot(upper, "BB Upper", color=color.yellow, linewidth=3)
plot(basis, "BB Basis", color=color.new(color.yellow, 55), linewidth=2)
plot(lower, "BB Lower", color=color.yellow, linewidth=3)
tfSec = timeframe.in_seconds()
use30 = tfSec <= 1800
use60 = tfSec <= 3600
use240 = tfSec <= 14400
// ---------------- Estructura ----------------
f_structure() =>
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
var float sh = na
var float sl = na
var int dir = 0
if not na(ph)
sh := ph
if not na(pl)
sl := pl
up = ta.crossover(close, sh)
dn = ta.crossunder(close, sl)
if up
dir := 1
if dn
dir := -1
[dir, up, dn]
[localDir, bosUp, bosDn] = f_structure()
f_trend4() =>
[dr, bu, bd] = f_structure()
dr[1]
trend4raw = request.security(syminfo.tickerid, "240", f_trend4(), lookahead=barmerge.lookahead_on)
trend4 = use240 ? trend4raw : localDir[1]
// ---------------- Barridos ----------------
f_sweep() =>
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
lastH = ta.valuewhen(not na(ph), ph, 0)
lastL = ta.valuewhen(not na(pl), pl, 0)
bull = not na(lastL) and low < lastL and close > lastL
bear = not na(lastH) and high > lastH and close < lastH
[bull[1], bear[1]]
[s30b, s30s] = request.security(syminfo.tickerid, "30", f_sweep(), lookahead=barmerge.lookahead_on)
[s60b, s60s] = request.security(syminfo.tickerid, "60", f_sweep(), lookahead=barmerge.lookahead_on)
[s240b, s240s] = request.security(syminfo.tickerid, "240", f_sweep(), lookahead=barmerge.lookahead_on)
new30b = use30 and s30b and not s30b[1]
new30s = use30 and s30s and not s30s[1]
new60b = use60 and s60b and not s60b[1]
new60s = use60 and s60s and not s60s[1]
new240b = use240 and s240b and not s240b[1]
new240s = use240 and s240s and not s240s[1]
// ---------------- Zonas ----------------
var array<box> obBoxes = array.new<box>()
var array<int> obDirs = array.new<int>()
var array<box> fvgBoxes = array.new<box>()
var array<int> fvgDirs = array.new<int>()
// 1) Invalidacion y toques de zonas existentes (antes de crear zonas nuevas)
bool activeTouchBull = false
bool activeTouchBear = false
if array.size(obBoxes) > 0
for i = array.size(obBoxes) - 1 to 0
z = array.get(obBoxes, i)
dr = array.get(obDirs, i)
top = box.get_top(z)
bot = box.get_bottom(z)
invalid = dr == 1 ? close < bot : close > top
if barstate.isconfirmed and invalid
box.delete(z)
array.remove(obBoxes, i)
array.remove(obDirs, i)
else
touching = high >= bot and low <= top
if touching
activeTouchBull := activeTouchBull or dr == 1
activeTouchBear := activeTouchBear or dr == -1
if array.size(fvgBoxes) > 0
for i = array.size(fvgBoxes) - 1 to 0
z = array.get(fvgBoxes, i)
dr = array.get(fvgDirs, i)
filled = dr == 1 ? low <= box.get_bottom(z) : high >= box.get_top(z)
if barstate.isconfirmed and filled
box.delete(z)
array.remove(fvgBoxes, i)
array.remove(fvgDirs, i)
// 2) OB de 1H: vela contraria seguida de desplazamiento ATR, detectado en 1H desde cualquier grafico <= 1H
f_ob1h() =>
a = ta.atr(14)
bull = close > open and close[1] < open[1] and close - open >= a * obAtr
bear = close < open and close[1] > open[1] and open - close >= a * obAtr
[bull[1], bear[1], high[2], low[2], time[2]]
[ob1Bull, ob1Bear, ob1Top, ob1Bottom, ob1Time] = request.security(syminfo.tickerid, "60", f_ob1h(), lookahead=barmerge.lookahead_on)
new1h = tfSec <= 3600 and timeframe.change("60")
if new1h and (ob1Bull or ob1Bear) and not na(ob1Time)
direction = ob1Bull ? 1 : -1
zoneColor = direction == 1 ? color.green : color.red
z = box.new(left=ob1Time, top=ob1Top, right=time, bottom=ob1Bottom, xloc=xloc.bar_time, extend=extend.right, bgcolor=color.new(zoneColor, showOB ? 88 : 100), border_color=color.new(zoneColor, showOB ? 45 : 100))
array.push(obBoxes, z)
array.push(obDirs, direction)
if array.size(obBoxes) > maxZones
box.delete(array.shift(obBoxes))
array.shift(obDirs)
// FVG: desequilibrio de tres velas, tamano minimo 0.15 ATR
bullFVG = barstate.isconfirmed and low > high[2] and low - high[2] >= atr * 0.15
bearFVG = barstate.isconfirmed and high < low[2] and low[2] - high >= atr * 0.15
if bullFVG or bearFVG
direction = bullFVG ? 1 : -1
top = bullFVG ? low : low[2]
bottom = bullFVG ? high[2] : high
c = direction == 1 ? color.teal : color.orange
z = box.new(bar_index - 2, top, bar_index + 1, bottom, bgcolor=color.new(c, showFVG ? 90 : 100), border_color=color.new(c, showFVG ? 65 : 100), extend=extend.right)
array.push(fvgBoxes, z)
array.push(fvgDirs, direction)
if array.size(fvgBoxes) > maxZones
box.delete(array.shift(fvgBoxes))
array.shift(fvgDirs)
// ---------------- EQH / EQL, CHoCH, ultimos pivotes ----------------
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
lastPH = ta.valuewhen(not na(ph), ph, 0)
lastPL = ta.valuewhen(not na(pl), pl, 0)
prevPH = ta.valuewhen(not na(ph), ph, 1)
prevPL = ta.valuewhen(not na(pl), pl, 1)
eqh = barstate.isconfirmed and not na(ph) and not na(prevPH) and math.abs(ph - prevPH) <= atr * 0.15
eql = barstate.isconfirmed and not na(pl) and not na(prevPL) and math.abs(pl - prevPL) <= atr * 0.15
chochUp = bosUp and localDir[1] == -1
chochDn = bosDn and localDir[1] == 1
plotshape(eqh, "EQH", shape.arrowdown, location.abovebar, color=color.yellow, size=size.small, offset=-pivotLen)
plotshape(eql, "EQL", shape.arrowup, location.belowbar, color=color.orange, size=size.small, offset=-pivotLen)
// ---------------- Senales ----------------
techBull = (rsi > 50 ? 1 : 0) + (k > d and k < 80 ? 1 : 0) + (close > basis ? 1 : 0)
techBear = (rsi < 50 ? 1 : 0) + (k < d and k > 20 ? 1 : 0) + (close < basis ? 1 : 0)
recentBullSweep = ta.barssince(new30b or new60b or new240b) <= 8
recentBearSweep = ta.barssince(new30s or new60s or new240s) <= 8
bullZone = activeTouchBull or recentBullSweep
bearZone = activeTouchBear or recentBearSweep
bullWith = trend4 == 1 and bullZone and techBull >= scoreWith and barstate.isconfirmed
bearWith = trend4 == -1 and bearZone and techBear >= scoreWith and barstate.isconfirmed
bullAgainst = trend4 == -1 and bullZone and chochUp and bullFVG and techBull >= scoreAgainst and barstate.isconfirmed
bearAgainst = trend4 == 1 and bearZone and chochDn and bearFVG and techBear >= scoreAgainst and barstate.isconfirmed
longWith = bullWith and not bullWith[1]
shortWith = bearWith and not bearWith[1]
longAgainst = bullAgainst and not bullAgainst[1]
shortAgainst = bearAgainst and not bearAgainst[1]
plotshape(longWith or longAgainst, "LONG green arrow", shape.arrowup, location.belowbar, color=color.lime, size=size.small)
plotshape(shortWith or shortAgainst, "SHORT red arrow", shape.arrowdown, location.abovebar, color=color.red, size=size.small)
// ---------------- Ejecucion de la estrategia ----------------
inRange = time >= startDate and time <= endDate
longSig = inRange and ((tradeWith and longWith) or (tradeAgainst and longAgainst))
shortSig = inRange and ((tradeWith and shortWith) or (tradeAgainst and shortAgainst))
reverseMode = exitMode == "Señal contraria"
flat = strategy.position_size == 0
f_stopLong() =>
atrStop = close - atr * slAtr
if exitMode == "Estructura" and not na(lastPL) and lastPL < close
s = lastPL - atr * slBuffer
close - s <= atr * maxRiskAtr ? s : atrStop
else
atrStop
f_stopShort() =>
atrStop = close + atr * slAtr
if exitMode == "Estructura" and not na(lastPH) and lastPH > close
s = lastPH + atr * slBuffer
s - close <= atr * maxRiskAtr ? s : atrStop
else
atrStop
var float slPrice = na
var float tpPrice = na
if longSig and (flat or (reverseMode and strategy.position_size < 0))
slPrice := f_stopLong()
tpPrice := reverseMode ? na : close + (close - slPrice) * rr
strategy.entry("L", strategy.long)
if reverseMode
strategy.exit("L-X", from_entry="L", stop=slPrice)
else
strategy.exit("L-X", from_entry="L", stop=slPrice, limit=tpPrice)
if shortSig and (flat or (reverseMode and strategy.position_size > 0))
slPrice := f_stopShort()
tpPrice := reverseMode ? na : close - (slPrice - close) * rr
strategy.entry("S", strategy.short)
if reverseMode
strategy.exit("S-X", from_entry="S", stop=slPrice)
else
strategy.exit("S-X", from_entry="S", stop=slPrice, limit=tpPrice)
if flat and not longSig and not shortSig
slPrice := na
tpPrice := na
plot(strategy.position_size != 0 ? slPrice : na, "Stop", color=color.new(color.red, 0), style=plot.style_linebr, linewidth=1)
plot(strategy.position_size != 0 ? tpPrice : na, "Target", color=color.new(color.green, 0), style=plot.style_linebr, linewidth=1)