Back to zero: Understanding seriestype: pine series basic example
time required: 10 minutes
level: medium (need to know the "array" data variable as a generic programming concept, basic Pine syntax)
tl;dr how variables and series work in Pine
Pine is an array/vector language. That's something that twists how it behaves, and how we have to think about it. A lot of misunderstandings come from forgetting this fact. This example tries to clear that concept.
First, you need to know what an array is, and how it works in a programmig language. Also, having javascript under your belt helps too. If you don't, google "javascript array basic tutorial" is your friend :)
So, in pine arrays are called "series". Every variable is an array with values for each candle in the chart. if we do:
myVar = true
this is not a constant. It is a series of values for each candle, { true, true,....., true }
In practice, the result is the same, but we can access each of the values in the series, like myVar{0}, myVar{7}, myVar{anyNumber}....
Again, it is not a constant, since you can access/modify the each value individually
so, lets show it:
plot (myVar, clolor = gray)
this plots an horizontal line of value 1 ( 1 is equal to true ) so it's all good.
On to a more usual series:
tipicalSeries = close > open ? true : false
plot(tipicalSeries, color= blue)
This gives the expected result, a tipical up and down line with values at 1 or 0. Naturally, "tipicalSeries" is an array, the "ups" and "downs" are all stored under the same variable, indexed by the candles.
In Pine, the ZERO position in the array is the last one, which corresponds to the last candle on the right. Say you have a chart with 12 candles. The close would be the closing value of what we intuitively think as first candle, the one on the left. then close ... and so on.... until close , the value of the "last" candle, the one on the right. It actually helps to start thinking of the positions backwards, counting down to zero, rocket launch style :)
And back to our series. The myVar will also be the same size, from myVar to myVar .
When we do some operation with them, something simple like
if ( myVar == tipicalSeries)
what is really happening is that internally, Pine is checking each of the indexes, as in myVar == tipicalSeries , myVar == tipicalSeries .... myVar == tipicalSeries
And we can store that stuff to check it. simply:
result = (myVar == tipicalSeries) ? true : false //yes, this is the same as tipicalSeries, but we're not in a boolean logic tut ;)
plot (result)
The reason we can plot the result is that it is an array, not a single value. The example indicator i provide shows a plot where the values are obtained from different places in the array, this line here:
mySeries3 = mySeries2 and mySeries1
this creates a series that is the result of the PREVIOUS values stored (the zero index is the one most at the right, or the "current" one), which here just causes a shift in the plotted line by one candle.
Go ahead, grab a copy of my code, try to change the indexes and see the results. Understanding this stuff is critical to go deeper into Pine :)
Pinescript
Backtesting Period Selector | ComponentDescription
It's nice to quickly be able to set the backtesting period when writing strategies.
To make this process faster I wrote a simple 'component'.
So this is not a strategy but rather code you can plug-into your strategy and use
if you need that specific functionality.
Then it's just a matter of selecting which dates you want to backtest.
You can also chose to color the background to visually show the testing period.
Unfortunately, the background color is fixed at 'blue' for now.
Ps. I like the idea of writing small components to be pluged into other strategies
I'll try to develop this idea a bit further and see how small pieces of code can
easily provide specific functionality to assist and make deving strategies a bit less 'Pineful'.
Usage
First copy the instructed part of the component code over to your strategy.
Next, use the testPeriod() function to limit strategies to the specified backtesting period.
Example usage:
if testPeriod()
strategy.entry("LE", strategy.long)
Todo / Improvements
There are many ways to improve this component and I'm not a very good coder so this is a very crude solutions.
Anyway, here are some things which would be nice to improve:
1. Enable color selection so that the user can choose the background color of his own liking.
2. Improve naming of variables.
3. Test for ilogical choices, such as test period start being at a later date, than test period stop.
4. Account for time zones.
As always, any feedback, corrections or thoughts are very much welcome!
/pbergden
Simple Strategy Code StubThis is a very basic strategy implementation
Use as a code stub for your strategy code. I wrote it because I could not find one.
This particular strategy goes long on Tuesdays at 10 am and goes short at 3 pm on Thursdays.
Because US markets open at 9:30 you have to have your chart in 30 minute or less resolution for trades to fire.
You can gut that code and replace it with your own to start testing your own indicators and strategies.
If you build a strategy that doesn't use "hour" like I have this resolution requirement won't apply.
For giggles, compare its performance to other strategies. Weird, huh? About 53% effective on most equities and indexes.
This strategy does the minimum needed to get a strategy working
and uses default position sizes and buys at market with no stops.
Again, it is the minimal code stub needed to test an indicator/rule based strategy.
A great code reference for building more sophisticated strategies can be
found here =>
The code is written by @greatwolf and is very well structured for anyone looking to fully utilize
strategy features for position sizing, limit orders, stops and cancellations.
"Smoothed" CandlesHi!
This new functions plotbar and plotcandle are amazing! Just look at this smoothed candles here)))
Higher Resolution Bars on Intraday ChartHi everybody!
With new plotbar and plotcandle functions you may plot somewhat "stretched" daily bars over intraday chart. Enjoy!
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
CM_3-Stochastics_No%D_UserRequestCreated By ChrisMoody on 1-19-2014 by User Request
Plots 3 Stochastic Lines.....No %D Lines...by User Request.
CM_Donchian Channels Modified_V2 - Alert CapableCM_Donchian Channels Modified_V2 With Alert Capability
***This Indicator was created by user Request to Add Alerts Capabilities for Donchian Channels.
New Features:
***Alerts Work - Ability To Create Alerts From Main Indicator.
***Can Also Be Used In Conjunction with Lower Indicator - CM_Donchian Channels Modified_V2_Lower_Alert
***Added Ability To Turn On/Off Highlight Bars.
***Added Ability to Turn On/Off Donch Channel Midline
***Added Ability to Turn On/Off Triangles That Plot At Top and Bottom Of Chart When Breakout Condition is TRUE.
Special Indicator Features:
***Ability To Use Different LookBack Period on Upper and Lower Donch Channel Lines.
How To Create Alerts:
***Create Alert by selecting Indicator - Either the name of the Upper Or Lower Indicator...
***Then select either Alert Breakout Upside or Downside(To The Right Of Indicator Name)
***Select Greater Than
***Select Value
***For Value put .99
Original Post Explaining Indicator is -
***If You Need Help Getting Custom Indicators to Trigger Alerts then View This Post.
CM_Donchian Channels Modified_V2_Lower_Alert***This Indicator was created by user Request to Add Alerts Capabilities for Donchian Channels.
New Features:
***Alerts Work - Ability To Create Alerts From Main Indicator.
***Can Also Be Used In Conjunction with Upper Indicator - CM_Donchian Channels Modified_V2 With Alert Capability
***Added Ability To Turn On/Off Highlight Bars.
***Added Ability to Turn On/Off Donch Channel Midline
***Added Ability to Turn On/Off Triangles That Plot At Top and Bottom Of Chart When Breakout Condition is TRUE.
Special Indicator Features:
***Ability To Use Different LookBack Period on Upper and Lower Donch Channel Lines.
How To Create Alerts:
***Create Alert by selecting Indicator - Either the name of the Upper Or Lower Indicator...
***Then select either Alert Breakout Upside or Downside(To The Right Of Indicator Name)
***Select Greater Than
***Select Value
***For Value put .99
Original Post Explaining Indicator is -
***If You Need Help Getting Custom Indicators to Trigger Alerts then View This Post.
CM ATR Stops/Bands - Multi-TimeFrameCM_MTF ATR Bands/Stops
Many Options Available Via Input Tab:
-Chart Defaults to Upper and Lower ATR's Based on Current Chart TimeFrame
-Ability to Plot either Upper and/or Lower ATR's
-Ability to Change the Time Frame ATR's are Based On!
-Ability to change Look Back Period and ATR Multiplier Individually for Both Time Frames
-This Gives you the ability to plot same Time Frame with (for ex.) a 5 ATR with a 1.5 Mult and a 14 ATR with a 2.0 Mult etc.
-Or you can plot Daily ATR's on a 60 minute Chart etc.
-ATR Multipliers are Calculated with Code that allows "Non Whole Numbers" Allowing Ability to use 1.5 ATR's, 1.8 ATR's etc.
***Endless # of Combinations can be used!!!!
CM_ADX_V1ADX System Overview
So I Came Across Another Trading System for Only $997. However, if you purchased in the next 24hours the whole system could be Yours For Only $497.
So I decided to Code it. This is only Version 1, and I discuss in the Video What I’ve found so for, some plans for Version 2 of the indicator, and I ask for your feedback on anything you find.
Indicators used in System:
CM_DI_Plus_Minus_V1 (Indicator On Bottom).
CM_ADX_V1 (Indicator On 2nd Pane).
CM_Gann_Swing_Hi_Lo (Indicator on Price Pane). This Indicator was published before…Link Below.
CM_DI_Plus_Minus_V1
In Video I go over settings and how to customize charts.
Link To Video:
vimeopro.com
Link To Downloadable PDF Shown in Video:
d.pr
CM_DI_Plus_MinusADX System Overview
So I Came Across Another Trading System for Only $997. However, if you purchased in the next 24hours the whole system could be Yours For Only $497.
So I decided to Code it. This is only Version 1, and I discuss in the Video What I’ve found so for, some plans for Version 2 of the indicator, and I ask for your feedback on anything you find.
Indicators used in System:
CM_DI_Plus_Minus_V1 (Indicator On Bottom).
CM_ADX_V1 (Indicator On 2nd Pane).
CM_Gann_Swing_Hi_Lo (Indicator on Price Pane). This Indicator was published before…Link Below.
In Video I go over settings and how to customize charts.
Link To Video:
vimeopro.com
Link To Downloadable PDF Shown in Video:
d.pr
CM_DayOfWeek All Instruments V2Updated Code That Highlights Bars Based On Days Of The Week.
Works On Daily and Intra-Day Bars.
Works on All Instruments. Stocks, Forex, Futures, Bitcoin.
Shows Correct Trading Sessions!!!
Ability to Turn On/Off Each Day Of The Week via Inputs Panel.
CM_Stochastic Highlight BarsCM_Stoch Highlight Bars
belgusinc Wanted to Know How To Create Highlight Bars based on Stochastic Bars Being Overbought/Oversold
Basics:
Ability to turn On/Off Crosses Only Above or Below High/Low Lines.
User sets Values Of High/Low lines. (Determines how highlight Bars are plotted, Based on the Value of the High/Low lines.
Ability to turn On/Off All Crosses, Both BackGround Highlights and “B”, “S” Letters.
Ability to turn On/Off BackGround Highlights if Stoch is Above Or Below High/Low Lines.
Ability to All or Any Combination of these Features.
Lower Indicator
CM Stochastic Multi-TimeFrameMulti TimeFrame Stochastic Loaded With Features.
Basics:
Ability to turn On/Off Crosses Only Above or Below High/Low Lines.
User sets Values Of High/Low lines.
Ability to turn On/Off All Crosses, Both BackGround Highlights and “B”, “S” Letters.
Ability to turn On/Off BackGround Highlights if Stoch is Above Or Below High/Low Lines.
Ability to All or Any Combination of these Features.
Multi Timeframe Capabilities:
Stoch defaults to current timeframe. You can change to many other timeframes.
Ability to turn On/Off Plotting 2nd Stoch on same TimeFrame with different settings
Ability to turn On/Off Plotting 2nd Stoch on Different TimeFrame
Much More…All Inputs and Options are Adjustable in Inputs Tab.
CM_Pivot Points Daily To IntradayNew Pivots Indicator With Options for Daily, 4 Hour, 2 Hour, 1 Hour, 30 Minute Pivot Levels!
Great for Forex Traders! - Take a Look at Chart with Weekly, Daily, and 4 Hour levels. Weekly Pivots Indicator is separate - Link is Below.
Plot one Pivot Level or Multiple at the Same Time via Check Boxes in the Inputs tab.
Defaults to 4 Hour Pivot Levels - Adjust in Inputs Tab.
S3 and R3 are turned off by Default - You can Activate Them In The Inputs Tab.
These Intraday Options were Requested By Users Using My CM_ Pivots Point Custom Indicator that Plots Daily, Weekly, Monthly, Quarterly, and Yearly Pivot Levels. Link is Below.
Now Both Longer-Term Traders and Shorter Term Traders Have All The Pivot Levels They Need. From Yearly Levels All The Way Down to 30 Minute Levels!
***The Candles On The Chart Are Custom Heikin-Ashi Paint Bars. Link is Below
CM_ Pivot Points Custom
Daily, Weekly, Monthly, Quarterly, Yearly Pivot Levels
Heikin-Ashi Paint Bars
CM Willams %R and CCI BackGround HighlightCM_Willams %R and CCI BackGround Highlight
Created By User Request
Indicator Highlights:
Creates Red BackGround Highlight if CCI Or Williams %R are Above Upper Line (User Defined)
Creates Green BackGround Highlight if CCI Or Williams %R are Below Lower Line (User Defined)
Ability to Turn On/Off either Williams %R or CCI Highlights in Inputs Tab via Check Boxes.
Ability To Set All Parameters for CCI and Williams %R in Inputs Tab.
Ability to Set High/Low “Threshold” Lines for Both CCI and Williams %R in Inputs Tab.
***I was asked if you could plot Back Ground Highlights on Two Individual Indicators AND have it show if BOTH Indicators were Overbought and Oversold.
***The answer is Yes. On the Chart Above I have the same Shade of Red and Green for Both Indicators. However, you will notice when Both Indicators Show OverBought…Both Plot Red Back Ground Highlights Which = a Brighter Red. The same is True for Oversold Conditions. The Green Shows a Brighter Shade of Green.
***VERY IMPORTANT - It is difficult for a programmer to release Indicators with this feature because depending on what color background you use on your charts…THE COLORS LOOK COMPLETELY DIFFERENT. So If You Don’t Use The Black Back Ground Shown Above You Most Likely Will Need To Adjust The Transparency, and Possibly The Colors Themselves!!!!
Reference Page
TimWest Long Short FiltersTimWest Long Short Filters
Indicator Has 3 Separate Filters that Create Green(Bullish) or Red(Bearish) BackGround Highlights
If Price is Above or Below a certain LookBack Period - Tim Defaults to 63 on Daily Chart to Quickly View if Price is Above or Below it’s Price 1 Quarter Ago.
A Simple Moving Average Filter - Tim Defaults to 50 SMA and 200 SMA also known as the “Golden Cross”.
A Exponential Moving Average Filter - For Those Who Want To View Shorter Term Market Swings. Defaults to 50 EMA and 100 EMA used By Chuck Hughes, 7 Time World Trading Champion. Chuck Claims the 50/100 EMA's Show the Earliest Change in Market Direction the Equal - Sustainable Moves
Inputs Tab has Checkboxes to Turn On/Off any of the 3 Filters Above.
Reference Chart Post www.tradingview.com
CM Sling Shot SystemSling Shot System + Even Better System.
I get this email about a Trend Following System that sells for $1000 but I could get it that day for only $500!!!
I watch the video showing this Amazing System which may have taken me an entire minute to figure out the code.
I code it up. And Hey…It’s not a bad system. It’s good for people who may need a Entry Signal to get them in a Trending Move, and KEEP them in a Trending Move while providing a defined Stop.
So I thought I would save the community the Very Fair price of Only $500 for a system that consists of a couple of EMA’s and a few Rules…and give it to you for free.
See Link Below for Main Chart Showing 2nd System!!!
CM Gann Swing High Low V2CM Gann Swing High Low V2
Added Improvements:
Used PineScript “linebr" code so solid lines plot only when condition = true.
Via Inputs Tab:
Ability to Turn On/Off Highlight Bars When Crossing Above/Below Swing High Low
Ability to Turn On/Off Back Ground Highlights When Crossing Above/Below Swing High Low
Ability to Turn On/Off linebr plots.
Other Features: All Available Via Inputs Tab
Ability to Adjust Moving Average Values to adjust Sensitivity.
Ability to Turn On/Off Triangles Above/Below Bars based on Indicator.
Ability to Turn On/Off Triangles at Top And Bottom Of Screen Showing Direction of Indicator.
***Basically you have Option to View Indicator about every way possible.
***Special Thanks to Glaz for Original Code.
CM Percent Move Upper V1CM Percent Move Upper V1 .... Goes With the Lower Indicator
Created by ChrisMoody on 9/3/2014 by Request from vlad.adrian
**Plots A BackGround Highlight if % Move is Greater or Equal to User Input
** % Move is based on Close of Current Bar Compared to Close of Previous Bar