Coding and using Center of Gravity Indicator in PineScript

 Center of Gravity is a oscillator type of indicator. It is formed by mean of weighted moving averages. It has lesser lag than other moving average indicators. A Center of Gravity indicator can be used for 

1. Generating buy sell signals

2. Marking support and resistance zones

3. Finding possibility of turning point through divergence.

How to use Center of Gravity Indicator

Method 1 : Any momentum or oscillator type of indicator can be used by creating a signal line by taking average of indicator value. Say, if I create a Centre of Gravity indicator with 10 periods than I can take a 3 or 5 days average of the indicator value to create a more smooth line to act as a signal line. 

Below is the code for creating COG with 10 period and signal line with 5 period.

//@version=4
study("implementing COG indicator")
cog_value = cog(close,10)
cog_avg =sma(cog_value,5)
plot(cog_value)
plot(cog_avg,color=color.red)

Here is the output generated by the code. You can always adjust the value of signal line to suit your requirement and better identification of buy/sell signals.

Method 2 : 
Use Divergence between COG and price as a signal for change of trend
Method 3 : Use RSI along with COG to filter signals.

Resources

Learn more on COG, coding and other technical indicators in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book

Buy Udemy Course on creating trading strategies and creating indicators in PINESCRIPT on trading view at 70% discounted price at USD 20. Buy Now  

Pinescript Indicator Development

 PineScript Technical Indicator Development is book by Minakshi. I have reviewed the book and found it well written for new coders with no past background of coding. It has many examples and charts for readers.

This book is by Trader and not from computer coder and the book claims that it is for novice coders. The book at the time of writing of this blog was also available for free on kindle. I have not gone through the entire book, however, I liked the way examples have been provided for understanding of technical concept. The parameters inside the functions have been compared with hotel room offering.

The example in the books says that in case you go to hire a room in hotel you expect bed, TV, toilets , etc and we you have some special requirement like to have blue covers, carpets, room-service you ask them from the manager. Similarly, all functions provide a basic offering and like a line will have blue colour with a pre-defined width,etc and if you want to have something special and extra , you have to ask manager. Here, in case of functions the parameters does that job. If you want a line with green colour and thick line you have to give that order to functions within its brackets , separated by commas.


The book however does not cover advance topics like back-testing and strategy. The book also does not include newer topics like arrays. However, if you are new to the coding world and are struggling and looking to start a fresh then this book is for you. This book does not teach un-necessary computer concepts that are not going to be use in pinescript but keep itself focused on concepts that are necessary for understanding of pinescript. 

If you are novice, I recommend this book for reading.

Pine Script Label Position

   The  xloc and yloc are two parameters (inputs) in label function. They tell how position values provided vide x,y (the other two parameters) are to be interpreted. Not to get confused , I summarise as :

1. x,y takes values for position of label

2. xloc and yloc can take input as constant. Example xloc can take values xloc.bar_index and xloc.bar_time, whereas yloc can take constant values as yloc.price, yloc,abovebar and yloc.belowbar. These xloc and yloc inform system on how to interpret data provided in x and y. Let say I provide a value as x=1089. Now, whether 1089 is on time axis or a bar number or price is not known to system. We provide this information vide xloc and yloc values.

The above will become more clear when we take examples.


In the above graph ( a 2-Dimensional Space), the location of any point can be represented in the form of  x, y. Let's say that the above is price of GOOG , then you can read from the graph that price is 410 and date is 16. Now , the confusion arises, whether the date is 16 or it is bar number. If xloc=xloc.bar_time is defined , then it is time and can be interpreted accordingly else if xloc=xloc.bar_time is defined, this 16 is the number of bar. 

In case of y, y is always price, however, if you are printing your label above or below bar , you can set yloc=yloc.abovebar or yloc=yloc=belowbar. In case you are using xloc=xloc.bar_time then you have to provide all time value in milliseconds. 

Summary

1. All x,y,xloc,yloc are parameters to label, other important parameters are text, color, style
2. If you don't define your xloc, then by default it is always xloc.bar_index
3. If you don't define your yloc, it is always yloc.price
4. If you don't define xloc and yloc, then 
label.new(x=bar_index, y=high,text="myLabel1") will print label on current bar at price = high.
5. If you set yloc=yloc.abovebar or yloc=yloc.belowbar then also you will have to provide x and y values.
6. I want to print a label one day before the current bar and I am using xloc=xloc.bar_time, then I can use x value as x=time - 86400000. Example is shown below:
label.new(x= time-86400000,y=high,xloc=xloc.bar_time,text="1")

Pine Script vs Python

 The PineScript and Python, both are used for trade programming, however, python has a larger domain and is also used for many other purposes. Overall python is a vast programming language than pinescript which only focuses on technical indicator development and back-testing. 

What to learn? Python or PineScript?

Answer is very simple, if you don't have prior programming experience, I would suggest learning PineScript as it has limited instructions and commands compared to python. Further, if the focus is only to make trading strategies, back-testing and indicator development, I would like to suggest pinescript.

Complicated code and live trading are not possible through pinescript. Backtrader, a python module, can allow you both backtesting and live trading.

If you are new at programming, it is suggested that you try books on pinescript and backtrading module from "Teach Yourself" series from amazon.

Is Python and PineScript similar?

Yes, to some extent both are similar in terms of uses of syntax, formatting of instructions, however, even if you have a slight experience on any other programming language like "C", "Java" , "BASICS", "PASCAL", etc you can learn pinescript very quickly.

In pinescript, arrays were not introduced till late 2020s, the array introduced in pinescript have syntax very similar to python. This has been done so that programmers working in python could learn these concepts quickly in pinescript.

Is PineScript based on python?

No, pinescript is not based on python. The syntax are similar to higher level programming language, therefore some people feel that it is based on python.

Coding and using Parabolic SAR in PineScript

 In pinescript we have in-built function for calculation of Parabolic SAR value. The parabolic SAR is used to identify direction of asset and is also used as stop-loss when you have taken a position in the direction of trade. Below is the chart showing parabolic SAR on "GOOG" Daily Chart. When the value of parabolic sar is below the price, the trend is considered bullish. A change from bearish to bullish sar is considered and buy signal and change from bullish to bearish sar is considered sell signal.


Parabolic SAR produces false signal when price of scrip is moving sideways with no clear direction. Recommended to use moving averages along with SAR to only trade in trending markets.

As you know functions are like black box which take input and provide output, you need not worry about real calculation part. The function used in pinescript for calculation of parabolic SAR is known as sar(). The two brackets after the name of sar signify that it is a function.  All the inputs to the function is provided inside these brackets and are separated by commas. The input to any function is known as parameter. 

Syntax of Parabolic SAR

The syntax of sar function is as under :
mySAR = sar(start, inc, max)
The input supported by sar() are :
start : The default value of start is 0.02
increment : The default value of start is 0.02
maximum : The default value of start is 0.20

Code for implementing Parabolic SAR

The below code will change the colour of SAR to red on SAR being bearish or green on being bullish

//@version=4
study(title="Parabolic SAR", shorttitle="SAR", overlay=true)
mySAR = sar(0.02, 0.02,0.2)
myColor = mySAR < low?color.green:color.red
plot(mySAR, "ParabolicSAR", style=plot.style_cross, color=myColor)

Below is the result produced by the SAR indicator.



How to debug pinescript?

  For debugging of pinescript, coders have a console window just below pinescript editor window. If the console window is not visible. Right click on the menu bar of editor window and select console. All the script related errors are generated and shown in console window. Coders can then take overview of error from the error description generated and debug pinescript errors. 

Taking Hints from Pinescript Console Window

The above shows console option when right clicked on the menu bar of editor window.When any error is found in script by the pinescript editor it highlights the error in console window with red colour. The line number of possible error is also generated. In the example below, line no 3 has generated error. The description of error is "Undeclared identifier close1" . This error means that you have used a variable without declaration, this normally happens when you have written the name of variable wrong or the variable name has typo error.  

In the above example , I have written close1 in place of close that has caused the error. Sometimes you may have logical errors that are not generated from syntax, but out of logical mistake in making the algorithm or arrangement of instructions. Here, you may be required to print output of pinescript variable for debugging. Such type of debugging can be done by printing variable values through labels.

This is very common question asked by almost every new coder. When you are new, you often make mistake and for learning debugging is very important.

How to add multiple indicators on TradingView Chart?

 You can add multiple indicators on TradingView by adding few codes to pinescript editor and merging all indicators in one mega custom indicator. There are two types of indicators 

1) the one which are ploted on price chart it self examples are SAR, Moving Averages, Bollinger's Band,Kelter's Channel and 

2) Set of indicators are drawn below the chart and are mostly oscillator type or momentum type example: RSI, center of gravity, stoch, William's  %R, ADX ,etc.

You can combine one set of indicator with another indicator which is of same type. You cannot combine indicator like SAR with RSI i.e. one that plots on chart and another that plots below chart. You will therefore may require maximum two custom made indicators to add all indicators on your chart irrespective of type of subscription taken by you. Below is example wherein moving average crossover, SAR indicator and Bollinger's Band is added in a single script. 

 

The Code for multiple indicators

//@version=4
study("Demo Multi Indicators",overlay=true)
plot(sma(close,14),color=color.red)
plot(sma(close,7),color=color.red)
mySAR = sar(.02,.02,.2)
plot(mySAR,style=plot.style_circles)
[mean,upperBand, lowerBand] = bb(close,20,2)
plot(upperBand,color=color.blue)
plot(lowerBand,color=color.blue)
plot(mean,color=color.green)

The output from the code

All indicators are in different colors. The red ones are moving averages, dots are for SAR and blue lines are upper and lower bands of Bollinger and green is middle line of Bollinger. These multiple indicators have been merged into one indicator named Demo Multi Indicators. Each indicators can be coloured differently.


How to use pine script alertcondition?

 The alertcondition() function in pinescript can be used to create option in drop down menu of alert creation window of TradingView pinescript platform. It only create option and therefore does not set, create or can be used to trigger alert.

Before we understand fully on how pinescript altercondition can be used, we must understand how manually alert can be set in tradingview platform using alert creation window.

Setting Alert in TradingView 

Step 1 : Open the chart of scrip for which you want to set alert in tradingview platform. Here, I have opened the chart of GOOG.

Step 2 : Open alert creation window by pressing "Alt +A" or alternatively you can click on the alert icon on right panel with icons as shown below:


Step 3 :  The below is alert creation window for "GOOG" script, here you can fill all details for creation of alert. You will find that in this window you don't have many options for setting up alert, but still this is a powerful tool. 


You have many option for receiving alert, the list of options are not visible on above image so the scrolled down image showing all the option is shown below:


Here, you can see we have several options like to notify on app or show pop-up or send email and webhook url, you can also play sound or receive alert on SMS. If you are a long term investor you won't be checking prices very often and receiving prices on email can work for you. If you are a intraday trader, probably you keep your tradingview account open on app or on computer then you can choose to receive alert as pop-up with sound or on app.

Step 4 : Just click create button and your alert will be saved and can be viewed, reviewed, edited by clicking alert icon or pressing alt+A.


Using PineScript's Function alertcondition

As discussed above, pinescript does not offer many options for settingup alert conditions. Most of the alert conditions are relating to price. If you want to set an alert for extremely high volume activity. There is no option in Alert creation window that we opened by pressing alt +A. In such cases, where you don't have option in the window , you can use alertcondition functions in pinescript to create option in the window. 

For example, I want to receive alert when volume is highest among last 60 bars. The code can be as under :

//@version=4
study("Demo Alertcondition",overlay=true)
volAlert = volume == highest(volume,60)
alertcondition(volAlert,"Volume highest 60 bars","Highest volume among last 60 bars found")
plot(close)
After you add the above code to the chart, again open alert creation window and you will find the option you were looking for. 


If you want to learn more on pinescript, goto out resource section.

Pine Learner's Educational Resources

Udemy on Strategy and Backtesting has paid course covering basics for implementation of Strategies in PINESCRIPT and backtesting them. For early subscribers, course is being offered at USD 20 in place of USD 69.99. Hurry up click here
Books on PineScript


TradingView Pine script programming from scratch is complete book on pinescript for beginners. This book covers all basics of indicator development and strategy development. This 200+ pages Ebook and paperback available on amazon.


Teach Yourself Coding Indicators in PineScript provides a good starting point for you in PineScript programming. It covers important topics in PineScript and lays a solid foundation for a serious beginner. After reading this book, you will be able to write basic PineScript programs on your own to develop Indicators in tradingview platform.



Teach Yourself Trading strategies in PineScript is second part of earlier book or can be read after reading the first book on indicators. This book specifically focus on building of trade strategies and analysis of back testing results on historical data.

Resources

Highest Rated Udemy Course on PineScript - Grab your Seat Now 

Udemy Discount Coupon Code : UDEMY-JAN23 (Valid upto 30th Nov 2023)

Learn more about coding on tradingview in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book200+ pages book


Point and Figure Charts : A Time-Tested Tool for Technical Analysis

In the dynamic world of financial markets, investors and traders constantly seek tools that can provide valuable insights into market trends...