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

Trading system classici, automatici vs nuovi indicatori – Classical, automatic trading systems vs new indicators

Trading yesterday and today: considerations of trading systems and on the work done in the last 4 years

Perhaps this is the most important post of all: as you can see in my blog over the past 4 years I have “translated” in ProRealTime code all the newest proposed indicators of Stocks & Commodities, magazine “leader” in technical analysis.

Why only the “Indicators” (with the concerning section of S & C)?
1 Because are the quickest and rational (ie quantifiable) device to analyze a market
2 Because the so-called “figures” are always subject to the discretion and human interpretation (unless massive simplifications that can be misleading)
3 Because, therefore, money management can be managed in a rational manner since it’s written in formula.

I have developed a trading system, periodically updated, in order to “capture” the beginning of a trend and to “stay” in position until the end, maximizing profits and minimizing errors in input and output, as well as any false signals.

The result was certainly a good system … but suitable for “secondary” daily trends (non-primary), as well as non-adaptable (at least easily) to automated trading.

Instead, the use of classic indicators, in particular for the Italian market (but also for the German and American one), led to the construction of a simple trading system, especially shared by operators since it refers to the indicators known to the public (MACD and SAR).
My job was simply to adapt the parameters of these indicators to the target market.

The logic is the following (very simple):
Open position (long or short) when prices (usually, closing) crosses the SAR (under the constraint that prices are above / below the 20-period moving average)
– Close (and reverse) position if prices cross the SAR or the moving average or if the lines of the MACD cross

Usually the authors of technical analysis follow a contrary rule, using the indicators MACD for open positions and SAR as stop loss, but so it distorts the logic with which it was born the Parabolic SAR.

A more “dynamic”system – in the course of testing (with good anticipations) –  consists in opening positions on the basis of the histogram of the MACD (and not on the basis of its lines as before) when they reach the points of maximum and local minimum.
In detail, long positions should be opened as soon as the MACD histogram retraces from the minimum (ie, begins to grow), even if the prices are below the SAR or the MMA20.
Vice-versa for short positions.
The closure and the reversal of portfolio follow the same rule, in reverse.
This technique is based on the local maxima / minima of the MACD can generate false signals on the 1st retracing (so … be careful!) but it is infallible on 2nd tracing, that is, you are “armored” when you see the so-called figure of the (double) camel hump.

The standard parameters are as follows:

– SAR: 0.01, 0.01, 0.1 with a best version (best) with acceleration factor 0.02 or 0.03  (for inputs and outputs a bit ‘more’ tempestive2)
– MACD: 9,15,10 but also in the classic version (12,26,9) or 11,3,5 (for fast trading) or 11,15,9

[see DAX and FTSEMIB charts]

In conclusion, it is sufficient to set the parameters of SAR and MACD and the game is done (for all markets and all time frames): we have much lighter trading system, – I repeat – “shared” and no substantial differences in profit.
Why this result? Because the environment (domain) in which we operate, ie the data provided by the market and then to the brokers and finally to individuals, it is – as you know – very “poor”: O, H, L, C and volume, but nothing more.
Even the linear treatment through the various indicators of these numbers can not offer, therefore, so “different” results or offer “quantum leaps” in the analysis.

OPERATIONAL NOTES
In the next posts I will indicate some formulations of trading system:
– A suggestion (and sometimes necessity) is to create by yourself formulas for a single line of MACD or its histogram (in order to recall them in the trading system without errors).
– The points of local maximum and minimum can be found with the inverse cotangent (see previous post), function unfortunately not supported in ProRealTime.
The adaptation of the system of “camel humps”, as described above, also using functions that calculate the differences of the MACD histogram, can not find a faithful representation in automated trading system, but it must be implemented only through manual trading .

Another “investing” trading system on weekly base

In a recent post I’ve published a strategy based upon a monthly pattern.
Good results, but if you want more gains (thus increasing a bit also risks) you may diminish the temporal frame, going into a weekly pattern.
These are the proposed indicators:
 – the “queen”  20-periods moving average (for determining the trend), placed side by side with the 50-periods moving average for determining levels of support and target;
– parabolic sar is used more than keeping position, for fixing “middle” target levels for long/short positions; 
– more “indicative” than psar, is 11-periods RSI, where overcoming the upper/lower bands give a good signal for exiting positions (and therefore a new entrance).
Below some examples (realized on m.prorealtime.com, where the instrument of automatic draw of oblique lines is very useful).
Patter is very easy and works weel with a huge variety of financial instruments (indexes, shares, etc.). The real confirm of the trend is simply the crossing up or down the 20-periods moving average. 
FTSEMIB (Italy)
Comment: Long structure since april 2016: we entered on the reversing of p-sar if we assume a “speculative” approach or, a bit after, on the crossing of the blue line (20-periods mov.avg.). RSI has revealed many “local” stop profit targets (no. 3); this instruments also helps for identifying clearl throwback towards the blue line. 
Recently, the support of 50-p. mov. avg. has avoided the formation of a short structure.
CAC- ALL SHARES (France)
Comment – Very strong long signal in the same period of the previous picture in 2016; no points of uncertainty on keeping long in the last year and half; RSI may have revealed some points of target profit. 
The throwbacks has been always limited to the support of p-sar line or 20-p. mov. avg. 
Simplifying more and more, another conclusion of this pattern is that for reaching good results you may use only 20 and 50 periods moving averages and then comparing the distance among them and the current close and/or the movements of the single/lat 2-3 bars.
I.e.: if the prices are very “distant” to the 20-p. mov. avg. you should except a correction (the probability increases each bar), that may start with a “violent” movement or confirmed by the “lighter” movement of the last 2/3 bars.
In the PAX pictures, there a no strong retracements because prices are increasing steadily: the 20 moving average seems to accompany prices.
L’OREAL (SHARES)

​ 

Comment long from February/March 2016. Clear target in zone 185-190 (see RSI). The decrease of RSI and the support of 50-p. mov. avg. in december 2017 have averted a worsening of the technical framework. Now we are in an oscillating period (use both 20-p. and p-sar for estabilishing levels). Maybe a short period will come soon  

Finding the maximum and minimum of an indicator

Many indicators (like hystogram of the Macd) reach important levels of local maxima/minima that could be useful for trader.
While manual trading does not need a precise formula for finding these levels (since they are visible to the human eye), on the other hand we must define a formula when approaching authomatic trading.

In this field, trigonometrical operators suit at the best sinusoidal function. In simple terms, you have to apply ARCOCOTANGENT formula to your indicator (e.g. Arcctan(Macd_hystogram)).

The Arcctan has the property of reaching level of -n or + n (depending on single situation), when respectvely the indipendent function (= your indicator) reaches local max or min.
This proxy is necessary because many trading programs naturally don’t support the calculation of derivatives function.

So writing a rule when the system has to open/close a position when absolute levels of n are reached is your easy last step.

Unfortunately, ProRealTime supports very few trigonometric function, i.e. sine, cosine, tangent, arctan.

In Tradingview, insted, you have the possibility of using such trigonometric functions.

Avaible for programming in Tradingview and Prorealtime

Hi everybody!! 🍾 
I’ve been contacted by many people after publishing Aroon’s Oscillator Tradingview Strategy (https://www.tradingview.com/script/s462P5NL/?amp
I am avaible, under payment of few euros, to personalization to this strategy and to develop indicators and backtests in
– Prorealtime
– Tradingview
Please, for any request,  please complete the contact form in the blog
Bye! 🖐️
———-————————————————-
Italiano 🇮🇹 

Ciao a tutti !! Sono stato contattato da molte persone dopo aver pubblicato la strategia Oscillator Tradingview di Aroon (https://www.tradingview.com/script/s462P5NL/?amp) Sono disponibile, dietro pagamento di pochi euro, alla personalizzazione di questa strategia e allo sviluppo di indicatori e backtests in 
– Prorealtime 
– Tradingview 

Per ogni richiesta, prego completate il form di contatto nel blog
Ciao! ️

“Revenge trading system” 2019 Strategy in Tradingview – use Triangular M.A. Bands (moving bands) like a trading system

TRADINGVIEW CODE

This system is long only, given the temporary extension of market of being long and not short (in extension ,you can prove to develp an inverse t.s. for short case)
————————————————————————-
//@version=2
////////////////////////////////////////////////////////////
//  Copyright by Saucius, 2019
////////////////////////////////////////////////////////////
strategy(title=”Revenge Long Saub bands only shares easy”,overlay = true,max_bars_back=2000)
Length = input(9, minval=1)
m = input(0.9, minval = 0.1, step = 0.1)
l1 = Length/2
l2 = round(l1)
l3 = Length – l2
TRIMH = sma(sma(high, l2), l3)
TRIML = sma(sma(low, l2), l3)
xHighBand = (1+m/100) * TRIMH
xLowBand = (1-m/100) * TRIML
halfband = (xHighBand + xLowBand)/2
// classical entry: like Keltner Channel, when close breaks upper Band
strategy.entry(“Long”, true, when=crossover(close,xHighBand))
// entry #2 from  the bottom: 2 closes upon inferior band. This means: if prices are lower than the Lower Band and the close confirms consecutevely twice to be over, it’s a good entry point, even if the trend is not clear again.
entry2 = close[2]<xLowBand[2] and close[1]>xLowBand[1] and close>xLowBand
strategy.entry(“Long”, true, when= entry2)
// exit at market cases:
//1. classical exit (like Keltner Channel, when prices are under the lower band
//2. “moderated” exit : when close is confirmed twice under the halfband (halfband is quite similar to a moving average)
//3. “scalping” exit: when prices retrace or go under the HigherBand. This exit is warmly suggested when you have opened in the #2 way, “from the bottom”, since it’s probable that there is a godd gain yet.
//. 4 when CCI reaches extreme values (you don’t need any confirm that prices are high enough)
// exit 2 = 2 close under halfband
exit2 = close[1] < halfband[1] and close < halfband
strategy.close(“Long”, when=crossunder(close, xHighBand))
strategy.close(“Long”, when=crossunder(close,halfband))
strategy.close(“Long”, when=crossunder(close, xLowBand))
//
CCIX = cci(close,20)
strategy.close(“Long”, when= (CCIX > 200 ))
———————–
GOOD TRADE and let me know if you lieke My Bands!!!

Swing Trading – Pro Real Formula!!! vs Ninjatrader 0 -1

After reading,

Swing Trading With Three Indicators

better using a classical and simpler system…with more efficacy
(k.i.s.s. = keep it simple stupid!!)

In Italian market I’ve experienced a RWI (5)  – Random Walk Index – on 5 days is very strong for swinging

In DAX the import of Ninja script has given hi results not for 5 periods, but for 6.

Change position long or short when the 1st balloon appears (even if points on the other sides are still present).
This indicator is quicker than combination supertrend + Vortex

Very, very nice!

Swing Indicator simple 

rd = 0
// Swing high
c1 = high[1] >= high AND high[1] >= high[2]

// Swing low
c2 = low[1] <= low AND low[2] >= low[1]

//c1 short, c2 long , c3 both, c4 nothing  (so we continue)
IF c1  THEN
d = high[1]
ELSIF c2  THEN
d = low[1]
else
d = d[1]
ENDIF

return d

Draw the indicator “d” as line+points
Change system position when swiing indicator 

This is the result:

For reducing noise, let’s introduce a n period, a local are where the test of the swing lows and highs should be tested


N-PERIOD SWING TRADING

// definition http://www.investopedia.com/terms/s/swinghigh.asp

// detecting SWING HIGHS AND LOWS in a period of ray “n”

d = 0
// Swing high
m = n + 2
him = highest[m]
c1 = high[1] >= him and high[1] >= high

// Swing low
lom = lowest[m]
c2 = low[1] <= lowest[n] and low[1]<=lom

//c1 short, c2 long , c3 both, c4 nothing  (so we continue)

IF c1  THEN
d = high[1]
ELSIF c2  THEN
d = low[1]
else
d = d[1]
ENDIF

return d

STRATEGY: enter long or short when condition change, i.e. when after a swing low(high) situation we pass to swing low(hi) situation, i.e. when swing indicator cut price (close price).
For instance, we do not change strategy 

NB: We have the same result of ninjatrader, but the optical effect is different


Well, it’s not the same BECAUSE PRO REAL TIME doesn’t have a correction for mantingale lines.I mean, the program does not accept the introduction of a variabile that gives the result constant in case of trend.

VERY NICE INDICATOR BUT ONLY IN NINJA TRADER, NOT IN pro Real time…

this is really not a succeSS!!!

Rediscovering volume: a proscreener proposal selection formula

Volume is really the engine of a market.
As stated in any site of trading, it is used:
– as anticipatory of price changes
– as confirmation for a change in trends in progress

Volume, unfortunately, is not avaible for all market: it is a good device for stocks and indexes.

Studying many indicators based upon prices and/or volume could be misleading and a trading desk could suffer of an “expensive” delay.

Here is a proposal for proscreener for a manual graphical analisys.
It extracts the titles whose the volume in the last bar is the maximum of the last twenties. It orders the stocks (or the financial instruments) by increase in percentage



 v1 = Volume

c1 = (v1= highest[20](v1))

criteria = Volume/Volume[1]-1

SCREENER[c1] (criteria AS “Volume perc”)

Here are some examples:

 
going long on Unilever:
















 long in Premuda at last





A new suggested strategy for investors (monthly)

For those who don’t want to be traders, following market everyday I suggest this strategy (only on technical basis, even in if the consultation of fundamentals and starcapital.de would be of great help):

– Use monthly graph
– enter with a cross of standard Parabolic Sar
– close when Aroon(7)gives a signal (undergoes line 70 or cross the other line) or when P-Sar crosses the line price (the first of 2). You can remove the Aroon rules if you don’t want to be histeric: a close far from the minimum or the maximum of the current month is just a good signal.

Don’t mind 20 periods-Moving Average Line.

Take position at the beginning of next month or in the very few days of the current month (after 25th of each month).

PS: I’ve tested a strategy based upon daily positions in accordance with monthly movement (e.g. in the last days of the graph I’ve opened only long positions), but it gives bad results.
You stay or on the months or in the days: do not use both!

Good swing trading : 2 alternative easy techniques

1) USING SAUCIUS’ BANDS:

Bands are set at 12 = period, multiplier = 2

-Enter long or short when prices crosses middleband. Exit long if close crosses under highband and viceversa, for lowband, in short case.
-Enter again if close is over previous close before closing long/short position (i.e. when prices come in the band again).
-Stop loss when close cross middleband (that is the “trigger line”): Stop and Reverse mode in this case!


2) Using simply a Heikin Ashi graph
Go long after a blue bar and viceversa for short (red one). Stop and reverse always (in the same morning). No other rule. Please notice almost 1/2 of entering are not correct.