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’)

Parabolic Sar trading system code ..for “a new life” (easy and profitable) – Tradingview e ProrealTime coding

Just a simple Parabolic Sar to make your life easy..

PROREALTIME TRADING SYSTEM CODE// Definizione dei parametri del codice
DEFPARAM CumulateOrders = False // Posizioni cumulate disattivate

// Condizioni per entrare su posizioni long
indicator1 = SAR[0.02,0.02,0.2]
c1 = (close CROSSES OVER indicator1)
c2 = (close >= DOpen(0))
// c2 is “green bar” condition
c3 = (close >= DHigh(1))

IF c1 AND c2 AND c3 THEN
BUY 20000 CASH AT MARKET
ENDIF

// Condizioni per uscire da posizioni long
indicator2 = SAR[0.02,0.02,0.2]
c4 = (close CROSSES UNDER indicator2)
indicator3 = SAR[0.02,0.02,0.2]
c5 = (close <= indicator3[1])

IF c4 AND c5 THEN
SELL AT MARKET
ENDIF

// no other money management

PROREALTIME SCREENER (you can use it once a week, for instance, not everyday)

indicator1 = SAR[0.02,0.02,0.2]
// you have to write every cicle, since Proscreener doesn’t “read” cycle instruction “for.. to”

// giorno oggi
C1 = (close CROSSES OVER indicator1)
c2 = (close > high[1])
c3 = (close > open)
c4 = (c1 and c2 and c3)
if c4 then
i = 0
endif
// ieri
C10 = (close[1] CROSSES OVER indicator1[1])
c20 = (close[1] > high[2])
c30 = (close[1] > open[1])
c40 = (c10 and c20 and c30)
if c40 then
i = 1
endif
// 2 giorni fa
C100 = (close[2] CROSSES OVER indicator1[2])
c200 = (close[2] > high[3])
c300 = (close[2] > open[2])
c400 = (c100 and c200 and c300)
if c400 then
i = 2
endif
// 3 giorni fa
C1000 = (close[3] CROSSES OVER indicator1[3])
c2000 = (close[3] > high[4])
c3000 = (close[3] > open[3])
c4000 = (c1000 and c2000 and c3000)
if c4000 then
i = 3
endif
// 4 giorni fa
C10000 = (close[4] CROSSES OVER indicator1[4])
c20000 = (close[4] > high[5])
c30000 = (close[4] > open[4])
c40000 = (c10000 and c20000 and c30000)
if c40000 then
i = 4
endif
// 5 giorni fa
C100000 = (close[5] CROSSES OVER indicator1[5])
c200000 = (close[5] > high[6])
c300000 = (close[5] > open[5])
c400000 = (c100000 and c200000 and c300000)
if c400000 then
i = 5
endif
// 6 giorni fa
C1000000 = (close[6] CROSSES OVER indicator1[6])
c2000000 = (close[6] > high[7])
c3000000 = (close[6] > open[6])
c4000000 = (c1000000 and c2000000 and c3000000)
if c4000000 then
i = 6
endif
SCREENER[c4 or c40 or c400 or c4000 or c40000 or c400000 or c4000000] (i as “day”, volume as “volume”)

TRADINGVIEW TRADING SYSTEM

//@version=5
// versione 20 redatta 1702 2022
strategy(‘psar_newlife_2023’, calc_on_order_fills=false, calc_on_every_tick=true, commission_type=strategy.commission.percent, commission_value=0.3, overlay=true, default_qty_type=strategy.cash, default_qty_value=20000, initial_capital=20000)
// === 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 = 2017, 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”

//INDICATORI
startsar = input(0.02, “Inizio Sar”)
increment = input(0.02, “Incremento Sar”)
maximum = input(0.2, “Max Sar”)
mysar = ta.sar(startsar, increment, maximum)
plot(mysar, “ParabolicSAR”, linewidth=2, style=plot.style_cross, color=#2962FF)
//sistema (come prorealtime)
c1 = ta.crossover(close,mysar)
c2 = close > open
c3 = close > high[1]
entryl = (c1 and c2 and c3)
strategy.entry(‘Long’, strategy.long, when=entryl)
c4 = ta.crossunder(close,mysar)
c5 = (close < mysar[1])
exit = (c4 and c5)
strategy.close(‘Long’, when=exit)
// altri disegni
mysma = ta.sma(ohlc4,20)
plot(mysma, title=’Media mob’, color = color.rgb(238, 0, 255), linewidth=1, style=plot.style_line)
//Go Saucius Go!!

————————————————————————–

Strategy Pine Script™ – Triband_Long Only for supporting Investments

Tradingview: guide for beginners

Investors very often correctly select stocks using fundamental analysis. However, the strategy suffers from shortcomings from a “momentum” perspective.
This simply system – which I recommend applying on a monthly basis – is simple and very effective: it uses a simple average of the opening, maximum and minimum of the currentmonth’s candle and compares it with the closing of the current month. If prices are higher than this average you enter/stay in the market, otherwise you exit. Since it is designed to support investment, short operations are not foreseen. In this way the performance compared to simple buy & hold is much improved.
If you want no to use strictly the strategy, however you may check week by week how prices are distant from this average.
You may also decide the period for backtesting.

CODE

//@version=5

strategy(title=’Triband_Long Only for Investments’, overlay=true, precision=4, calc_on_order_fills=true, calc_on_every_tick =true, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=100000, currency=currency.EUR, commission_type=strategy.commission.percent, commission_value=0.25)
// by Sauciusfinance

period_ = input.int(1, title=”Length”, minval=1)
halfband = (high[period_]+low[period_]+open[period_])/3
plot(halfband, title=”halfband”, color=color.blue, linewidth = 2, style=plot.style_stepline)

// === 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”

// entries

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

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

strategy.close(‘Long’, when=xentrys, comment=’chiudi’)
// MONEY MANAGEMENT
lossp = input.float(8, 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’)