Vous êtes sur la page 1sur 70

Pine Script Language Tutorial

Introduction
ExampleofanIndicatorinPine
StructureoftheScript
Comments
Identifiers
TypeSystem
Literals
IntegerLiterals
FloatingpointLiterals
BooleanLiterals
StringLiterals
ColorLiterals
Operators
ArithmeticOperators(+,,*,/,%)
ComparisonOperators(<,<=,!=,==,>,>=)
LogicalOperators(not,and,or)
ConditionalOperator?andtheFunctioniff
HistoryReferencingOperator(SquareBrackets[])
PriorityofOperators
FunctionsvsAnnotationFunctions
Expressions,DeclarationsandStatements
Expressions
VariableDeclarations
SelfReferencingVariables
PreventingNaNvalues,Functionsnaandnz
SimpleMovingAveragewithoutapplyingtheFunctionsma
ifstatement
DeclaringFunctions
SinglelineFunctions
MultilineFunctions
ScopesintheScript
FunctionswithselfrefVariablesintheBody
Functionsthatreturnmultipleresult
LinesWrapping
ContextSwitching,ThesecurityFunction
SessionsandTimeFunctions
FunctionsandtheVariabletime
BuiltinVariablesforworkingwithTime
ExtendedandRegularSessions
NonStandardChartTypesData
1

'heikinashi'function
'renko'function
'linebreak'function
'kagi'function
'pointfigure'function
AnnotationFunctionsOverview
Theannotationstudy
OutputofChartsplot
Barcoloringaseriesbarcolor
Backgroundcoloringbgcolor
InputsoftheIndicator
Pricelevelshline
Fillinginthebackgroundbetweenobjectswithfill'
Alertconditions
Shapesusingplotshape,plotchar,plotarrow
TheFunctionplotshape
Functionplotchar
TheFunctionplotarrow
CustomOHLCbarsandcandles
Strategies
Asimplestrategyexample
Howtoapplyastrategytothechart
Backtestingandforwardtesting
Brokeremulator
Orderplacementcommands
Closingmarketposition
OCAgroups
RiskManagement
Currency
HOWTOs
GetrealOHLCpriceonaHeikinAshichart
Plotbuy/sellarrowsonthechart
WherecanIgetmoreinformation?

Introduction
PineScriptisaprogramminglanguagethatisdesignedforcustomindicatorsdevelopmenton
TradingView.Thisisvectorbasedprogramminglanguage,engineeredspecificallytosolve
problemsinthefieldoftechnicalanalysis.

Example of an Indicator in Pine


AprogramwritteninPineiscomposedoffunctionsandvariables.Functionscontaininstructions
thatdescriberequiredcalculationsandvariablesthatsavethevaluesusedintheprocessof
thosecalculations.Thesourcecodelineshouldnotstartwithspaces(thereisanexception,see

syntaxofamultilinefunction
).
Ascriptshouldcontainastudyfunctionwhichspecifiesthescriptnameandsomeotherscript
properties.Scriptbodycontainsfunctionsandvariablesnecessarytocalculatetheresultwhich
willberenderedasachartwithaplotfunctioncall.
Asafirstexample,wellexaminetheimplementationoftheMACDindicator:

study("MACD")
fast=12,slow=26
fastMA=ema(close,fast)
slowMA=ema(close,slow)
macd=fastMAslowMA
signal=sma(macd,9)
plot(macd,color=blue)
plot(signal,color=orange)

Belowgivesadescriptionofhowthegivenscriptworks,linebyline:
study("MACD")

SetsthenameoftheindicatorMACD

fast=12,slow=26

Definestwointegervariables,fastandslow.

fastMA=ema(close,fast)

DefinesthevariablefastMA,containingtheresultofthe
calculationEMA(ExponentialMovingAverage)withthe
lengthequaltofast(12)oncloseseries(closingpricesof
bars).

slowMA=ema(close,slow)

DefinesthevariableslowMA,containingtheresultofthe
calculationEMAwiththelengthequaltoslow(26)from
close.

macd=fastMAslowMA

Definesthevariablemacd,whichisbeingcalculatedasa
differencebetweentwoEMAwithdifferentlengthinputs.

signal=sma(macd,9)

Definesthevariablesignal,calculatedasasmoothvalueof
thevariablemacdbythealgorithmSMA(SimpleMoving
Average)withlengthequalto9.

plot(macd,color=blue)

Callfunctionplot,whichwoulddrawachartbasedon
values,savedinthevariablemacd(thecolorofthelineis
blue).

plot(signal,color=orange)

Callfunctionplot,whichwoulddrawachartforthevariable
signalwithanorangecolor.

AfteraddingtheindicatorMACDtothechartwewouldseethefollowing:

Pinecontainsavarietyofbuiltinfunctionsforthemostpopularalgorithms(sma,ema,wma,
etc.)aswellasmakingitpossibletocreateyourcustomfunctions.Youcanfindadescriptionof
allavailablebuiltinfunctions
here
.

InthefollowingsectionsthedocumentwilldescribeinfullallthePineScriptcapabilities.

Structure of the Script


AscriptinPineissyntacticallyconsistsofaseriesofstatements.Eachstatementusuallyis
placedonaseparateline.Itspossibletoplaceafewstatementsononeline,dividingthemwith
acomma,.Thefirststatementonthelinemustbeplacedatthebeginning,keepinginmind
thatspaces

beforethestatementarenotallowed(thishasadirectrelationtothesyntaxof
multiplelinefunctions).Statementsareoneofthreekinds:

variabledefinitions
functiondefinitions
annotationfunctioncalls

Longstatementsthatdontfitwithininthewidthofthescreencanbesplittoafewlines,further
informationaboutthiscanbefound
here.

Comments
PineScripthassinglelinecommentsonly.Anytextfromthesymbol//untiltheendoftheline
isconsideredascomment.Anexample:

study(Test)
//Thislineisacomment
a=close//Thisisalsoacomment
plot(a)

ScriptEditorhashotkeysforcommenting/uncommentingblockofcode:Ctr+/Thankstothis,
thereisnoneedformultilinecommentsonecanhighlightthelargecodefragmentinScript
EditorandpressCtr+/.ThiswillcommentouthighlightedfragmentifCtrl+/ispressedagain,
commentarywillbetakenaway.

Identifiers
Identifiersaresimplynamesforuserdefinedvariablesandfunctions.Identifierscanbe
composedfromloweranduppercaseletters(fromtheEnglishalphabet),underscore_and
numbers,howeveranidentifiercannotbeginwithanumber.Lineanduppercasesymbolsdiffer
(Pineiscasesensitive).Herearesomeexamplesofvalididentifiers:
myVar
_myVar
my123Var
MAX_LEN
max_len

Type System
ThebasictypeofdatainPineisalistofvalues,namedseries.

Examplesofbuiltinseries
variablesare:open,high,low,close,volume.Thesizeofthesevectorsareequaltothe
quantityofavailablebarsbasedonthecurrenttickerandtimeframe(resolution).Theseriesmay
containnumbersoraspecialvalueNaN(meaningabsenceofvalue).(Furtherinformation
aboutNaNvaluescanbefound
here
).Anyexpressionthatcontainsaseriesvariablewillbe
treatedasaseriesitself.Forexample:

a=open+close//additionoftwoseries
b=high/2 //divisionofaseriesvariable
//totheintegerliteralconstant(bwillbea
//series)
c=close[1] //Referringtothepreviousclosevalue

Footnote:Theoperator[]alsoreturnsavalueofaseriestype.

Pinehastwotypestorepresentnumbers:integerandfloat.Theresultofanarithmetical
expressioncontainingonlynumberswillbeanumberitself.

Thereisalsostringtypewhichisusedfortheindicatorsnames,inputs,linegraphs,namesof
tickers,resolutions,tradesessions,etc.

AlsoPinehasbooltype.Therearetwobuiltinconstants:
true
and
false
.Itsimportanttonote
thatnumerictypecanbeautoconvertedtoalogicaltype0ornaare
false
,andtherest
true
.

Andthelastbasictypeiscolor.

Apartfromconfiguringacolorvaluedirectlywithaliteral

(in
hexadecimalformat),inthelanguagetherearemoreconvenient,builtinvariablesofthetype
color.Forbasiccolorsthereare:black,silver,gray,white,maroon,red,purple,fuchsia,green,
lime,olive,yellow,navy,blue,teal,aqua,orange.

Afewfunctionannotations(inparticularplotandhline)returnvalueswhichrepresentobjects
createdonthechart.Thefunctionplotreturnsanobjectofthetypeplot,representedasaline
ordiagramonthechart.Thefunction'hline'returnsanobjectofthetypehline,representedas
ahorizontalline.Theseobjectscanbepassedtothefunctionfilltofillareabetweenthem.

Literals
Fixedvaluesassignedwithimmediatevalues(e.g.,10,2,"value"),whichmaynotbealteredby
thescript,arecalledliterals.Literalscanonlybeatypeofinteger,float,boolandstring.
Footnote:inPinetherearenoliteralswhichrepresentvaluesofaseriestype.Instead,thereare
builtinvariablesofaseriestype(suchasopen,high,low,close,volume,hl2,hlc3,ohlc4).
Thesevariablesare
not
literals.

Integer Literals
Integralvaluedliteralscanbepresentedonlyinindecimalsystem.Examples:

1
750
94572
100

Floatingpoint Literals
Realliteralsincomparisonwithintegralvaluedliteralscontainadelimiter(thesymbol.)and/or
thesymbole(whichmeansmultiplyby10tothepowerofX,whereXisthenumberafterthe
symbole)orboth.Examples:

3.14159//3.14159
3
6.02e23//6.02*102

19
1.6e19//1.6*10
3.0//3.0
ThefirstnumberistheroundednumberPi(),thesecondnumberisverylarge,whilethethird
isverysmall.Thefourthnumberissimplythenumber3asafloatingpointnumber.
Footnote:itspossibletouseuppercaseEinsteadoflowercasee.

Boolean Literals
Thereareonlytwoliteralsforrepresentinglogicalvalues:
true
//truevalue
false
//falsevalue

String Literals
Stringliteralsmaybeenclosedbysingleordoublequotationmarks,forexample:
"Thisisadoublequotedstringliteral"
'Thisisasinglequotedstringliteral'
Singleordoublequotationmarksarecompletelythesameyoumayusewhatyouprefer.

Thelinethatwaswrittenwithdoublequotationmarksmaycontainasinglequotationmark,just
asalinethatiswrittenwithsinglequotationmarksmaycontaindoublequotationmarks:
"It'sanexample"
'The"Star"indicator'

Ifauserneedstoputeitherdoublequotationmarksinalinethatisenclosedbydouble
quotationmarks(orputsinglequotationmarksinalinethatisenclosedbysinglequotation
marks,)thentheymustbeprecededwithbackslash.Examples:
'It\'sanexample'
"The\"Star\"indicator"

Color Literals
Colorliteralshavethefollowingformat:#followedby6hexadecimaldigitsthatcorrespondwith
anRGBvalue.Thefirsttwo

digitsdeterminethevaluefortheRedcolorcomponent,thesecond
twoforgreen,andthethirdpairthevaluefortheBluecomponent.Examples:
#000000
//blackcolor
#FF0000
//redcolor
#00FF00
//greencolor
#0000FF
//bluecolor
#000000
//whitecolor
7

#808080
#3ff7a0

//graycolor
//somecustomcolor

Footnote:Whenusinghexadecimalfiguresitspossibletousethemineitherupperor
lowercase.

Operators
Arithmetic Operators (+, , *, /, %)
Operator

Description

Addition

Subtraction

Multiplication

Division

Taketheremainderafterdividing

Arithmeticoperationsabovearebinary.Thetypeofresultdependsonthetypeofoperands.Ifat
leastoneoftheoperandsisaseries,

thentheresultalsowillhaveaseriestype.Ifboth
operandsarenumeric,butatleastoneofthesehasthetypefloat,thentheresultwillalsohave
thetypefloat.Ifbothoperandsareintegers,thentheresultwillalsohavethetypeinteger.
Footnote:ifatleastoneoperandisNaNthentheresultisalsoNaN.

Comparison Operators (<, <=, !=, ==, >, >=)


Operator

Description

<

LessThan

<=

LessThanorEqualTo

!=

NotEqual

==

Equal

>

GreaterThan

>=

GreaterThanOrEqualTo

Comparisonoperationsarebinary.Theresultisdeterminedbythetypeofoperands.Ifatleast
oneoftheseoperandshasaseriestype,thenthetypeofresultwillalsobetheseries(aseries
ofnumericvalues).Ifbothoperandshaveanumericaltype,thentheresultwillbeofthelogical
typebool.

Logical Operators (not, and, or)


Operator

Description

not

Negation

and

LogicalConjunction

or

LogicalDisjunction

Alllogicaloperatorscanoperatewithbooloperands,numericaloperands,orseriestype
operands.Similartoarithmeticandcomparisonoperators,ifatleastoneoftheseoperandsof
anoperatorhasaseriestype,thantheresultwillalsohaveaseriestype.Inallothercasesthe
operatorstypeofresultwillbethelogicaltypebool.

Theoperatornotisunary.Ifanoperatorsoperandhasatruevaluethentheresultwillhavea
falsevalueiftheoperandhasafalsevaluethentheresultwillhaveatruevalue.

andOperatortruthtable:
a

aandb

true

true

true

true

false

false

false

true

false

false

false

false

orOperatortruthtable:
a

aorb

true

true

true

true

false

true

false

true

true

false

false

false

Conditional Operator ? and the Function iff


ConditionalTernaryOperator
calculatesthefirstexpression(condition)andreturnsavalue
eitherofthesecondoperand(iftheconditionistrue)orofthethirdoperand(iftheconditionis
false).Syntax:
9

condition?result1:result2

Ifconditionwillbecalculatedtotrue,thenresult1willbetheresultofallternaryoperator,
otherwise,result2willbetheresult.

Thecombinationofafewconditionaloperatorshelpstobuildconstructionssimilartoswitch
statementsinotherlanguages.Forexample:
isintraday?red:isdaily?green:ismonthly?blue:na

Thegivenexamplewillbecalculatedinthefollowingorder(bracketsshowtheprocessingorder
ofthegivenexpression):
isintraday?red:(isdaily?green:(ismonthly?blue:na))

Firsttheconditionisintradayiscalculatedifitistruethenredwillbetheresult.Ifitisfalsethen
isdailyiscalculated,ifthisistrue,thengreenwillbetheresult.Ifthisisfalse,thenismonthlyis
calculated.Ifitistrue,thenbluewillbetheresult,otherwiseitwillbe
na
.

Forthosewhofindusingtheoperatorsyntax?:inconvenient,inPinethereisanalternative
(withequivalentfunctionality)thebuiltin
functioniff
.Thefunctionhasthefollowing
signature:
iff(condition,result1,result2)

Thefunctionactsidenticallytotheoperator?:,i.e.,iftheconditionistruethenitreturnsresult1,
otherwiseresult2.
Thepreviousexampleusingiffwilllooklike:
iff(isintraday,red,iff(isdaily,green,
iff(ismonthly,blue,na)))

History Referencing Operator (Square Brackets [])


Itispossibletorefertothehistoricalvaluesofanyvariableofaseriestype(valueswhichthe
variablehadonthepreviousbars)withthe[]operator
.
Forexample,wewillassumethatwe
havethevariableclose,containing10values(thatcorrespondtoachartwithacertain
hypotheticalsymbolwith10bars):

Index

close

15.25

15.46

15.35

15.03

15.02

14.80

15.01

12.87

12.53

12.43

Applyingtheoperator[]witharguments1,2,3,wewillreceivethefollowingvector:

Index

9
10

close[1]

NaN

15.25

15.46

15.35

15.03

15.02

14.80

15.01

12.87

12.53

close[2]

NaN

NaN

15.25

15.46

15.35

15.03

15.02

14.80

15.01

12.87

close[3]

NaN

NaN

NaN

15.25

15.46

15.35

15.03

15.02

14.80

15.01

Whenavectorisshifted,aspecialNaNvalueispushedtovector'stail.NaNmeansthatthe
numericalvaluebasedonthegivenindexisabsent.

Thevaluestotheright,whichdonothave
enoughspacetobeplacedinavectorofalineof10elementsaresimplyremoved.Thevalue
fromthevector'sheadispopped.

Inthegivenexampletheindexofthecurrentbarisequalto
9.
thevalueofthevectorclose[1]onthecurrentbarwillbeequaltothepreviousvalueof
theinitialvectorclose
thevalueclose[2]willbeequaltothevalueclosetwobarsago,etc.

Sotheoperator[]canbethoughtofasthehistoryreferencingoperator.

Footnote1.AlmostallbuiltinfunctionsinPinesstandardlibraryreturnaseriesresult,for
examplethefunctionsma.Thereforeitspossibletoapplytheoperator[]directlytothefunction
calls:
sma(close,10)[1]

Footnote2.Despitethefactthattheoperator[]returnstheresultoftheseriestype,its
prohibitedtoapplythisoperatortothesameoperandoverandoveragain.Hereisanexample
ofincorrectuse:
close[1][2]
//Error:incorrectuseofoperator[]
Acompilationerrormessagewillappear.

Insomesituations,theusermaywanttoshifttheseriestotheleft.Negativeargumentsforthe
operator[]areprohibited.Thiscanbeaccomplishedusingoffsetargumentinplotannotation.
Itsupportsbothpositiveandnegativevalues.Note,thoughthatitisavisualshift.,i.e.,itwillbe
appliedafter

allthecalculations.Furtherdetailsaboutplotanditsargumentscanbefound
here
.

Thereisanotherimportantconsiderationwhenusingoperator[]inPinescripts.Theindicator
executesacalculationoneachbar,beginningfromtheoldestexistingbaruntilthemostrecent
one(thelast).Asseeninthetable,close[3]hasavaluethatisNaNonthefirstthreebars.NaN
representsavaluewhichisnotanumberandusingitinanymathexpressionwillresultinalso
NaN.SoyourcodeshouldspecificallyhandleNaNvaluesusingfunctions
naandnz
.

11

Priority of Operators
Theorderofthecalculationsisdeterminedbytheoperatorspriority.Operatorswithgreater
priorityarecalculatedfirst.Belowarealistofoperatorssortedbydecreasingpriority:

Priority

OperationSymbol

[]

+(unary)
(unary)
not

*
/
%

>
<
>=
<=

==
!=

and

or

?:

Ifinoneexpressionthereareseveraloperatorswiththesamepriority,thentheyarecalculated
lefttoright.

Ifitsnecessarytochangetheorderofcalculationstocalculatetheexpression,thenpartsofthe
expressionshouldbegroupedtogetherwithparentheses.

Functions vs Annotation Functions


Pinebesidesoperatorshasalsofunctionsandannotationfunctions.Occasionally,forbrevitys
sake,thismanualwillrefertoannotationfunctionsassimplyannotations.Syntacticallytheyare
similar(howevertherearesomedifferenceswhichwillnowbediscussed),buttheyhave
differentpurposesandusageeffects.

12

Functionsareusedforcalculatingvaluesandalwaysreturnaresult.Functionsneverhaveside
effects.Functioncallsareusedinexpressionsalongwithoperators.Essentially,theydetermine
thecalculationalgorithm.Functionsaredividedintobuiltinorcustom(userdefined).Examples
ofbuiltinfunctions:
sma,ema,iff
.

Functionannotationsareusedfordeterminingmetainformationwhichdescribesanindicator
beingcreated(theyalsohave

sideeffects).Allannotationsarebuiltin.Annotationsmay
assignanametoanindicator
determinewhichvariablesappearincomingandoutgoing(bydefault,Itsalsopossibleto
assignanameanddefaultvaluesforincomingvariables).

Outgoingvariablesare
displayedonthechartasgraphsorotherlayouts.
someothervisualeffects(e.g.,backgroundcoloring)

Name,colorandeachgraphsdisplay

stylearedeterminedinannotations.Examplesoffunction
annotations:study,input,plot.

Afewannotationshavenotonlysideeffects(intheformofdeterminingmetainformation)but
alsoreturnaresult.Plotandhlinearesuchannotations.Howeverthisresultcanbeusedonly
inotherannotationsandcanttakepartintheindicatorscalculations(see
annotationfill
).

Syntactically,functionsandannotationfunctionsaresimilarinusewithinthescript:touseeither
functionorannotationoneshouldspecifyitsnameaswellasthelistofactualargumentsin
parentheses.Themaindifferenceisinusagesemantic.Also,thereisadifferenceinpassing
argumentsannotationsacceptkeywordargumentswhilefunctionsdoesnot.

Functioncallsallowstopassargumentsonlybyposition.Formostofprogramminglanguages
it'stheonlyavailablemethodofargumentspassing.Functionannotationcallsalsoaccepts
keywordarguments.Thisallowstospecifyonlypartofargumentsleavingothersbydefault.
Comparethefollowing:
study('Example','Ex',true)
and
study(title=Example,shorttitle=Ex,overlay=true)

Itspossibletomixpositionalandkeywordarguments.Positionalargumentsmustgofirstand
keywordargumentsshouldfollowthem.Sothefollowingcallisnotvalid:
study(precision=3,Example)

Expressions, Declarations and Statements


Expressions
Anexpressionisasequenceofapplyingbothoperatorsandfunctioncallstooperands
(variables,values),whichdeterminesthecalculationsandactionsdonebythescript.

13

ExpressionsinPinealmostalwaysproducearesult(onlyannotationfunctionsareanexception,
suchasstudyorfill).Theyproducesideeffectsandwillbecoveredlater.

Herearesomeexamplesofsimpleexpressions:
(high+low+close)/3
sma(highlow,10)+sma(close,20)

Variable Declarations
VariablesinPinearedeclaredwiththehelpofthespecialsymbol=inthefollowingway:
<identifier>=<expression>

Inplaceof<identifier>willbethenameofthedeclaredvariable.Variablesareconnectedwith
theexpressiononetime(atthemomentofdeclaration)andtorelinkthevariabletoanother
expressionisprohibited.

ExamplesofVariableDeclarations:
src=close
len=10
ma=sma(src,len)+high

Threevariablesweredeclaredhere:
src
,
len
and
ma
.Identifiers
close
and
high
arebuiltin
variables.Theidentifier
sma
isabuiltinfunctionforcalculatingSimpleMovingAverage.

Self Referencing Variables


Theabilitytoreferencethepreviousvaluesofdeclaredvariablesinexpressionswheretheyare
declared(usingtheoperator[])isausefulfeatureinPine.Thesevariablesarecalledself
referencingvariables.ForExample:
study("Fibonaccinumbers")
fib=na(fib[1])orna(fib[2])?1:fib[1]+fib[2]
plot(fib)

ThevariablefibisaseriesofFibonaccinumbers:1,1,2,3,5,8,13,21,Wherethefirsttwo
numbersareequalto1and1

andeachsubsequentnumberisthesumofthelasttwo.Inthe
givenexample,thebuiltinfunctionnaisusedandreturnstrueifthevalueofitsargumenthas
stillnotbeendetermined(isNaN).Intheexampleproducedbelow,thevaluesfib[1]andfib[2]
havenotbeendeterminedonthefirstbar,whileonthesecondbarfib[2]hasnotbeen
determined.Finally,onthethirdbarbothofthemaredefinedandcanbeadded.

14


Footnote:SincethesequenceofFibonaccinumbersgrowsratherfast,thevariablefibvery
quicklyoverflows.Assuch,theusershouldapplythegivenindicatoronthemonthlyMor
yearlyYresolution,otherwisethevaluen/awillbeonthechartinsteadofFibonaccinumbers.

TODO:Addinfoaboutsocalledforwardreferencingvariables.

Preventing NaN values, Functions na and nz


Selfreferencingvariablesallowfortheaccumulationofvaluesduringtheindicatorscalculation
onthebars.Howeverthereisonepointtoremember.Forexample,let'sassumewewantto
countallthebarsonthechartwiththefollowingscript:
barNum
=
barNum
[1]+1

TheselfreferencingvariablebarNumreferstoitsownvalueonthepreviousbar,meaning,
whentheindicatorwillbecalculatedoneverybar,thevaluebarNum[1]willbeequaltoNaN.
Therefore,onthefirstbarbarNum[1]willnotbedefined(NaN).

Adding1toNaN,NaNwillstill
betheresult.Intotal,theentirebarNumserieswillbeequaloneverybartoNaN.Onnextbar,
barNum=NaN+1=NaNandsoon.Intotal,barNumwillcontainonlyNaNvalues.

Inordertoavoidsimilarproblems,Pinehasabuiltinfunctionnz.Thisfunctiontakesan
argumentandifitisequaltoNaNthenitreturns0,otherwiseitreturnstheargumentsvalue.
Afterwards,theproblemwiththebarscalculationissolvedinthefollowingway::
barNum
=nz(
barNum
[1])+1

Thereisanoverloadedversionofnzwithtwoargumentswhichreturnsthesecondargumentif
thefirstisequaltoNaN.Furtherinformationaboutnzcanbefound
here
.

15

Inaddition,thereisasimplefunctionwithoneargumentthatreturnsalogicalresultcalledna.
ThisfunctionmakesitpossibletocheckiftheargumentisNaNornot.Checkitout
here
.

Simple Moving Average without applying the Function sma


Whileusingselfreferencingvariables,itspossibletowritetheequivalentofthebuiltinfunction
smawhichcalculatestheSimpleMovingAverage.
study("CustomSimpleMA",overlay=true)
src=close
len=9
sum=nz(sum[1])nz(src[len])+src
plot(sum/len)

Thevariablesumisamovingsumwithonewindowthathasalengthlen.Oneachbarthe
variablesumisequaltoitspreviousvalue,thentheleftmostvalueinamovingwindowis
subtractedfromsumandanewvalue,whichenteredthemovingwindow(therightmost),is
added.Thisisthealgorithmoptimizedforvectorlanguages,see
MovingAverage
foradetailedbasicalgorithmdescription.

Further,beforethegraphisrendered,thesumisdividedbythewindowsizelenandthe
indicatorisdisplayedonthechartastheSimpleMovingAverage.

Selfreferencingvariablescanalsobeusedinfunctionswrittenbytheuser.Thiswillbe
discussedlater.

if statement
Ifstatementdefineswhatblockofstatementsmustbecheckedwhenconditionsofthe
expressionaresatisfied.

Tohaveaccesstoandusetheifstatement,oneshouldspecifytheversionofPineScript
languageintheveryfirstlineofcode://@version=2

Generalcodeform:

var_declarationX=ifcondition
var_decl_then0
var_decl_then1

var_decl_thenN
return_expression_then
else
var_decl_else0
16

var_decl_else1

var_decl_elseN
return_expression_else

where:
var_declarationXthisvariablegetsthevalueoftheifstatement

conditioniftheconditionistrue,thelogicfromtheblockthen(var_decl_then0,
var_decl_then1,etc)isused,iftheconditionisfalse,thelogicfromtheblockelse
(var_decl_else0,var_decl_else1,etc)isused.

return_expression_then,return_expression_elsethelastexpressionfromtheblock
thenorfromtheblockelsewillreturnthefinalvalueofthestatement.Ifdeclarationof
thevariableisintheend,itsvaluewillbetheresult.

Thetypeofreturningvalueoftheifstatementdependsonreturn_expression_thenand
return_expression_elsetype(theirtypesmustmatch:itisnotpossibletoreturnanintegervalue
fromthen,whileyouhaveastringvalueinelseblock).

Example:
//Thiscodecompiles
x=ifclose>open
close
else
open

//Thiscodedoesntcompile
x=ifclose>open
close
else
open

Itispossibletoomittheelseblock.Inthiscaseiftheconditionisfalse,anemptyvalue(na,
orfalse,or)willbeassignedtothevar_declarationXvariable.

Example:
x=ifclose>open
close
//Ifcurrentclose>currentopen,thenx=close.
//Otherwisethex=na.

17

Theblocksthenandelseareshiftedby4spaces.Ifstatementscanincludeeachother,+4
spaces:
x=ifclose>open
b=ifclose>close[1]
close
else
close[1]
b
else
open

Itispossibletoignoretheresultingvalueofanifstatement(var_declarationX=canbeomited).
Itmaybeusefulifyouneedthesideeffectoftheexpression,forexampleinstrategytrading:
if(crossover(source,lower))
strategy.entry("BBandLE",strategy.long,stop=lower,
oca_name="BollingerBands",
oca_type=strategy.oca.cancel,comment="BBandLE")
else
strategy.cancel(id="BBandLE")

Declaring Functions
InPineScriptthereisanextensivelibraryofbuiltinfunctionswhichcanbeusedtocreate
indicators.Apartfromthesefunctions,theuserisabletocreatehisorherownpersonal
functionsinPine.

Singleline Functions
Simpleshortfunctionsareconvenienttowriteononeline.Thefollowingisthesyntaxof
singlelinefunctions:
<identifier>(<listofarguments>)=><expression>

Thenameofthefunction<identifier>islocatedbeforetheparentheses.Then,locatedin
parenthesisis

<listofarguments>,whichissimplyalistoffunctionarguments

separatedbya
comma.<expression>intheexampleisthefunctionsbody.

Hereisanexampleofasinglelinefunction:
f(x,y)=>x+y

Afterthefunctionfhasbeendetermined,itspossibletocallit::
a=f(open,close)
b=f(2,2)
c=f(open,2)

18

Payattentiontothefactthatthetypeofresultwhichisbeingreturnedbythefunctionfcanbe
different.Intheexampleabove,thetypeofvariableawillbeaseries.Thetypeofvariablebis
aninteger.Thetypeofvariablecisaseries.Pineusesdynamicargumentstypingsoyou
shouldnotassignthetypeofeachargument.

Thetypeofresultisdeducedautomatically.Itdependsonthetypeofargumentswhichwere
passedtothefunctionandthestatementsofthefunctionbody.

Footnote:inPineitspossibletocallotherfunctionsfromfunctions

excepttheoriginal
function,i.e.,recursionisnotsupported.

Multiline Functions
Ofcourseitsdifficulttodoanysortofadvancedcalculationswithonlyonelinefunctions.Sowe
decidedtoexpandthesyntaxofdeclaringfunctionsbymakingthemmultiline.Heresasyntax
ofamultilinefunction:

<identifier>(<listofarguments>)=>
<VariableDeclaration>
...
<VariableDeclaration>
<expression>or<VariableDeclaration>

Thebodyofamultilinefunction

consistsofafewstatements.Eachstatementisplacedona
separatelineandmustbeprecededby1indentation(fourspacesor1tab).Theindentation
beforethestatementindicatesthatitispartofthebodyofthefunctionandnotintheglobal
scope.Thefirststatementmetthatisplacedwithoutanindent(atthestartoftheline)will
indicatethatthebodyofthefunctionhasfinishedonthepreviousstatement.

Eitheranexpressionoradeclaredvariableshouldbethelaststatementofthefunctionsbody.
Theresultofthisexpression(orvariable)willbearesultoftheentirefunctionscall.

Forexample:
geom_average(x,y)=>
a=x*x
b=y*y
sqrt(a+b)

Thefunctiongeom_averagehastwoargumentsandcreatestwovariablesinthebody:aand
b.Thelaststatementcallsthefunctionsqrt(anextractionofthesquareroot).The
geom_averagecallwillreturnthelastexpressionvalue(sqrt(a+b)).

19

Scopes in the Script


Variableswhicharedeclaredoutsidethebodyofanyfunctionbelongtotheglobalscope.
Userdeclaredfunctionsalsobelongtotheglobalscope.Allbuiltinvariablesandfunctionsalso
belongtotheglobalscope.

Eachfunctionhasitsownlocalscope.Allthevariablesdeclaredinsidethefunction(andthis
functionargumentstoo)belongtoscopeofthatfunction,meaningthatitisimpossibleto
referencethemfromoutsidee.g.,fromtheglobalscopeorthelocalscopeofanother
function.Atthesametime,fromthescopeofanyfunction,itspossibletorefertoanyvariable
declaredintheglobalscope.

Soit'spossibletoreferenceanyglobaluservariablesandfunctions(apartfromrecursivecalls)
andbuiltinvariables/functionsfromuserfunction'sbody.Onecansaythatthelocalscopehas
beenembeddedthetheglobalone.

InPine,nestedfunctionsarenotallowed,i.e.onecantdeclarefunctioninsideanotherfunction.
Alluserfunctionsaredeclaredintheglobalscope.

Localscopesdonotintersectbetweenone
another.

Functions with self ref Variables in the Body


Thebodyofamultilinefunctionisasequenceofexpressionsand/orvariabledeclarations.Any
variablethatisbeingdeclaredinthebodyofafunctioncanbeaselfreferencingone.An
exampleofthefunctionmy_smawhichisequivalenttothebuiltinfunctionsma:

study("CustomSimpleMA",overlay=true)
my_sma(src,len)=>
sum=nz(sum[1])nz(src[len])+src
sum/len
plot(my_sma(close,9))

PayattentiontotheuseoffunctionnztopreventNaNvaluestheyappearfromtheleftsideof
theseriesasaresultofshiftingittotheright.

Aslightlymoredifficultexample,thefunctionmy_emaisidenticaltothebuiltinfunctionema:

study("CustomExpMA",overlay=true)
my_ema(src,len)=>
weight=2.0/(len+1)
sum=nz(sum[1])nz(src[len])+src
ma=na(src[len])?na:sum/len
out=na(out[1])?ma:(srcout[1])*weight+out[1]
out
20

plot(my_ema(close,9))

Payattentiontothefactoutisthelaststatementofthefunctionmy_ema.Itisasimple
expressionconsistingofoneofthevariablereference.Thevalueofthevariableoutin
particular,isavaluebeingreturnedbythewholefunctionmy_ema.

Ifthelastexpressionisa
variabledeclarationthenitsvaluewillbethefunction'sresult.Sothefollowingtwofunctionsare
completelythesame:
f1(x)=>
a=x+a[1]
a
f2(x)=>
a=x+a[1]

Functions that return multiple result


Inmostcasesafunctionreturnsoneresult.Butitispossibletoreturnalistofresults:
fun(x,y)=>
a=x+y
b=xy
[a,b]
Thereisaspecialsyntaxforcallingsuchfunctions:
[res0,res1]=fun(open,close)
plot(res0)
plot(res1)

Lines Wrapping
AnystatementthatistoolonginPineScriptcanbeplacedonafewlines.Syntactically,
a
statementmustbeginatthebeginningoftheline.Ifitwrapstothenextlinethenthe
continuationofthestatementmustbeginwithoneorseveral(differentfrommultipleof4)
spaces.
Forexample,theexpression:
a=open+high+low+close

maybewrappedas

a=open+
high+
low+
close

Thelongplotcalllinemaybewrappedas

plot(correlation(src,ovr,length),
21

color=purple,
style=area,
transp=40)

Statementsinsideuserfunctionsalsocanbewrappedtoseverallines.However,since
syntacticallyalocalstatementmustbeginwithanindentation(4spacesor1tab)then,when
splittingitontothefollowingline,thecontinuationofthestatementmuststartwithmorethan
oneindentation(andnotequaltomultipleof4spaces).Forexample:
updown(s)=>
isEqual=s==s[1]
isGrowing=s>s[1]
ud=isEqual?
0:
isGrowing?
(nz(ud[1])<=0?
1:
nz(ud[1])+1):
(nz(ud[1])>=0?
1:
nz(ud[1])1)

Context Switching, The security Function


Thefunctionsecurityletstheusertorequestdatafromadditionalsymbolsandresolutions,
otherthantheonestowhichtheindicatorisapplied.

WewillassumethatweareapplyingascripttothechartIBM,1.Thefollowingscriptwilldisplay
thecloseoftheIBMsymbolbutona15resolution.

study("Examplesecurity1",overlay=true)
ibm_15=security("NYSE:IBM","15",close)
plot(ibm_15)

22

Asseenfromthesecurityarguments
description
,thefirstargumentisthenameofthe
requestedsymbol.Thesecondargumentistherequiredresolution,andthethirdoneisan
expressionwhichneedstobecomputedontherequestedseries.

Thenameofthesymbolcanbesetusingtwovariants:withaprefixthatshowstheexchange
(ordataprovider)orwithoutit.Forexample:NYSE:IBM,BATS:IBMorIBM.Inthecaseof
usingthenameofasymbolwithoutanexchangeprefix,theexchangeselectedbydefaultis
BATS.Currentsymbolnameisassignedtotickerandtickeridbuiltinvariables.Thevariable
tickercontainsthevalueofthesymbolnamewithoutanexchangeprefix,forexampleMSFT.
Thevariabletickeridisasymbolnamewithanexchangeprefix,forexample,BATS:MSFT,
NASDAQ:MSFT.Itsrecommendedtousetickeridtoavoidpossibleambiguityinthe
indicatorsdisplayedvaluesofdatatakenfromdifferentexchanges.

Theresolution(thesecondargumentofthesecurityfunction)isalsosetasastring.Any
intradayresolutionissetbyspecifyinganumberofminutes.Thelowestresolutionisminute
whichissetbytheliteral1.Itspossibletorequestanynumberofminutes:5,10,21,etc.
Hourlyresolutionisalsosetbyminutes.Forexample,thefollowinglinessignifyanhour,two
hoursandfourhoursrespectively:60,120,240.Aresolutionwithavalueof1dayissetby
thesymbolsDor1D.Itspossibletorequestanynumberofdays:2D,3D,etc.Weekly
andmonthlyresolutionsaresetinasimilarway:W,1W,2W,,M,1M,2M.Mand
1Maresortsofonemonthresolutionvalue.Wand1Warethesameweeklyresolution
value.
Thethirdparameterofthesecurityfunctioncanbeanyarithmeticexpressionorafunctioncall,
whichwillbecalculatedinchosenseriescontext.Forexample,withthesecuritytheusercan
viewaminutechartanddisplayanSMA(oranyotherindicator)basedonanyotherresolution
(i.e.daily,weekly,monthly).
23

study(title="HighTimeFrameMA",overlay=true)
src=close,len=9
out=sma(src,len)
out1=security(tickerid,'D',out)
plot(out1)

Oronecandeclarethevariable
spread=highlow

andcalculateitin1,15and60minutes:
spread_1=security(tickerid,'1',spread)
spread_15=security(tickerid,'15',spread)
spread_60=security(tickerid,'60',spread)

Thefunctionsecurity,asshouldbeunderstoodfromtheexamples,returnsaserieswhichis
adaptedcorrespondinglytothetimescaleofthecurrentchart'ssymbol.Thisresultcanbeeither
showndirectlyonthechart(i,e,,withplot),orbeusedinfurthercalculationsoftheindicators
code.TheindicatorAdvanceDeclineLineofthefunctionsecurityisamoredifficultexample:

study(title="AdvanceDeclineLine",shorttitle="ADL")
sym(s)=>security(s,period,close)
difference=(sym("ADVN")sym("DECN"))/(sym("UNCN")+1)
adline=cum(difference>0?sqrt(difference):
sqrt(difference))
plot(adline)

Thescriptrequeststhreesecuritiesatthesametime.Resultsoftherequestsarethenaddedto
anarithmeticformula.Asaresult,wehaveastockmarketindicatorusedbyinvestorsto
measurethenumberofindividualstocksparticipatinginanupwardordownwardtrend(read
more
).

Payattentiontothefactthat,outofconvenience,thecallsecurityiswrappedupintheuser
functionsym.(justtowriteabitlessofcode).

securityfunctionwasdesignedtorequestdataofatimeframehigherthanthecurrentchart
timeframe.Forexample,ifyouhavea1hchart,youcanrequest4h,1D,1W(oranyhigher
timeframe)andplottheresults.Itsnotrecommendedtorequestlowertimeframe,forexample
15mindatafrom1hchart.

24

Sessions and Time Functions


Functions and the Variable time
InPinetherearespecialmeansforworkingwithtradesessions,timeanddate.Wewillreviewa
simplechart,IBM,30onwhichhasbeenapplied2scripts:Bardate/timeandSessionbars.

Hereistheinitialcodeofthefirstscript"Bardate/time":
study("Bardate/time")
plot(time)

Thisillustratesthemeaningofthevariable

time
.Thevariabletimereturnsthedate/time
(timestamp)ofeachbaronthechartinUNIXformat.Ascanbeenseenfromthescreenshot,
thevaluetimeonthelastbarisequalto1397593800000.Thisvalueisthenumberof
millisecondsthathavepassedsince00:00:00UTC,1January,1970andcorrespondsto
Tuesday,15thofApril,2014at20:30:00UTC.(Therearealotofonlineconvertors,forexample
OnlineConversion.com
).Thechartstimegaugeinthescreenshotshowsthetimeofthelastbar
as2014041516:30(intheexchangetimezone,fromherethedifferencebetweenthistimeand
UTCis4hours).

Thesecondscript,"Sessionbars":

study("Sessionbars")
t=time(period,"09301600")
plot(na(t)?0:1)

Thisshowshowtheusercandistinguishbetweensessionbarsandbarsthatgetintoextended
hoursbyusingthebuiltinfunctiontimeandnotthevariabletime

(thebackgroundbehind
25

thesebarshasbeencoloredoverwithgrey).Thefunctiontimereturnsthetimeofthebarin
millisecondsUNIXtimeorNaNvalueifthebarislocatedoutsidethegiventradesession
(09:3016:00inourexample).timeacceptstwoarguments,thefirstisresolution,thebarsof
whichareneededtodeterminetheirtimestamp,andthesecondsessionspecification,which
isastringthatspecifiesthebeginningandendofthetradesession(intheexchangetimezone).
Thestring09301600correspondstothetradesessionsymbolIBM.Examplesoftrade
sessionconfigurations:
00000000acomplete24hourswiththesessionbeginningatmidnight.
17001700acomplete24hourswiththesessionbeginningat17:00.
"09001600,17002000"asessionthatbeginsat9:00withabreakat16:00until17:00
andendingat20:00
"20001630"anovernightsessionthatbeginsat20:00andendsat16:30thenext
day.

Sessionspecification,whichisbeingpassedtothefunctiontime,isnotrequiredtocorrespond
withtherealtradesessionofthesymbolonthechart.Itspossibletopassdifferent
hypotheticalsessionspecificationswhichcanbeusedtohighlightthoseor(other?)barsina
dataseries.Itspossibletotransferthedifferenthypotheticalsessionspecificationswhichcan
beusedtohighlightthoseorotherbarsinadataseries.

Thereisanoverloadedfunctiontimethatallowstheusertoskipcustomsessionspecification.
Inthiscase,internally,itwillusearegularsessionspecificationofasymbol.Forexample,its
possibletohighlightthebeginningofeachhalfhourbaronaminutebasedchartinthefollowing
way:

study("new30minbar")
is_newbar(res)=>
t=time(res)
change(t)!=0?1:0
plot(is_newbar("30"))

26

Thefunctionis_newbarfromthepreviousexamplecanbeusedinmanysituations.For
example,itsessentialtodisplayonanintradaychartthehighsandlowswhichbeganatthe
marketsopening:

study("Openinghigh/low",overlay=true)

highTimeFrame=input("D",type=resolution)
sessSpec=input("09301600",type=session)

is_newbar(res,sess)=>
t=time(res,sess)
change(t)!=0?1:0

newbar=is_newbar(highTimeFrame,sessSpec)
s1=newbar?low:nz(s1[1])
s2=newbar?high:nz(s2[1])

plot(s1,style=circles,linewidth=3,color=red)
plot(s2,style=circles,linewidth=3,color=lime)

27

PayattentiontothevariableshighTimeFrameandsessSpec.Theyhavebeendeclaredina
specialwaywiththevariableofthefunctionsinput.Furtherinformationaboutindicatorsinputs
canbefoundhere:
inputvariables
.

Builtin Variables for working with Time


Pinesstandardlibraryhasanassortmentofbuiltinvariableswhichallowabarstimeinthe
logicofanargumentsalgorithmtobeusedinscripts:
timeUNIXtimeofthecurrentbarinmilliseconds
(inUTCtimezone).
yearCurrentbaryear.
monthCurrentbarmonth.
weekofyearWeeknumberofcurrentbartime.
dayofmonthDateofcurrentbartime.
dayofweekDayofweekforcurrentbartime.Youcanuse
sunday
,
monday
,
tuesday
,
wednesday
,
thursday
,
friday
and
saturday
variablesforcomparisons.
hourCurrentbarhour.
minuteCurrentbarminute.
secondCurrentbarsecond.

Thefollowingarealsobuiltinfunctions:
year(x)ReturnsyearforprovidedUTCtime.
month(x)ReturnsmonthforprovidedUTCtime.
weekofyear(x)ReturnsweekofyearforprovidedUTCtime.
dayofmonth(x)ReturnsdayofmonthforprovidedUTCtime.
dayofweek(x)ReturnsdayofweekforprovidedUTCtime.
hour(x)ReturnshourforprovidedUTCtime.
minute(x)ReturnsminuteforprovidedUTCtime.
28

second(x)Returnssecondforprovidedtime.
Allthesevariablesandfunctionsreturn
timeinexchangetimezone
,exceptforthe
time
variablewhichreturnstimeinUTCtimezone.

Extended and Regular Sessions


InTradingViewthereisanoption(RightClickonChart,Properties
Timezone/Sessions

ExtendedHours)thatcontrolstypeofcurrentchartsession.Therearetwotypesofsession:
regular
(withoutextendedhoursdata)and
extended
(withthem).InPinescriptsitispossibleto
specifysessiontypeforadditionaldata,thatisrequestedwithsecurityfunction.

Usuallyyoupassto'security'functionfirstargumentsymbolnameinformof
EXCHANGE_PREFIX:TICKER
,e.g."BATS:AAPL".Insuchacase,datawithregularsession
typewillberequested.Forexample:

study("Example1:RegularSessionData")
cc=security("BATS:AAPL",period,close,true)
plot(cc,style=linebr)

Ifyouwanttorequestthesamedatabutwithextendedsessiontype,youshoulduse'tickerid'
function(don'tconfuseitwithvariable'tickerid').Example:

study("Example2:ExtendedSessionData")
t=tickerid("BATS","AAPL",
session.extended
)
cc=security(t,period,close,true)
29

plot(cc,style=linebr)

Nowyoushouldseethedifferencethegapsarefilledwithdata.

Firstargumentof'tickerid'isanexchangeprefix("BATS"),andthesecondargumentisaticker
("AAPL").Thirdargumentspecifiesthetypeofthesession(session.extended).Thereisalsoa
builtinvariablesession.regularforrequestingregularsessiondata.So,Example1couldbe
rewrittenas:

study("Example3:RegularSessionData(usingtickerid)")
t=tickerid("BATS","AAPL",
session.regular
)
cc=security("BATS:AAPL",period,close,true)
plot(cc,style=linebr)

Ifyouwanttorequestthesamesessionthatissetforthecurrentmainsymbol,justomitthe
thirdargument.Itisoptional.Or,ifyouwanttoexplicitlydeclareinthecodeyourintentions,
pass'syminfo.session'builtinvariableasthirdparameterto'tickerid'function.Variable
'syminfo.session'holdsthesessiontypeofthecurrentmainsymbol.

study("Example4:SameasMainSymbolSessionTypeData")
t=tickerid("BATS","AAPL")
cc=security(t,period,close,true)
plot(cc,style=linebr)

30

WritingcodesimilartoExample4whateversessiontypeyousetinChartProperties,yourPine
Scriptwouldusethesametype.

NonStandard Chart Types Data


Thereareadditionalfunctionsthatyoumayapplyto'tickerid'functionreturnvalue.Theyare
'heikinashi','renko','linebreak','kagi'and'pointfigure'.Allofthemworkinthesamemanner,they
justcreateaspecialtickeridentifierthatcouldbepassedlateras'security'functionfirst
argument.

'heikinashi' function

HeikinAshimeansaveragebarinJapanese.Open,High,LowandClosepricesofHA
candlesticksarenotactualprices,theyareresultsfromavergaingvaluesofthepreviousbar,
whichhelpseliminaterandomvolatility.

Pinefunction'heikinashi'createsaspecialtickeridentifierforrequestingHeikinAshidatawith
'security'function.

ThisscriptrequestslowpricesofHeikinAshibarsandplotsthemontopofusualOHLCbars:

study("Example5",overlay=true)
ha_t=
heikinashi
(tickerid)
ha_low=security(ha_t,period,low)
plot(ha_low)

NotethatlowpricesofHeikinAshibarsaredifferentfromusualbarslowprices.

Youmaywanttoswitchoffextendedhoursdatain"Example5".Inthiscaseweshoulduse
'tickerid'functioninsteadof'tickerid'variable:

study("Example6",overlay=true)
31

t=
tickerid(syminfo.prefix,ticker,session.regular)
ha_t=heikinashi(t)
ha_low=security(ha_t,period,low,true)
plot(ha_low,style=linebr)

Notethatwepassadditionalfourthparametertosecurity('true'),anditmeansthatpointswhere
dataisabsent,willnotbefilledupwithpreviousvalues.Sowe'dgetemptyareasduringthe
extendedhours.Tobeabletoseethisonchartwealsohadtospecifyspecialplotstyle
('style=linebr'LineWithBreaks).

YoumayplotHeikinAshibarsexactlyastheylookfromPinescript.Hereisthesourcecode:

study("Example6.1")
ha_t=heikinashi(tickerid)
ha_open=security(ha_t,period,open)
ha_high=security(ha_t,period,high)
ha_low=security(ha_t,period,low)
ha_close=security(ha_t,period,close)
palette=ha_close>=ha_open?lime:red
plotcandle(ha_open,ha_high,ha_low,ha_close,color=palette)

Readmoreaboutplotcandle(andplotbar)functions
here
.

'renko' function

32

Thischarttypeonlyplotspricemovements,withouttakingtimeorvolumeintoconsideration.It
isconstructedfromticksandlookslikebricksstackedinadjacentcolumns.Anewbrickisdrawn
afterthepricepassesthetoporbottomofpreviouslypredefinedamount.

study("Example7",overlay=true)
renko_t=
renko
(tickerid,"open","ATR",10)
renko_low=security(renko_t,period,low)
plot(renko_low)

PleasenotethatyoucannotplotRenkobricksfromPinescriptexactlyastheylook.Youcan
justgetaseriesofnumbersthataresomewhatOHLCvaluesforRenkochartandusethemin
youralgorithms.

Fordetailedreferenceonall'renko'argumentsgo
here
.

'linebreak' function

Thischarttypedisplaysaseriesofverticalboxesthatarebasedonpricechanges.

study("Example8",overlay=true)
lb_t=
linebreak
(tickerid,"close",3)
lb_close=security(lb_t,period,close)
33

plot(lb_close)

PleasenotethatyoucannotplotLineBreakboxesfromPinescriptexactlyastheylook.You
canjustgetaseriesofnumbersthataresomewhatOHLCvaluesforLineBreakchartanduse
theminyouralgorithms.

Fordetailedreferenceonall'linebreak'argumentsgo
here
.

'kagi' function

Thischarttypelookslikeacontinuouslinethatchangesdirectionsandswitchesfromthinto
bold.Thedirectionchangeswhenthepricechangesbeyondapredefinedamount,andtheline
switchesbetweenthinandboldifthelastchangebypassedthelasthorizontalline.

study("Example9",overlay=true)
kagi_t=
kagi
(tickerid,"close",1)
kagi_close=security(kagi_t,period,close)
plot(kagi_close)

34


PleasenotethatyoucannotplotKagilinesfromPinescriptexactlyastheylook.Youcanjust
getaseriesofnumbersthataresomewhatOHLCvaluesforKagichartandusetheminyour
algorithms.

Fordetailedreferenceonall'kagi'argumentsgo
here
.

'pointfigure' function

PointandFigure(PnF)charttypeonlyplotspricemovements,withouttakingtimeinto
consideration.AcolumnofXsisplottedasthepricerisesandOsasthepricedrops.

PleasenotethatyoucannotplotPnFX'sandO'sfromPinescriptexactlyastheylook.Youcan
justgetaseriesofnumbersthataresomewhatOHLCvaluesforPnFchartandusethemin
youralgorithms.EverycolumnofX'sorO'sarerepresentedwithfournumbers,youmaythinkof
themassomeimaginaryOHLCPnFvalues.InPinescriptyoumayrequestandgetthose
numbersandplotthemonchart.

study("Example10",overlay=true)
pnf_t=
pointfigure
(tickerid,"hl","ATR",14,3)
pnf_open=security(pnf_t,period,open,true)
pnf_close=security(pnf_t,period,close,true)
35

plot(pnf_open,color=lime,style=linebr,linewidth=4)
plot(pnf_close,color=red,style=linebr,linewidth=4)

Fordetailedreferenceonall'pointfigure'argumentsgo
here
.

Annotation Functions Overview


The annotation study
AswasnotedinthesectionProgramStructure,eachscriptmustcontainonecallofthe
annotationfunction
study
.Functionshavethefollowingsignatures:
study(title,shorttitle,overlay,precision)

Thegivenfunctiondeterminesthecharacteristicsofallindicatorsasawhole.Onlytitleisa
necessaryargumentwhichsetsthenameoftheindicator.

Thisnamewillbeusedinthe
Indicatorsdialogue.

shorttitleistheshortnameofanindicatordisplayedinthechartslegend.Ifithasnotbeen
specified,thenitwillusethetitlevalue.

overlayisalogicaltypeofargument.Ifitistruethenthestudywillbeaddedasanoverlayon
topofthemainseries.Ifitisfalsethenitwillbeaddedonaseparatechartpanefalseisthe
defaultsetting.
36


precisionnumberofdigitsafterthefloatingpointforstudyvaluesonthepriceaxis.Mustbea
nonnegativeinteger.Precision0hasspecialrulesforformattingverylargenumbers(like
volume,e.g.'5183'willbeformattedas'5K').Defaultvalueis4.

Output of Charts plot


Theannotation
plot
accepts

onemandatoryargument:thevalueofaseriestypeanddisplaysit
onthechartasaline.Averybasiccalllookslikethis:
plot(close)

However,becausethereareautomatictypeconversionsinPine,insteadofaseriestypevalue,
anynumericalvaluecanbetransmitted.Forexample:
plot(125.2)

Inthiscase,thevalue125.2willbeautomaticallyconvertedtoaseriestypevaluewhichwillbe
thesamenumberoneverybar.Theplotwillberepresentedasahorizontalline.

Theannotationplothasamultitudeofoptionalarguments,inparticularthosewhichsetthe
graphsdisplaystyle:style,color,title,linewidth,transparency,andothers.Additional
descriptionsoftheseargumentscanbefound
here
:

Theparametercolorcanhaveadifferenteffectdependingonthetransmittedvalue.Ifitisset
equaltoacolortypesconstant,forexamplered,thenthewholechartwillbeplottedwithared
color:
plot(close,color=red)

However,theargumentcolorcanreceiveanexpressionofaseriestypeofcoloredvaluesas
values.Thisseriesofcolorswillbeusedtocolorthechartwhenrendered.Forexample:
c=close>=open?lime:red
plot(close,color=c)

37

Interestalsorepresentstheargumentoffsetofthefunctionplot.Itspecifiestheshiftused
whenthechartisplotted(negativevaluesshiftthecharttotheleft,whilepositivevaluesto
theright)Forexample:
study("MyScript12",overlay=true)
plot(close,color=red,offset=5)
plot(close,color=lime,offset=5)

Ascanbeseeninthescreenshot,theredserieshasbeenshiftedtotheleft(sincethe
argument'svalueoffsetisnegative),whilethegreenserieshasbeenshiftedtotheright(its
valueoffsetispositive).
Footnote.InPinethereisabuiltinfunction
offset
whichalsoenablesthevaluesofaseriesto
beshifted,butonlytotheright.Atthesametimethevaluesoutofrangeofthecurrentbarare
discarded.Theadvantageofoffsetliesinthefactthatitsresultcanbeusedinother
expressionstoexecutecomplexcalculations.Inthecaseoftheargumentoffsetofthefunction
plot,theshiftappearstobemerelyavisualeffectoftheplot.

Barcoloring a series barcolor


Theannotationfunctionbarcolorletsyouspecifyacolorforabardependentonthefulfilment
ofacertaincondition.Thefollowingexamplescriptrenderstheinsideandoutsidebarsin
differentcolors:
study("barcolorexample",overlay=true)
isUp()=>close>open
isDown()=>close<=open
isOutsideUp()=>high>high[1]andlow<low[1]andisUp()
isOutsideDown()=>high>high[1]andlow<low[1]andisDown()
isInside()=>high<high[1]andlow>low[1]
barcolor(isInside()?yellow:isOutsideUp()?aqua:isOutsideDown()
?purple:na)
38


Asyoucansee,whenpassingthenavalue,thecolorsstaythedefaultchartcolor.

Background coloring bgcolor


Similartothebarcolorfunction,thebgcolorfunctionchangesthecolorofthebackground.
Functionwillthecolorofthatcanbecalculatedinanexpression,andanoptionalparameter
transptransparencyfrom0100,whichis90bydefault.
Asanexample,heresascriptforcoloringtradingsessions(useitonEURUSD,30min
resolution):
study("bgcolorexample",overlay=true)
timeinrange(res,sess)=>time(res,sess)!=0
premarket=#0050FF
regular=#0000FF
postmarket=#5000FF
notrading=na
sessioncolor=timeinrange("30","04000930")?premarket:
timeinrange("30","09301600")?regular:timeinrange("30",
"16002000")?postmarket:notrading
bgcolor(sessioncolor,transp=75)

39

Inputs of the Indicator


inputannotationsmakeitpossibletoindicatewhichvariablesintheindicatorscodeare
incoming.Widgetswillbegeneratedforthevariablesontheindicators(properties/attributes)
pageinordertochangethevaluesviaamoreconvenientwaythanmodifyingthescripts
sourcecode.Youcanalsospecifythetitleoftheinputintheformofashorttextstring.Thetitle
ismeanttoexplainthepurposeoftheinput,andyoucanspecifylowestandhighestpossible
valuesfornumericalinputs.

Whenthedocumentiswritten,inPinetherearethefollowingtypesofinputs:
bool,
integer,
float,
string,
symbol,
resolution,
session,
source.
Thefollowingexamplesshowhowtocreate,incode,eachinputandhowitswidgetslooklike.

b=input(title="On/Off",type=
bool
,defval=true)
plot(b?open:na)

40

i=input(title="Offset",type=
integer
,defval=7,minval=10,
maxval=10)
plot(offset(close,i))

f=input(title="Angle",type=
float
,defval=0.5,minval=3.14,
maxval=3.14,step=0.2)
plot(sin(f)>0?close:open)

sym=input(title="Symbol",type=
symbol
,defval="SPY")
res=input(title="Resolution",type=
resolution
,defval="60")
plot(close,color=red)
plot(security(sym,res,close),color=green)

Theinputwidgetsymbolhasabuiltinsymbolsearchwhichisturnedonautomaticallywhen
thetickersfirstsymbolsareentered.

s=input(title="Session",type=
session
,defval="24x7")
plot(time(period,s))

src=input(title="Source",type=
source
,defval=close)
ma=sma(src,9)
plot(ma)

41


Findmoreinformationaboutindicatorinputsin
PineReference
.

Price levels hline


Theannotationfunctionhlinerendersahorizontallineatagivenfixedpricelevel.Forexample:

study(title="ChaikinOscillator",shorttitle="ChaikinOsc")
short=input(3,minval=1),long=input(10,minval=1)
osc=ema(accdist,short)ema(accdist,long)
plot(osc,color=red)
hline(0,title="Zero",color=gray,linestyle=dashed)

Anumbermustbethefirstargumentofhline.Valuesofatypeseriesareforbidden.
Itspossibletocreateafewhorizontallineswiththehelpofhlineandfillinthebackground
betweenthemwithatranslucentlightusingthefunctionfill.

Filling in the background between objects with fill'


Thefillannotationfunctionletsyoucolorthebackgroundbetweentwoseries,ortwohorizontal
lines(createdwithhline).Thefollowingexampleillustrateshowitworks:
42

study("fillExample")
p1=plot(sin(high))
p2=plot(cos(low))
p3=plot(sin(close))
fill(p1,p3,color=red)
fill(p2,p3,color=blue)
h1=hline(0)
h2=hline(1.0)
h3=hline(0.5)
h4=hline(1.5)
fill(h1,h2,color=yellow)
fill(h3,h4,color=lime)

Footnote:Neverexecuteafillbetweenplotandhline.Howeveritspossibletodisplay,with
thehelpofplot,aseriesoftheidenticalvalues(whichwilllooklikeahorizontalline,similarto
hline)andexecuteafillbetweenitandanotherplot.Forexample:
study("Fillexample2")
src=close,len=10
ma=sma(src,len)
osc=100*(masrc)/ma
p=plot(osc)
//NOTE:fill(p,hline(0))wouldn'twork,insteadusethis:
fill(p,plot(0))

43

Alert conditions
Theannotationfunction
alertcondition
allowsyoutocreatecustomalertconditionsinPine
studies.
Thefunctionhasthefollowingsignature:

alertcondition(condition,title,message)

conditionisaseriesofbooleanvaluesthatisusedforalert.Availablevalues:true,false.True
meansalertconditionismet,alertshouldtrigger.Falsemeansalertconditionisnotmet,alert
shouldnottrigger.Itisarequiredargument.
tiileisanoptionalargumentthatsetsthenameofthealertcondition.
messageisanoptionalargumentthatspecifiestextmessagetodisplaywhenthealertfires.

Hereisexampleofcreatinganalertcondition:
//@version=2
study("Exampleofalertcondition")
src=input(close)
ma_1=sma(src,20)
ma_2=sma(src,10)
c=cross(ma_1,ma_2)
alertcondition(c,title='Redcrossesblue',message='Redandblue
havecrossed!')
plot(ma_1,color=red)
plot(ma_2,color=blue)

44


ThefunctioncreatesalertconditionthatisavailableinCreateAlertdialog.Pleasenote,that
alertcondition
doesNOTfirealertsfromcodeautomatically,itonlygivesyouopportunityto
createacustomconditionforCreateAlertdialog.Alertsmustbestillsetmanually.Also,analert
triggeredbasedonacustomconditionyoucreatedinPinecodeisnotdisplayedonachart.
Onescriptmayincludemorethanonealertcondition.
Tocreateanalertbasedonalertcondition,oneshouldapplyaPinecode(study,strategy)with
alertcontidiontocurrentchart,opentheCreateAlertdialog,selecttheappliedPinecodeas
mainconditionforthealertandchoosethespecificalertcondition(implementedinthecode
itself).

45

Whenalertfires,youllseethemessage:

Shapes using plotshape, plotchar, plotarrow


Insituationswhenyouneedtomark,highlightbarsonachartandnotdrawausualplotinthe
formofaline,thefunctionplotmaynotbeenough.Althoughitspossibletoexecutethiskind
oftaskbyapplyingplotincombinationwiththestylesstyle=circlesorstyle=cross,its
recommendedtousethefunctionsplotshape,plotchar,plotarrow.

The Function plotshape


Thefunctionplotshapeisdesignedfordisplaying,underorabovebars,afewiconshapes.For
example,thescriptbelowwilldrawanXaboveallgreenbars:

study('plotshapeexample1',overlay=true)
data=close>=open
plotshape(data,style=shape.xcross)

46


Thefirstparameter,data,isconsideredasaseriesoflogicalvalues.Thecrossesaredrawnon
eachtruevalueandnotonfalsevaluesornavalues.Itspossibletotransferaseriesoflogical
valuesinplotshapetoanyseriesofnumbers.Itspossibletotransferanyseriesofnumbersto
plotshape.A0ornaisconsideredafalsevalue,anyothervalueisconsideredtrue.

Bychangingthevalueoftheparameterstyleispossibletochangetheformoftheiconshape.
Theavailablestylesare:
StyleName

Display

shape.xcross

shape.cross

shape.circle

shape.triangleup

shape.triangledown

shape.flag

shape.arrowup

shape.arrowdown

shape.square

shape.diamond

shape.labelup

shape.labeldown

Thefunctionplotshapedraws,bydefault,icons/shapesabovebars.Tosetanotherpositionfor
theshapes,itspossiblewiththeparameterlocation.Forexample,thefollowingscriptdrawsa
greenarrowshape.triangleupabovegreenbarsandaredarrowshape.triangledownabove
redbars:
47


study('plotshapeexample2',overlay=true)
data=close>=open
plotshape(data,style=shape.triangleup,
location=location.abovebar,color=green)
plotshape(notdata,style=shape.triangledown,
location=location.belowbar,color=red)

Possiblevaluesfortheparameterlocation:
location.abovebaraboveabar
location.belowbarbelowabar
location.toptopofachart
location.bottombottomofachart
location.absoluteanyset/specifiedpointonachart

Thevaluelocation.absoluteshouldbeappliedwhentheshapesneedtobeappliedonthe
chartwithoutbeinglinkedtothechartsbarsoredges.Avalueofthefirstparameterofthe
functionplotshapeisusedasaycoordinate.

Assuch,theshapeisdisplayedonnullvalues
andnotonlyonthenavalues.

Theexampleplotshapeexample2alsoillustratesthattheshapescolorcanbesetbythe
parametercolor,whichcanacceptmorethanconstantvaluesofcolorconstants.

Similartotheparametercolorofthefunctionplot,itspossibletotransferexpressionswhich
willcalculatetheiconshapescolordependingonconditions
.
Forexample:

study('plotshapeexample3',overlay=true)
48

data=close>=open
plotshape(true,style=shape.flag,color=data?green:red)

Inthegivenexample,thefirstparameterofthefunctionplotshapeisequaltotruewhich
meansthattheshapewillbedisplayedoneachbar.Thecolorwillbesetbythecondition:
color=data?green:red

Thefunctionplotshapehasotherpossibilities:
Setthenameofadisplayedseriesofdatausingtheparametertitle
Shiftaseriesofshapestotheleft/rightusingtheparameteroffset
Setthetransparencyofshapesbytheparametertransp
Parametertexttodisplaysomeshorttextabove/belowtheshape.Youmayuse\nto
separatetextlines

Function plotchar
Plotcharsprimarydifferencefromplotshapeisinthewayitassignsiconshapes.Inplotchar,it
issetthroughtheinlineparameterchar,allowinganyencodingunicodesymboltobeused
(whicharesupportedbytheinusefont).Forexample:

study('plotcharexample',overlay=true)
data=close>=open
plotchar(data,char='a')

49

Bydefault,theparametercharacceptsthevalue('BLACKSTAR',U+2605).Itspossibleto
useanyletters,digitsorvarioussymbols,forexample:,,,,,,,.

Exampleofsnowflakes

:
study('plotcharexample',overlay=true)
data=close>=open
plotchar(data,char='')

Likeplotshape,thefunctionplotcharallows:
Setashapescolor,withaconstantorcomplexarithmeticexpression
Setashapeslocation,theparameterlocation
50

Setthenameofadisplayedseriesofdatausingtheparametertitle
Shiftaseriesofshapesleft/rightusingtheparameteroffset
Setthetransparencyofshapesusingtheparametertransp
Parametertexttodisplaysomeshorttextabove/belowtheshape.Youmayuse\nto
separatetextlines

The Function plotarrow


Thefunctionplotarrowallowsforup/downarrowstobedisplayedonthechart.Thearrows
lengthsarenotthesameoneachbarandarecalculatedbythescriptcode(dependingonthe
conditionscalculated).
Thefirstseriesparameterofthefunctionplotarrowisusedtoplacearrowsonthechart,using
thefollowinglogic:
Ifavalueseriesonthecurrentbarisgreaterthan0,thenanuparrowwillbedrawn,the
lengthofthearrowproportionallytoanabsolutevalue.
Ifavalueseriesonthecurrentbarislessthan0,thenadownarrowwillbedrawn,the
lengthofthearrowproportionaltoanabsolutevalue.
Ifavalueseriesonthecurrentbarisequalto0ornathenthearrowisnotdisplayed.

Hereisasimplescriptthatillustrateshowplotarrowfunctionworks:

study("plotarrowexample",overlay=true)
codiff=closeopen
plotarrow(codiff,colorup=teal,colordown=orange,transp=40)

Asyoucansee,themoreabsolutevalueofthedifferencecloseopenthelongerthearrow.If
closeopenisgreaterthanzero,thenanuparrowisrendered,otherwise(whencloseopen
islessthanzero)wehaveadownarrow.

51

Foranotherexample,itspossibletotaketheindicatorChaikinOscillatorfromthestandard
scriptsanddisplayitasanoverlayaboveaseriesintheformofarrowsusingplotarrow:

study("ChaikinOscillatorArrows",overlay=true)
short=input(3,minval=1),long=input(10,minval=1)
osc=ema(accdist,short)ema(accdist,long)
plotarrow(osc)

ThisscreenshotshowstheoriginalChaikinOscillatoralongsidethescriptforbetter
understanding.

Aswasstatedearlier,thehighofthearrowischosenproportionallytotheabsolutevalueofthe
firstseriesparameterofthefunctionplotarrow.Themaximumandminimumpossiblesizesfor
thearrows(inpixels)aresetbytheparametersminheightandmaxheightrespectively.

Additionally,thefunctionplotarrowallows:
Setthenameofadisplayedseriesofdatausingtheparametertitle
Setthecolorofanuparrow,parameterusingcolorup
Setthecolorofadownarrowandparameterusingcolordown
Shiftaseriesofarrowsleft/rightusingtheparameteroffset
Setthetransparencyofshapeswiththeparametertransp

Itsimportanttonotethatcolorupandcolordownshouldreceiveaconstantvalueofthetype
color.Usingexpressionsfordeterminingcolor(asisdoneinplot,plotshape,plotchar)isnot
allowed.

52

Custom OHLC bars and candles


YoumaydefineyourowncustombarsandcandlesinPinescripts.Therearefunctions
plotbar
and
plotcandle
forthatpurpose.Hereisasmallexample:

study("Example1")
plotbar(open,high,low,close)

Thescript"Example1"simplyreplicatesbarsofthecurrentsymbol.Nothingoutstanding.We
canpaintthemwithgreenandredcolors:

study("Example2")
palette=close>=open?lime:red
plotbar(open,high,low,close,color=palette)

53

The"Example2"illustratescolorargument,whichcouldbegivenconstantvaluesasred,lime,
"#FF9090",aswellasexpressionsthatcalculatecolor(palettevariable)inruntime.

Functionplotcandleissimilartoplotbar,itjustplotscandlesinsteadofbarsandhaveoptional
argumentwickcolor.

Bothplotbarandplotcandleneedfourseriesargumentsthatwillbeusedasbar/candleOHLC
pricescorrespondingly.IfforexampleoneoftheOHLCvariablesatsomebarhaveNaNvalue,
thenthewholebarisnotplotted.Example:

study("Example3")
c=close>open?na:close
plotcandle(open,high,low,c)

54

OfcourseyoumaycalculateOHLCvalueswithoutusingavailableopen,high,lowandclose
values.Forexampleyoucanplotsmoothedcandles:

study("Example4")
len=input(9)
smooth(x)=>
sma(x,len)
o=smooth(open)
h=smooth(high)
l=smooth(low)
c=smooth(close)
plotcandle(o,h,l,c)

55

Youmaygetaninterestingeffect,ifyouplotOHLCvaluestakenfromhighertimeframe.Let's
sayyouwanttoplotdailybarson60minutechart:

//NOTE:addthisscriptonintradaychart
study("Example5")
higherRes=input("D",type=resolution)
is_newbar(res)=>
t=time(res)
change(t)!=0?1:0
o=security(tickerid,higherRes,open)
h=security(tickerid,higherRes,high)
l=security(tickerid,higherRes,low)
c=security(tickerid,higherRes,close)
plotbar(is_newbar(higherRes)?o:na,h,l,c,color=c>=o?lime:
red)

56

Functionsplotbarandplotcandlealsohavetitleargument,sousercandistinguishthemin
StylestabofFormatdialog.

Strategies
A
strategy
isastudythatcansend,modifyandcancelorders(tobuy/sell).Strategiesallowyou
toperform
backtesting
(emulationofstrategytradingonhistoricaldata)and
forwardtesting
(emulationofstrategytradingonrealtimedata)accordingtoyourprecodedalgorithms.

AstrategywritteninPineScriptlanguagehasallthesamecapabilitiesasaPineindicator.
Whenyouwriteastrategycode,itshouldstartwiththekeyword
strategy
,not
study
.
Strategiesnotonlyplotsomething,butalsoplace,modifyandcancelorders.Theyhaveaccess
toessentialstrategyperformanceinformationthroughspecifickeywords.Thesameinformation
isavailableforyouontheStrategyTestertab.Onceastrategyiscalculatedonhistoricaldata,
youcanseehypotheticalorderfills.

A simple strategy example


//@version=2
strategy("test")
ifn>4000
strategy.entry("buy",strategy.long,10,
when=strategy.position_size<=0)
strategy.entry("sell",strategy.short,10,
when=strategy.position_size>0)
plot(strategy.equity)

57

Assoonasthescriptiscompiledandappliedtoachart,youcanseefilledordermarksonitand
howyourbalancewaschangingduringbacktesting(equitycurve).Itisasimpleststrategythat
buysandsellsoneverybar.

Thefirstline
strategy(test)
statesthecodebelongstostrategytypeanditsnameistest.
strategy.entry()
isacommandtosendbuyandsellorders.
plot(strategy.equity)
plotsthe
equitycurve.

How to apply a strategy to the chart


Totestyourstrategy,applyittothechart.Usethesymbolandtimeintervalsthatyouwantto
test.YoucanuseabuiltinstrategyfromtheIndicators&Stratediesdialogbox,orwriteyour
owninPineEditor.

StrategyperfomancereportisdisplayedontheStrategyTestertabonthebottomtoolbar:

Backtesting and forwardtesting


OnTradingViewstrategiesarecalculatedonallavailablehistoricaldataonthechartand
automaticallycontinuecalculationwhenrealtimedatacomesin.

Bothduringhistoricalandrealtimecalculation,codeiscalculatedonbarclosesbydefault.

Ifthisisforwardtesting,codecalculatesoneverytickinrealtime.Toenablethis,checkoffthe
optionRecalculateOnEveryTickinsettingsordoitinscriptitself:
strategy(...,
calc_on_every_tick=true,...)
.

Youcansetthestrategytoperformadditionalcalculationafteranorderisfilled.Forthisyou
needtocheckoffRecalculateAfterOrderfilledinsettingsordoitinscriptitself:
strategy(,
calc_on_order_fills=true,...)
.

Broker emulator
ThereisabrokeremulatoronTradingViewfortestingstrategies.Unlikerealtrading,the
emulatorfillsordersonlyatchartprices,thatiswhyanordercanbefilledonlyonnexttickin
forwardtestingandonnextbarinbacktesting(orlater)afterstrategycalculated.

Asstatedabove,inbacktestingstrategyiscalculatedonbarsclose.Thefollowinglogicisused
toemulateorderfills:

58

1. Ifopeningpriceofbarisclosertohighestpriceofthesamebar,thebrokeremulator
assumesthatintrabarpricewasmovingthisway:OpenHighLowClose.
2. Ifopeningpriceofbarisclosertolowestpriceofthesamebar,thebrokeremulator
assumesthatintrabarpricewasmovingthisway:OpenLowHighClose.
3. Brokeremulatorassumesthattherewerenogapsinsidebar,meaningallintrabarprices
areavailablefororderexecution.
4. IftheoptionRecalculateOnEveryTickinstrategypropertiesisenabled(or
strategy(...,calc_on_every_tick=true,...)
isspecifiedinscript),codeisstillcalculated
onlyonbarsclose,followingtheabovelogic.

Hereisthestrategydemonstratinghowordersarefilledbythebrokeremulator:
strategy("HistorySAWdemo",overlay=true,pyramiding=100,
calc_on_order_fills=true)
strategy.entry("LE",strategy.long)

Thiscodeiscalculatedonceperbarbydefault,onitsclose,howeverthereisanadditional
calculationassoonasanorderisfilled.Thatiswhyyoucansee4filledordersoneverybar:2
ordersonopen,1orderonhighand1orderonlow.Thisisbacktesting.Ifitwereinrealtime,
orderswouldbeexecutedoneverynewtick.

Itisalsopossibletoemulateorderqueue.ThesettingiscalledVerifyPriceForLimitOrders
andcanbefoundinstrategypropertiesorsetinscriptitself:
strategy(...
backtest_fill_limits_assumption=X,...)
.Thespecifiedvalue=numberofpoints/pips
(minimumpricemovements),defaultvalue=0.Alimitorderisfilledifcurrentpriceisbetter
(higherforsellorders,lowerforbuyorders)forthespecifiednumberofpoints/pips.The
executionpricestillmatchesthelimitorderprice.

Example:
backtest_fill_limits_assumption=1.Minimumpricemovement=0.25.
Abuylimitorderisplacedatprice12.50.
59

Currentpriceis12.50.
Theordercannotbefilledatcurrentpriceonlybecausebacktest_fill_limits_assumption
=1.Tofilltheorderthepricemustbecome0.25*1lower.Theorderisputinqueue.
Assumethatthenexttickcomesatprice12.00.Thispriceis2pointslower,whatmeans
theconditionbacktest_fill_limits_assumption=1issatisfied,sotheordershouldbefilled.The
orderisfilledat12.50(originalorderprice),evenifthepriceisnotavailableanymore.

Order placement commands


Allkeywordsthataredesignedforstrategiesstartwith
strategy.
prefix.Thefollowing
commandsareusedforplacingorders:
strategy.entry
,
strategy.order
and
strategy.exit
:
strategy.entry
thiscommandplacesonlyentryorders.Itisaffectedbypyramiding
setting(isstrategyproperties)andby
strategy.risk.allow_entry_in
keyword.Ifthereis
anopenmarketpositionwhenanoppositedirectionorderisgenerated,thenumberof
contracts/shares/lots/unitswillbeincreasedbythenumberofcurrentlyopencontracts
(scriptequivalent:
strategy.position_size
+
quantity
).Astheresult,thesizeofmarket
positiontoopenwillbeequaltoordersize,specifiedinthecommand
strategy.entry
.
strategy.order
thiscommandplacesbothentryandexitorders.Itisnotaffectedby
pyramidingsettingandby
strategy.risk.allow_entry_in
keyword.Itallowsyoutocreate
complexenterandexitorderconstructionswhencapabilitiesofthe
strategy.entry
and
strategy.exit
arenotenough.
strategy.exit
thiscommandallowsyoutoexitamarketpositionbyanorderoror
formmultipleexitorderstrategy(stoploss,profittarget,trailingstop).Allsuchorders
arepartofthesame
strategy.oca.reduce
group.Anexitordercannotbeplacedifthere
isnoopenmarketpositionorthereisnoactiveentryorder(anexitorderisboundtoID
ofanentryorder).Itisnotpossibletoexitapositionwithamarketorderusingthe
command
strategy.exit
.Forthisgoalthefollowingcommandsshouldbeused:
strategy.close
or
strategy.close_all
.Ifnumberofcontracts/shares/lots/unitsspecified
forthe
strategy.exit
islessthanthesizeofcurrentopenposition,theexitwillbepartial.
Itisnotpossibletoexitfromthesameentryordermorethan1timeusingthesameexit
order(ID),thatallowsyoutocreateexitstrategieswithmultiplelevels.Incase,whena
marketpositionwasformedbymultipleentryorders(pyramidingenabled),eachexit
ordersisboundtoeachentryorderindividually.

Example1:
//@version=2
strategy("reversdemo")
ifn>4000
strategy.entry("buy",strategy.long,4,when=strategy.position_size<=0)
strategy.entry("sell",strategy.short,6,
when=strategy.position_size>0)
plot(strategy.equity)

60

Theabovestrategyconstantlyreversesmarketpositionfrom+4to6,backandforth,whatis
shownbyitsplot.

Example2:
strategy("exitoncedemo")
strategy.entry("buy",strategy.long,4,when=strategy.position_size<=0)
strategy.exit("bracket","buy",2,profit=10,stop=10)

Thisstrategydemonstratesthecase,whenmarketpositionisneverclosed,becauseitusesexit
ordertoclosemarketpositiononlypartiallyanditcannotbeusedmorethanonce.Ifyoudouble
thelineforexiting,thestrategywillclosemarketpositioncompletely.

Example3:
//@version=2
strategy("Partialexitdemo")
ifn>4000
strategy.entry("buy",strategy.long,4,when=strategy.position_size<=0)
strategy.exit("bracket1","buy",2,profit=10,stop=10)
strategy.exit("bracket2","buy",profit=20,stop=20)

Thiscodegenerates2levelsofbrackets(2takeprofitordersand2stoplossorders).Both
levelsareactivatedatthesametime:firstleveltoexit2contractsandthesecondonetoexitall
therest.

Thefirsttakeprofitandstoplossorders(level1)areinoneOCAgroup.Theotherorders(level
2)areinanotherOCAgroup.Itmeansthatassoonasanorderfromlevel1isfilled,theorders
fromlevel2arenotcancelled,theystayactive.

EverycommandplacinganorderhasID(stringvalue)uniqueorderidentifier.Ifanorderwith
sameIDisalreadyplaced(butnotyetfilled),currentcommandmodifiestheexistingorder.If
modificationisnotpossible(conversionfrombuytosell),theoldorderiscancelled,thenew
orderisplaced.
strategy.entry
and
strategy.order
workwiththesameIDs(theycanmodifythe
sameentryorder).
strategy.exit
workswithotherorderIDs(itispossibletohaveanentryorder
andanexitorderwiththesameID).
61


Tocancelaspecificorder(byitsID)thecommand
strategy.cancel(stringid)
shouldbeused.
Tocancelallpendingordersthecommand
strategy.cancel_all()
shouldbeused.Strategy
ordersareplacedassoonastheirconditionsaresatisfiedandcommandiscalledincode.
Brokeremulatordoesntexecuteordersbeforenexttickcomesafterthecodewascalculated,
whileinrealtradingwithrealbroker,anordercanbefilledsooner.Itmeansthatifamarket
orderisgeneratedatcloseofcurrentbar,itisfilledatopenoifnextbar.

Example:
//@version=2
strategy("nextbaropenexecutiondemo")
ifn>4000
strategy.order("buy",strategy.long,when=strategy.position_size==0)
strategy.order("sell",strategy.short,when=strategy.position_size!=0)

Ifthiscodeisappliedtoachart,allordersarefilledatopenofeverybar.

Conditionsfororderplacement(
when
,pyramiding,
strategy.risk
)arecheckedwhenscriptis
calculated.Ifallconditionsaresatisfied,theorderisplaced.Ifanyconditionisnotsatisfied,the
orderisnotplaced.Itisimportanttocancelpriceorders(limit,stopandstoplimitorders).

Example(forMSFT1D):
//@version=2
strategy("PricedEntrydemo")
c=year>2014?nz(c[1])+1:0
ifc==1
strategy.entry("LE1",strategy.long,2,
stop=high+35*syminfo.mintick)
strategy.entry("LE2",strategy.long,2,
stop=high+2*syminfo.mintick)

Eventhoughpyramidingisdisabled,thesebothordersarefilledinbacktesting,becausewhen
theyaregeneratedthereisnoopenlongmarketposition.Bothordersareplacedandwhen
pricesatisfiesorderexecution,theybothgetexecuted.Itisrecommendedtotoputtheordersin
1OCAgroupbymeansof
strategy.oca.cancel
.inthiscaseonlyoneorderisfilledandthe
otheroneiscancelled.Hereisthemodifiedcode:
//@version=2
strategy("PricedEntrydemo")
c=year>2014?nz(c[1])+1:0
ifc==1
strategy.entry("LE1",strategy.long,2,
stop=high+35*syminfo.mintick,
oca_type=strategy.oca.cancel,oca_name="LE")
strategy.entry("LE2",strategy.long,2,
stop=high+2*syminfo.mintick,

62

oca_type=strategy.oca.cancel,oca_name="LE")

If,forsomereason,orderplacingconditionsarenotmetwhenexecutingthecommand,the
entryorderwillnotbeplaced.Forexample,ifpyramidingsettingsaresetto2,existingposition
alreadycontainstwoentriesandthestrategytriestoplaceathirdone,itwillnotbeplaced.
Entryconditionsareevaluatedattheordergenerationstageandnotattheexecutionstage.
Therefore,ifyousubmittwopricetypeentrieswithpyramidingdisabled,onceoneofthemis
executedtheotherwillnotbecancelledautomatically.Toavoidissueswerecommendusing
OCACancelgroupsforentriessowhenoneentryorderisfilledtheothersarecancelled.

Thesameistrueforpricetypeexitsorderswillbeplacedoncetheirconditionsaremet(i.e.an
entryorderwiththerespectiveidisfilled).

Example:
strategy("orderplacedemo")
counter=nz(counter[1])+1
strategy.exit("bracket","buy",profit=10,stop=10,when=counter==1)
strategy.entry("buy",strategy.long,when=counter>2)

Ifyouapplythisexampletoachart,youcanseethattheexitorderhasbeenfilleddespitethe
factthatithadbeengeneratedonlyoncebeforetheentryordertobeclosedwasplaced.
However,thenextentrywasnotclosedbeforetheendofthecalculationastheexitcommand
hasalreadybeentriggered.

Closing market position


Despiteitispossibletoexitfromaspecificentryincode,whenordersareshownintheListof
TradesonStrategyTestertab,theyallarelinkedaccordingFIFO(firstin,firstout)rule.Ifan
entryorderIDisnotspecifiedforanexitorderincode,theexitorderclosesthefirstentryorder
thatopenedmarketposition.Letsstudythefollowingexample:

strategy("exitDemo",pyramiding=2,overlay=true)
strategy.entry("Buy1",strategy.long,5,
when=strategy.position_size==0andyear>2014)
strategy.entry("Buy2",strategy.long,
10,stop=strategy.position_avg_price+
strategy.position_avg_price*0.1,
when=strategy.position_size==5)
strategy.exit("bracket",loss=10,profit=10,
when=strategy.position_size==15)

Thecodegivenaboveplaces2orderssequentially:Buy1atmarketpriceandBuy2at10%
higherprice(stoporder).Exitorderisplacedonlyafterentryordershavebeenfilled.Ifyou
applythecodetoachart,youwillseethateachentryorderisclosedbyexitorder,thoughwe
63

didnotspecifyentryorderIDtocloseinthisline:
strategy.exit("bracket",loss=10,
profit=10,when=strategy.position_size==15)

Anotherexample:
strategy("exitDemo",pyramiding=2,overlay=true)
strategy.entry("Buy1",strategy.long,5,when=strategy.position_size==0)
strategy.entry("Buy2",strategy.long,
10,stop=strategy.position_avg_price+
strategy.position_avg_price*0.1,
when=strategy.position_size==5)
strategy.close("Buy2",when=strategy.position_size==15)
strategy.exit("bracket","Buy1",loss=10,profit=10,
when=strategy.position_size==15)
plot(strategy.position_avg_price)

Itopens5contractslongpositionwiththeorderBuy1.
Itextendsthelongpositionbypurchasing10morecontractsat10%higherpricewiththe
orderBuy2.
Theexitorder(strategy.close)tosell10contracts(exitfromBuy2)isfilled.

Ifyoutakealookattheplot,youcanseethataverageentryprice=Buy2executionpriceand
ourstrategyclosedexactlythisentryorder,whileontheTradeListtabwecanseethatitclosed
thefirst"Buy1"orderandhalfofthesecondBuy2.Itmeansthatthenomatterwhatentryorder
youspecifyforyourstrategytoclose,thebrokeremulatorwillstillclosethethefirstone
(accordingtoFIFOrule).Itworksthesamewaywhentradingwiththroughbroker.

OCA groups
Itispossibletoputordersin2differentOCAgroupsinPineScript:
strategy.oca.cancel
assoonasanorderfromgroupisfilled(evenpartially)or
cancelled,theotherordersfromthesamegroupgetcancelled.Oneshouldkeepinmind
thatiforderpricesarethesameortheyareclose,morethan1orderofthesamegroup
maybefilled.ThisOCAgrouptypeisavailableonlyforentryordersbecauseallexit
ordersareplacedin
strategy.oca.reduce
.
Example:
//@version=2
strategy("oca_canceldemo")
ifyear>2014andyear<2016
strategy.entry("LE",strategy.long,oca_type=strategy.oca.cancel,
oca_name="Entry")
strategy.entry("SE",strategy.short,oca_type=strategy.oca.cancel,
oca_name="Entry")

64

Youmaythinkthatthisisareversestrategysincepyramidingisnotallowed,butinfact
bothorderwillgetfilledbecausetheyaremarketorder,whatmeanstheyaretobe
executedimmediatelyatcurrentprice.Thesecondorderdoesntgetcancelledbecause
botharefilledalmostatthesamemomentandthesystemdoesnthavetimetoprocess
firstorderfillandcancelthesecondonebeforeitgetsexecuted.Thesamewould
happenifthesewerepriceorderswithsameorsimilarprices.Strategyplacesallorders
(whichareallowedaccordingtomarketposition,etc).

Thestrategyplacesallordersthatdonotcontradicttherules(inourcasemarket
positionisflat,thereforeanyentryordercanbefilled).Ateachtickcalculation,firstlyall
orderswiththesatisfiedconditionsareexecutedandonlythentheordersfromthegroup
whereanorderwasexecutedarecancelled.

strategy.oca.reduce
thisgrouptypeallowsmultipleorderswithinthegrouptobefilled.
As one of the orders within the group starts to be filled, the size of other orders is
reduced by the filled contracts amount. It is very useful for the exit strategies. Oncethe
price touches your takeprofit order and it is being filled, the stoploss is not cancelled
but its amount is reduced by the filled contracts amount, thus protecting the rest of the
openposition.
strategy.oca.none
the order is placed outside of the group (default value for the
strategy.order
and
strategy.entry
commands).

Everygrouphasitsownuniqueid(thesamewayastheordershave).Iftwogroupshavethe
sameid,butdifferenttype,theywillbeconsidereddifferentgroups.Example:
//@version=2
strategy("MyScript")
ifyear>2014andyear<2016
strategy.entry("Buy",strategy.long,oca_name="Myoca",
oca_type=strategy.oca.reduce)
strategy.exit("FromBy","Buy",profit=100,loss=200,oca_name="Myoca")
strategy.entry("Sell",strategy.short,oca_name="Myoca",
oca_type=strategy.oca.cancel)
strategy.order("Order",strategy.short,oca_name="Myoca",
oca_type=strategy.oca.none)

Buy and Sell will beplaced indifferentgroupsastheirtypeisdifferent.Orderwillbe


outside of any group as its type is set to
strategy.oca.none.
Moreover, Buy will be placed in
theexitgroupasexitsarealwaysplacedinthe
strategy.oca.reduce_size
typegroup.

Risk Management
Itisnoteasytocreateauniversalprofitablestrategy.Usually,strategiesarecreatedforcertain
marketpatternsandcanproduceuncontrollablelosseswhenappliedtootherdata.Therefore
stoppingautotradingintimeshouldthingsgobadisaseriousissue.Thereisaspecialgroup
ofstrategycommandstomanagerisks.Theyallstartwiththe
strategy.risk.*
prefix.
65


Youcancombineanynumberofrisksinanycombinationwithinonestrategy.Everyrisk
categorycommandiscalculatedateverytickaswellasateveryorderexecutionevent
regardlessofthe
calc_on_order_fills
strategysetting.Thereisnowaytodisableanyriskrule
inruntimefromscript.Regardlessofwhereinthescripttheriskruleislocateditwillalwaysbe
appliedunlessthelinewiththeruleisdeletedandthescriptisrecompiled.

Ifonthenextcalculationanyoftherulesistriggered,noorderswillbesent.Thereforeifa
strategyhasseveralrulesofthesametypewithdifferentparameters,itwillstopcalculating
whentherulewiththemoststrictparametersistriggered.Whenastrategyisstoppedall
unexecutedordersarecancelledandthenamarketorderissenttoclosethepositionifitisnot
flat.

Furthermore,itisworthrememberingthatwhenusingresolutionshigherthan1day,thewhole
barisconsideredtobe1dayfortherulesstartingwithprefix
strategy.risk.max_intraday_

Example(MSFT1):
//@version=2
strategy("multiriskdemo",overlay=true,pyramiding=10,
calc_on_order_fills=true)
ifyear>2014
strategy.entry("LE",strategy.long)
strategy.risk.max_intraday_filled_orders(5)
strategy.risk.max_intraday_filled_orders(2)

The position will be closed and trading will be stopped until the end of every trading session
after two orders are executed within this session as the second rule is triggered earlier and is
validuntiltheendofthetradingsession.

One should remember that the


strategy.risk.allow_entry_in rule isappliedtoentriesonlysoit
will be possible to enter in a trade using the
strategy.order command as this command is not
an entry command per se. Moreover, when the
strategy.risk.allow_entry_in
rule is active,
entriesinaprohibitedtradebecomeexitsinsteadofreversetrades.

Example(MSFT1D):
//@version=2
strategy("allow_entry_indemo",overlay=true)
ifyear>2014
strategy.entry("LE",strategy.long,when=strategy.position_size<=0)
strategy.entry("SE",strategy.short,when=strategy.position_size>0)
strategy.risk.allow_entry_in(strategy.direction.long)

As short entries are prohibitedbytheriskrules,insteadofreversetradeslong exittradeswillbe


made.
66


Currency
TradingViewstrategiescanoperateinthecurrencydifferentfromtheinstrumentcurrency.
NetProfitandOpenProfitarerecalculatedintheaccountcurrency.Accountcurrencyissetinthe
strategypropertiesthe
BaseCurrency
dropdownlistorinthescriptviathe
strategy(...,
currency=currency.*,...)
keyword.Atthesametime,performancereportvaluesarecalculated
intheselectedcurrency.

Tradeprofit(openorclosed)iscalculatedbasedontheprofitintheinstrumentcurrency
multipliedbythecrossrateontheCloseofthetradingdayprevioustothebarwherethe
strategyiscalculated.

Example:wetradeEURUSD,DandhaveselectedEURasthestrategycurrency.Ourstrategy
buysandexitsthepositionusing1pointprofitTargetorstopLoss.
//@version=2
strategy("Currencytest",currency=currency.EUR)
ifyear>2014
strategy.entry("LE",true,1000)
strategy.exit("LX","LE",profit=1,loss=1)
profit=strategy.netprofit
plot(abs((profitprofit[1])*100),"1pointprofit",
color=blue,linewidth=2)
plot(1/close[1],"prevusdeur",color=red)

Afteraddingthisstrategytothechartwecanseethattheplotlinesarematching.This
demonstratesthattheratetocalculatetheprofitforeverytradewasbasedonthecloseofthe
previousday.

Whentradingonintradayresolutionsthecrossrateonthecloseofthetradingdaypreviousto
thebarwherethestrategyiscalculatedwillbeusedanditwillnotbechangedduringwhole
tradingsession.

Whentradingonresolutionshigherthan1daythecrossrateonthecloseofthetradingday
previoustothecloseofthebarwherethestrategyiscalculatedwillbeused.Letssaywetrade
onaweeklychart,thenthecrossrateonThursdayssessionclosewillalwaysbeusedto
calculatetheprofits.

Inrealtimetheyesterdayssessioncloserateisused.

67

HOWTOs
Get real OHLC price on a Heikin Ashi chart
Suppose,wehaveaHeikinAshichart(orRenko,Kagi,PriceBreaketc)andweveaddedapine
scriptonit:

//@version=2
study("VisibleOHLC",overlay=true)
c=close
plot(c)

YoumayseethatvariablecisaHeikinAshiclosepricewhichisnotthesameasrealOHLC
price.Becauseclosebuiltinvariableisalwaysavaluethatcorrespondstoavisiblebar(or
candle)onthechart.

So,howdowegettherealOHLCpricesinPineScriptcode,ifcurrentcharttypeis
nonstandard?Weshouldusesecurityfunctionincombinationwithtickeridfunction.Hereis
anexample:

//@version=2
study("RealOHLC",overlay=true)
t=tickerid(syminfo.prefix,ticker)
realC=security(t,period,close)
plot(realC)

InasimilarwaywemaygetotherOHLCprices:open,highandlow.

Plot buy/sell arrows on the chart


Youmayuseplotshapewithstyle
shape.arrowupandshape.arrowdown:

study('Ex1',overlay=true)
data=close>=open
plotshape(data,color=lime,style=shape.arrowup,text="Buy")
plotshape(notdata,color=red,style=shape.arrowdown,text="Sell")

68

Youmayuseplotcharfunctionwithanyunicodecharacter:

study('buy/sellarrows',overlay=true)
data=close>=open
plotchar(data,char='',color=lime,text="Buy")
plotchar(data,char='',location=location.belowbar,color=red,
text="Sell")

69

Where can I get more information?


First,additionaldescriptionsofallbuiltinoperators,variables,functionsandannotation
functionscanbefoundhere:
https://www.tradingview.com/studyscriptreference/

Second,writeyourownscriptsbyanexample.Opennewchart,pushthePineScriptEditor
buttononthetoolbar.IntheopenededitorwindowclicktheNewbutton.Youllfindlotsof
examplesofTradingViewstandardindicatorsinthedropdownlist.

Third,youcanalwaysaskquestionsonTradingViewssupportforum:
https://getsatisfaction.com/tradingview

Finally,informationaboutlargereleasesandmodificationstoPineScript(aswellasother
features)areregularlypublishedinTradingViewsblog:

http://blog.tradingview.com

70

Vous aimerez peut-être aussi