Pinescript
Tips And Tricks In PinescriptConclusion
I’am starting with the conclusion since i don’t plan to be on tradingview for some time. Pinescript is a really easy to use and learn language and i had a lot of fun writing all my indicators, i remember the first time i used it, it was a really nice day and i opened the script editor to edit the awesome oscillator indicator, i changed the sma to an ema, how cute, changing a letter, i was 16.
However we made a lot of progress in three years, i have often heard that i was a prolific, creative and talented indicator maker, and since my only goal in tradingview was to share and help people, i will leave all the tips and tricks related to pinescript i have to help you make great indicators.
Show the code
When publishing you can hide the code of your indicator, my first tips is to always show the code of your indicator/strategy except if you have a really good reason to hide it. Showing your code can help other people spot errors thus making you improve. If you think that your code is the holy grail and this is why you have to hide it i must tell you that there are a lot of researchers publishing papers that you can read about machine learning and other mega complex stuff applied to financial markets. At the end sharing is caring so share everything from your indicator !
Structure Your Code
Its common to make an indicator, save it, and start a new project from scratch, then if you come back to the saved indicator you can get lost, this happened with me several times. First create sections in your code, then delimit each section with a commentary, commentaries can be made in pine with //, i personally use //---- but you can use whatever you want like //ma section or //plots etc. The name of your variables can also be important, i’am conformable with an alphabet like variable declaration. Therefore you could structure you code like this :
study(…..)
length = input(14)
//----
a = …
b = …
c = …
//----
plot(…)
So try to find a structure style such that you will be confortable with :)
Making Different Types Of Filters in Pine
There are different types of filters, i explain each ones in my post Digital Filters And DSP . Here is the code to compute all common types of filters :
low-pass (lp) = lp(x)
high-pass (hp) = x - lp(x)
bandpass (bp) = lp(x - lp(x))
band-reject (br) = x - lp(x - lp(x))
with a simple moving average this give you :
low-pass moving average = sma(close, length)
high-pass moving average = x - sma(x, length)
bandpass moving average = sma(x - sma(x,length),length)
bandreject moving average = x - sma(x - sma(x,length),length)
This is a easy way to compute each filters types. You can use other filters types instead of the simple moving average.
Understand The Exponential Window Function
The exponential window function is my favorite equation and in my opinion one of the most elegant thing i had the chance to use. This window function is widely used and have the following form :
alpha*x + (1-alpha)*y
or
y + alpha*(x - y)
alpha is called a smoothing constant, when a = 0.5 you are just computing the average between x and y because a = 0.5 and 1 - a = 0.5, therefore you end up with : 0.5*x + 0.5*y = (x + y)/2. But the beauty of this function is that as long as a is greater than 0 and lower than 1 you will give more weight to x or y depending of a. There are a lot of indicators using this, the most well known being the exponential moving average.
Rescaling Inputs in A Certain Range
Scaling involve putting the input in a certain range such that the output is always equal or lower than a certain value and always equal or higher than another value, there are several ways to rescale values in a certain range, here are some ways to rescale values in Pine :
rsi(x, length) - rescale values in range of (100,0), higher length will converge the results toward 50, if you don’t want that use smooth values for x.
stoch(x,x,x,length) - rescale values in range of (100,0)
correlation(x,n,length) - rescale values in range of (1,-1)
sign(x) - rescale values in a range of (1,-1), 1 when x > 0 and -1 when x < 0.
x/highest(x,length) - values will always be equal or greater than 0 and equal or lower than 1, when x is high the output will be closer to 1.
lowest(x,length)/x - values will always be equal or greater than 0 and equal or lower than 1, when x is low the output will be closer to 1.
a = change(src,length)
b = abs(a)/highest(abs(a),length) * sign(a) - rescale values in a range of (1,-1)
a/(a + b) - rescale values in a range of (1,0) if a > 0 or (1,-1) if a < 0 as long as a < (a + b)
(x - b)/(a - b) - rescale in a range of (1,0) if x > b and a > x.
see also :
Use operations to scale in a desired range, when the rescaling is in a range (1,-1) use the following operations :
0.5 * rescaling + 0.5 if you want to rescale in a range of
(1 + rescaling) * (maximum/2) if you need a custom range
Use Recursion With The Exponential Window Function
Recursion is the process of using outputs as inputs for a function. Pine allow you to use outputs as inputs thanks to the nz() function. Lets use an example, imagine the following code with the version 2 of pinescript :
a = change(nz(a ,close),9)
This code compute the difference between a and a 9 bars back, now when the code will make the first calculation you want a numerical value for a because a will be equal to na (non attributed), this is why you need to have an initial value (also called a seed) for a and this is what nz() do , attribute a value to a when a = na. By running the code above you will end up with a periodic results, so how can you use recursion with your indicators ? Here the following code example show you how :
alpha = 0.5
a = scale(close, length)
b = function(alpha*a+(1-alpha)*nz(b ,a))
When you want to use recursion in a function you must first declare alpha, alpha can be any value as long as alpha is greater than 0 and lower than 1, then you must scale your input (here the closing price), this is done because depending on the price scale you could get different results when using recursion, when your rescaling range is low (1,0) your results could be more periodic than in a range like (100,0).
function is the function you want to use, if you rescaled the input you should use a function that don’t plot in the chart, if your function is a simple moving average sma or another filter you won’t need to scale the input, however if you use function such as change, rsi, stochastic…or any other oscillator you will need to rescale the values in a certain range. Recursion can help you get smooth, predictive, periodic and reactive results. If you need adaptive results you can even make alpha a variable by rescaling something you want in a range of (1,0), for example :
alpha = scale(tr,length)
a = scale(close)
b = function(alpha*a+(1-alpha)*nz(b ,a))
Create Adaptive Exponential Filters Easily
Adaptive moving averages are greats because market exhibit a dynamical behavior, so adaptivity is a good way to have really great filters. An easy way to have adaptive filters is by using exponential averaging, in short using the structure of an exponential moving average, the ema of x is calculated as follow in pine :
y = alpha*x + (1-alpha)*nz(y ,x)
which can derived to :
y = nz(y ,x) + alpha*(x - nz(y ,x))
where alpha = 2/(length + 1)
As you can see we go back to the exponential window function and thanks to this function the ema is really efficient to compute. An adaptive filter will use a variable alpha instead of a constant one, so as long as 1 >= alpha >= 0 you will get an adaptive filter. If you want to adapt the filter to market volatility just rescale a volatility indicator like the atr in a range of (1,0), in pine this would look like :
alpha = scale(tr,length)
y = alpha*close + (1-alpha)*nz(y ,close)
If you need alpha to decrease when length increase you can divide your rescaling by length, for example if you use the stochastic of the true range as alpha you can make :
alpha = stoch(tr,tr,tr,length)/100 / sqrt(length)
y = alpha*close + (1-alpha)*nz(y ,close)
Create An Adaptive Simple Moving Average
In pine you can compute a simple moving average by using the sma() function :
sma = sma(x,length)
now imagine you want to use a non constant length, like for example the barssince() function, well you can’t because the sms function only work with constant integers, so how can you use non constant integers for calculating an adaptive sma ? Well you can derive the sma formula like this :
length = barssince(cross(close,vwap)) + 1
rsum = cum(close)
asma = (rsum - rsum )/length
Make sure that length is always greater or equal to 1, if length is a float use the round() function :
length = round(barssince(cross(close,vwap)) + 1)
Use Fixnan For Colors
When plotting an indicator with a plot fonction using a condition to change colors, you will have a different color if the indicator value is equal to its previous value, this image describe this case :
with :
a = highest(50)
c = if a > a
lime
else
if a < a
red
plot(a,color=c)
Instead you can use a ternary operator and use fixnan to fix this issue, the plot code look like this :
plot(a,color=fixnan(a>a ?lime:a 4000 ? 1 : 0
b = sma(a,length)
plot(a),plot(b)
The time it takes to the filter to get to the maximum value of the step function will tell you about its reactivity while seeing if the filter exceed the maximum value of the step function will tell you about its overshoot response, after an overshoot the filter can also go back under the step function, this is an undershoot, there are also tons of other things about the step response like ringing, but some only happen with recursive filter like the ema.
In order to check for smoothness against another filter you can use this code :
a = abs(change(filter1))
b = abs(change(filter2))
If you see that filter 1 have overall greater values than filter 2 it means that filter 1 smooth less.
Estimate A Gaussian Filter
You don’t really need fancy math’s to make a gaussian filter, the central limit theorem will help you estimate it just fine. A gaussian filter is a filter which impulse response is a gaussian function (bell shaped curve), a gaussian filter can be approximated with this code :
a = sma(sma(sma(sma(close,length/4),length/4),length/4),length/4)
In short the more sma function you add the better the estimation.
Some Other Tips
You can declare a float by using 0. instead 0.0
You can find the average highest frequency of a signal a with :
b = a > a and a < a or a < a and a > a ? 1 : 0
c = 1/(cum(b)/n) * 2
Learn all the shortcuts, some in mac :
cmd + enter = add to chart
cmd + i = new script
cmd + click on a function = display the reference manual of the function
Double click on one indicator line will display its settings window.
Know some maths, its not a requisite but it sure help.
And finally work and share with a group, its not something that i did but the truth is that it help a lot.
Final Words
I can’t cite all the person i want to thanks, there are to many, but without support its hard to improve, so thank you all. If this article helped you in any way then i’am more than satisfied. Oh and if you want to thanks and support me for all those years just use, change, improve and learn from my indicators as well as sharing your work or knowledge and have a lot of fun, that’s all i want.
Lets conclude this adventure with the memorable thanks for reading !
Week in Review: All of Old. Nothing Else Ever. Except Sometimes.First Off
If you enjoy these weekly publications and would like to keep up-to-date with the latest and greatest scripts, share this article and follow me on TradingView.
No Turning Back Now
Last week the TradingView community made an effort to publish some high-quality, open-source studies and strategies for everyone to benefit from, which in turn required from me a better quality articles on the week. This seemed to be a popular decision and (hopefully) better sponsors the script that I discuss.
This week I’ll try to do more of the same, but in order to improve I’ll need some input from the readers. So please, if you have any suggestions on how to improve these articles, don’t be afraid to express them either in the comments or via a direct message.
In this Week’s Charts
Let’s first mention MichelT’s “Average True Range in pine”. Although the function for the atr() is already available in Pine, it’s handy to understand the math behind the function should you need to circumvent some error messages that TradingView is giving you when using the built-in atr(), or if you wish to modify the formula to fit another purpose.
Speaking of changes to fit another purpose, jaggedsoft’s “RSX Divergence - Shark CIA” takes everget’s “Jurik RSX” and modifies it to include divergences, the code of which was snipped from Libertus’s “Relative Strength Index - Divergences - Libertus”. This implementation calmly spots meaningful anomalies between price action and the oscillator in question.
everget himself was relatively prolific this week, doing what he does best and adding to the open-source repository of moving averages available on TradingView (a repository that he’s had a heavy hand in establishing). This week he’s gifted us the “McNicholl Moving Average”, developed by Dennis McNicholl, as well as the “Quadruple Exponential Moving Average” and the “Pentuple Exponential Moving Average”, both developed by Bruno Nio. It’s great to see him publishing open-source work again and hopefully this continues into the future.
And Left Out of Last Week’s Charts
Last week was probably a more appropriate time to include them, but, alas, I had a (major) oversight. So allow me to give a quick introduction to puppytherapy through the two scripts published in the last week, “APEX - ADX/ADXR/DI+/DI- ” and “APEX - Moving Averages ”. Both are insightful compositions on how to get the most from simple indicators. I look forward to seeing more of his work (and I’ll try, in future, not to disclude good work like what he put out last week)
Milk it for What it’s Worth
I mean, who doesn’t enjoy seeing people apply simple methods to maximum effectiveness? Much like puppytherapy , nickbarcomb’s (a joke some of my Northern Irish friends would appreciate) “Market Shift Indicator” could be a lesson to a lot of us on how to get more from our moving averages and I’ll certainly be applying some of his concepts to develop prototypical signal systems with moving averages in the future.
Someone who’s concepts I’ve borrowed from before with great success is shtcoinr , a user who, along with many others, has appeared regularly in this series. A master of compiling simple and effective S/R indicators (something that was a bit of a mystery to the TradingView community for a while), shtcoinr has done it again with his “Volume Based S/R”, a S/R indicator that paints boxes according to volume activity, and “Grimes Modified MACD Supply Demand”, a modification of his “RSI-Based Automatic Supply and Demand”. shtcoinr has hopefully exhibited to the TradingView community that one can derive S/R areas with almost anything.
Another regular who’s recently released a few scripts that render S/R is RafaelZioni . This week he published his “Hull channel”, which is a creative use of the Hull MA and ATR. Like many of his past scripts, there’s a trove of helpful information buried deep in the code of his work, so don’t hesitate to get your fingers dirty. You’ll likely learn some very helpful things.
Nice to Meet You
Let’s go over some new faces this week, many of whom have brought something genuinely new to the TradingView community.
When I say new faces, I mean new to the series of articles, as many of you are likely very familiar with the psychedelic and, at times, enigmatic work of simpelyfe . This week he released two highly creative, open-source scripts that can have a number of applications; his “Randomization Algorithm ” (which returns a number between 1 - 10 and is a nice alternative to RicardoSantos’s “Function Pseudo Random Generator”) and his “Pivots High/Low ” (with a bit of tinkering this might have an application in automatically painting trendlines). It’s great to see how he does some of his wonderful work and I’ll definitely be following him closely in the future with the hopes of improving my own work.
westikon’s “Time Volume Accum” is (as far as I know) another new indicator to the TradingView community. Unfortunately the very short description is in Russian (I think) and I’m not too sure in what capacity this is supposed to be used, but I’m always looking to get new perspectives on volume and I’ll be studying this idea to do just that.
RyanPhang , also partial to speaking a language I don’t understand, has created , which roughly translates to “Volume drives ups and downs”. Again, not too sure what ideas or systems this pertains to, but (for me anyway) it’s, again, a new way of looking at something old.
Another volume indicator with the bunch is “Better X-Trend / Volume”, published by rimko . This is an iteration of emini-watch’s Better Volume indicator, which is available for purchase through his website. Due to the fact the TradingView doesn’t allow one to glean tick volume, this is as much fidelity rimko can show to the original as possible. Hopefully this will change in the future.
mwlang published “John Ehlers Universal Oscillator ” this week. The purpose of this release was to fix “a degrees to radians bug in LazyBear’s version” of the indicator, something I’m sure Ehlers’ fans will be thankful for.
Call Security
One of the benefits of using TradingView is having access to a wealth of data, but being allowed access to it is not the same as knowing how to get access to it, and even further from getting the most out of it. kishin’s “Mining Cash Flow Line” takes data from Quandl, does some mathemagic and spits out the price that it costs to mine Bitcoin. Knowing how to utilise this kind of data in the future will likely help to seperate the men from the boys, so it’s important we come to understand and learn how to apply it as a community in order to keep our head above water. kishin’s script leads the open-source foray into this unchartered TradingView territory.
Another user that’s made some great use out of Quandl data is deckchairtrader . This week they published “Deckchair Trader COT Index”, “Deckchair Trader COT MACD” and “Deckchair Trader COT Open Interest”. As it was in the paragraph above, this isn’t simply a matter of relaying the raw data from Quandl, but requires running it through a couple functions to get the final result. This is also one of the few scripts that performs fundamental analysis on TradingView.
Do you know what the maximum amount of securities you can call is? It’s 40. Just ask danarm , who’s “Aggregate RSI”, “TDI on Top 40 Coins” and “Top 5 coins cummulated Upvol/Dnvol and Money Flow” (r/increasinglyverbose) call on many securities. Each one can give good insight into the market breadth of any give move and each one invites the user to consider ways they might use the security() function.
At It Again
No doubt you know who I’ll be focusing on this week and regular readers are probably wondering, “where is he?”. But before I start (it’s dasanc by the way), let me say this: since the start of this month to the date-of-writing (27/02/2019) dasanc has published 20 open-source indicators, with (as far as I can count) fifteen of them being completely unique. Most of them are the work of the highly-renowned technical analyst John Ehlers, someone who many, if not all, algo traders are aware of. With four new open-source scripts under his belt from the past week, two of them unique, I feel justified in more thoroughly looking at dasanc’s work.
First off we’ll look at the “Bitcoin Liquid Index”. This is a script calling from the tickers that compose the BNC Index. If you’re a TradingView user that doesn’t have a PRO account, but that does want a “fair” price for BTC, this script can help you achieve exactly that. They’re not the exact same, but they’re very close (as the below screenshot shows).
The “Stochastic Center of Gravity” is dasanc’s stochastic translation of of Ehlers CG indicator. On the page for the indicator he’s provided a link to the paper that discusses it. As dasanc mentions, it’s reliability as a trading indicator is a kind of questionable that TradingView’s backtester doesn’t have the resources to answer. It doesn’t fit BTC on the daily, as you can see below (green line = buy, red line = sell).
“Fisher Stochastic Center of Gravity” simply runs the “Stochastic Center of Gravity” through a fisher transform, the result of which are smooth, filtered signals.. (As a sidenote, transforming data through a fisher transform, or some other transform, is applicable to many different indicators.)
To use the “Fisher Stochastic Center of Gravity” dasanc suggests first defining the direction of the trend. How do we do that? Luckily he’s provided an open-source method for us to do that called the “Instantaneous Trend”. (By the way, if someone says iTrend to you, they’re not talking about trading software released by Apple, they’re talking about the Instantaneous Trend by John Ehlers). The iTrend is a “low-lag trend follower for higher timeframes”.
Want to learn?
If you'd like the opportunity to learn Pine but you have difficulty finding resources to guide you, take a look at this rudimentary list: docs.google.com
The list will be updated in the future as more people share the resources that have helped, or continue to help, them. Follow me on Twitter to keep up-to-date with the growing list of resources.
Suggestions or Questions?
Don't even kinda hesitate to forward them to me. My (metaphorical) door is always open.
Profile’s of Mentioned
MichelT: www.tradingview.com
Libertus: www.tradingview.com
jaggedsoft: www.tradingview.com
everget: www.tradingview.com
puppytherapy: www.tradingview.com
nickbarcomb: www.tradingview.com
shtcoinr: www.tradingview.com
RafaelZioni: www.tradingview.com
simpelyfe: www.tradingview.com
RicardoSantos: www.tradingview.com
westikon: www.tradingview.com
RyanPhang: www.tradingview.com
rimko: www.tradingview.com
kishin: www.tradingview.com
deckchairtrader: www.tradingview.com
danarm: www.tradingview.com
mwlang: www.tradingview.com
LazyBear: www.tradingview.com
dasanc: www.tradingview.com
SEARCH>>> #cisTOPIX ::: How to Purchase>>> #TradingViewTOOLKIT $DO NOT SELL TVC:DXY TO CREATE INFLATION & INCREASE STOCK PRICES... WARNING!!!
TVC:DXY TARGET 99.01-103.10
Important NOTE: "If the U.S. Dollar declines in VALUE at all then the implicit interpretation is that capital market traders and market investors using the U.S. Dollar as principle currency ARE LOSING MONEY IN THE MARKET which results in a decreased Market Value of the U.S. Dollar... The U.S. Dollar does not devalue in the MARKETS unless their are NO Real Capital Gains in Market Exchanges denominated in U.S. Dollar."
Ben Lichtenstein and Brad Augunas @TDAmeritrade @ThinkOrSwim @theDemocrats HAVE USED A PROGRAM for @BarackObama @Harvard @theDemocrats to ILLEGALLY TAMPER WITH MARKETS trying to short the U.S. Dollar to CREATE Inflation and FALSELY Raise Stock Prices in 2015 & 2017 August 2018 & December 2018 at peak drops and peak tops in stock markets... ALL U.S. Dollar induced money value changing (not trading)...
These men have violated my four young children and tortured me physically for 5 yrs using a satellite frequency and sound waves moving through my body... I can hear them communicating by radio through a substance used in the atmosphere to monitor weather patterns and have compiled 50+ yrs of evidence of @Harvard and Multiple Other Organizations heralding economists who intentionally manipulated market data price fixing and changed the value of money "off market" INCLUDING an effort to use currency devaluation to raise stock prices IN ORDER TO HIDE THAT ECONOMISTS and ECONOMIC ADVISERS not only FAILED in the U.S. but ARE TRYING TO DESTROY MARKET ECONOMICS to CLAIM that CAPITALISM is a failure POLITICALLY !
This is not a joke!
The LORD YHWH hates anything taken by iniquity>>> $$$






















