Breakout candle max min long only – Tradingview Strategy

According to my previous post, I’ve inserted a proposal of script for tradingview Strategy (to be improved-revised).

Remember that this authomatical strategy is not solid, because it is based upon technical analisys, while the indicator must be used in coniunjction with target price (or, at limit, alone on ETF for index prices)

//@version=5

// In this strategy, enter long if close is the higher than last x-days’ highs and exit when close is lower then x-days’ lows

strategy(title=’Breakout candle max min long only v2′, calc_on_order_fills=false, calc_on_every_tick=true, max_bars_back=5000, initial_capital=100000, commission_type=strategy.commission.cash_per_order, commission_value=50, overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=20)

// INPUTS

length = input.int(2, ‘period of days ago- immodificabile’, minval=1)

lossp = input.int(13, ‘stop loss percentage’, minval=2, step=1)

targetp = input.int(25, ‘target profit percentage’, minval=2, step=1)

// === INPUT BACKTEST RANGE ===

fromMonth = input.int(defval = 1,    title = “From Month”,  minval = 1, maxval = 12)

fromDay   = input.int(defval = 1,    title = “From Day”,    minval = 1, maxval = 31)

fromYear  = input.int(defval = 2019, title = “From Year”,   minval = 1970)

thruMonth = input.int(defval = 1,    title = “Thru Month”,  minval = 1, maxval = 12)

thruDay   = input.int(defval = 1,    title = “Thru Day”,    minval = 1, maxval = 31)

thruYear  = input.int(defval = 2112, title = “Thru Year”,   minval = 1970)

// === FUNCTION EXAMPLE limit for backtest ===

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)            // backtest start  window

finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)            // backtest finish window

window()  => time >= start and time <= finish ? true : false           // create function “within window of time”

hl2 = (high+close)/2

hl21 = (high[1]+close[1])/2

hl22 = (high[2]+close[2])/2

//ENTRY CONDITION

entry1 = hl2 >= math.max(hl21,hl22)

/// Entry orders

strategy.entry(‘Long’, strategy.long, comment=’bar up’, when=entry1 and window())

//CONDIZIONI DI USCITA

lc1= (low+close)/2

lc21 = (low[1]+close[1])/2

lc22 =  (low[2]+close[2])/2

exit3 = lc1 <= math.min(lc21, lc22)

losspel = strategy.position_avg_price * (1 – lossp / 100)

exit4 = close < losspel

profitplev = strategy.position_avg_price * (1+ targetp / 100)

exit2 = close > profitplev

// exit orders

strategy.close(‘Long’, when=exit3, comment=’bar down’)

// FIXED MONEY MANAGEMENT

strategy.close(‘Long’, when=exit4, comment=’stop loss’)

strategy.close(‘Long’, when=exit2, comment=’target profit’)

// to reader, adding trailing stop

Breakout Arrow Indicator (High/Low Custom) – Tradingview

Overview

This light and effective indicator highlights momentum breakout signals by plotting visual arrows directly on your chart whenever the current price breaks above the highest high or below the lowest low of a customizable lookback period.

It is designed to give clean, actionable visual cues without cluttering your chart.

Key Features

  • Customizable Lookback Period: Choose how many previous bars to evaluate for high/low breakout thresholds (default is set to 2).
  • Flexible Signal Pricing: Fine-tune your breakout conditions independently for both bullish and bearish directions. Options include:
    • Bullish Source: Close, High, or Custom Average (High + Close) / 2
    • Bearish Source: Close, Low, or Custom Average (Low + Close) / 2
  • Clean Visual Aids: Green up-arrows below the candle for bullish breakouts and red down-arrows above the candle for bearish breakdowns.

Recommended Usage & Best Practices

While this indicator works across all timeframes and asset classes, it shines exceptionally well on the Weekly Chart (1W) for stock target price tracking and multi-week trend positioning.

  • Weekly Stock Target Reaching: Using (High + Close) / 2 or Close on a weekly chart helps filter out intraday/intraweek noise, confirming whether a stock is closing strongly above multi-week resistance levels.
  • Trend Following & Position Sizing: A weekly breakout arrow provides strong conviction for swing traders and investors looking to ride medium-to-long term momentum or set trailing stop/target alerts.

How to Use

  1. Add the indicator to your chart.
  2. Select your preferred lookback period (e.g., 2 weeks for short-term breakouts or higher for major structure breaks).
  3. Adjust the source price to match your risk tolerance (e.g., use High for instant breakout detection or Close / (High+Close)/2 for candle-close confirmation).

PINESCRIPT CODE

//@version=5
indicator(“Breakout High/Low Arrow Indicator Custom”, overlay=true)

// ==========================================
// INPUT E CONFIGURAZIONE
// ==========================================

// Periodo di lookback per il calcolo del massimo/minimo precedente
lookback = input.int(2, title=”Periodo candele precedenti”, minval=1, group=”Parametri”)

// Selezione del tipo di prezzo per il segnale Rialzista
bull_source_type = input.string(“Chiusura”, title=”Prezzo segnale Rialzista”, options=[“Chiusura”, “Massimo”, “(Massimo + Chiusura) / 2″], group=”Segnale Rialzista”)

// Selezione del tipo di prezzo per il segnale Ribassista
bear_source_type = input.string(“Chiusura”, title=”Prezzo segnale Ribassista”, options=[“Chiusura”, “Minimo”, “(Minimo + Chiusura) / 2″], group=”Segnale Ribassista”)

// Visualizzazione e stile
show_bull = input.bool(true, title=”Mostra freccia rialzista”, group=”Stile”)
show_bear = input.bool(true, title=”Mostra freccia ribassista”, group=”Stile”)

// ==========================================
// CALCOLI E LOGICA
// ==========================================

// Determinazione della sorgente per il segnale rialzista
float bull_price = na
if bull_source_type == “Chiusura”
bull_price := close
else if bull_source_type == “Massimo”
bull_price := high
else if bull_source_type == “(Massimo + Chiusura) / 2”
bull_price := (high + close) / 2.0

// Determinazione della sorgente per il segnale ribassista
float bear_price = na
if bear_source_type == “Chiusura”
bear_price := close
else if bear_source_type == “Minimo”
bear_price := low
else if bear_source_type == “(Minimo + Chiusura) / 2”
bear_price := (low + close) / 2.0

// Calcolo del Massimo dei Massimi e del Minimo dei Minimi delle candele precedenti (escludendo la candela attuale [1])
highest_high = ta.highest(high[1], lookback)
lowest_low = ta.lowest(low[1], lookback)

// Condizioni di breakout
bull_signal = bull_price > highest_high
bear_signal = bear_price < lowest_low

// ==========================================
// TRACCIAMENTO SUL GRAFICO
// ==========================================

// Freccia Verde (Rialzista) SOTTO la candela con punta verso l’alto
plotshape(
series=show_bull and bull_signal,
title=”Segnale Rialzista”,
style=shape.arrowup,
location=location.belowbar,
color=color.green,
size=size.small
)

// Freccia Rossa (Ribassista) SOPRA la candela con punta verso il basso
plotshape(
series=show_bear and bear_signal,
title=”Segnale Ribassista”,
style=shape.arrowdown,
location=location.abovebar,
color=color.red,
size=size.small
)

Golden Cross for Proreal Time – optimizing by using EMA or SMA

// Condizioni per entrare su posizioni long
DEFPARAM cumulateorders = false
ma1 = ExponentialAverage[breve](totalprice)
ma2 = ExponentialAverage[lungo](totalprice)
ma01 = Average[breve](totalprice)
ma02 = Average[lungo](totalprice)
// dummy = 1 per EMA veloci, = 0 per SMA
IF dummy = 1 and NOT LongOnMarket AND ma1 crosses over ma2 THEN
BUY 20000 CASH AT MARKET
elsif dummy = 0 and NOT LongOnMarket AND ma01 crosses over ma02 THEN
BUY 20000 CASH AT MARKET
ENDIF

if longonmarket and dummy = 1 and ma1 crosses under ma2 then
sell at market
elsif longonmarket and dummy = 0 and ma01 crosses under ma02 then
sell at market
endif
graphonprice ma1 coloured(0,51,153) as “media veloce EMA”
graphonprice ma2 coloured(255,77,6) as “media lunga EMA”
graphonprice ma01 coloured(0,71,171) as “media veloce SMA” // blu cobalto
graphonprice ma1 coloured(55, 165, 0) as “media lunga SMA” // arancione

**VARIABLES : breve 10 – 80 step 5 – lungo 20,220 passo 10 – dummy 0,1 step 1


BACKTEST su 5000 barre 0,3% commissione 20 Ek fissi – FREE
(2Ema o 2Sma ott), 25 march 2025

TEXAS INSTRUMENTS
guadangno +319%
max drawdonwns 10%
runup 417%
Coppie dummy = 0 80,130 75,110 80,140

CREDEM
guadangno +257%
max drawdonwns 29%
runup 210%
dummy = 0 10,200 70,200 10,190

FINECOBANK
guadangno +277%
max drawdonwns 28%
runup 160%
dummy = 0 20,90 35,40 25,50

ZALANDO
guadangno +213%-426%
max drawdonwns 25%
runup 220%
dummy = 0 75,70 75,60 25,40

DANIELI
guadangno +1787
max drawdonwns 31%
runup 1213%
dummy = 1 10,190 10,200 15,190

1MICROSOFT
guadangno +437%
max drawdonwns 18%
runup 250%
dummy = 0 40,200 e 0 70, 180 e d= 1 40,90

.ITF file

Create your own target price – Tradingview Code

In fundamental analisys investors rely on “recommendation”: however, in many cases, professional anaysts use a technique with a marginal logic, i.e. they adjust progressively their last target prices. This could lead to “historical” price indications that are very far from the real situation (especially in the event of large drops in profit). Therefore, the indicator uses the EPS ttm and the historical P/E ration of the last 2 years (markets have “no memory”) to be able to set your personal target price and return that adjusts that of analysts. In the case of “big opportunities” it is always necessary to ask oneself whether personal evaluation is not “out of the market”. 

//@version=4

study(“Calcolo Target Price e Rendimento”, shorttitle=”Target Price”, overlay=true)

// Funzione per calcolare il P/E ratio

pe_ratio(eps) =>

 close / eps

// Funzione per calcolare il massimo P/E degli ultimi 2 anni

max_pe_2_years(eps) =>

 var float max_pe = na

 if (not na(eps))

 max_pe := na(max_pe) ? pe_ratio(eps) : max(max_pe, pe_ratio(eps))

 max_pe

// Input dell’EPS TTM

eps_ttm = input(defval=2.0, title=”EPS TTM”, type=input.float)

// Calcolo del massimo P/E degli ultimi 2 anni

max_pe = max_pe_2_years(eps_ttm)

// Calcolo del target price

target_price = max_pe * eps_ttm

// Calcolo del rendimento del target price rispetto al prezzo corrente

rendimento = (target_price / close) – 1

// Plotta il target price e il rendimento come linee separate

plot(target_price, title=”Target Price”, color=color.blue, linewidth=2)

// Aggiungi una freccia sull’ultimo prezzo che indichi il rendimento

var label rendimento_label = na

if (not na(rendimento))

 if (not na(rendimento_label))

 label.delete(rendimento_label)

 rendimento_label := label.new(bar_index, close, text=”Rendimento: ” + tostring(rendimento * 100, “#.##”) + “%”, xloc=xloc.bar_index, yloc=yloc.price, color=color.blue, textcolor=color.white, style=label.style_label_down, size=size.small)

———— Image from Tradingview with analysts’ target price (Price target indicator)———–

simple moving average tradingview created with Copilot / Semplice strategia a fascio di medie mobili creata con l’aiuto di Copilot

//@version=5

strategy(“IA MA 20 50 200”, overlay=true, overlay=true, initial_capital=20000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value=0.25)

// Parametri personalizzabili

periodo_ma_20 = input.int(20, title=”Periodo MA 20″)

periodo_ma_50 = input.int(50, title=”Periodo MA 50″)

periodo_ma_200 = input.int(150, title=”Periodo MA 150/200″)

stop_loss_percentuale = input.float(10, title=”Stop Loss %”) // Percentuale di Stop Loss

data_inizio = timestamp(2018, 1, 1, 0, 0) // Data di inizio negoziazioni

// Calcolo delle medie mobili

ma20 = ta.sma(ohlc4, periodo_ma_20)

ma50 = ta.sma(ohlc4, periodo_ma_50)

ma200 = ta.sma(close, periodo_ma_200)

// Condizioni di acquisto

incrocio_rialzo = ta.crossover(ma20, ma50)

prezzi_sopra_ma200 = close > ma200

incroci_passati = 0

condizione_acquisto = ta.crossover(ma20, ma50) and prezzi_sopra_ma200 and (time >= data_inizio)

// ATTENDERE 2 INCROCI PASSATI SAREBBE LA MIGLIORE

//if (ta.crossover(ma20, ma50)) and (close < ma200)

//    incroci_passati := incroci_passati + 1

//condizione_acquisto_sotto_ma200 = ta.crossover(ma20, ma50) and incroci_passati >= 2 and close < ma200 and (time >= data_inizio)

// Acquisto

if condizione_acquisto //or condizione_acquisto_sotto_ma200

    strategy.entry(“Acquisto”, strategy.long)

// Condizioni di vendita

condizione_vendita = ta.crossunder(ma20, ma50)

// Vendita

if condizione_vendita

    strategy.close(“Acquisto”)

// Stop Loss

if (strategy.opentrades > 0)

    strategy.exit(“Stop Loss”, from_entry=”Acquisto”, stop=close * (1 – stop_loss_percentuale / 100))

— Commento: sarebbe stato poter implementare anche un “ritardo” di qualche barra nell’esecuzione dell’ordine ma non ci sono riuscito

Up/Down Volume Coeherent Strategy (Tradingview)

strategy(“Up/Down Volume Coeherent Strategy”, overlay=true, initial_capital=20000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value=0.003)

//@version=5

// Inputs

startDate = input.time(timestamp(“2014-01-01 00:00″), title=”Data di inizio backtest”)

endDate = input.time(timestamp(“2024-11-24 23:59″), title=”Data di fine backtest”)

targetProfit = input.float(50, title=”Target Profit (%)”, step=0.1) / 100

stopLoss = input.float(8, title=”Stop Loss (%)”, step=0.1) / 100

// Indicator

lowerTimeframeTooltip = “The indicator scans lower timeframe data to approximate Up/Down volume. By default, the timeframe is chosen automatically. These inputs override this with a custom timeframe.\n\nHigher timeframes provide more historical data, but the data will be less precise.”

useCustomTimeframeInput = input.bool(true, “Use custom timeframe”, tooltip = lowerTimeframeTooltip)

lowerTimeframeInput = input.timeframe(“D”, “Timeframe”)

upAndDownVolume() =>

    posVol = 0.0

    negVol = 0.0

    switch

        close >  open     => posVol += volume

        close <  open     => negVol -= volume

        close >= close[1] => posVol += volume

        close <  close[1] => negVol -= volume

    [posVol, negVol]

lowerTimeframe = switch

    useCustomTimeframeInput => lowerTimeframeInput

    timeframe.isintraday    => “1”

    timeframe.isdaily       => “5”

    => “60”

[upVolumeArray, downVolumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, upAndDownVolume())

upVolume = array.sum(upVolumeArray)

downVolume = array.sum(downVolumeArray)

delta = upVolume + downVolume

plot(upVolume, “Up Volume”, style=plot.style_columns, color=color.new(color.green, 60))

plot(downVolume, “Down Volume”, style=plot.style_columns, color=color.new(color.red, 60))

plotchar(delta, “delta”, “—”, location.absolute, color=delta > 0 ? color.green : color.red, size=size.tiny)

c1long = (close > open and delta[2] < 0 and delta[1] > 0 and delta > 0)

c1short = (delta[2] > 0 and delta[1] < 0 and delta < 0)

plotshape(c1long ? low : na, title=”Buy”, text=”Buy”, location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)

plotshape(c1short ? high : na, title=”Sell”, text=”Sell”, location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)

// Strategy Logic

if (time >= startDate and time <= endDate)

    if (c1long)

        strategy.entry(“Long”, strategy.long)

    if (strategy.position_size > 0)

        stopPrice = strategy.position_avg_price * (1 – stopLoss)

        targetPrice = strategy.position_avg_price * (1 + targetProfit)

        if (close < stopPrice)

            strategy.close(“Long”, comment=”Stop Loss”)

        if (close > targetPrice)

            strategy.close(“Long”, comment=”Target Profit”)

    if (c1short)

        strategy.close(“Long”, comment=”Sell Signal”)

Up/Down Volume Coeherent : indicator for Tradingview

//@version=5

indicator(“Up/Down Volume Coeherent”, “Up/Down Vol Coeherent”, format=format.volume)

lowerTimeframeTooltip = “The indicator scans lower timeframe data to approximate Up/Down volume. By default, the timeframe is chosen automatically. These inputs override this with a custom timeframe.

 \n\nHigher timeframes provide more historical data, but the data will be less precise.”

useCustomTimeframeInput = input.bool(true, “Use custom timeframe”, tooltip = lowerTimeframeTooltip)

lowerTimeframeInput = input.timeframe(“D”, “Timeframe”)

upAndDownVolume() =>

    posVol = 0.0

    negVol = 0.0

    switch

        close >  open     => posVol += volume

        close <  open     => negVol -= volume

        close >= close[1] => posVol += volume

        close <  close[1] => negVol -= volume

    [posVol, negVol]

lowerTimeframe = switch

    useCustomTimeframeInput => lowerTimeframeInput

    timeframe.isintraday    => “1”

    timeframe.isdaily       => “5”

    => “60”

[upVolumeArray, downVolumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, upAndDownVolume())

upVolume = array.sum(upVolumeArray)

downVolume = array.sum(downVolumeArray)

delta = upVolume + downVolume

plot(upVolume, “Up Volume”, style = plot.style_columns, color=color.new(color.green, 60))

plot(downVolume, “Down Volume”, style = plot.style_columns, color=color.new(color.red, 60))

plotchar(delta, “delta”, “—”, location.absolute, color = delta > 0 ? color.green : color.red, size = size.tiny)

c1long = (close > open and delta[2] <0 and delta[1]> 0 and delta >0)

c1short =  (delta[2]> 0 and delta[1] <0 and delta<0)

plotshape(c1long? low: na, title=”Buy”, text=”Buy”, location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)

plotshape(c1short? high: na, title=”Sell”, text=”Sell”, location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)

var cumVol = 0.

cumVol += nz(volume)

if barstate.islast and cumVol == 0

    runtime.error(“The data vendor doesn’t provide volume data for this symbol.”)

Halfband (hi-lo middle) 2024 trading system – in support for investments

Here is the transformation of the the trading system presented on 1.1.2024 in this blog in Prorealcode for Proreal time:

Please notice the very few lines of code

// from sauciusfinance post of 1.1.2024
halfband = (High[n]+low[n])/2

// default n = 1
centry = close CROSSES OVER halfband
centry2 = close > open
// Condizioni per entrare su posizioni long
IF NOT LongOnMarket AND centry and centry2 THEN
BUY 20000 cash AT MARKET
ENDIF
cexit = close CROSSES under halfband
// Condizioni per uscire da posizioni long
If LongOnMarket AND cexit THEN
SELL AT MARKET
ENDIF

// Stop e target: Inserisci qui i tuoi stop di protezione e profit target
set target %profit pr
set stop %loss lo

graphonprice halfband

Halfband (=hi-lo middle value) Trading System in support for investments (2024)

First of all, Happy New 2024 and a big hug to Japanese friends… we hope all ok for you all.

This is a very effective system in support for entries and exits for swing traders and investments (i.e. if you want not to see graphs everyday but only once or twice per week and you want to keep a position for some days or weeks). This system beats continually the lazy but good “Buy and Hold” for many and many stocks.

Just Trade in these stocks:

  • * Trade stocks with a ROE> 20% (it depends in the purpose of your investments, but you may select a more ambitious 30%, but there are more risks for going lower than going higher). – Tradingview stock screener is a great help for all market (not only U.S. like Finviz) – Do not regard of any other indicator, like P/E, analysts’ opionions and target price and so on. The behaviour of the market is collapsed into prices movements, and in this technical analsys
  • * Entry when close overcomes the average of the high and low of the last but one bar on weekly chart (=so called “Halfband“). There is a filter of a “green bar” (close > open) for the last bar, i.e. the overcome should not due to a so low level of the halfband (typical in falling markets).
  • * Since in the trading system the order are placed at the opening of the next bar, but the instructions calc_on_order_fills=true is critical, before entry a position check only if the monday’s open (or of first day of the week of market opened) is not below “Haldfband”. Otherwise, stay flat

EXIT the market

  • * in case of a fixed stop loss (risk management), in trading system = 7%
  • * if close is under Haldfband.

The system is very simple, but effective. You don’t need any I.A. or trading machines to implement it. You may do it manually and take into observation dozens of stocks, since analysis is very quick and collapsed in just one or two moment a week.

TRADINGVIEW CODE (fundamental passages are in bold)

//@version=5

strategy(title=’Halfband 2 W_lo’, overlay=true, precision=4, calc_on_order_fills=true, calc_on_every_tick =true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=20000, currency=currency.EUR, commission_type=strategy.commission.percent, commission_value=0.25)

period_ = input.int(1, title=”Length”, minval=1)

halfband = (high[period_]+low[period_])/2

plot(halfband, title=”halfband”, color=color.rgb(243, 222, 33), linewidth = 2, style=plot.style_stepline, precision = 4)

// === INPUT BACKTEST RANGE ===

fromMonth =  input.int (defval = 1, title = “From Month”, minval = 1, maxval = 12)

fromDay =  input.int (defval = 1, title = “From Day”, minval = 1,maxval = 31)

fromYear = input.int(defval = 2022, title = “From Year”,   minval = 1970)

thruMonth = input.int(defval = 1,    title = “Thru Month”,  minval = 1, maxval = 12)

thruDay   = input.int(defval = 1,    title = “Thru Day”,    minval = 1, maxval = 31)

thruYear  = input.int(defval = 2112, title = “Thru Year”,   minval = 1970)

// === FUNCTION EXAMPLE limit for backtest ===

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)            // backtest start  window

finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)            // backtest finish window

window()  => time >= start and time <= finish ? true : false           // create function “within window of time”

// entries: version 2 variant is here, in xentryl

Entry1= ta.crossover(close, halfband) and window()

Entry2 = close> open

xentryl = Entry1 and Entry2

xentrys = ta.crossunder(close, halfband) and window()

strategy.entry(‘Long’, strategy.long, when= xentryl)

strategy.close(‘Long’, when=xentrys, comment=’change’)

// MONEY MANAGEMENT

lossp = input.float(7, minval=1, step=1)

losspel = strategy.position_avg_price * (1 – lossp / 100)

fixed_stop_long = close < losspel

strategy.close(‘Long’, when=fixed_stop_long, comment = ‘Stop loss’)