[TEMPLATE] Code Block Comments█ OVERVIEW
Here I present to the community at large a collection of code comment blocks that I think will be useful, especially for larger script projects bordering on 2,000 lines or above of code.
█ PLANNED FUTURE UPDATES
Work with the community to expand this template to be even more useful with the inclusion of useful global colour sets, variables, tooltips, groups, etc.
better script thumbnail.
full-screen table or label outlining the script's use-cases.
Code
Max Drawdown Calculating Functions (Optimized)Maximum Drawdown and Maximum Relative Drawdown% calculating functions.
I needed a way to calculate the maxDD% of a serie of datas from an array (the different values of my balance account). I didn't find any builtin pinescript way to do it, so here it is.
There are 2 algorithms to calculate maxDD and relative maxDD%, one non optimized needs n*(n - 1)/2 comparisons for a collection of n datas, the other one only needs n-1 comparisons.
In the example we calculate the maxDDs of the last 10 close values.
There a 2 functions : "maximum_relative_drawdown" and "maximum_dradown" (and "optimized_maximum_relative_drawdown" and "optimized_maximum_drawdown") with names speaking for themselves.
Input : an array of floats of arbitrary size (the values we want the DD of)
Output : an array of 4 values
I added the iteration number just for fun.
Basically my script is the implementation of these 2 algos I found on the net :
var peak = 0;
var n = prices.length
for (var i = 1; i < n; i++){
dif = prices - prices ;
peak = dif < 0 ? i : peak;
maxDrawdown = maxDrawdown > dif ? maxDrawdown : dif;
}
var n = prices.length
for (var i = 0; i < n; i++){
for (var j = i + 1; j < n; j++){
dif = prices - prices ;
maxDrawdown = maxDrawdown > dif ? maxDrawdown : dif;
}
}
Feel free to use it.
@version=4
CC - Consolidated Interval Display (CID)Ever wish you didn't have to rapidly flip between 6 different intervals to get the full picture?
Yeah, me too. Do you also wish that you kind of understood how the shift / unshift function works for arrays?
Yeah, I did too. Both of those birds are taken care of with one stone!
The Consolidated Interval Display uses the new Array structure and security to display data for 5m, 15m, 45m, 1h, 4h and 1d intervals SIMUTANEOUSLY! Regardless of which interval you're looking at you can get the full picture of numerical data without flipping around to get it.
This is my first script trying to use arrays. It basically shows the following for the given ticker:
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 5 minute level.
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 15 minute level.
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 45 minute level.
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 1 hour level.
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 4 hour level.
ATR14, RSI7, RSI14, SMA50, SMA200 and VWAP at the 1 day level.
To make it more or less busy, I've allowed you to toggle off any of the levels you wish. I've also chosen to leave this as open source, as it's nothing too experimental, and I hope that it can gain some traction as an Array example that the public can use! If you don't like the different values that are shown, use this source code example as a spring-board to put values that you do care about onto the labels.
If this code has helped you at all please drop me a like or some constructive criticism if you do not think it's worth a like.
Good luck and happy trading friends.
If this gets traction, I will post something similar for a combination of SPY, VIX, GOLD, QQQ, IWM and TLT.
Incremental Order size +This is an old and incomplete script that is being pulled up and dusted off as per request.
The sole purpose of this script was to provide code snippets allowing one to easily convert their own script/strategy to include incremental order sizes. More control over your pyramiding orders.
**It may repaint, and was not intended for trading but more as an attempt to provide examples for more control with pyramiding.
Coding ema in pinescriptWhat is EMA ?
Ema is known as exponential moving average, it comes from the class of weighted moving average. It gives more weightage to the recent price changes, thus making it much more relevant to the current market analysis. Also it provides a dynamic way of calculating support and resistances in a trend following setup.
The most common way to mint profit out from the market is to use trend following setups which can be easily achieved by using a group of EMA’s
So how’s this EMA calculated ?
Before understanding the calculation of EMA let’s look into a much wider topic:
“The Law of Averages”
It states : If you do something often enough a ratio will appear, simply put, any time series data, tend to deviate from its average.
EMA provides a way to statistically calculate the exponential moving average for a provided time series data giving much more emphasis on the most recent data in the series.
So in the 17th century, when the people were playing with numbers in their free time, they came up with a statistical strategy to envelop any time series data to detect the direction of the data flow , they called it exponential moving average.
Later in 1940’s with the increase in signal processing requirements in the field of electronic devices scientists started using Exponential moving average onto the electronic signal followers, just to classify the signals as above or below a moving/dynamic threshold.
So EMA is a smoothed time-series data.
The simplest form of EMA Smoothing can be given by the formula:
S(t) = alpha * X(t) + (1 - alpha) * X(t - 1).
The value of alpha must lie between 0 and 1
Where
alpha , is the smoothing factor
X(t) , is the current observation data point
X(t - 1), is the past observational data point.
t , is the current time
Generally,
In current day trading setups for EMA the alpha is calculated by
alpha = 2 / (time period window + 1)
Things to note here is that the alpha calculated above is the most generally used factor calculation method for EMA ,
You can tweak the alpha function above until it gives value between 0 and 1 for example alpha can also be written as
alpha = ln ( current price / past price )
Note it’s just a weighing scheme,
But for Our Case of EMA
We will be using
alpha = 2 / (time period window + 1)
Please refer to the script code below
Ignore Extended Session CodeLooking at the extended session is awesome and can certainly give you an edge on trading the open of a market. If you're more of a technical trader, though, you run into the problem of the extended session data throwing your indicators off. To fix that, use the code below as a template for whatever indicators you use.
Strategy Code Example 2 - Time Limiting*** THIS IS JUST AN EXAMPLE OF STRATEGY TIME LIMITING CODE IMPLEMENTATION ***
This is a follow up to my example for risk management implementation here:
Code remains mostly unchanged, but now includes a time limiting implementation.
Relevant code blocks for the time factor are preceded with a comment stating:
*** FOCUS OF EXAMPLE ***
Cheers!
Strategy Code Example - Risk Management*** THIS IS JUST AN EXAMPLE OF STRATEGY RISK MANAGEMENT CODE IMPLEMENTATION ***
For my own future reference, and for anyone else who needs it.
Pine script strategy code can be confusing and awkward, so I finally sat down and had a little think about it and put something together that actually works (i think...)
Code is commented where I felt might be necessary (pretty much everything..) and covers:
Take Profit
Stop Loss
Trailing Stop
Trailing Stop Offset
...and details how to handle the input values for these in a way that allows them to be disabled if set to 0, without breaking the strategy.exit functionality or requiring a silly amount of statement nesting.
Also shows how to use functions (or variables/series) to execute trade entries and exits.
Cheers!
Engulfing below EMA 120Buy bullish engulfing above EMA 24
Sell bullish engulfing below EMA 24
Mercurius A.M.
Code for Cup With Handle calculations (using Pine)Cup with Handle formation calculations using Pine.
First of all, ignore all other lines in the example chart except the two FAT lines. The two fat lines are the ones that define the Cup With handle or in the example chart: a Reversed Cup With Handle.
Note: Handle does not always develop and sometimes the final target price is reached without forming any handle.
This script can calculate both Cup With Handle ( CH ) and Reversed Cup With Handle ( RCH ). Just order the input values accordingly.
For more information about Cup With Handle, use google:
www.google.se
The script need two input parameters : The highest price in the Cup formation and the lowest price in the cup formation or vice versa for the Reversed Cup formation.
Best regards,
/Hull, 2015.05.20.16:31
Custom Indicator Clearly Shows If Bulls or Bears are in Control!The Two Versions of this Indicator I learned from Two Famous and Highly Successful Traders. This Indicator shows With No Lag Clear Up and Down Trends in Market by Documenting Clearly If Bulls or Bears are in Control. The Version In SubChart 1 Shows Consecutive Closes if the Current Close is Greater than of Less than the Midpoint of the Previous Bar (Why Midpoint Explained in Detail in 1st Post). The Version in SubChart 2 Shows Consecutive Closes that are Greater than or Less Than the Previous Close (Will Discuss Specific Uses in 1st Post). Works on Stocks, Forex, Futures, on All Timeframes.