Think Script Manual



Comments



Description

[email protected] In this document you will find information on the thinkScript language. Using the price data in conjunction with functions, variables, and operators allows you to build up a whole system of your own studies and strategies. Being integrated into various features of the thinkorswim platform, thinkScript can be used for issuing alerts, scanning the market, customizing quotes, and submitting orders automatically. The Getting Started section will help you get acquainted with thinkScript and start writing your first scripts. The Reference section provides you with information on constants, data types, declarations, functions, operators, and reserved words, explaining how to use them when writing scripts with thinkScript. The thinkScript Integration section contains articles demonstrating usage of thinkScript integration features. ThinkScript ThinkScript • Getting Started o o • Reference o o o o o o • thinkScript Integration o o o o Reserved Words Declarations Functions Constants Data Types Operators Writing Your First Script Advanced Topics Conditional Orders Custom Quotes Study Alerts Study Filters 37 68 78 256 312 315 5 19 35 4 325 327 329 331 324 Getting Started This section contains tutorials that will help you get acquainted with thinkscript and start writing your first scripts. • Getting Started o Writing Your First Script 5  Defining Plots  Defining Variables  Def Variables  Rec Variables  Rec Enumerations  Using Functions  Formatting Plots  Adjusting Parameters Using Inputs  Accessing Data  Using Strategies o Advanced Topics 19  Concatenating Strings  Creating Local Alerts  Referencing Data  Referencing Secondary Aggregation  Referencing Historical Data  Referencing Other Price Type Data  Referencing Other Studies  Referencing Other Symbol's Data  Past Offset  Using Profiles 20 22 23 24 27 28 29 31 32 34 5 6 7 8 10 12 13 16 17 18 o This section contains tutorials that will help you write your first thinkscript study or strategy. In order to visualize data calculated by studies, you can use plots. Writing Your First Script o Defining Plots plot SMA = Average(close, 10); This example script plots a 10 period simple moving average of the Close price. When working with charts, you might need to use several plots. The following example script plots two moving averages of the Close price: the 10 period simple moving average and the 10 period exponential moving average. plot SMA = Average(close, 10); plot EMA = ExpAverage(close, 10); Average(close, 10) In case you only need one plot and don't need any inputs or intermediate variables, you can use short syntax: This example script plots a 10 period simple moving average of the Close price. Note that if you use the short syntax, your script must be a single expression. See also: Reserved Words: plot; Formatting Plots. Thinkscript provides different types of variables to work with. This section contains tutorials that will teach you to work with these variables. 7 • Def Variables • Rec Variables 8 • Rec Enumerations 10 o Defining Variables By defining a variable such as: You can use that variable sma in your code as part of another calculation. def MyClosingPrice = Close. plot tripleSMA = SMA * 3.low. 20). For example. then create another variable: def percentrange = range / close. if you want to divide the range of a stock price by the closing price. you can create a variable for the range: def range = high . This let's you construct complex formulas from simpler elements. For example. For instance. you can create a variable that can be used in another formula in the study. def SMA = average(close. you can define something called MyClosingPrice as: Def Variables By using the def reserved word.The def reserved word defines a variable you'd like to work with. . Doing it this way lets you re-use variables and gives you the power to combine complex variables in your formulas more easily. plot doubleSMA = SMA * 2. drop / 100) * x[1].drop / 100) * x[1] then Max(close. Before the calculation. rec x = x[1] + x[10] * 0 + 1.5). the maximum value resets.0.0. plot Drops = close < (1 .BOOLEAN_ ARROW_UP). Rec Variables rec x = x[1] + (random() . When the price reduces on the defined percentage from the maximum. As a result. In this example the rec variable holds the maximum close value starting from the moment of the last fall. plot line = x. This script takes data for the previous 10 bars. the rec calculation starts 10 bars prior to the beginning of the time period. Drops.SetPaintingStrategy(PaintingStrategy. the rec value is set to 0 for all moments of time. input drop = 5. the first drawn value of the plot line is 11. When you assign a value to the rec variable you can use its values calculated for the previous bars. If you use data related to the period prior to the beginning of the time period then the rec variable is also calculated for the period. . rec x = if close >= (1 . Thus. Shows random walk. x[1]) else close. declare lower. plot MaxPrice = x. Values of such variables are calculated one after another in a chronological manner.Rec variables are used to store floating point data. plot RandomWalk = x. rec x = x[1] + 1. . Thus. This is why the first visible value equals 2.declare lower. Similarly. it will produce an error. This script refers to data that has not been calculated yet. This applies to any calculation of a rec variable which attempts to use its current or future value. rec x = x[-1] + close. plot data = x. in this example the calculation starts 1 bar prior to the beginning of the time period. plot line = x. neutral else if (close > close[1]) then a. The first line of the script is a declaration of a rec enumeration a having neutral. } rec a = {default neutral. Note that rec enumerations can contain only string values. plot q.neutral else if (close > close[1]) then a.You can use rec enumeration constructions to create something like a usual rec in thinkScript but with limited possible values. and down values.up else a. up. case down: q = high. a = if (close == close[1]) then a. a = if (close == close[1]) then a. . plot q. up. down}. Rec Enumerations rec a = {default neutral. down}. If you do not assign a value to a. Note that a rec enumeration can have only one assignment statement. case neutral: q = close. up. switch(a) { case up: q = low. The third line is just a plot declaration.down.down. it will always be equal to its default neutral value . The default keyword indicates the default value of the rec enumeration.up else a. The second line of this script is the assignment statement. w. y}. default r. rec b = {q.q. rec a = {q. default r.q. rec c = {q. e. rec a = {q.q. y}. w. w. case neutral: q = close. ### error in this line plot y = a != if (1==2) then a else a. case down: q = high. b = b. a = a. t. default r. plot w = if (1==2) then a else a. b = a. switch(a) { case up: q = low. w. y}. t.q. t. e. e. y}.q. t. default r.q.q != if (1==2) then b else b.q. } Note that rec enumerations are independent. plot z = a[1] == a. e. y}. It is similar to the switch having an input enumeration as a parameter. default r. ### error in this line c = a. t. w. ### error in this line plot z = 1. rec b = {q. This means that you cannot assign the same values to two different enumerations like in the following example. ### error in this line Both sides of statements in the enumeration assignment should be of the same type: . e.The rest of the script is a switch statement having the rec enumeration as a parameter. a = a. plot x = a == z. displays the average of the last 12 days' closing prices. o Using Functions plot CloseAvg = average(close. 12). You can specify these parameters in any order. requires data (open. . etc. For example. for example. and plot SMA = average(length = 50. plot SMA = average(data = close. will show the same result on the chart. The thinkScript has a number of functions that can be performed on the price data to generate the desired study or strategy. For example. close. Each function has required parameters.) and length (number of bars). length = 50). Average. data = close). 7).). then the Line Painting Strategy is used.BOOLEAN_ARROW_UP PaintingStrategy.HISTOGRAM ). plot AvgVolume = Average(volume. Note that plots from the following "signal" painting strategy category are drawn above plots from the common category: • • • • • • • • • • PaintingStrategy. Here is the common syntax for that: o Formatting Plots <plot_name>. declare lower.ARROW_DOWN PaintingStrategy. line.POINTS PaintingStrategy.DASHES PaintingStrategy. color. AvgVolume. In case this function is not called.SQUARES PaintingStrategy.BOOLEAN_ARROW_DOWN PaintingStrategy.<L&F_function_name>(L&F_function_parameters ) In order to specify a plot type.The thinkscript contains lots of Look & Feel functions used to format a plot: define a plot type (histogram.SetPaintingStrategy(PaintingStrategy.HORIZONTAL PaintingStrategy. etc. .BOOLEAN_POINTS PaintingStrategy. point.TRIANGLES Plots defined first are drawn above plots defined later in the same painting strategy category. Note that you can use this function only in combination with Painting Strategy constants. use the SetPaintingStrategy function.ARROW_UP PaintingStrategy. line style and other. . 10).In this example the average volume plot is represented by a histogram. plot UpperBand = Highest(high[1]. e. • Use the Color function to reference named a plot color previously defined using defineColor • Use the GetColor function. In order to specify a color you can: • Use Color constants. or AssignNormGradientColor functions. plot Middle = (LowerBand + UpperBand) / 2. 7).g. In order to define a plot line style and its width use the SetStyle and SetLineWeight functions. Line width ranges from 1 to 5 pixels. AssignNormGradientColor is used to color a plot in a gradient color depending on values.SetLineWeight(3). then a solid line with 1 pixel width is used.LONG_DASH). Color. AssignValueColor is used to color a plot in different colors depending on specified conditions.RED. • • • plot SMA = Average(close. • Use the TakeValueColor function to reference color for anohter plot Example plot LowerBand = Lowest(low[1].SetStyle(Curve. • Use the CreateColor function. If this function is not called. This function can only be used in combination with the curve style constants. 7). SetDefaultColor is used to color the whole plot in a specific color. SMA. You can set plot color with the help of the SetDefaultColor. SMA. AssignValueColor. The Middle plot will be colored in a gradient depending on 14 last bar values and colors selected for "Highest" and "Lowest". Middle. 10).SetDefaultColor(GetColor(5)). CreateColor(250. The "Highest" color is defined using a constant.DefineColor("Lowest". Middle. For the LowerBand the example uses a color from the dynamic color palette. LowerBand. UpperBand. plot PastPrice = close[5].setHiding(getAggregationPeriod() < AggregationPeriod.DefineColor("Highest". PastPrice.HideBubble().RED). SMA10. PastPrice. Middle. Color.hide().AssignNormGradientColor(14.This example defined two named colors for the Middle plot.TakeValueColor()).AssignValueColor(LowerBand. plot SMA15 = Average(close.color("Lowest")). In this example the SMA10 plot is hidden by default and the SMA15 is hidden only on intraday charts by default.color("Highest"). "Lowest" is defined using the CreateColor function by defining the RGB components of the color. The setHiding function is diffenent from hide because it can hide/show a plot dynamically depending on certain conditions. .HideTitle(). Middle. Middle. If you want to hide the a plot you can use the hide and setHiding functions. 150. plot SMA10 = Average(close. 25)). plot SMA5 = Average(close. You can also hide the last plot value bubble and title in the status string with the current plot value using the HideBubble and HideTitle functions. 15). SMA15. 5). The TakeValueColors function is used to indicate that the UpperBand should be colored in the same color as the LowerBand.DAY). .Most studies and strategies are adjustable in terms of length. plot SMA = average(data = price. length = length). You can create an adjustable parameter for your thinkScript study using the input reserved word. bounds or levels. Here 12 and close are default values which you can override on the preferences panel the way you adjust any pre-defined studies. o Adjusting Parameters Using Inputs Example input length = 12. An input is like a def that can be adjusted in the Edit Studies and Strategies window. input price = close. data period. append the name of the symbol in quotes and parentheses to the data type you want to use. For example on accessing another data periods or price types.close("GOOG"). Note that you can use the price type data for Forex symbols only. or price type in your code. . see the open function desctiption in the Fundamental Functions section.In order to access data from another symbol. The code will give you a line that is the difference between the closing price for the symbol that you have in the chart and the closing price for Google (GOOG). o Accessing Data Example plot data = close . number of contracts. close > 70). When strategies are drawn on a chart. addOrder(OrderType.BUY_AUTO. This strategy comprises orders of both buying and selling sides. you should define a condition upon which the strategy should trigger. close < 50). . You can open a performance report by right clicking a signal and choosing "Show Report" from the pop-up menu in order to backtest selected strategies. Example addOrder(OrderType. It adds a Buy (Entry) signal when the Close price drops below 50 and a Sell (Exit) trigger when the price exceeds 70. Buy and Sell triggers appear in response to the conditions defined in the strategy. you must add strategies with both buying and selling orders. You can also specify trade price.You can use thinkScript for fine-tuning pre-defined strategies or creating strategies of your own in the TOS Charts charting package. o Using Strategies You can add the following types of orders defined by the corresponding constants using addOrder function: • BUY_AUTO • BUY_TO_CLOSE • SELL_AUTO • SELL_TO_CLOSE • Note that to be able to close and open positions.SELL_TO_CLOSE. and color of signals. Note that currently you cannot send real orders using strategies. After defining the order type. Here is a list of the tutorials: o Advanced Topics • • • • Concatenating Strings Creating Local Alerts Referencing Data Using Profiles .This section contains tutorials that will help you write your first thinkscript study or strategy. • • • • Example 1 AddVerticalLine(getMonth() <> getMonth()[1].TICK). This may be useful when you want to pass the resulting string as a parameter to one of the following functions: o Concatenating Strings AddChartLabel AddVerticalLine alert AddChartBubble Note that the concat function preliminarily converts values of different types to a string. concat(" is greater than ". concat("Current price ". concat(value2. Example 2 (Concatenating more than two values) input price = close. open)). Alert. alert(price > threshold. concat("Open: ". concat(price. For this reason you can use any numeric values as the function's parameters. threshold))). This example draws a vertical line with the open value for the beginning of each month. This example defines a local alert that is triggered once a new quotation arrives in case the current price is higher that the specified price. value3)) .You can concatenate two strings using the concat function. input threshold = 100. In order to concatenate more than two values the example uses nested concat function calls: concat(value1. close)). concat(if isVerbose then "Close: " else "". As you can see from the example. This example draws a chart label and a note depending on the isVerbose parameter. in order to pass a numeric value as a string you need to preliminarily concatenate it with an empty string using the concat function: concat(numerical_value. AddChartLabel(yes.Example 3 (Converting numerical value to a string) input isVerbose = yes. "") . Ring Example alert(open > 400. The alert is triggered once and it plays the ring sound. alert. concat("Open is greater than 400! Current value is".TICK – alert can be triggered after each tick The sound parameter plays a sound when the alert is triggered. Sound. alert type.NoSound • Sound. In general. The text parameter places a specified text next to the alert. The common syntax for thinkscript alerts is the following: alert(condition.Bell • Sound. • Alert. text.ONCE – alert can be triggered only once after adding a study. . open). The condition parameter defines a condition on which you want this alert to be triggered. Valid sound values are: • Sound. o Creating Local Alerts Available alert type values are: • Alert.In thinkscript you have the ability to create local alerts.Ding • Sound.BAR – alert can be triggered only once per bar. • Alert. alerts are signals that are triggered when a condition is satisfied.Chimes • Sound. The alert type parameter defines a type of the alert. sound).ONCE. This example tiggers an alert when the open price becomes higher than 400.Ring). o Referencing Data Here is a list of the tutorials: • Referencing Secondary Aggregation • Referencing Historical Data • Referencing Other Price Type Data • Referencing Other Studies • Referencing Other Symbol's Data • Past Offset 24 27 28 29 31 32 .In this section you will find tutorials that describe ways of referencing data in the thinkscript. specify the period parameter using the corresponding Aggregation Period constant. Example plot Data = Average(close(period = AggregationPeriod. Opt Exp. 10). You can also use a pre-defined string value for this purpose: 1 min. 3 Days.DAY). 4 min. plot Data = Average(dailyClose.In order to access data of a different aggregation period in your code. This code plots daily Open price for the current symbol. Month. and <current period>. Week. Referencing Secondary Aggregation Example plot dailyOpen = open(period = AggregationPeriod. This code plots weekly Close price for IBM.WEEK). 3 min. This code returns a 10 day average of the Close price.DAY)[1]. However. plot weeklyClose = close("IBM". 10). period = AggregationPeriod. This code plots the High price reached on the previous day. Day. 2 min. . 10 min. 30 min. 2 Days. 20 min. All indexers with such price functions use secondary aggregation period until you save it in some variable. plot yesterdayHigh = High(period = AggregationPeriod. 15 min. 4 Days.DAY). 4 hours. will return an average of the Close price calculated for the last ten bars (the aggregation period used in calculation will depend on the current chart settings).DAY). plot dailyClose = close(period = AggregationPeriod. 2 hours. 5 min. 1 hour. plot FullD = Average(Average((close(period = AggregationPeriod.WEEK). Example plot Data = close(period = AggregationPeriod. KPeriod)) / (Highest(high(period = AggregationPeriod. input DPeriod = 10.WEEK). KPeriod)) * 100.Lowest(low(period = AggregationPeriod.Lowest(low(period = AggregationPeriod.MONTH). Example declare lower.Lowest(low(period = AggregationPeriod. the secondary aggregation period cannot be less than the primary aggregation period defined by chart settings. DPeriod).WEEK). KPeriod) . slowing_period).MONTH) + close(period = AggregationPeriod. def a = close(period = AggregationPeriod.Lowest(low(period = AggregationPeriod. . slowing_period). KPeriod)) * 100. plot Data = a + b. KPeriod)) / (Highest(high(period = AggregationPeriod.Note that two different secondary aggregation periods cannot be used within a single variable.WEEK).WEEK).WEEK) . In addition. KPeriod) . input slowing_period = 3.WEEK) . def b = close(period = AggregationPeriod.WEEK).WEEK). This code will not work on a daily chart. input KPeriod = 10.WEEK). The correct script is: plot FullK = Average((close(period = AggregationPeriod. .Example shows the Stochastic Full study using weekly price regardless of the current chart aggregation period. See the Stochastic Full for a detailed study description. close from -1 bar ago returns the Close price one bar forward. etc. For example. For example.Example plot momentum = close . close[-2] returns the Close price 2 bars forward. etc. close[1] returns the Close price from one bar ago.close[5]. Example plot scan = close from 4 bars ago + high from 1 bar ago. . At the same time. close[2] returns the Close price 2 bars ago. Indexing Positive indexes are used to refer to data in the past and negative indexes to refer to data in the future. Negative numbers refer to data in the future. close from 1 bar ago returns the Close price one bar ago. Referencing Historical Data Verbal Syntax Verbal syntax allows using reserved human-readable sentences in the script. close from 2 bars ago returns the Close price from two bars ago. etc. low from -2 bars ago returns the Low price two bars forward. The example will plot a line that is the sum of the Close price 5 bars ago and the High price 1 bar ago. etc. close[-1] returns the Close price 1 bar forward. For example. you can use each of the two possible ways. The example will plot a line that is the difference between the current Close price and the Close price 5 bars ago. To access data in the past and in the future. Referencing Other Price Type Data Example plot ask = close(priceType = "ASK"). . put the priceType parameter with the name of the aggregation period in parentheses to the Fundamentals you want to use. plot bid = close(priceType = "BID"). Note that only Forex symbols support different price type data.In order to access data from another price type in your code. all other symbols support only data based on the "LAST" price. On the "MARK" price type chart for some Forex symbol this code will give you a ask and bid plots. The thinkScript allows you to reference pre-defined studies or defined using the script reserved word in your code. .EMA . This code will plot the 20 bar moving average of the volume. Referencing Other Studies The code will plot a simple moving average with the default parameters of that study. length).avg(20).EMA.avg(20). plot SMA = Average(close. plot EMA = ExpAverage(close. length). } declare lower. plot EMAOsc = avg(10). Note that currently you cannot reference userdefined studies. 20). To see the input parameters of a particular study. plot SMAOsc = avg(10) . Example 1 (Using the reference reserved word) plot SMA = reference SimpleMovingAvg. click that study in the Edit Studies and Strategies window. For details see the reference reserved word article. Example 3 (Referencing another plot in the embedded script) script avg { input length = 10. You will see available parameters listed in the study properties section. Example 2 (Referencing a pre-defined study with given parameters) plot SMA = simplemovingavg(volume. Below). script study { input direction = CrossingDirection. direction). The first plot uses the short syntax ("Above"). For details see the script reserved word article. plot a = crosses(close. This script exemplifies two methods of referencing constant inputs of the embedded study. The SMA plot is omitted in the reference because the first study plot is referenced by default. plot test2 = Study(CrossingDirection. Example 4 (Two ways of referencing studies with constant inputs) declare lower. Average(close.The code will produce two moving average oscillators in a separate subgraph. 20). .Below) by specifying the full name of the CrossingDirection constant.Any. } plot test1 = Study("Above"). while the second one uses the full syntax (CrossingDirection. close("GOOG"). append the name of the symbol in quotes and parentheses to the Fundamentals you want to use. The code will give you a line that is the difference between the closing price for the symbol that you have in the chart and the closing price for Google (GOOG).In order to access data from another symbol in your code. Referencing Other Symbol's Data Example plot spread = close . . Let us study the following example: declare lower. In this very example. plot myline = x. This calculation mechanism is obvious for bars from the sixth through the last one. if additional historical data is available for the chart you are currently using. but how this plot will be calculated for the first five bars? Past offset is a number of additional bars from the past. it means that calculation will start with the sixth bar using price data obtained from the first five bars. However. variable x uses past offset equal to 1. Let us study the following example. In the example script. Past Offset This example script will plot the Close price five bars prior to the current bar. it will be used for calculating the plot for the first five bars.When referencing historical data. 11). the highest past offset overrides lower offsets in the same study. . you might need to use several different past offsets for expressions in your script. not 2 as one might have expected. past offset is equal to five. In this example. plot Average11 = Average(close. necessary for calculating a study. This is why the myline plot will return 11 for the first bar. rec x = x[1] + 1. plot CloseOffset = close[5]. one should mind a feature called past offset. When writing a study. this offset is equal to 10 and is assigned to both expressions. while function average uses past offset equal to 10. In thinkScript. which means that all expressions in a single study will have the same (highest) past offset. rec x = compoundValue(1. low). plot myline = x. . 10). However. plot ATR = average(TrueRange(high.declare lower. close. x[1]+1. and all the other values of this plot will be calculated corresponding to it. if for some reason you need an independent initialization point for an expression. 1). Note that past offset might affect calculation mechanism of some studies due to setting a single intialization point for all expressions. you can use the compoundValue function: This would explicitly set the value for the myline plot for the first bar. You can find the detailed description of these functions in the Profiles section.show("color" = Color. and Monkey Bars profiles can be created in thinkScript using corresponding Profile functions. tpo. . Here is the code: o Using Profiles def allchart = 0. let's create a TPO profile study (colored blue) that aggregates all chart data on the right expansion.BLUE). profile tpo = timeProfile("startnewprofile" = allchart). Volume. In order to demonstrate the use of the functions.The TPO. All interrelated thinkscript items are cross-linked to ensure you have the fullest information about the relations inside the thinkscript. Declarations. Each article provides the syntax. declarations. and Reserved Words. constants. Functions. etc. Here is the list of the reference sections: 37 • Reserved Words • Declarations 68 • Functions 78 • Constants 256 • Data Types 312 • Operators 315 . and an example of use of the selected item. description.Reference The reference describes thinkscript elements (functions.) required to create studies and strategies. The items are distributed alphabetically among the following sections: Constants. • Reference o Reserved Words 37 o Declarations 68 o Functions 78  Fundamentals  Option Related  Technical Analysis  Mathematical and Trigonometrical  Statistical  Date and Time  Corporate Actions  Look and Feel  Profiles  Others o Constants 256  Aggregation Period  Alert  ChartType  Color  CrossingDirection  Curve  Double  EarningTime  FundamentalType  OrderType  PaintingStrategy  PricePerRow  Sound o Data Types 312 o Operators 315 257 268 269 273 283 285 289 291 293 297 299 309 310 79 92 104 132 156 170 185 191 220 234 . . o above o ago Syntax <value> from 1 bar ago <value> from <length> bars ago Description This reserved word is used to specify a time offset in a humanfriendly syntax. see the Referencing Historical Data article. These commands control the basic behavior of your thinkScript study. Choose your command from the list: o Reserved Words Syntax See the crosses reserved word article. plot. For more information.The thinkScript supports a number of simple commands such as for example: declare. and input. Description The above reserved word is used with the crosses operator to test if a value gets higher than another value. SetPaintingStrategy(PaintingStrategy.Syntax <condition1> and <condition2> Description The and logical operator is used to define complex conditions. Draws a dot near each inside price bar. see the Referencing Historical Data article. This reserved word is also used to define an interval in the between expression. o and o bar Syntax <value> from 1 bar ago Description This reserved word is used to specify a time offset in a humanfriendly syntax. In order to define the operator you can also use &&. InsideBar. Example plot InsideBar = high <high[1] and low > low[1].BOOLEAN _POINTS). Note that bar and bars reserved words can be used interchangeably. For more information. . For a complex condition to be true it is required that each condition from it is true. Note that bar and bars reserved words can be used interchangeably.1. The isOut plot reflects the opposite condition. o below o between In this example between is used to check whether the current closing price hits the 10% channel of the previous closing price. see the Referencing Historical Data article. plot isOut = !isIn. . Description The below reserved word is used with the crosses operator to test if a value becomes less than another value. For more information. Example declare lower. Syntax <parameter> between <value1> and <value2> Description This reserved word is used in the between logical expression. It tests if the specified parameter is within the range of value1 and value2 (inclusive). Syntax See the crosses reserved word article.9 and close[1] * 1. The thinkscript also has the between function with a different syntax and usage.o bars Syntax <value> from <length> bars ago Description This reserved word is used to specify a time offset in a humanfriendly syntax. def isIn = close between close[1] * 0. o case Syntax See the switch statement. Description The reserved word is used in combination with the switch statement to define a condition. o crosses Syntax <value1> crosses above <value2> <value1> crosses below <value2> <value1> crosses <value2> Description This reserved word is used as a human-readable version of the Crosses function. It tests if value1 gets higher or lower than value2. Example plot Avg = Average(close, 10); plot ArrowUp = close crosses above Avg; plot ArrowDown = close crosses below Avg; plot Cross = close crosses Avg; ArrowUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARR OW_UP); ArrowDown.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ ARROW_DOWN); Cross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS ); This code plots up arrows indicating the bars at which the Close price gets higher than its 10 period average, and down arrows at which the Close price gets lower than its 10 period average. The same result can be achieved by using the Crosses function: plot Avg = Average(close, 10); plot ArrowUp = Crosses(close, Avg, CrossingDirection.Above); plot ArrowDown = Crosses(close, Avg, CrossingDirection.Below); plot Cross = Crosses(close, Avg, CrossingDirection.Any); ArrowUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARR OW_UP); ArrowDown.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ ARROW_DOWN); Cross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS ); Example plot Avg = Average(close, 10); plot Cross = close crosses Avg; Cross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS ); This code plots arrows indicating the bars at which the Close price gets higher or lower than its 10 period average. The equivalent code is: plot Avg = Average(close, 10); plot Cross = close crosses above Avg or close crosses below Avg; Cross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS ); Syntax declare <supported_declaration_name> Description The declare keyword is a method for telling the chart something basic about the appearance of the study or strategy you are creating. You can find the list of supported declarations in the Declarations section. Example declare lower; plot PriceOsc = Average(close, 9) - Average(close, 18); o declare The example shows how to use one of the most commonly used declations called lower. For other examples on declarations, see the Declarations section. o def Syntax def <variable_name>=<expression>; or def <variable_name>; <variable_name>=<expression>; Description Defines a variable you would like to work with. Example def base = Average(close, 12); plot UpperBand = base * 1.1; plot LowerBand = base * 0.9; This example shows a simplified SMAEnvelope study, where the def reserved word is used to define the base. The rational of defining this variable is to avoid double calculations (increase performance) in UppderBand and LowerBand plots, because def variable values are cached (by means of increasing memory usage). You can separate the variable definition from its value assignment as shown in the following example where a variable value is assigned depending on the selected averageType input value. See the Defining Variables section for more details. input averageType = {default SMA, EMA}; def base; switch (averageType) { case SMA: base = Average(close, 12); case EMA: base = ExpAverage(close, 12); } plot UpperBand = base * 1.1; plot LowerBand = base * 0.9; Syntax See the enum rec, enum input, and switch statements. Description The default reserved word is used in combination with the enum rec, enum input, and switch statements to specify a default value. o default o do Syntax def <result> = fold <index> = <start> to <end> with <variable> [ = <init> ] [ while <condition> ] do <expression>; Description This reserved word defines an action to be performed when calculating the fold function. For more information, see the fold reserved word article. o else Syntax See the if reserved word article. Description The else reserved word is used to specify an additional condition in the if-expression and if-statement. o equals Syntax equals Description The reserved word is used as a logic operator to test equality of values. In order to define this operator you can also use the double equals sign ==. The code draws points on bars having the Doji pattern (equal close and open). Example plot Doji = open equals close; Doji.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS); plot factorial = fold index = 1 to n + 1 with p = 1 do p * index. The index is iterated from start (inclusive) to end (exclusive) with step 1. i) else Double. The value of variable after the last iteration is returned and can be used in assignments and expressions. You can also specify a condition upon violation of which the loop is terminated. variable is initialized to zero. o fold Example 2 input price = close. The initial value of variable is defined by init. -i) > 40 then getValue(high. Calculates the factorial of a number. At each iteration. Finds the next High price value greater than 40 among the following 100 bars.NaN.1)) / length. Description The fold operator allows you to perform iterated calculations similarly to the for loop. if it is omitted. It uses variable to store the result of the calculation. n. expression is calculated and assigned to variable. Value of index and previous value of variable can be used in expression. plot SMA = (fold n = 0 to length with s do s + getValue(price. length . input length = 9. Example 3 plot NextHigh = fold i = 0 to 100 with price = Double. . Calculates the simple moving average using fold. Example 1 input n = 10.Syntax def <result> = fold <index> = <start> to <end> with <variable> [ = <init> ] [ while <condition> ] do <expression>.NaN while IsNaN(price) do if getValue(high. see the Referencing Historical Data article.o from Syntax <value> from 1 bar ago <value> from <length> bars ago Description This reserved word is used to specify a time offset in a humanfriendly syntax. For more information. . there is also if-function having syntax and usage different from those of the reserved word. if <condition> [then] { <plot_name> = <expression1>. } } Description As a reserved word.o if Syntax (if-expression) plot <plot_name> = if <condition> then <expression1> else <expression2>. Syntax (if-statement) plot <plot_name>. } else { if <condition2> [then] { <plot_name> = <expression2>. If-expression always calculates both then and else branches. } else { <plot_name> = <expression3>. plot <plot_name> = if <condition1> then <expression1> else if <condition2> then <expression2> else <expression3>. } else { <plot_name> = <expression2>. if is used in if-expressions and ifstatements to specify a condition. In thinkScript. if <condition1> [then] { <plot_name > = <expression1>. while if-statement calculates either of these. } plot <plot_name>. depending on the condition. The if-expression . . etc. } else { ExpAvg = ExpAverage(price. plot SimpleAvg = Average(price.can also be used in other functions such as. Example input price = close. 12). AssignValueColor. Note that you can also use the def and rec instead of plot in the syntax provided above. input long_average = yes. } In this example. for example. if long_average then 26 else 12). if-expression and if-statement are used to control the length parameter of moving averages. if long_average { ExpAvg = ExpAverage(price. AssignPriceColor. 26). plot ExpAvg. • Inputs titles are always displayed on the GUI in the lowercase. The following code will result in compilation error. or levels. o input Find the full list of inputs in the following list: • boolean • constant • enum • float • integer • price • string . The following two definitions are similar on the GUI.Most studies are adjustable in terms of length. • Inputs can't have empty spaces in their definitions. Code snippet 2 input TEST = "test in uppercase". When defining inputs take the following notes into consideration: • Inputs are displayed on the GUI in the same order as they appear in the source code. You can create an adjustable parameter for your thinkScript study using the input reserved word. bounds. Code snippet 4 input input_name_with_spaces = "OK". Code snippet 1 input test = "test in lowercase". input "input name with spaces" = "ERROR". In order to have titles displayed on the GUI with spaces you can do one of the following: Code snippet 3 input inputNameWithSpaces = "OK". The default value of the input can either be "yes" or "no". 10). plot LowPrice = if useHighLow then Lowest(low. Whether to use or not the high and low prices instead of the closing price can be defined using the correspondent input. 10) else Highest(close.Profile: Studies and Strategies Syntax input <input name>=<boolean_value_used_by_default>. boolean Example input useHighLow = yes. Draws the channel based on the highest and lowest price for the length equal to 10. 10). which is set to "yes" by default. plot HighPrice = if useHighLow then Highest(high. . 10) else Lowest(close. Description Defines a boolean input. For the full list of supported constants. constant This example script draws the Open price plot with specified aggregation period. Description Defines an input expressed by a constant of particular type. plot SecondaryPeriodOpen = open(period = secondaryPeriod).DAY. .Example input secondaryPeriod = AggregationPeriod. see the Constants section. Note that color constants cannot be used for input definition. Profile: Studies and Strategies Syntax input <input name>=<constant_used_by_default>. EMA. 10).Example input averageType = {default SMA. <enum_value_N>}. • have one value (not necessarily first) specified with the default reserved word which defines the default value for the input. plot Avg. In order to define the input it is required to: • have all values specified in braces.. "Wilder's Average"}. case EMA: Avg = ExpAverage(close. 10). . • place a value in double quotes if it contains a space symbol. 10). • avoid equal values. The type of the moving average can be changed using the correspondent input. See other examples on inputs in the Fundamentals section. switch (averageType) { case SMA: Avg = Average(close. which is set to "SMA" by default. . <enum_value_1>. enum Draws the moving average based on the closing price with length equal to 10. Description Defines an enum input of string values. } Profile: Studies and Strategies Syntax input <input name>={default <enum_value_used_by_default>. case "Wilder's Average": Avg = WildersAverage(close.. Draws the SMA using the close price data. Description Defines an integer input. which is set to 10. Description Defines a float input.Profile: Studies and Strategies Syntax input <input name>=<float_number_used_by_default>.percentShift / 100). Note that in order to define this input you need to use a fullstop as a delimiter in its default value. plot LowerBand = close * (1 . Example input percentShift = 10. Draws the envelope based on the closing price. integer plot SMA = Average(close. length). The percent shift value can be adjusted using the correspondent input. The length value can be adjusted using the correspondent input. which is set to 10 by default . Example input length = 10. float plot UpperBand = close * (1 + percentShift / 100).0. Profile: Studies and Strategies Syntax input <input name>=<integer_number_used_by_default>.0 by default. Description Defines a price input. price Valid parameters for the price type are: • open • high • low • close • hl2 • hlc3 • ohlc4 • volume Example input price = close. The type of price data can be adjusted using the correspondent input. .Profile: Studies and Strategies Syntax input <input name>=<price_value_used_by_default>. Draws the EMA with the length equal to 10. which is set to "close" by default. 10). plot EMA = ExpAverage(price. Profile: Studies and Strategies Syntax input <input name>="<string_value_used_by_default>". Note that in order to have this input defined you need to specify double quotes in its default value. The symbol for the comparison plot can be adjusted using the correspondent input. string plot Comparison = close(symbol). Draws the comparison plot based on the closing price. which is set to "SPX" by default. Description Defines a string input. . Example input symbol = "SPX". .o no Syntax no Description The no reserved word is used as a value for the boolean input or as the false condition. Since the condition is always false.BOOLE AN_POINTS). you can also use the 0 value. rec barsDown = if close < close[1] then barsDown[1] + 1 else 0. plot ConsecutiveBars = barsUp >= NumberOfBars or barsDown >= NumberOfBars. In order to define the false condition. the low plot is always displayed. ConsecutiveBars. Example input NumberOfBars = 3. o or Syntax or Description The reserved word is used to define complex conditions. This example highlights bars having the closing price lower than the closing price of the specified number of previous bars with a dot. rec barsUp = if close > close[1] then barsUp[1] + 1 else 0.SetPaintingStrategy(PaintingStrategy. Example plot Price = if no then high else low. For a complex condition to be true it is required that at least one condition from it is true. EMA}. see the Formatting Plots tutorial. Description Renders the data you are working with on the chart. plot MA. } . case EMA: MA = ExpAverage(close. switch (averageType) { case SMA: MA = Average(close. This example draws a simple moving average study plot. 12). You can separate the plot definition from its value assignment as shown in the following example where a plot value is assigned depending on the selected averageType input value. or plot <plot_name>. 12). For more information about the reserved word. 12).o plot Syntax plot <plot_name>=<expression>. input averageType = {default SMA. Example plot SMA = Average(close. <plot_name>=<expression>. plot CumulativeVolume = C. <variable_name>=<expression>. Rec is short for "recursion". o rec Syntax rec Description Enables you to reference a historical value of a variable that you are calculating in the study or strategy itself. Description Defines a profile to be displayed on the chart. Example rec C = C[1] + volume. . This example plots the cumulative volume starting from the beginning of the time period.o profile Syntax profile <variable_name>=<expression>. See the Defining Variables section for more details. or profile <variable_name>. 0... Referenicing the VWAP study: plot MyVWAP1 = reference VWAP. If the plot name is not defined. The reference reserved work is required to distinguish the VWAP study from the vwap function. because they have fixed order of inputs in the code: Full form: plot MyBB2 = BollingerBandsSMA(price = open.Syntax reference <StudyName>(parameter1=value1. Calling the vwap function: plot MyVWAP1 = vwap. default values should be used. o reference . If parameters values are not defined. Compact form: plot MyBB = BollingerBandsSMA(open. length = 30).. study's main plot should be referenced (main is the first declared in the source code). Inputs' names can be dropped only for ThinkScript studies. displace = 0. Note that the reference reserved word can be dropped but in this case parenthesis are necessary. 30). MoneyFlow study from the moneyflow function. Compressed form: plot MyMACD = MACDHistogram(). Full form: plot MyMACD = reference MACDHistogram. parameterN=valueN).<PlotName> Description References a plot from another script. Example The following example references def and rec instead of the plot as shown at the top of the article.SellSignal == yes. if bs then "Buy!" else "Sell!".CURRENT). . def bs = !IsNaN(close) and ATRTrailingStop().BuySignal == yes. def st = ATRTrailingStop(). bs and ss are references to the BuySignal and SellSignal def from the same study.state. AssignPriceColor(if st == 1 then GetColor(1) else if st == 2 then GetColor(0) else Color. def ss = !IsNaN(close) and ATRTrailingStop(). if bs then GetColor(0) else GetColor(1)). AddVerticalLine(bs or ss. st is the reference to the state enum rec from the ATRTrailingStop study. } Description This reserved word is used to define new scripts you may need to reference later within a certain study or strategy.1) / (length + 1) * EMA[1]. rec EMA = compoundValue(1.MyEMA(close. Example script MyEMA { input data = close. input length = 12. plot Osc = MyEMA(close. 2 / (length + 1) * data + (length . The main section of the code creates an oscillator based on the MyEMA difference for different lenghts. length)). } declare lower. This code defines the MyEma script where the first EMA value is calculated as SMA in contrast to the ExpAverage function whose first value is assigned the closing price. 50). 25) .o script Syntax script <script_name> { <script_code>. Average(data. plot MyEma = EMA. . WMA}. case WMA: Avg = wma(price)... and enum input."Green EMA" then color.o switch plot <plot_name>. . switch (plot_type) { case SMA: Avg = Average(price). "Red EMA". In the switch statement you either need to define the case with all values from the enum. } Avg.BLUE). plot Avg. } Description The switch statement is used to control the flow of program execution via a multiway branch using the enum rec. "Green EMA". Example input price = close.SetDefaultColor( if plot_type == plot_type.RED else if plot_type == plot_type. Note that in this approach you cannot use case with equal enums. default: <plot_name> = <expression>."Red EMA" then color. default: Avg = ExpAverage(price).GREEN else color. Or you can use the default statement to define actions for all enums that are not defined using the case. switch (<enum input or enum_rec>) { case <enum value1>: <plot_name> = <expression1>. input plot_type = {default SMA. Syntax . This example illustrates the usage of the switch reserved word to assign different values to plots. The default keyword must be used unless all possible values of variable are explicitly listed. . For more information. For more information. see the fold reserved word article. Description The reserved word is used to define an interval to be used when calculating the fold function. o to Syntax def <result> = fold <index> = <start> to <end> with <variable> [ = <init> ] [ while <condition> ] do <expression>. This reserved word is used only in combination with the if statement. see the fold reserved word article. Description This reserved word defines a condition upon violation of which the loop is terminated when calculating the fold function. o while . Syntax def <result> = fold <index> = <start> to <end> with <variable> [ = <init> ] [ while <condition> ] do <expression>. Description The reserved word is used to specify an action to be performed when the if condition is satisfied.o then Syntax See the if reserved word article. For more information. .SetHiding(!DisplayPlot). Example input DisplayPlot = yes. Data. you can also use 1 or any non-zero number. plot Data = close. Its default value is yes.o with Syntax def <result> = fold <index> = <start> to <end> with <variable> [ = <init> ] [ while <condition> ] do <expression>. Description The reserved word is used to define an iteration step value in the fold function. DisplayPlot input controls visibility of plot. In this study. see the fold reserved word article. In order to define the true condition. o yes Syntax yes Description The yes reserved word is used as a value for the boolean input or as the true condition. The section contains the following declarations: • all_for_one • hide_on_daily • hide_on_intraday • lower • on_volume • once_per_bar • real_size • upper • weak_volume_dependency • zerobase o Declarations . An important difference of declarations from other thinkscript items is that in order to define a declaration you need to use the declare reserved word.Declarations are responsible for basic operations performed with charts such as changing the recalculation mode or setting the minimal chart value to zero. Description Keeps the volume value either in all price inputs or in none of them.o all_for_one Syntax declare all_for_one. plot UpperBand = Average(HighPrice) * 1.9. As a result. input HighPrice = high.1. If you change the inputs to close and volume. StochasticFull. This function is used to prevent visualizing irrelevant data in case the volume value does not combine with other price input values. Usage in: SMAEnvelope. . This example plots the high and low price envelopes at 10 percent above and below for the 12 day simple moving average. the two volume values will be plotted. plot LowerBand = Average(LowPrice) * 0. StochasticSlow. StochasticFast. input LowPrice = low. Example (Price Envelopes) declare all_for_one. the all_for_one declaration will automatically change the HighPrice and LowPrice inputs to the two volumes because the close and volume in combination lead to irrelevant data. declare lower. SMA. Due to declaration. Example (Implied Volatility) declare hide_on_intraday. data for implied volatility is not available for intraday charts. By definition. Description Hides a study on charts with aggregation periods equal to or greater than 1 day.AssignValueColor(GetColor(secondsFromTime(0) / 3600)). this study will be hidden on daily charts. This study plots SMA of Close price and assigns a different color to the plot each hour. you can use the declaration to automatically hide studies on this type of charts.o hide_on_daily Syntax declare hide_on_daily. Description Hides a study on intraday charts (time charts with aggregation period less than 1 day and tick charts). plot SMA = average(close). Example declare hide_on_daily. o hide_on_intraday Syntax declare hide_on_intraday. plot ImpVol = IMP_VOLATILITY(). OpenInterest. Usage in: ImpVolatility. . Therefore. Usage in: Multiple . input slowLength = 18. input fastLength = 9. it is reasonable to put the plot on the lower subgraph to avoid scaling the main chart. Therefore. fastLength) . plot PriceOsc = Average(price. The result value is lower compared to the price value.o lower Syntax declare lower. Example (Price Oscillator) declare lower. The example plots the difference between the two average values calculated on 9 and 18-bar intervals. Description Places a study on the lower subgraph. slowLength).Average(price. This declaration is used when your study uses values that are considerably lower or higher than price history or volume values. input price = close. The code in the example contains both volume and base subgraph related values. However. it may be required to forcibly place the study on the volume subgraph regardless of the values you are using. To study an example that uses only non-volume values.(high + low) / 2) * volume. If the study contains volume values and values not related to the base subgraph. General Information By default. plot VolumeAccumulation = (close . . In order to place the study on the volume subgraph. see the real_size function article.o on_volume Syntax declare on_volume. the application automatically defines where to place a study. then this study is displayed on the volume subgraph. the code uses the on_volume declaration. Usage in: OpenInterest. Example (Volume Accumulation on the Volume Subgraph) declare on_volume. otherwise it is displayed on the base subgraph. Description Places a plot on the volume subgraph. This study plots a verical line at the specified time point in EST time zone for each day. AddVerticalLine(secondsFromTime(time)[1] < 0 && secondsFromTime(time) >= 0. the study is forced to recalculate the last values only once per bar. time)).o once_per_bar Syntax declare once_per_bar. If this declaration is applied. Since the time value is fixed. there is no need to recalculate the study after each tick. . Example declare once_per_bar. input time = 0930. This declaration can be used to reduce CPU usage for studies which do not need to be recalculated per each tick. By default. concat("". last study values are recalculated after each tick. Description Changes the recalculation mode of a study. plot Data = open_interest(). declare on_volume. For the described two cases it may be required to use the axis of the volume or base subgraph. • Study that is placed on the base subgraph by default is forcibly moved to the volume subgraph (using the on_volume declaration). instead of the native plot axis. in order to use the axis of the volume subgraph. Syntax declare real_size. Note that the axis of the volume subgraph can be used in case you use only volume values in your study. .o real_size Example declare real_size. General Information Studies always use the axis of the subgraph where you plot them except for the following two cases when the native plot axis are used: • Study that is created for a separate subgraph (using the lower declaration) is moved to the base or volume subgraph using the On base subgraph check box. In the code above. Description Forces a study to use axis of either base subgraph or volume subgraph. ProbabilityOfExpiringCone. you specify the real_size declaration. declare hide_on_intraday. Usage in: OpenInterest. Note that a study is placed on the volume subgraph in case only volume values are used in the study. This declaration is applied by default to all studies not containing the lower and on_volume declarations. plot AvgWtd = wma(price. .o upper Syntax declare upper. the upper declaration places the weighted moving average plot on the main chart. length). Example (Price Oscillator) declare upper. Description Enables you to place a study either on the base subgraph or on the volume subgraph. input price = close. input length = 9. In this example. the study will be displayed on the base subgraph. In order to implement the logics. o weak_volume_dependency def shift = factor * AvgTrueRange(high. Example (Keltner Channels) declare weak_volume_dependency. you use the weak_volume_declaration. plot Avg = average. Usage in: KeltnerChannels. def average = Average(price. plot Lower_Band = average .shift. close.5. length). You want to display the plot on the base subgraph except for cases when you use at least one volume value. Consider you are analyzing data that contains both volume and base subgraph related values using the code provided above. . If you use the close price input in the code. low. Description Places a study on the volume subgraph when at least one volume value is used. For the latter case. you would like to use the volume subgraph. input factor = 1. input price = close. length). plot Upper_Band = average + shift. then there is a weak volume dependency and the study will be displayed on the volume subgraph. input length = 20. STARCBands. If you use the volume price input.Syntax declare weak_volume_dependency. In this example. VolumeAvg. Volume. . Example (Price Oscillator) declare zerobase. the Vol plot contains no negative values. plot Vol = Volume.o zerobase Syntax declare zerobase. declare lower. It is reasonable to set the minimum value on the study axis to zero using the zerobase declaration. Description Sets the minimal value on a study axis to zero if there are no negative values in the study. SpectrumBars. Usage in: AwesomeOscillator. each thinkscript function receives input parameters and produces a result. data = close) produce the same result. All the functions are spread among the following sections: 79 • Fundamentals • Option Related 92 • Technical Analysis 104 • Mathematical and Trigonometrical 132 • Statistical 156 • Date and Time 170 • Corporate Actions 185 • Look and Feel 191 • Profiles 220 • Others 234 o Functions . In thinkscript the parameters can be specified in any order. length = 50) and plot SMA = average(length = 50.Similar to functions in programming languages. For example plot SMA = average(data = close. Here is the full list: • ask • bid • close • high • hl2 • hlc3 • imp_volatility • low • ohlc4 • open • open_interest • volume • vwap Trading analysis tightly relates to close. All of them are collected in this section. or high values. volume weighted average. there are functions to work with data such as implied volatility. The thinkscript contains functions to work with these values. open interest. low. open. o Fundamentals . and volume. In addition. .ask Syntax ask Description Returns current value of ask price for current symbol. Note that you cannot reference historical data using this function.YELLOW else Color.RED). This function is only available in thinkScript integration features: Custom Quotes.25 then Color. AssignBackgroundColor(if spread < 0.g.05 then Color. ask[1] is an invalid expression. and Conditional Orders.bid.GREEN else if spread < 0. It calculates a bid-ask spread and assigns different colors according to its value. e. Study Alerts. This example script is used as a custom quote. Example plot spread = ask . and Conditional Orders. Note that you cannot reference historical data using this function. . %" = round(100 * ((bid + ask) / 2 . 2). e. bid[1] is an invalid expression. Example plot "Diff. AssignBackgroundColor(if "Diff. This example script is used as a custom quote. %" > 0 then Color. It calculates percentage difference between mark and last prices and assigns colors according to its sign. %" < 0 then Color. Study Alerts.DOWNTICK else Color.bid Syntax bid Description Returns current value of bid price for current symbol.UPTICK else if "Diff. This function is only available in thinkScript integration features: Custom Quotes.close) / close.GRAY).g. RelativeStrength. PairCorrelation. Draws the close plot of either IBM. Any period. Correlation. GOOG divided by three. PersonsPivots. CumulativeVolumeIndex. Day. Spreads. ASK. and GE. DailyHighLow. String priceType). plot PriceClose = close(symbol).g. Week. Example declare lower. aggregation period and price type. Usage in: . "GOOG/3". Each of the symbols can be selected in the Edit Studies dialog. Alpha2. You can use both Aggregation Period constants and pre-defined string values (e. BID (for Forex symbols only) input symbol = {default "IBM". etc. PairRatio.) as valid parameters for the aggregation period. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. McClellanSummationIndex. AlphaJensen. GOOG.Syntax close(String symbol. Beta2. "(2*IBM GOOG/6 + GE)/2"} . Month. or a composite price consisting of IBM. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the Close price for the specific symbol. 2 Days. McClellanOscillator. Beta. Valid parameters for the price type are: • LAST • MARK. close AdvanceDecline. WoodiesPivots. Example declare lower. BID (for Forex symbols only) input symbol = "IBM". You can use both Aggregation Period constants and pre-defined string values (e.g. 2 Days. WoodiesPivots. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Week. PersonsPivots. plot PriceHigh = high(symbol).) as valid parameters for the aggregation period. This example script plots High price for IBM. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the High price for the specific symbol. ASK. aggregation period and price type. .high Syntax high(String symbol. Valid parameters for the price type are: • LAST • MARK. Month. String priceType). Usage in: DailyHighLow. etc. Any period. Day. ) as valid parameters for the aggregation period.hl2 Description Returns (High + Low)/2. Day.g. period). You can use both Aggregation Period constants and pre-defined string values (e. input period = AggregationPeriod. input symbol = "IBM". Example declare lower. Syntax hl2(String symbol. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Any period. String priceType). Week. 2 Days. plot MedianPrice = hl2(symbol. . Month. etc.WEEK. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" This example script plots weekly median price for IBM. Day. ASK. BID (for Forex symbols only) Example plot TypicalPrice = hlc3. Low. Week. etc. Any period.) as valid parameters for the aggregation period. You can use both Aggregation Period constants and pre-defined string values (e. This example script draws the typical price plot.g. Valid parameters for the price type are: • LAST • MARK. aggregation period and price type.hlc3 Syntax hlc3(String symbol. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. and Close price values) for the specific symbol. 2 Days. Month. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the typical price (arithmetical mean of High. . String priceType). plot ImpliedVolatility = imp_volatility(). Week. Any period. String priceType). Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the implied volatility for the specific symbol.) as valid parameters for the aggregation period. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Valid parameters for the price type are: • LAST • MARK. BID (for Forex symbols only) Example declare lower. You can use both Aggregation Period constants and pre-defined string values (e.Draws the implied volatility plot for the current symbol. 2 Days. imp_volatility . aggregation period and price type. Syntax imp_volatility(String symbol. etc. Day. ASK. Usage in: ImpVolatility. Month.g. You can use both Aggregation Period constants and pre-defined string values (e. aggregation period and price type. This example script draws daily. BID (for Forex symbols only) Example plot LowDaily = low(period = AggregationPeriod. WoodiesPivots. etc. and monthly Low price plots for the current symbol. ASK. . String priceType).MONTH). PersonsPivots.low Syntax low(String symbol. plot LowMonthly = low(period = AggregationPeriod. Week. weekly.DAY). Month. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the Low price for the specific symbol. Valid parameters for the price type are: • LAST • MARK.g.WEEK). The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Day. Usage in: DailyHighLow. Any period.) as valid parameters for the aggregation period. 2 Days. plot LowWeekly = low(period = AggregationPeriod. String priceType). 2 Days. etc. Month. .ohlc4 Syntax ohlc4(String symbol.) as valid parameters for the aggregation period. Day. Week.g. aggregation period and price type. Low and Close price values. Any period. High. You can use both Aggregation Period constants and pre-defined string values (e. This example script plots the arithmetical mean of Open. Example plot OHLCMean = ohlc4. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the (Open + High + Low + Close)/4 value for the specific symbol. Valid parameters for the price type are: • LAST • MARK. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the Open price for the specific symbol. String priceType). etc. Week. input period = AggregationPeriod. plot Data = open(symbol. price_type). "MARK"}. WoodiesPivots. 2 Days.g. ASK. Usage in: DailyOpen. "BID".open Syntax open(String symbol. input price_type = {default "LAST". BID (for Forex symbols only) Example input symbol = "EUR/USD". Day. Month. This example script plots daily Open price plot for EUR/USD with LAST price type. Any period. . aggregation period and price type.MONTH. "ASK".) as valid parameters for the aggregation period. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. You can use both Aggregation Period constants and pre-defined string values (e. period. 2 Days. . You can use both Aggregation Period constants and pre-defined string values (e. etc.) as valid parameters for the aggregation period. Week. open_interest This example script draws the open interest plot for the current symbol. Month. ASK. Example declare lower.g. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Any period.Syntax open_interest(String symbol. Valid parameters for the price type are: • LAST • MARK. Usage in: OpenInterest. aggregation period and price type. BID (for Forex symbols only) plot OpenInterest = open_interest(). String priceType). Day. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the open interest value for the specific symbol. etc. BID (for Forex symbols only) input divider = 1000000. You can use both Aggregation Period constants and pre-defined string values (e. String priceType). The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. Valid parameters for the price type are: • LAST • MARK. the divider is equal to 1000000. By default. aggregation period and price type. plot VolumeDivided = volume / divider. VolumeDivided.Syntax volume(String symbol. Any period. Week. HISTOGRAM). Day. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the volume value for the specific symbol.) as valid parameters for the aggregation period. Month.g. . 2 Days. volume This example script plots the histogram of volume value divided by a specified number. Example declare lower.SetPaintingStrategy(PaintingStrategy. ASK. DAY). and monthly VolumeWeightedAveragePrice values for the current symbol. Day. .g. Any period. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. BID (for Forex symbols only) Example plot DailyVWAP = vwap(period = AggregationPeriod. You can use both Aggregation Period constants and pre-defined string values (e.WEEK). plot MonthlyVWAP = vwap(period = AggregationPeriod. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description Returns the volume weighted average price value for the specific symbol. Month. weekly. ASK.vwap Syntax vwap(String symbol. aggregation period and price type. Valid parameters for the price type are: • LAST • MARK. String priceType). 2 Days. Week.MONTH). etc. plot WeeklyVWAP = vwap(period = AggregationPeriod.) as valid parameters for the aggregation period. This example script plots daily. This section contains functions to work with options. Here is the full list: o Option Related • • • • • • • • • • • • delta gamma getDaysToExpiration getStrike getUnderlyingSymbol isEuropean isOptionable isPut optionPrice rho theta vega . plot approxDelta = (optionPrice(underlyingPrice = close(getUnderlyingSymbol()) + epsilon) . This example illustrates the approximate calculation of delta by dividing a change in the theoretical option price by a change in the underlying symbol price. Default values: • Underlying Price: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) Description Calculates the delta option greek. def epsilon = 0.01 * close(getUnderlyingSymbol()).optionPrice()) / epsilon. IDataHolder Volatility). plot Delta = delta().delta Syntax delta(IDataHolder Underlying Price. Example declare lower. . Usage in: OptionDelta. gamma Syntax gamma(IDataHolder Underlying Price. Default values: • Underlying Price: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) Description Calculates the gamma option greek. plot theoreticalprice = optionPrice(underlyingPrice = close(getUnderlyingSymbol()) + shift). While the expression using delta is only a rough estimate of the resulting price.1*close(getUnderlyingSymbol()). Usage in: OptionGamma. . IDataHolder Volatility). plot firstorder = optionPrice() + shift * delta(). Example def shift = 0. This example illustrates the use of the gamma function to calculate changes in the theoretical option price when the underlying symbol price changes significantly. plot secondorder = firstorder + shift*shift/2 * gamma(). taking gamma into account results in much better approximation. AddChartBubble( getDaysToExpiration() == 1.YELLOW. Example declare hide_on_intraday. yes ). yes ).RED. input weeks = 4. concat("Weeks till expiration: ". color. AddChartBubble( getDaysToExpiration() == 7 * weeks + 1.Syntax getDaysToExpiration(). high. weeks). Description Returns the number of days till the expiration of the current option. getDaysToExpiration This script shows two bubbles on the option chart: the red one indicating the Expiration Friday and the yellow one indicating a bar four weeks prior to the Expiration Friday. color. "Expiration Friday". high. . input steps = 1. getStrike This example plots the theoretical price of an option with a different strike. concat(concat(getSymbolPart(). " is an option for "). Example AddChartLabel(yes. Description Returns the underlying symbol for the current option. getUnderlyingSymbol Syntax getUnderlyingSymbol(). Syntax getStrike(). Description Returns the strike price for the current option. . This script adds a chart label showing the underlying symbol for the current option.Example input strike_price_interval = 5. plot OtherPrice = optionPrice(getStrike() + steps * strike_price_interval). getUnderlyingSymbol())). this example displays a label informing whether it is an American or a European style option. concat("IV: ". concat(concat("This is ". " style option. Example AddChartLabel(yes. false otherwise. Syntax isOptionable(). if isEuropean() then "a European" else "an American"). isOptionable .")). concat(imp_volatility() * 100. Displays a label for optionable symbols showing the implied volatility in percentage. Description Returns true if the current symbol is optionable. Description Returns true if the current option is European. Example AddChartLabel(isOptionable().isEuropean Syntax isEuropean(). false if American. "%"))). For option symbols. strike price. Syntax isPut(). false if CALL. and expiration but the opposite right. This example plots theoretical price of an option with the same underlying. Description Returns true if the current option is PUT.isPut Example plot Opposite = optionPrice(isPut = !isPut()). . is_put. Default values: • strike: getStrike() • isPut: isPut() • daysToExpiration: getDaysToExpiration() • underlyingPrice: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) • isEuropean: isEuropean() • yield: getYield() • interestRate: getInterestRate() Description Calculates the theoretical option price. By default. this function uses implied volatility averaged over different options for the underlying. input is_put = no. IDataHolder Volatility. close(underlying).optionPrice Syntax optionPrice(IDataHolder strike. input expiration_date = 20101220. double interestRate). . input yield = 0. input strike = 21.0. IDataHolder isPut. plot TheoOptPrice = optionPrice(strike. is_european. IDataHolder daysToExpiration. interest_rate). double yield. daysTillDate(expiration_date). so the returned result is approximate. imp_volatility(underlying). yield. double isEuropean. Example input underlying = "ORCL". input is_european = no. IDataHolder underlyingPrice. input interest_rate = 0.06.0. Usage in: TheoreticalOptionPrice. plot approxRho = (optionPrice(interestRate = getInterestRate() + epsilon) . rho Syntax rho(IDataHolder Underlying Price. IDataHolder Volatility).optionPrice()) / epsilon / 100. This example illustrates the approximate calculation of rho by dividing a change in the theoretical option price by a change in the risk-free interest rate. Usage in: OptionRho. . plot Rho = rho().This script plots the theoretical price of Oracle December 2010 call option with $21 strike and interest rate of 6%. def epsilon = 0.0001. Default values: • Underlying Price: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) Description Calculates the rho option greek. Example declare lower. Default values: • Underlying Price: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) Description Calculates the theta option greek. IDataHolder Volatility). Example declare lower. Usage in: OptionTheta.theta Syntax theta(IDataHolder Underlying Price. This example illustrates the approximate calculation of theta by finding a change in the theoretical option price produced by increasing the time to expiration by one day. . plot Theta = theta(). plot approxTheta = (optionPrice() optionPrice(daysToExpiration = getDaysToExpiration() + 1)). .vega Syntax vega(IDataHolder Underlying Price. This example illustrates the approximate calculation of vega by dividing a change in the theoretical option price by a change in implied volatility of the underlying. Usage in: OptionVega. Default values: • Underlying Price: close(getUnderlyingSymbol()) • Volatility: imp_volatility(getUnderlyingSymbol()) Description Calculates the vega option greek. IDataHolder Volatility).01 * imp_volatility(getUnderlyingSymbol()). plot Vega = vega(). plot approxVega = (optionPrice(Volatility = imp_volatility(getUnderlyingSymbol()) + epsilon) optionPrice()) / epsilon / 100. def epsilon = 0. Example declare lower. Functions featured in the adjacent sections relate to analysis indirectly. However. Technical analysis functions address this task. o Technical Analysis Here is the full list of the functions: • AccumDist • Average • AvgTrueRange • BodyHeight • Ema2 • ExpAverage • FastKCustom • GetMaxValueOffset • GetMinValueOffset • Highest • HighestAll • HighestWeighted • IsAscending • IsDescending • IsDoji • IsLongBlack • IsLongWhite • Lowest • LowestAll • LowestWeighted • MidBodyVal • moneyflow • TrueRange • Ulcer • WildersAverage • wma . these functions cannot solve direct technical analysis tasks. fundamentals provide functions to work with data and so on. For example. the look and feel functions help you paint a chart to achieve better visualization. Description Returns the Accumulation/Distribution value.low) * volume else 0). volume). IDataHolder low. input low = low. use the simplified formula to calculate the Accumulation/Distribution. declare lower. General Information Some studies. . The example calculates the Accumulation/Distribution with the help of the AccumDist and AccumDistTS functions. Usage in: AccumDistPrVol. ChaikinOsc. open. plot AccumDist2 = AccumDistTS(high.AccumDist Example script AccumDistTS { input high = high.open) / (high .low > 0 then (close . for example the AccDist. plot AccumDistTS = TotalSum(if high . low. The formula does not contain open prices. input volume = volume. input open = open. IDataHolder close. } Syntax AccumDist(IDataHolder high. IDataHolder open. volume). input close = close. close. low. close. Both the functions provide equal results that are represented by a single plot. open. plot AccumDist1 = AccumDist(high. The AccumDistTS function is implemented using the thinkScript and the AccumDist is a regular built-in function. IDataHolder volume). If the length of the data set is not specified. length) / length. Usage in: Multiple The example displays the moving average for the last 20 closing prices. plot SMA1 = Average(price. Example 1 script AverageTS { input data = close. input length = 12. plot AverageTS = sum(data. The example plots an average value using the thinkScript implementation called AverageTS and the built-in function. length). input length = 12. .Average Syntax Average(IDataHolder data. Example 2 plot SMA = average(close. length). 20). Since both the implementations produce the same result the plots coincide with each other forming a single curve. int length). See the following example to learn how the average is calculated. Default values: • length: 12 Description Returns the average value of a set of data for the last length bars. plot SMA2 = AverageTS(price. the default value is used. } input price = close. int length). . AvgTrueRange Example 1 script AvgTrueRangeTS { input high = high. plot AvgTrueRange1 = AvgTrueRange(high. The results of the approaches are equal which means that both the calculations result in equal plots that coincide with each other.Syntax AvgTrueRange(IDataHolder high. ATRWilder) use Wilder's smoothing instead of simple moving average to calculate the TrueRange average. length). input low = low. input close = close. plot AvgTrueRangeTS = Average(TrueRange(high. low). The code provides two approaches to calculate and plot the average of the true range. General Information Some studies (e. Default values: • length: 12 Description Returns the average of the TrueRange function. close. plot AvgTrueRange2 = AvgTrueRangeTS(high.g. IDataHolder low. The first approach is implemented through the built-in AvgTrueRange function. close. low. length). low. The second approach uses a manual implementation. input length = 15. length). IDataHolder close. } input length = 14. close. LBR_PaintBars. VoltyExpanCloseLX. .Usage in: ATRTrailingStop. KeltnerChannels. SeparatingLines. ThreeStarsInTheSouth. Deliberation. This script plots the 12 period average body height on the lower subgraph. OnNeck. HighPriceGappingPlay. Harami. It is equal to the absolute value of the difference between the open and close values. MeetingLines. ConcealingBabySwallow. plot AverageBodyHeight = Average(BodyHeight(). RisingThreeMethods. UniqueThreeRiverBottom. Sample Example declare lower. input length = 12. StickSandwich. HangingMan. MatHold. length). SideBySideWhiteLines. LongLeggedDoji. FallingThreeMethods. Marubozu. Description Returns the height of the candlestick body.BodyHeight Syntax BodyHeight(). MatchingLow. InNeck. IdenticalThreeCrows. AdvanceBlock. LowPriceGappingPlay. Hammer. InvertedHammer. EveningStar. Usage in: . Kicking. BeltHold. MorningStar. ShootingStar. HomingPigeon. 2).initialization. plot ExpAvg = Ema2(close. Note that studies using ema2 fetch a necessary number of additional bars for correct Example input additionalBars = 0. Ema2 The code plots the exponential average of a security Close price with a smoothing factor of 0. int prefetch. double smoothing factor. so adding more initialization data by increasing additionalBars input has little impact on the study.2. int First Bar). The First Bar parameter is deprecated and should not be used. . additionalBars. The prefetch parameter controls the number of historical data points used to initialize EMA for the first bar. Syntax Ema2(IDataHolder data. 0. Default values: • prefetch: 0 • First Bar: 0 Description Returns the Exponential Moving Average (EMA) of data with smoothing factor. RSI_EMA. PriceZoneOscillatorLX. MovAvgTwoLines. VolumeWeightedMACD. ElderRayBearPower. RangeIndicator. BalanceOfMarketPower. EMAEnvelope. ChaikinOsc. RelativeVolatilityIndex. int length). DEMA. MovAvgExponential. DisplacedEMA. PriceAverageCrossover. VolumeFlowIndicator. VolumeZoneOscillator. PriceZoneOscillatorLE. ForceIndex. MassIndex. KeltnerChannels. Example input price = close. BollingerBandsEMA. length). RelativeMomentumIndex. StochasticFull. TrendPeriods. TRIX. MovAvgExpRibbon. . ReverseEngineeringRSI. ChaikinOscillator. PriceZoneOscillatorSE. MACD. PolarizedFractalEfficiency. ElderRay. The example plots an exponential moving average of a security's Close price. TrueStrengthIndex. Default values: • length: 12 Description Returns the Exponential Moving Average (EMA) of data with length. input length = 12. WoodiesCCI. MovingAvgCrossover. TEMA. Usage in: ATRTrailingStop. ElderRayBullPower. DoubleSmoothedStochastics. PriceZoneOscillatorSX. DisparityIndex. plot ExpAvg = ExpAverage(price.ExpAverage Syntax ExpAverage(IDataHolder data. KlingerOscillator. StochasticMomentumIndex. PriceZoneOscillator. Zero value is assigned if the current closing price is the lowest on the last 14 bars. 255. If the price is the lowest for the last length bars then 0 is returned. 0). The function is calculated according to the following algorithm: FastKCustom = if highest(close. def normVal = FastKCustom(abs. def abs = AbsValue(Price). The example plots the EMA using the manual thinkScript implementation and the built-in function. The resulting plots coincide forming a single curve.lowest(close. Default values: • length: 14 Description Returns values from 0 through 100 depending on a price. The normVal is used in the AssignValueColor function to paint a plot with colors ranging from red (255. The FastKCustom function is used to assign a normVal value to each bar depending on its price. 12)) / (highest(close.FastKCustom Syntax FastKCustom(IDataHolder data. 0) ). 100 is assigned if the current closing price is the highest on the last 14 bars. . 12) > 0 then (close . 12))*100 else 0 Example declare lower. input colorNormLength = 14.55 * normVal.AssignValueColor( CreateColor(255. Price.0) to yellow (255. 12) lowest(close.lowest(close. plot Price = close. 2. If the price is the highest for the last length bars then 100 is returned. 12) . int length). The green component of the color varies depending on the current value of normVal. colorNormLength). 0. Example declare lower.0 / length.downIndex) * 100. def upIndex = GetMaxValueOffset(high. AroonOscillator. int length).GetMaxValueOffset Syntax GetMaxValueOffset(IDataHolder data. plot AroonDown = (length . LookUpHighest. plot AroonUp = (length . When drawing the AroonUp. length). Default values: • length: 25 Description Returns the offset of the highest value of data for the last length bars. The example calculates the Aroon Indicator.0 / length. length). The GetMaxValueOffset is used to calculate the upIndex variable that defines the number of bars appeared starting from the maximum value for the last length bars. def downIndex = GetMinValueOffset(low. the upIndex is recorded as a percentage from the overall number of length bars.upIndex) * 100. Usage in: AroonIndicator. input length = 25. . Example declare lower. Default values: • length: 25 Description Returns the offset of the lowest value of data for the last length bars.upIndex) * 100. . AroonOscillator. def downIndex = GetMinValueOffset(low. The GetMinValueOffset is used to calculate the downIndex variable that defines the number of bars appeared starting from the minimum value for the last length bars. input length = 25. Then the downIndex value and the upIndex values are used to draw the resulting AroonOsc plot. def upIndex = GetMaxValueOffset(high. Usage in: AroonIndicator.GetMinValueOffset Syntax GetMinValueOffset(IDataHolder data. int length). The example calculates the Aroon Oscillator.0 / length. length). plot AroonOsc = (downIndex . LookUpLowest. length). StochasticFull. Ichimoku. Default values: • length: 12 Description Returns the highest value of data for the last length bars. DailyHighLow. StochasticMomentumIndex. RangeIndicator. int length). length). HighPriceGappingPlay. FisherTransform. Usage in: BollingerBandwidth. LBR_PaintBars. plot MiddleBand = (LowerBand + UpperBand) / 2. In order to implement this approach the [1] index is applied to the corresponding parameters. LowPriceGappingPlay. . length). PercentR. The plots in the example illustrate the Donchian Channels system where the Lower Band and the Upper Band are calculated as the minimum low and maximum high for the previous length bars. PriceChannel. VerticalHorizontalFilter.Highest Syntax Highest(IDataHolder data. plot LowerBand = Lowest(low[1]. DemandIndex. plot UpperBand = Highest(high[1]. KeyRevLX. Note that the low and high for the current bar are left out of account. WilliamsPercentR. Example input length = 20. SemiCupFormation. LinearRegCh100. def dist = HighestAll(AbsValue(MiddleLR . The deviation is calculated for all bars using the HighestAll function. plot MiddleLR = InertiaAll(price). LinearRegCh50. Description Returns the highest value of data for all bars in the chart. ZigZagSign. plot LowerLR = MiddleLR .dist.price)). ZigZagPercent. . MajorGannLevels. Example input price = close.HighestAll Syntax HighestAll(IDataHolder data). LinearRegChVar. The code draws a regression channel where the highest and the lowest borders are defined with the help of the maximum deviation between the price and regression line. Usage in: DarvasBox. plot UpperLR = MiddleLR + dist. Default values: • length: 14 Description Returns the highest value of data weighted with the coefficient for the last length bars. This example shows how the HighestWeighted is constructed by taking maximum of several values. . price1[1] + delta).price1. plot HWBuiltin = HighestWeighted(price1. int length. plot HW = Max(Max(price1. price1[2] + 2 * delta). IDataHolder coefficient). The two plots coincide. Usage in: ProjectionBands. input price1 = close. def delta = price2 . Example declare lower. input price2 = open. ProjectionOscillator. delta).HighestWeighted Syntax HighestWeighted(IDataHolder data. 3. SideBySideWhiteLines.GREEN else Color. 10) then Color. AdvanceBlock. SeparatingLines. Breakaway. HangingMan. Example AssignPriceColor(if IsAscending(close. UpsideTasukiGap. EveningDojiStar. UpsideGapThreeMethods. IdenticalThreeCrows. Deliberation. UpsideGapTwoCrows. BeltHold. DarkCloudCover. . LongLeggedDoji. TriStar. MeetingLines. RisingThreeMethods. Engulfing. Default values: • length: 3 Description Tests if the trend is ascending by calculating the average slope coefficient of trendlines whose start points are MidBodyVal for a specified number of bars and end points are value for current bar. HighPriceGappingPlay. If the slope is positive then the trend is considered ascending. EveningStar. This example paints price bars in green color if the closing price in comparison to the MidBodyVal for the last 10 bars is considered ascending and in red color otherwise. ThreeLineStrike. TwoCrows. Harami.RED). ThreeBlackCrows. ShootingStar. HaramiCross.Syntax IsAscending(IDataHolder value. MatHold. int length). Usage in: IsAscending AbandonedBaby. . DownsideGapThreeMethods. InvertedHammer. StickSandwich. MorningDojiStar. ThreeWhiteSoldiers. MatchingLow. If the slope is negative then the trend is considered descending. Usage in: AbandonedBaby. MeetingLines. 10). ThreeStarsInTheSouth. DescBar. InNeck. LongLeggedDoji. HaramiCross. ConcealingBabySwallow. SeparatingLines. Harami.BOOLEAN_P OINTS). BeltHold. LowPriceGappingPlay. MorningStar. Hammer. OnNeck. ThreeLineStrike. Default values: • length: 3 Description Tests if the trend is descending by calculating the average slope coefficient of trendlines whose start points are MidBodyVal for a specified number of bars and end points are value for current bar. This example draws points at the closing prices for all bars considered as descending in comparison to the MidBodyValfor the last 10 bars. PiercingLine. DownsideTasukiGap. SideBySideWhiteLines. int length). Breakaway. Engulfing.Syntax IsDescending(IDataHolder value.SetPaintingStrategy(PaintingStrategy. FallingThreeMethods. HomingPigeon. Thrusting. TriStar. IsDescending Example plot DescBar = IsDescending(close. Default values: • length: 20 • bodyFactor: 0. In this case. Usage in: AbandonedBaby. a candle will be considered Doji if its body height does not exceed 5% (default value) of the average body height calculated for last 25 candles. HaramiCross. EveningDojiStar. Example input length = 25. The average body height is calculated for a specified number of preceding candles.05 Description Returns true if the current candle is Doji (i. MorningDojiStar. LongLeggedDoji. Engulfing. .IsDoji Syntax IsDoji(int length.e. double bodyFactor). Doji. Note that a candle is considered Doji if its body height does not exceed average body height multiplied by the specified factor. TriStar.BOOLEAN _POINTS). ThreeDoji. plot ThreeDoji = IsDoji[2] and IsDoji[1] and IsDoji. This example marks the last of three consecutive Doji candles. def IsDoji = IsDoji(length).SetPaintingStrategy(PaintingStrategy. its Close price and Open price are equal or almost the same) and false otherwise. InNeck.SetPaintingStrategy(PaintingStrategy. MorningStar. • Its body is longer than the average body size calculated for the specified number of preceding candles. HaramiCross. MatchingLow. MorningDojiStar. ThreeBlackCrows. TwoLongBlack. PiercingLine. Default values: • length: 20 Description Returns true for the current candle if: • Its Close price is lower than the Open price. Marubozu. Breakaway.IsLongBlack Syntax IsLongBlack(int length). Example input length = 20. This example draws an arrow marking the last of two consecutive long bearish candles. ThreeStarsInTheSouth. DownsideGapThreeMethods. def IsLongBlack = isLongBlack(length). OnNeck. LowPriceGappingPlay.BOOL EAN_ARROW_DOWN). BeltHold. • Its body is longer than each shadow. SeparatingLines. IdenticalThreeCrows. . FallingThreeMethods. plot TwoLongBlack = IsLongBlack[1] and IsLongBlack. HomingPigeon. MeetingLines. Harami. ThreeLineStrike. Usage in: AbandonedBaby. SetPaintingStrategy(PaintingStrategy. TwoLongWhite. MeetingLines.BOO LEAN_ARROW_UP). HighPriceGappingPlay. RisingThreeMethods. AbandonedBaby.IsLongWhite Syntax IsLongWhite(int length). Breakaway. UpsideGapTwoCrows. Harami. • Its body is longer than each shadow. EveningDojiStar. ThreeWhiteSoldiers. ThreeLineStrike. TwoCrows. SeparatingLines. def IsLongWhite = isLongWhite(length). • Its body is longer than the average body size calculated for the specified number of preceding candles. MatHold. HaramiCross. plot TwoLongWhite = IsLongWhite[1] and IsLongWhite. BeltHold. Default values: • length: 20 Description Returns true for the current candle if: • Its Close price is higher than the Open price. Usage in: . This example draws an arrow marking the last of two consecutive long bullish candles. UpsideGapThreeMethods. DarkCloudCover. Example input length = 20. Marubozu. Deliberation. EveningStar. Example declare lower.Lowest Syntax Lowest(IDataHolder data. LBR_PaintBars. RangeIndicator.LL) * (-100). length). StochasticMomentumIndex. FisherTransform. LowPriceGappingPlay. VerticalHorizontalFilter. HighPriceGappingPlay. to define the minimum. it is required to define the minimum low for the last length bars including the current bar. length). Default values: • length: 12 Description Returns the lowest value of data for the last length bars. DailyHighLow. int length). The example shows the Williams %R calculation. . def HH = Highest(high. def LL = Lowest(low. Ichimoku. StochasticFull. DemandIndex. KeyRevLE. In particular. input length = 10. PercentR. Therefore. the example uses the Lowest function. Usage in: plot "Williams %R" = if HH == LL then -100 else (HH close) / (HH . BollingerBandwidth. PriceChannel. WilliamsPercentR. Usage in: MajorGannLevels. ZigZagSign. .LL) / 4 + LL. plot G2 = (HH + LL) / 2. def LL = LowestAll(low). plot G3 = HH / 4. ZigZagPercent. plot G1 = HH / 2. Description Returns the lowest value of data for all bars in the chart. plot G4 = (HH . The example shows the Major Gann Levels which uses all chart bars to calculate the maximum high and minimum low values. Example def HH = HighestAll(high).LowestAll Syntax LowestAll(IDataHolder data). .LowestWeighted Syntax LowestWeighted(IDataHolder data. Example declare lower. This example shows how the LowestWeighted is constructed by taking minimum of several values. delta).price1. price1[1] + delta). The two plots coincide. 3. int length. def delta = price2 . Usage in: ProjectionBands. plot LWBuiltin = LowestWeighted(price1. plot LW = Min(Min(price1. ProjectionOscillator. IDataHolder coefficient). input price2 = open. input price1 = close. Default values: • length: 14 Description Returns the lowest value of data weighted with the coefficient for the last length bars. price1[2] + 2 * delta). MidBodyVal Syntax MidBodyVal(). MorningStar. EveningDojiStar. EveningStar.5 * BodyHeight(). .5 * BodyHeight(). Sample Example plot CandleBodyTop = MidBodyVal() + 0. PiercingLine. LongLeggedDoji. Usage in: DarkCloudCover.0. Thrusting. This price can be calculated as (open + close)/2. This script plots two lines: the first one connecting all the candle body tops and the second one connecting all the candle body bottoms. plot CandleBodyBottom = MidBodyVal() . Description Returns the price corresponding to the middle of the candelstick body. MorningDojiStar. length). volume. } declare lower. length). input length = 14. volume. def price = high + close + low. The first implementation is based on the moneflowTS function. length). Default values: • length: 12 Description Returns the money flow value.moneyflow Syntax moneyflow(IDataHolder high. IDataHolder low. def positiveMoneyFlow = sum(if price >price[1] then moneyFlow else 0. close. . Example script moneyflowTS { input high = high. int length). input close = close. plot moneyflow2 = moneyflowTS(high. input low = low. the second one is based on the builtin moneyflow function. length). Usage in: MoneyFlowIndex. input length = 14. low. input volume = volume. plot moneyflowTS = if totalMoneyFlow != 0 then 100 * positiveMoneyFlow / totalMoneyFlow else 0. IDataHolder close. low. def moneyFlow = price * volume. IDataHolder volume. close. plot moneyflow1 = moneyflow(high. In this example the money flow is calculated and plotted based on two different implementations that have equal results. def totalMoneyFlow = sum(moneyFlow. VortexIndicator. input close = close. } plot TrueRange1 = TrueRange(high. IDataHolder low). TR is the greatest of the following: • the difference between the current high and current low • the difference between the current high and previous close • the difference between the previous close and current low . Usage in: ATRWilder. high) . UltimateOscillator. DMI. The example plots the TR using the manual thinkScript implementation and the built-in function. low). close. CSI.min(close[1]. RangeIndicator. low). Description Returns the true range (TR). plot TrueRange2 = TrueRangeTS(high. TrueRangeSpecifiedVolume. The resulting plots coincide forming a single curve. low). IDataHolder close. close. RandomWalkIndex. Syntax TrueRange(IDataHolder high. input low = low. TrueRangeIndicator. STARCBands. AverageTrueRange.TrueRange Example script TrueRangeTS { input high = high. plot TrueRangeTS = max(close[1]. input length = 100.01. This example calculates the Martin Ratio for an instrument. plot MartinRatio = (annualreturn . Usage in: UlcerIndex.Ulcer Syntax Ulcer(IDataHolder data. def days = daysFromDate(somedate) daysFromDate(somedate)[length]. input risk_free_rate = 0.risk_free_rate) * 100 / Ulcer(close. def somedate = 20000101. def annualreturn = growth / close[length] * 365 / days. def growth = close . int length). . Default values: • length: 14 Description Returns the Ulcer Index of data for the last length bars.close[length]. Example declare lower. length). 0. ReverseEngineeringRSI. BalanceOfMarketPower. This code draws two plots: the first is a Wilder's average of the Close price. 1 / length). and the second is the exponential moving average with the corresponding smoothing factor. RSIWilder. WildersSmoothing. PriceAverageCrossover. . int length). Usage in: ATRWilder. The two plots differ to a certain extent due to variance in initialization.WildersAverage Syntax WildersAverage(IDataHolder data. Example input length = 10. length). MovingAvgCrossover. plot WildersAvg = WildersAverage(close. DMI. plot ExpAvg = Ema2(close. The first value is calculated as the simple moving average and then all values are calculated as the exponential moving average. Default values: • length: 12 Description Returns the Wilder's Moving Average of data with smoothing factor that equals 1 / length. CSI. Default values: • length: 9 Description Returns the Weighted Moving Average value. The total is then divided by the sum of the factors. int length). TrueStrengthIndex. LinearRegressionSlope. MovingAvgCrossover. . MovAvgWeighted. PriceAverageCrossover. RSquared. Example plot WMA = wma(close. The example displays the weighted moving average for the last 20 closing prices. HullMovingAvg. Usage in: BalanceOfMarketPower.wma Syntax wma(IDataHolder data. That factor is equal to the number of days past the first day. 20). The Weighted Moving Average is calculated by multiplying each of the previous days' data by a weight factor. this section collects mathematical and trigonometrical functions. For example. cosine. Besides traditional functions such as sine. • AbsValue • ACos • ASin • ATan • Ceil • Cos • Crosses • exp • Floor • isInfinite • IsNaN • lg • log • Max • Min • Power • Random • round • roundDown • roundUp • Sign • Sin • Sqr • Sqrt • sum • Tan • TotalSum o Mathematical and Trigonometrical . it has the isNaN function that defines if a parameter is a number.As appears from the section title. or the round function that rounds a value to a certain number of digits. or logarithm the section also contains some more specific ones. IdenticalThreeCrows. DMI. MovAvgAdaptive. DynamicMomentumIndex. SeparatingLines. KlingerOscillator. If the argument is negative. Usage in: Example declare lower. plot Absolute = AbsValue(open . the negation of the argument is returned. LinearRegChVar. MatchingLow. MeetingLines. . or negative. AdvanceDecline. ZigZagPercent. RSI_EMA. VerticalHorizontalFilter. DemandIndex. WoodiesCCI. BeltHold. MESASineWave. LinearRegCh100. If the argument is positive. SemiCupFormation. The example plots the absolute value of difference between the open and close price which can be either positive. SwingIndex. OnNeck. RangeExpansionIndex. SideBySideWhiteLines. Description Returns the absolute value of an argument. TrendQuality. TrueStrengthIndex. LinearRegCh50. the argument is returned.close). VariableMA.AbsValue Syntax AbsValue(double value). StickSandwich. TrendNoiseBalance. ZigZagSign. RSIWilder. VortexIndicator. The arc cosine of 0.Syntax ACos(double value). Description Returns the arc cosine of an angle in the range from 0 through pi. plot Data = Acos(0. So the example draws the unit plot.5) == Double. If the two values are equal. it draws the zero (false) plot. it draws the unit (true) plot . Example declare lower.5 equals pi/3. Otherwise. The expression in the second line of code compares two values and draws a plot. ACos .Pi / 3. ASin Syntax ASin(double value). The arc sine of 0. def height = close . input length = 3.close[length].Pi. plot Data = Asin(0. the zero (false) plot is drawn. The code draws a line that connects the current close value with the close value on the desired bar in the past. def hypotenuse = sqrt( sqr(length) + sqr(height) ). the code above compares two values and draws the unit (true) plot if they are equal.5) == Double.5 is not equal pi/3. Description Returns the arc sine of an angle in the range from -pi/2 through pi/2. In case the values are not equal. deg" = Asin(height/hypotenuse) * 180 / Double. . Similar to the ACos example. Example 2 declare lower. The example draws the zero plot. plot "Angle. The Asin function is used to calculate the angle of slope of the line. Example 1 declare lower.Pi / 3. avg[length]. The code calculates the angle of slope of the simple moving average with the given length. .Pi. deg" = Atan(height/length) * 180 / Double. WoodiesCCI. Example declare lower. Description Returns the arc tangent of an angle in the range of -pi/2 through pi/2. input length = 3. length). def height = avg . def avg = Average(close. The angle itself is calculated using the ATan function. Usage in: MESASineWave.ATan Syntax ATan(double value). plot "Angle. Example plot data = ceil(close). MovAvgTriangular. . Description Rounds a value up to the nearest integer (which is not less than the value). Usage in: DynamicMomentumIndex. HullMovingAvg. The example returns the integer that is equal to or next higher than the close price.Ceil Syntax Ceil(double value). x[1] + 1.Cos Syntax Cos(double angle). The code draws the cosine function depending on a variable which starts from one and increments by one on each bar.Pi / periodBars. The cyclic frequency(w) is calculated based on the periodBars input. Description Returns the trigonometric cosine of an angle. rec x = compoundValue(1. Usage in: MESASineWave. plot F = a + b * Cos(w * x). input a = 0. Example declare lower. input b = 10. . input periodBars = 20. 0). def w = 2 * Double. Crosses Syntax Crosses(IDataHolder data1, IDataHolder data2, double direction); Default values: • direction: CrossingDirection.Any Description The Crosses function tests if data1 gets higher or lower than data2. It returns true when data1 becomes greater than data2 if the direction parameter is CrossingDirection.Above. Conversely, the function returns true when data1 becomes less than data2 if the direction parameter is CrossingDirection.Below. The function can also indicate a crossover irrespective of its direction if the direction parameter is CrossingDirection.Any. The crossing1 and crossing2 variables are equal definitions of a condition when the Close price crosses the simple moving average with the length equal to 10. In other words, the Crosses function serves as a more compact and flexible way of defining intersections. Example 1 plot avg = Average(close, 10); plot crossing1 = close > avg and close[1] <= avg[1]; plot crossing2 = Crosses(close, avg, CrossingDirection.Above); crossing1.SetPaintingStrategy(PaintingStrategy.BOOLEAN _ARROW_UP); crossing2.SetPaintingStrategy(PaintingStrategy.BOOLEAN _ARROW_DOWN); The example first determines the crossing type of the Close price and the simple moving average for the last 10 bars. Depending on whether the crossing is up or down, the code draws either the arrow up or arrow down mark below and above the corresponding bars. Note that above and below here are enumeration constants. Usage in: ADXCrossover; ATRTrailingStop; BollingerBandsCrossover; MACDHistogramCrossover; MomentumCrossover; MoneyFlowIndexCrossover; MovingAvgCrossover; ParabolicSARCrossover; PriceAverageCrossover; RSIWilderCrossover; RateOfChangeCrossover; StochasticCrossover; WoodiesCCI. Example 2 input crossingType = {default above, below}; def avg = Average(close, 10); plot Crossing = Crosses(close, avg, crossingType == CrossingType.above); Crossing.SetPaintingStrategy(if crossingType == CrossingType.above then PaintingStrategy.BOOLEAN_ARROW_UP else PaintingStrategy.BOOLEAN_ARROW_DOWN, yes); exp Syntax exp(double number); Description Returns the exponential value of a number. Example 1 declare lower; input x = 3; plot Calculate1 = exp(x); plot Calculate2 = power(Double.E, x); The example calculates the value of the exponent raised to the power of x using two different approaches. The results of the calculations are equal. Example 2 declare lower; def temp = 0.1 * (RSIWilder() - 50); def x = wma(temp, 9); plot IFT_RSI = (exp(2 * x) - 1) / (exp(2 * x) + 1); The code plots the Inversed Fisher Transform indicator based on the smoothed RSI value. Initially, the code subtracts the standart RSIWilder by 50 and multiplies the result by 0.1 to get values starting from -5 and through 5. Then it smoothes the values using the wma function. Finally, it calculates the IFT for the values. Usage in: DemandIndex; SemiCupFormation. Floor Syntax Floor(double value); Description Rounds a value down to the nearest integer (which is not greater than the value). Example plot Lower = Floor(low); plot Upper = Ceil(high); This example draws a channel at integer levels which fits high and low prices. Usage in: DynamicMomentumIndex; MonkeyBars; MonkeyBarsExpanded; SeriesCount; TPOProfile; VWAP; VolumeProfile. isInfinite Syntax isInfinite(double value); Description Returns true if the specified number is infinitely large in magnitude. input dividend = 10; input divisor = 0; Example 1 declare lower; The example draws the result of division the dividend by the divisor on a separate subgraph. If the divisor is equal to zero then the division produces the infine number. The isInfinite returns true as a result of verifying the infinite number and the result is assigned 0. Example 2 declare lower; input dividend = 10; input divisor = 0; def tempResult = dividend / divisor; plot Result = if isInfinite(tempResult) then 0 else tempResult; plot Result = if divisor == 0 then 0 else dividend / divisor; This example is similar to the previous one. But here the validation is performed before the division which makes the code simplier. IsNaN Syntax IsNaN(double value); Description Returns true if the specified parameter is not a number, returns false otherwise. The example draws the highest close and open on the right expansion of the subgraph. For more information about the expansion chart, see thinkDesktop User Manual. Example 2 declare lower; input symbol = "IBM"; def closeSymbol = close(symbol); rec closeSymbolWithOutNaN = CompoundValue(1, if IsNaN(closeSymbol) then closeSymbolWithOutNan[1] else closeSymbol, closeSymbol); plot Data = closeSymbolWithOutNaN; Example 1 def onExpansion = if IsNaN(close) then yes else no; plot HighestClose = if onExpansion then HighestAll(close) else double.NaN; plot LowestClose = if onExpansion then LowestAll(close) else double.NaN; Usage in: The code draws the comparison close chart replacing gaps containing no data with lines. If the plot contains the NaN value then the last available non-NaN value is used. ATRTrailingStop; AdvanceDecline; CumulativeVolumeIndex; DailyHighLow; DailyOpen; DailySMA; DarvasBox; DemandIndex; DynamicMomentumIndex; FisherTransform; McClellanOscillator; McClellanSummationIndex; MonkeyBars; Next3rdFriday; PersonsPivots; RelativeStrength; SemiCupFormation; SpectrumBarsLE; TPOProfile; ThreeBarInsideBarLE; ThreeBarInsideBarSE; TrailingStopLX; TrailingStopSX; TrendNoiseBalance; TrendQuality; VariableMA; VolumeProfile; WoodiesCCI; WoodiesPivots; ZigZagPercent; ZigZagSign; ZigZagTrendPercent; ZigZagTrendSign. The code draws the plot of the logarithm of the closing price of a stock. Example declare lower. Usage in: FisherTransform. Example declare lower. . VolatilityStdDev. SeriesCount. VolumeFlowIndicator. Description Returns the natural logarithm of an argument. plot data = log(close). log Syntax log(double number). TRIX. HistoricalVolatility. Usage in: DynamicMomentumIndex. plot data = lg(close).lg Syntax lg(double number). Description Returns the base-10 logarithm of an argument. The example draws the base-10 logarithm plot of the close values. SemiCupFormation. VoltyExpanCloseLX. ParabolicSAR. ZigZagTrendPercent. HaramiCross. SwingIndex. RangeExpansionIndex. Harami. ParabolicSAR. RelativeMomentumIndex. MarkerIndicator. ZigZagSign. RangeExpansionIndex. Usage in: Example plot data = Min(close. Description Returns the smaller of two values. ZigZagTrendSign. VWAP. ShootingStar. plot data = Max(close. Min Syntax Min(double value1. BeltHold. Engulfing. double value2). Engulfing. AccumDistBuyPr. ZigZagTrendSign. HangingMan. SemiCupFormation. MonkeyBars. TPOProfile. SwingIndex. Deliberation. InvertedHammer. HaramiCross. double value2). ZigZagPercent. HangingMan. The code draws the smaller value of the close and open values. MonkeyBarsExpanded. VolumeProfile. LongLeggedDoji. SemiCupFormation. Harami. ATRTrailingStop. Description Returns the greater of two values. Usage in: This example displays the higher value of either the closing price or the simple moving average. SMA). LongLeggedDoji. DynamicMomentumIndex. TrailingStopSX. BollingerBandsSE. AccumDistBuyPr. open). ReverseEngineeringRSI. ZigZagPercent. Example def SMA = SimpleMovingAvg().Max Syntax Max(double value1. DemandIndex. ShootingStar. VolumeFlowIndicator. RandomWalkIndex. Hammer. BeltHold. Hammer. UltimateOscillator. . ZigZagSign. TrailingStopLX. ZigZagTrendPercent. MomentumLE. BollingerBandsLE. InvertedHammer. ATRTrailingStop. double power). input limit = 10. SemiCupFormation. . Usage in: MovAvgExpRibbon. greater than or equal to 0.Power Syntax Power(double number. Description Returns a value with a positive sign. Syntax Random(). 1. The example draws the plot of the close value raised to the power of 1.5).0 Example declare lower. Random The code draws a plot of random values ranging from 0. Example declare lower. to 10. plot Noise = Random() * limit.5. Description Returns the value of the first argument raised to the power of the second argument. plot Close1_5 = power(close.0 and less than 1. Example plot SMA = round(Average(close. 0) * tickSize(). Usage in: VWAP.round Syntax round(double number. 12) / tickSize(). . Default values: • numberOfDigits: 2 Description Rounds a number to a certain number of digits. This example script plots 12 period SMA rounded to the nearest tick size value. roundDown(double number. int numberOfDigits). SemiCupFormation. Usage in: AdvanceDecline. Default values: • numberOfDigits: 2 Description Rounds a number towards zero to a certain number of digits. roundDown Syntax Example See the roundUp function example. int numberOfDigits). WoodiesCCI. input digits = 0. plot floor = rounddown(price. digits).roundUp Syntax roundUp(double number. Default values: • numberOfDigits: 2 Description Rounds a number up to a certain number of digits. int numberOfDigits). Example input price = close. plot ceiling = roundup(price. digits). This example plots bands representing a price of the instrument rounded up and down to a certain number of digits. . VolumeZoneOscillator. or -1(bearish) values depending on the difference between two EMAs. Usage in: MESASineWave. plot Trend = sign( ExpAverage(close. Example 2 declare lower. 0 if zero and -1 if negative. 30) ). PriceZoneOscillator. 0(neutral).Sign Syntax Sign(double number). . plot Data = Average(Sign(close . 15) ExpAverage(close.close[1]) * (high . The example draws a plot showing the current trend as 1(bullish). Description Returns the algebraic sign of a number: 1 if the number is positive. Example 1 declare lower. TrendPeriods. The example draws the average range for 15 bars considering the closing price change as compared to the previous bar. 15).low). input a = 0. The cyclic frequency(w) is calculated based on the periodBars constant.Sin Syntax Sin(double angle). x[1] + 1. def w = 2 * Double. Description Returns the trigonometric sine of an angle. input periodBars = 20.Pi / periodBars. The code draws the sine function depending on the variable which starts from one and increments by one on each bar. rec x = compoundValue(1. input b = 10. plot F = a + b * Sin(w * x). Example declare lower. Usage in: MESASineWave. . 0). RSquared.Sqr Syntax Sqr(double value). PolarizedFractalEfficiency. Variance by definition is a square of the standard deviation. Example declare lower. VolatilityStdDev. VWAP. Usage in: . TrendQuality. TrendNoiseBalance. HullMovingAvg. 10)). Example declare lower. Usage in: Beta. Beta2. RandomWalkIndex. HistoricalVolatility. The draws the plot of the square root of the closing price of a stock. MovAvgAdaptive. Description Calculates the square root of an argument. VWAP. SeriesCount. plot Data = Sqr(stdev(close. PolychromMtm. CyberCyclesOscillator. PolarizedFractalEfficiency. Description Calculates the square of an argument. CSI. The example draws the variance of close for the last 10 bars. plot data = Sqrt(close). Sqrt Syntax Sqrt(double value). WoodiesCCI. UltimateOscillator. MovAvgAdaptive. VerticalHorizontalFilter. 20)/20. VolumeWeightedMACD. The example displays a line that is the sum of the last 20 days' closing prices. VortexIndicator. Default values: • length: 12 Description Returns the sum of values for the specified number of bars. . Alpha2. VariableMA. MassIndex. RangeExpansionIndex. Example 1 declare lower. AlphaJensen. This value is called 20 day moving average. The default value of length is 12. int length). EhlersDistantCoefficientFilter. PolarizedFractalEfficiency. This example returns the sum of the last 20 days' closing prices divided by 20. ChaikinMoneyFlow. plot data = sum(close. ChandeMomentumOscillator. Usage in: Example 2 plot data = sum(close. 20). VolumeFlowIndicator.sum Syntax sum(IDataHolder data. .Pi / 180). Tan(max * double. Description Returns the trigonometric tangent of an angle. input min = 30.Tan Syntax Tan(double angle). input max = 90. plot CheckingTangentHit = between((close .close[length]) / length. The code checks if the tangle of the closing price angle of slope is within the defined limits.Pi / 180)). input length = 5. Example declare lower. Tan(min * double. Example declare lower. PriceAndVolumeTrend. . Usage in: AccDist. OnBalanceVolume. plot data = TotalSum(volume). AccumulationSwingIndex. DarvasBox. AccumDistBuyPr. MoneyFlow. Description Returns the sum of all values from the first bar to the current. CumulativeVolumeIndex. TradeVolumeIndex. McClellanSummationIndex. The example returns the total accumulated volume for the time frame of the current chart.TotalSum Syntax TotalSum(IDataHolder data). Statistics is the area that closely relates to trading analysis. refer to the General Information sub-section featured in the articles. For this reason the thinkscript also includes statistical functions. Here is the full list of the statistical functions: o Statistical • • • • • • • • • correlation covariance Inertia InertiaAll lindev stdev stdevAll sterr sterrAll . If you lack for the general understanding of functions from the section. the section also contains formulas for the functions. In order to provide a better understanding. length) ). length) * stdev(data2. IDataHolder data2. the second plot is based on it's thinkScript implementation. Example script correlationTS { input data1 = close. close(secondSymbol). plot Correlation1 = correlation(close. plot CorrelationTS = covariance(data1. length) / ( stdev(data1. length). The first plot is drawn based on the built-in correlation function. The example draws two plots that show the correlation for the close price of the current and the specified symbol on the defined period. close(secondSymbol). Both plots are equal on the entire interval. int length).correlation Syntax correlation(IDataHolder data1. plot Correlation2 = correlationTS(close. input data2 = close. Default values: • length: 10 Description Returns the correlation coefficient between the data1 and data2 variables for the last length bars. General Information Correlation defines the relation between two variables. length). input length = 10. input length = 12. } declare lower. For more information about the . data2. input secondSymbol = "SPX". See the following example to learn how the coefficient is calculated. covariance function. PairCorrelation. . Usage in: Correlation. see the covariance function in this section. close(secondSymbol). then the two values move in the same direction. the Covariance2 plot is based on it's . If the covariance is positive. IDataHolder data2. if negative the two values move inversely. int length). input secondSymbol = "SPX". plot Covariance2 = covarianceTS(close. close(secondSymbol). The covariance formula is provided in the following example. length) Average(data1. The code draws two plots that show the covariance for the close price of the current and the specified symbol on the defined period. length). length) * Average(data2. input length = 10. Default values: • length: 10 Description Returns the covariance coefficient between the data1 and data2 variables for the last length bars. Example script covarianceTS { input data1 = close. plot Covariance1 = covariance(close. } declare lower. length). input length = 12. General Information Covariance defines whether two variables have the same trend or not. The Covariance1 plot is based on the builtin function.covariance Syntax covariance(IDataHolder data1. length). plot CovarianceTS = Average(data1 * data2. input data2 = close. For more information about the Average function. see the Average function in the Tech Analysis section.thinkScript implementation. Usage in: Beta. . Beta2. Both the plots coincide with each other forming a single plot. def b = (sum(Sqr(x). The resulting interpolation function for each set of bars is defined by the y = a * current_bar + b equation. n) * sum(y. length). int length). Usage in: ForecastOscillator. def a = (n * sum(x * y.sum(x. Example script inertiaTS { input y = close. n) . n) ) / ( n * sum(Sqr(x). TimeSeriesForecast. Inertia. plot LinReg1 = Inertia(close. LinearRegrIndicator. n) .Inertia Syntax Inertia(IDataHolder data. . Draws the linear regression plot for the close value for the defined set of bars.sum(x. plot InertiaTS = a * x + b. n))).Sqr(sum(x. WoodiesCCI. See the following example for details. StandardErrorBands. n) ) / ( n * sum(Sqr(x).Sqr(sum(x. LinearRegrReversal. LinearRegCurve. n) . rec x = x[1] + 1. n) * sum(x * y. n) . n) * sum(y. } input length = 20. Description Draws the linear regression curve using the least-squares method to approximate data for each set of bars defined by the length parameter. input n = 20. plot LinReg2 = InertiaTS(close. n))). length). NaN at any moment in time outside the interval used for calculation of linear regression. Default values: • length: all chart • startDate: 0 • startTime: 0 • extendToLeft: no • extendToRight: no Description Draws the linear regression function either for the entire plot or for the interval defined by the length parameter. This behavior can be changed by using non-zero values of extendToLeft and extendToRight parameters. The example draws the linear recession for the close value for the defined number of last bars. StandardErrorChannel. plot MiddleLR = InertiaAll(close. double extendToRight). int startDate. LinearRegTrendline. InertiaAll . See the Inertia function for more information. The startDate (specified in the YYYYMMDD format) and startTime (specified in the HHMM format) define the date and time for the starting point of linear regression. LinearRegCh50. Example input length = 20. StandardDevChannel.Syntax InertiaAll(IDataHolder data. These parameters override any value of the length if the startDate is non-zero. otherwise the approximation is applied for the entire plot and it is calculated based on all bars from the plot. int length. By default. If you specify length. length). the approximation is applied only for the last length bars of the plot. the function will return Double. LinearRegChVar. int startTime. double extendToLeft. Usage in: LinearRegCh100. plot LinearDev = lindev(close.lindev Syntax lindev(IDataHolder data. . int length). General Information Linear deviation measures difference between the mean value and the current value. Example declare lower. length). Default values: • length: 12 Description Returns the linear deviation of data for the last length bars. input length = 10. Usage in: CCI. The code draws the linear deviation plot for the current symbol for the defined number of bars. StandardDeviation. int length). length). General Information Standart deviation measures how widely values range from the average value. RelativeVolatilityIndex. VolatilityStdDev. HistoricalVolatility. BollingerBandsLE. BollingerBandsSMA. Example declare lower. Standard deviation is calculated as a square root of variance. VolumeFlowIndicator. Default values: • length: 12 Description Returns the standard deviation of data for the last length bars. input length = 10. which is the average of the squared deviations from the mean. The code draws the plot of the standard deviation for the close value for the defined number of bars. plot StdDev = stdev(close. . Usage in: Beta. BollingerBandsSE. DynamicMomentumIndex. BollingerBandsEMA. Beta2.stdev Syntax stdev(IDataHolder data. the function will return Double.NaN at any moment in time outside the interval used for calculation of linear regression. int startDate. The difference of the function from the stdev function is that the output result for the last bar is used for the whole calculated interval. def regression = InertiaAll(price. int startTime. If the length parameter is not specified. int length. double extendToRight). the function is calculated for the entire plot.stdDeviation. double extendToLeft. 30). These parameters override any value of the length if the startDate is non-zero. plot UpperLine = regression + stdDeviation. Default values: • length: all chart • startDate: 0 • startTime: 0 • extendToLeft: no • extendToRight: no Description Returns the standard deviation of data for the entire plot or for the interval of the last bars defined by the length parameter. The startDate (specified in the YYYYMMDD format) and startTime (specified in the HHMM format) define the date and time for the starting point of linear regression. def stdDeviation = stdevAll(price.stdevAll Syntax stdevAll(IDataHolder data. 30). By default. Example input price = close. . plot LowerLine = regression . This behavior can be changed by using non-zero values of extendToLeft and extendToRight parameters. which is the linear regression channel spaced by standard deviation. . Usage in: StandardDevChannel.The example draws the Standard Deviation Channel. The deviation channel is based on price data for the last 30 bars. length). StandardErrorBands. The example calculates the standard error of close values for the defined number of bars. Usage in: StandardError. Default values: • length: 12 Description Returns the standard error calculated for the last length bars from current bar. plot StdError = sterr(close. Returns the standard deviation between data and linear regression of data. input length = 10. Example declare lower. int length).sterr Syntax sterr(IDataHolder data. . NaN at any moment in time outside the interval used for calculation of linear regression. the function will return Double. def stdError = sterrAll(price). int startTime.stdError. These parameters override any value of the length if the startDate is non-zero. . def regression = InertiaAll(price). the function is calculated for the entire plot. int startDate. The difference of the function from the sterr function is that the output result for the last bar is used for the whole calculated interval. If the length parameter is not specified. This behavior can be changed by using non-zero values of extendToLeft and extendToRight parameters. plot LowerLine = regression . By default. int length. double extendToRight). Default values: • length: all chart • startDate: 0 • startTime: 0 • extendToLeft: no • extendToRight: no Description Returns the standard error of data around the regression line for the entire plot or for the interval of last bars defined by the length parameter. The startDate (specified in the YYYYMMDD format) and startTime (specified in the HHMM format) define the date and time for the starting point of linear regression. double extendToLeft. plot UpperLine = regression + stdError. Example input price = close.sterrAll Syntax sterrAll(IDataHolder data. Usage in: StandardErrorChannel. . The error channel is based on the price data for the last 30 bars.The example draws the Standard Error Channel which is the linear regression channel spaced by a standard error. with the help of the functions you can draw the close plot for the last three years or draw the open plot for the first half of each year. For this reason you will find useful the date and time functions featured in this section. For example.  Date and Time Here is the full list of the functions: • countTradingDays • daysFromDate • daysTillDate • getDay • getDayOfMonth • getDayOfWeek • getLastDay • getLastMonth • getLastWeek • getLastYear • getMonth • getWeek • getYear • getYyyyMmDd • regularTradingEnd • regularTradingStart • secondsFromTime • secondsTillTime .During analysis you often work with quote historical data. Description Returns the number of trading days in the specified time period (including both starting and ending dates) for the current symbol. This script displays a chart label indicating the number of trading days from the first day of the year to the current day for the chosen symbol.countTradingDays Syntax countTradingDays(int fromDate. AddChartLabel(yes. getYyyyMmDd()). " trading days since year start")). . Note that fromDate and toDate parameters should be specified in the YYYYMMDD format. Example def yearstart = getYear() * 10000 + 101. TPOProfile. VolumeProfile. MonkeyBarsExpanded. concat(countTradingDays(yearstart. int toDate). Usage in: MonkeyBars. VWAP. Description Returns the number of days from the specified date.NaN. plot Price = if daysFromDate(BeginDate) >= 0 and daysFromDate(BeginDate) <= 50 then close else double. Note that the fromDate argument is specified in the EST timezone and has the YYYYMMDD format. MonkeyBarsExpanded. VolumeProfile. . This example script draws the close plot for bars in the 50 days interval starting from BeginDate. TPOProfile. Example input BeginDate = 20090101. daysFromDate Usage in: MonkeyBars.Syntax daysFromDate(IDataHolder fromDate). SeriesCount. NaN. Note that the tillDate argument is specified in the EST timezone and has the YYYYMMDD format. . Example plot Price = if getDay() <= 100 then close else Double.NaN.daysTillDate Syntax daysTillDate(IDataHolder tillDate). The output is returned in the range from 1 through 365 (366 for leap years). The example draws the close plot for bars in the 50 days interval ending on EndDate. Description Returns the number of days till the specified date. Description Returns the number of the current bar day in the CST timezone. The code draws the close plot for the first 100 days of each year. Usage in: Next3rdFriday. Example input EndDate = 20090101. getDay Syntax getDay(). plot price = if daysTillDate(EndDate) >= 0 and daysTillDate(EndDate) <= 50 then close else double. Example input first_day = 10. TPOProfile. Description Returns the day of a month based on the given YYYYMMDD parameter. VolumeProfile. Displays the close price only for days of month falling into a specified interval. plot Data = if getDayofMonth(getYyyyMmDd()) between first_day and last_day then close else double. input last_day = 20. Next3rdFriday. . Usage in: MonkeyBars.getDayOfMonth Syntax getDayOfMonth(int yyyyMmDd). MonkeyBarsExpanded.NaN. MonkeyBarsExpanded. Sunday}. Wednesday. The output is returned in the range from 1 through 365 (366 for leap years). VWAP. Displays bubbles with text for a certain day of week. This example draws the close plot for the last bar day of the current year. Description Returns the number of the last bar day in the CST timezone. high. Saturday. input day_of_week = {default Monday. Tuesday.getDayOfWeek Syntax getDayOfWeek(int yyyyMmDd). Example declare hide_on_intraday. The return value ranges from from 1 (Monday) to 7 (Sunday). getLastDay Syntax getLastDay(). VolumeProfile. "Here it is"). Description Returns the day of week based on the given YYYYMMDD parameter. . Friday. TPOProfile. AddChartBubble(getDayofWeek(getYyyyMmDd()) == day_of_week + 1. Thursday. Usage in: MonkeyBars. Example plot Price = if getLastDay() == getDay() and getLastYear() == getYear() then close else Double.NaN. Next3rdFriday. The example draws the close plot for the last month of the current year. Example 1 plot Price = if getLastMonth() == getMonth() and getLastYear() == getYear() then close else Double. This code draws the open plot for the last month of each year.getLastMonth Syntax getLastMonth(). The output is returned in the range from 1 through 12. Example 2 plot Price = if getLastMonth() == getMonth() then open else Double. Description Returns the number of the last bar month in the CST timezone. .NaN.NaN. NaN.getLastWeek Syntax getLastWeek(). . This example draws the high plot for the last week of the current year. getLastYear Syntax getLastYear(). The code draws the close plot for the current year. The output is returned in the range from 1 through 53. Description Returns the number of the last bar year in the CST timezone.NaN. Example plot Price = if getLastYear() == getYear() then close else Double. Description Returns the number of the last bar week in the CST timezone. Example plot Price = if getLastWeek() == getWeek() and getLastYear() == getYear() then high else Double. getMonth Example plot Price = if getMonth() <= 6 then close else Double. Description Returns the number of the current bar month in the CST timezone. Next3rdFriday. VolumeProfile. The example draws the close plot for the first half of each year. Usage in: MonkeyBars. MonkeyBarsExpanded. TPOProfile. . The output is returned in the range from 1 through 12.NaN.Syntax getMonth(). The example draws the close plot for the last three years. Example plot Price = if getWeek() % 2 == 1 then close else Double. TPOProfile. Next3rdFriday.3 then open else Double.getWeek Syntax getWeek(). The output is returned in the range from 1 through 53. Description Returns the number of the current bar year in the CST timezone. .NaN. Description Returns the number of the current bar week in the CST timezone. Usage in: MonkeyBars. MonkeyBarsExpanded. getYear Syntax getYear(). Example plot Price = if getYear() > getLastYear() . VolumeProfile.NaN. The example draws the close plot for odd weeks of each year. getYyyyMmDd Syntax getYyyyMmDd(). this date and the actual date might not be the same for Forex and Futures symbols. VolumeProfile.NaN. Description Returns the date of the current bar in the YYYYMMDD format. This example plots closing price only when the date of the current bar is less than the one specified in the endDate input. def cond = getYyyyMmDd() < endDate. input endDate = 20100101. Note that on intraday charts. Usage in: MonkeyBars. Example declare lower. plot Price = if cond then close else Double. TPOProfile. Next3rdFriday. This date corresponds to the day whose trading session contains the current bar. MonkeyBarsExpanded. WoodiesCCI. VWAP. . Usage in: WoodiesCCI. 1970. Description Returns the end of the regular trading hours for the current symbol on the trading day specified in the YYYYDDMM format. 00:00:00 GMT).regularTradingEnd Syntax regularTradingEnd(int yyyyMmDd). Example See the regularTradingStart function example. This value is the number of milliseconds since the epoch (January 1. . concat("RTH duration (hrs): ". (regularTradingEnd(getYyyyMmDd()) regularTradingStart(getYyyyMmDd())) / AggregationPeriod. This value is the number of milliseconds since the epoch (January 1. 00:00:00 GMT). . Example AddChartLabel(yes.regularTradingStart Syntax regularTradingStart(int yyyyMmDd). Description Returns the start of the regular trading hours for the current symbol on the trading day specified in the YYYYDDMM format. This example script displays a chart label with duration of a regular trading session in hours. Usage in: WoodiesCCI.HOUR)). 1970. .NaN. Example input OpenTime = 0930. def durationSec = DurationHours * 60 * 60. TPOProfile.secondsFromTime Syntax secondsFromTime(int fromTime). input DurationHours = 1. plot Price = if secondsPassed >= 0 and secondsPassed <= durationSec then close else double. Usage in: MonkeyBars. Note that this function always returns zero when chart's aggregation period is greater than or equal to 1 day. VolumeProfile. SeriesCount. MonkeyBarsExpanded. def secondsPassed = secondsFromTime(OpenTime). Description Returns the number of seconds from the specified time (24-hour clock notation) in the EST timezone. The plot displays the close value based on the specified duration and the beginning in the EST timezone format. input DurationHours = 1. def durationSec = DurationHours * 60 * 60. plot Price = if secondsRemained >= 0 and secondsRemained <= durationSec then close else double. Example input CloseTime = 1600. . Note that this function always returns zero when chart's aggregation period is greater than or equal to 1 day.secondsTillTime Syntax secondsTillTime(int tillTime). def secondsRemained = secondsTillTime(closeTime). This example draws the close plot based on the defined duration and through the specified time in EST.NaN. Description Returns the number of seconds till the specified time (24hour clock notation) in the EST timezone. o Corporate Actions Here is the full list: • getActualEarnings • getDividend • getEstimatedEarnings • getSplitDenominator • getSplitNumerator • hasConferenceCall • hasEarnings .This section contains functions related to corporate actions. Note that this example works only for daily charts because it uses an assumption that there are 252 daily bars in a year. Also it shows the current Price-Earnings Ratio in the chart label. close / EPS_TTM)). getActualEarnings Example 1 declare lower. The example draws values of diluted earnings for the current symbol. rec AECont = if IsNaN(getActualEarnings()) then AECont [1] else getActualEarnings().Syntax getActualEarnings().NaN. Description Returns actual earnings for the current symbol. The code draws values of diluted earnings for approximately twelve months. Example 2 declare lower. . plot EPS_TTM = sum(AE. Values between earnings are saved using the AECont rec. 252). rec AE = if IsNaN(getActualEarnings()) then 0 else getActualEarnings(). plot DilutedEarnings = if AECont <> 0 then AECont else Double. AddChartLabel(yes. concat("P/E Ratio: ". rec DCont = if IsNaN(getDividend()) then DCont[1] else getDividend(). concat(DivA / close * 100. The example draws the annual dividend plot (considering that dividends are quarterly and they remain on the same level through the year). plot DivA = if DCont <> 0 then DCont * 4 else Double.takeValueColor()). Example 1 declare lower. Example 2 declare lower. DivA.NaN. rec DCont = if IsNaN(getDividend()) then DCont[1] else getDividend(). AddChartLabel(yes. "% Yield").getDividend Syntax getDividend(). The example plots dividends for the current symbol on a separate subgraph. Also the code in this example defines a chart label that indicates the calculated dividend yield value in percentage and draws it using the same color as the main plot. . plot Dividend = if DCont <> 0 then DCont else Double. Values between different Ex-Dividend dates are saved using the DCont rec. Description Returns a dividend amount for the current symbol.NaN. see the AddVerticalLine function.POINTS). The example draws estimated earnings for the current symbol as points on a separate subgraph. getSplitDenominator Syntax getSplitDenominator(). .SetPaintingStrategy(PaintingStrategy. Color.getEstimatedEarnings Syntax getEstimatedEarnings(). if getSplitNumerator() > getSplitDenominator() then "Split!" else "Reverse Split!". Example AddVerticalLine(!IsNaN(getSplitDenominator()). plot EstEarning = getEstimatedEarnings(). Example declare lower. The code draws a gray vertical line with the "Split!" or "Reverse Split!" label for days when a corresponding split took place. For more information. Description Returns the split denominator for the current symbol.GRAY). EstEarning. Description Returns estimate earnings for the current symbol. rec position = CompoundValue(1. see the PaintingStrategy. ConfCall. hasConferenceCall Syntax hasConferenceCall(). Description Returns true if there is an earnings conference call. false otherwise. plot CurrentPosition = position. input initialPosition = 100.SetPaintingStrategy(PaintingStrategy. Description Returns a split numerator for the current symbol.Example declare lower. For more information. Example plot ConfCall = hasConferenceCall().BOOLEAN_POINTS constant. Syntax getSplitNumerator().BOOLEAN_ POINTS). The code draws a dot based on the close price when the current symbol has a conference call. . getSplitNumerator This example shows trader position changes taking into account the splits presented on the chart. if !IsNaN(getSplitDenominator()) then position[1] * getSplitNumerator() / getSplitDenominator() else position[1]. initialPosition). Default values: • type: EarningTime.SetPaintingStrategy(PaintingStrategy. isBefore.ANY Description Returns true if there are announced earnings.hasEarnings Syntax hasEarnings(int type). and false otherwise. isAfter. plot isAfter = hasEarnings(EarningTime.SetPaintingStrategy(PaintingStrate gy. down arrow if they are expected after market close. isDuringOrUnspecified.BOOLEAN_A RROW_DOWN). and a dot if they are expected during market trading hours or the time is not specified.BEFORE_MARKET). plot isDuringOrUnspecified = hasEarnings() and !isBefore and !isAfter.SetPaintingStrategy(PaintingStrategy. Example plot isBefore = hasEarnings(EarningTime. .AFTER_MARKET). This example script marks announced earnings with an up arrow if they are expected before market open. Use an EarningTime constant to specify the time of announcement.BOOLEAN_ ARROW_UP).BOOLEAN_POINTS). One of these functions is AddCloud that highlights the area between charts. Although the majority of these settings can be made through the application GUI. or AssignNormGradientColor that paints a chart with a gradient. o Look and Feel The full set of the functions is provided in the following list: • AddChartBubble • AddChartLabel • AddCloud • AddVerticalLine • AssignBackgroundColor • AssignNormGradientColor • AssignPriceColor • AssignValueColor • color • CreateColor • DefineColor • DefineGlobalColor • EnableApproximation • GetColor • globalColor • hide • HideBubble • hidePricePlot • HideTitle • setChartType • SetDefaultColor • setHiding • SetLineWeight • SetPaintingStrategy • SetStyle • TakeValueColor .The thinkscript enables you to adjust the look and feel of charts you analyse. some of them can be done only with the help of the thinkscript. AddChartBubble This example shows bubbles with values and a description on the selected time frame extremums. WEEK. no). concat(": ". . Default values: • color: Color. Example input timeFrame = {default DAY. color. high))).RED • up: yes Description Adds a bubble with a text to the specified location. concat(": ". "4 DAYS". concat("High of ".red. concat("Low of ". low. color.green. Any text. The color parameter defines the color of the bubble. high. double price location. "3 DAYS". concat(timeFrame. The bubble will be displayed above the specified point if the up parameter is true and below the specified point if it is false. CustomColor color. MONTH. boolean up). concat(timeFrame. "OPT EXP"}. AddChartBubble(low == low(period = timeFrame). AddChartBubble(high == high(period = timeFrame). "2 DAYS". low))).Syntax AddChartBubble(boolean time condition. The tip of the bubble is at the point specified by the price location parameter. yes). Bubbles are displayed next to bars for which the time condition is true. The text parameter defines the text to be displayed in the bubble. . close)). Any text. AddChartLabel Usage in: AdvanceDecline.Profile: Studies Syntax AddChartLabel(boolean visible. WoodiesCCI. SemiCupFormation. Example AddChartLabel(yes. Displays a label with the last price. Next3rdFriday. concat("Last price is ". CustomColor color).RED Description Adds a label with a text to the top-left graph corner. Default values: • color: Color. color. while red cloud corresponds to bear candles. ClosePrice. IDataHolder data2. CustomColor color1. The AddCloud function can use both defined variables and plots as parameters.Profile: Studies Syntax AddCloud(IDataHolder data1.RED Description Visualizes the difference between two values by filling the intermediate area with a translucent background. def ClosePrice = close. the AddCloud draws the translucent "cloud" and paints it according to the following rule: • if CurrentPrice > PastPrice then the cloud is violet. Color. Color. CustomColor color2). PastPrice. In this example. AddCloud(OpenPrice.YELLOW • color2: Color.PINK). the AddCloud function draws a translucent "cloud" that highlights the difference between the OpenPrice and ClosePrice values. color.VIOLET. AddCloud Example 1 def OpenPrice = open.RED. plot PastPrice = close[10].GREEN). In this example. Green cloud corresponds to bull candles. AddCloud(CurrentPrice. otherwise color2 is used. The sections where data1 value exceeds data2 value are assigned color1. Example 2 plot CurrentPrice = close. Default values: • color1: Color. . VIOLET. For example. the rule will be: • if PastPrice > CurrentPrice then the cloud is violet.PINK). . • if PastPrice < CurrentPrice then the cloud is pink. AddCloud(PastPrice. if you swap over the PastPrice and the CurrentPrice: plot CurrentPrice = close.• if CurrentPrice < PastPrice then the cloud is pink. CurrentPrice. Note that the order in which the arguments appear in the AddCloud function affects the logics. Color. Usage in: Ichimoku. plot PastPrice = close[10]. Color. SHORT_DASH).Profile: Studies Syntax AddVerticalLine(boolean visible. Usage in: SeriesCount. • stroke: defines the style of the line. curve. int stroke). "".MONTH and getMonth() <> getMonth()[1]). Lines are only displayed before bars for which this parameter is true. • text: defines a text to be shown with the line. default MONTH}. • color: defines the color of the line. AddVerticalLine Example input period = {WEEK. AddVerticalLine((period == period. Parameters Specify the following parameters for this function: • visible: defines a condition controlling line visibility. Any of the Curve constants can be used for this parameter.ORANGE.WEEK and getWeek() <> getWeek()[1]) or (period == period. . Color. This text is displayed vertically to the left from the line. The code draws orange short-dashed vertical lines with a defined frequency. Any text. Default values: • color: Color. CustomColor color.RED • stroke: 3 Description Adds a vertical line with specified text. DARK_RED). this function sets the background color of the quote cell. Description Sets a background color. Note that when used in script for a custom quote. Sets the background color to dark red. . AssignBackgroundColor Example AssignBackgroundColor(color.Profile: Studies Syntax AssignBackgroundColor(CustomColor color). LIGHT_RED. PriceOsc. Example declare lower. the lowest. Usage in: ChaikinOsc. PriceOsc. CustomColor highestColor). then it is painted with the highestColor. then it is painted with the lowestColor. Color. fastLength) . and the highest values of the last length bars to define a specific color. The example shows the Price Oscillator study which is a momentum study calculated as the difference between two moving averages. EaseOfMovement. slowLength). . plot PriceOsc = Average(close. input fastLength = 9. TRIX. VolumeRateOfChange. If the current plot value is negative and the lowest. The center color of the gradient is always situated on the zero level which means that the positive part of the plot uses the higher colors of the gradient. Description Fills a plot with a gradient using the current. DetrendedPriceOsc. The biggest positive difference for the last colorNormLength is painted yellow. input slowLength = 18. input colorNormLength = 14.AssignNormGradientColor(colorNormLength. CustomColor lowestColor. and the negative part uses the lower colors. If the current plot value is positive and the highest.YELLOW). Color. the smallest is painted light red.AssignNormGradientColor Profile: Studies Syntax AssignNormGradientColor(int length. RateOfChange. VolumeOsc.Average(close. The rest of the values are painted using intermediate colors depending on how far they are located from the two extreme points. plot OverBought = 80. Usage in: .DefineColor("OverBought". If the MFI is greater or equals 80 then the price plot is colored orange.CURRENT constant. plot MFI = MoneyFlowIndex(). AssignPriceColor Example declare lower. In the rest of cases the color will not change and will remain grey which is defined by the Color.ORANGE). Description Sets a color of the price bar.color("OverSold") else Color. In order to be able to change colors for the AssignPriceColor function without actually changing the code. MFI. AssignPriceColor(if MFI >= OverBought then MFI. TTM_Trend. if the MFI is lower or equals 20 then it is colored blue. OverSold. LBR_PaintBars.color("OverBought") else if MFI <= OverSold then MFI.DefineColor("OverSold".SetDefaultColor(Color. the example refers to colors of the MFI plot. Color. In this example price bars are colored depending on the MFI plot which refers to the MoneyFlowIndex study.Profile: Studies Syntax AssignPriceColor(CustomColor color).SetDefaultColor(Color. MFI.BLUE). Note that you cannot paint the same price bar using multiple studies simultaneously. SpectrumBars.GRAY). OverBought. Color.GRAY). plot OverSold = 20.CURRENT). • Note that you can change colors of a plot in the Edit Studies dialog only if you use the color function to define these colors.DOWNTICK is red.UPTICK and the Color.Profile: Studies Syntax AssignValueColor(CustomColor color). AssignValueColor Example plot Diff = close . otherwise it is painted red. Colors can be specified in the following ways: • Explicitly. see the Color constant in the Constants section. for example Color.DOWNTICK). the Diff plot is painted green. • Using the Color. For more information about the color constants. • Using the CreateColor function.DOWNTICK constants.AssignValueColor(if Diff >= 0 then Color. Color. this function sets the color of the quote value. • Using the color function. Diff.close[1]. In the rest of cases you can change the colors only by editing the source code of a study. Description Paints intervals of a plot with desired colors depending on a condition. .RED. In this example.UPTICK is a green color.UPTICK else Color. Color. • Using the GetColor function. if the difference between the current closing value and the closing value for the previous bar is positive. The specified colors override the default color set for the plot. Note that when used in script for a custom quote. WoodiesCCI.ADXCrossover. MACDHistogramCrossover. PercentR. AwesomeOscillator. MovingAvgCrossover. TrendQuality. ElliotOscillator. LBR_ThreeTenOscillator. VolumeAvg. RSIWilder. MACD. PriceAverageCrossover. MoneyFlowIndex. VolumeWeightedMACD. LBR_SmartADX. BalanceOfMarketPower. ParabolicSARCrossover. KlingerHistogram. MoneyFlowIndexCrossover. AdvanceDecline. SpectrumBars. RSIWilderCrossover. ATRTrailingStop. StochasticCrossover. RateOfChangeCrossover. Usage in: . AccelerationDecelerationOsc. MACDHistogram. PercentChg. MomentumCrossover. HullMovingAvg. PersonsPivots. ErgodicOsc. BollingerBandsCrossover. SpectrumBars. EaseOfMovement. AwesomeOscillator. Usage in: .DOWNTICK). PersonsPivots. StochasticCrossover. AdvanceDecline. RateOfChangeCrossover. Price. MACDHistogram. AccelerationDecelerationOsc. KlingerHistogram. Color. MomentumCrossover. BollingerBandsCrossover. ATRTrailingStop. MovingAvgCrossover. MACD. ErgodicOsc. TRIX.color("Down")). RSIWilder. LBR_SmartADX. LBR_ThreeTenOscillator. MoneyFlowIndexCrossover. Note that the color should be defined using the DefineColor function. ADXCrossover.DefineColor("Up".DefineColor("Down".color("Up") else Price. RSIWilderCrossover. WoodiesCCI. ElliotOscillator. Price. The code paints the closing plot with "Up" and "Down" colors depending on the price change as compared to the previous bar. MACDHistogramCrossover. PriceAverageCrossover. VolumeAvg. MoneyFlowIndex. PriceOsc.UPTICK). color Example declare lower.AssignValueColor(if Price >= Price[1] then Price. RateOfChange. HullMovingAvg. plot Price = close. TrendQuality. Color. ParabolicSARCrossover. PercentR. Price. VolumeWeightedMACD. ChaikinOsc. VolumeOsc. PercentChg.Profile: Studies Syntax color(String name). DetrendedPriceOsc. VolumeRateOfChange. Description Gets a plot color using the title of the color. DarvasBox.SetDefaultColor(CreateColor(255. Doji. CreateColor Example plot Price = close. This example paints the Price chart in color that has the 255. RibbonStudy. 220. 220. double blue). Usage in: BeltHold. double green. Description Generates a color based on its rgb code. 210)).Profile: Studies Syntax CreateColor(double red. Price. 210 rgb code. . MovAvgExpRibbon. DefineColor This example paints the Momentum plot in different colors according to its trend. Color. The DefineColor function defines Positive and Negative color names as aliases for Color.DefineColor("Positive". input length = 12. Momentum. If the trend of the plot is positive then it is painted in Positive (Uptick) color. Color. Note that in order to refer to a specific color the code uses the color function.DOWNTICK constants.AssignValueColor(if Momentum >= 0 then Momentum.DOWNTICK).color("Negative")).close[length]. Momentum.color("Positive") else Momentum. Profile: Studies Syntax DefineColor(String name. Usage in: Multiple . Description Defines a named color for a plot with the default color value. CustomColor color).DefineColor("Negative".Example declare lower. You can change the colors in the Edit Studies dialog and their order is the same as in the source code. Momentum. the plot is painted in Negative (Downtick) color. If the trend is negative.UPTICK). This color can be changed in the Edit Studies dialog. plot Momentum = close .UPTICK and Color. signal. LBR_PaintBars. DefineGlobalColor Example DefineGlobalColor("Global1". CreateColor(128.SetDefaultColor(globalColor("Global1")). Description Defines a named color for a plot with a default color value. CustomColor color). This color can be changed in the Globals sub-tab of the Study Properties.BOOLEAN_AR ROW_DOWN).Profile: Studies Syntax DefineGlobalColor(String name. SeriesCount. . Usage in: Ichimoku. This color can be changed in the menu. This example defines and uses a global color.SetDefaultColor(globalColor("Global1")). 128)). VolumeProfile. MonkeyBarsExpanded. TPOProfile.9*close. NinetyPercent. 0. MonkeyBars. signal. SpectrumBars.SetPaintingStrategy(PaintingStrategy. plot signal = high > highest(high[1]). plot NinetyPercent = 0. EnableApproximation(). Usage in: . Description Connects adjacent non-NaN values. ZZ. EnableApproximation Example plot ZZ = ZigZagSign(). ZigZagPercent. The first line of the code defines the ZZ plot as a reference to the ZigZagSign plot. The second line enables the approximation for the plot in order to connect separate reversal points with lines.Profile: Studies Syntax EnableApproximation(). ZigZagSign. FourPercentModel. . Note that colors in color palettes vary depending on the current Look and Feel you are using.GetColor Syntax GetColor(int index). the colors in the color palettes are chosen in a way that your data is visualized in an optimal way. Default values: • index: 0 Description Gets a color from the color palette. that is. The following table lists the available colors for different look and feel settings. the same 10 colors are repeated in a cycle. 0 1 2 3 4 5 6 7 8 9 Index Black White and Metal Calling GetColor with any index outside of this range is equal to calling GetColor(AbsValue(index) % 10). Despite different Look and Feels. Example input length = 12.SetDefaultColor(GetColor(1)).SetDefaultColor(GetColor(5)). This script plots two lines: the 12 period simple moving average and exponential moving average of the Close price using colors 1 and 5 from the predefined palette respectively. length). plot EMA = MovAvgExponential(close. length). Usage in: Multiple . plot SMA = SimpleMovingAvg(close. SMA. EMA. . Profile: Studies Syntax globalColor(String name).DefineColor(name.Example See the DefineGlobalColor function example. SeriesCount. VolumeProfile. globalColor Usage in: Ichimoku. TPOProfile. LBR_PaintBars. color) statement. The color should be defined by the plot. SpectrumBars. Description Gets a plot color by name. MonkeyBars. MonkeyBarsExpanded. TrueStrengthIndex. MonkeyBarsExpanded. Description Makes a plot hidden by default.hide().Profile: Studies Syntax hide(). This example makes the PriceOpen plot invisible by default. TPOProfile. PersonsPivots. Usage in: BalanceOfMarketPower. hide Example plot PriceClose = close. PriceOpen. plot PriceOpen = open. LBR_PaintBars. . MonkeyBars. This function may be required to hide plot data that is not used in the analysis at the moment. VolumeProfile. The example hides the last value bubble of the Data plot. HideBubble Example plot Data = volume. Description Makes the last value bubble of a plot invisible. . Usage in: WoodiesCCI.HideBubble(). Data.Profile: Studies Syntax HideBubble(). . hidePricePlot Example plot closeOnly = close. The example code solely displays the Close price plot.Profile: Studies Syntax hidePricePlot(double hide price). Default values: • hide price: yes Description Hides the price plot for the current symbol if the Boolean condition value is yes. hidePricePlot(yes). PriceOscLine. Usage in: LBR_ThreeTenOscillator.HideTitle().SetPaintingStrategy(PaintingStrategy. ZeroLine. plot PriceOsc = Average(close.Profile: Studies Syntax HideTitle().PINK). 9) . plot PriceOscLine = PriceOsc. .HISTOGRA M). PriceOsc.HideTitle().a histogram and line.SetDefaultColor(Color. PriceOscLine. The example draws the Price Oscillator study consisting of two plots .Average(close. PriceOsc. Description Removes the plot value from the graph title. HideTitle Example declare lower.SetDefaultColor(Color. ZeroLine.VIOLET). WoodiesCCI. plot ZeroLine = 0. The HideTitle function is used to deallocate equal values of PriceOsc and PriceOscLine plots and a permanent zero value for the ZeroLine plot from the status string.SetDefaultColor(Color. 18).LIGHT_GRAY). setChartType(ChartType. see the Appearance Settings article. This code sets the Area chart type and outlines it with the Close price plot. . Example plot price = close. see the ChartType constants section.LINE For more information about the constants.AREA • ChartType.CANDLE • ChartType.BAR • ChartType.AREA).HEIKIN_ASHI • ChartType.CANDLE_TREND • ChartType. Description Sets a desirable non-Monkey chart type directly from the script.Profile: Studies Syntax setChartType(double chart type). setChartType Valid parameters are: • ChartType. for more information on that. Note that you can also set the chart type along with its color settings within the Chart Settings window. SetDefaultColor(color. This setting affects the color of the plot when the study is first initialized or added to the chart.Profile: Studies Syntax SetDefaultColor(CustomColor color). Multiple . Usage in: The example sets the default color of the Data plot to red. Description Sets the default color of a plot.RED). SetDefaultColor Example plot Data = close. Data. The weekly plot is hidden if the aggregation period is not less than one week week.DAY). setHiding Example plot DailyClose = close(period = AggregationPeriod.WEEK).SetHiding(getAggregationPeriod() >= AggregationPeriod. otherwise the plot is visible.DAY). plot MonthlyClose = close(period = AggregationPeriod.MONTH). In this example. DailyClose. plot WeeklyClose = close(period = AggregationPeriod.WEEK). the plot is hidden. . The monthly plot is hidden if the aggregation period is greater than or equal to one month.Profile: Studies Syntax setHiding(double condition).MONTH). MonthlyClose. If this condition is true. Usage in: PersonsPivots.SetHiding(getAggregationPeriod() >= AggregationPeriod. For more information about the aggregation period. see the AggregationPeriod article in the Constants section. the daily plot is hidden if the aggregation period is greater than or equal to one day.SetHiding(getAggregationPeriod() >= AggregationPeriod. Description Controls visibility of a plot depending on a condition. WeeklyClose. For a list of valid style parameters. Description Controls a painting style of a line.setPaintingStrategy(PaintingStrategy.HISTOGRAM). In this example.SetLineWeight(5). see the PaintingStrategy constant in the Constants section. The value is measured in pixels and ranges from 1 to 5 inclusively. Data. the painting style of the Data plot is a histogram.Profile: Studies Syntax SetLineWeight(int lineWeight). Usage in: Multiple . Description Sets a weight of a line. SetLineWeight Example plot Price = close. Price. SetPaintingStrategy Example plot Data = open. Usage in: Multiple This code sets the weight of a line to 5. Profile: Studies Syntax SetPaintingStrategy(int paintingStrategy). This example script draws the Low price plot using a short-dashed curve. SetStyle For more information about the constants.LONG_DASH • Curve. Data.FIRM • Curve.POINTS . PersonsPivots. Valid parameters are: • Curve.Profile: Studies Syntax SetStyle(int curve).SHORT_DASH). Example plot Data = low. WoodiesPivots. Usage in: BollingerBandwidth.setStyle(Curve. Description Controls a style of a curve.MEDIUM_DASH • Curve.SHORT_DASH • Curve. see the Curve constant in the Constants section. TakeValueColor()). Description Returns the color of the current bar. Avg. plot Avg = Average(price. the TakeValueColor is called to ensure that the bubble is the same color as the SMA plot. WoodiesCCI. AddChartBubble(Avg == HighestAll(Avg). Usage in: Next3rdFriday.Profile: Studies Syntax TakeValueColor(). TakeValueColor In this example. "Max. Avg. Example input price = close. . input length = 12. length). Average". o Profiles The list of functions: • getHighest • getHighestValueArea • getLowest • getLowestValueArea • getPointOfControl • monkeyBars • show • timeProfile • volumeProfile .This section contains articles on profile functions used in thinkScript. getHighest(). Description Returns the highest price value reached by the instrument within the time period for which the profile is accumulated. Example def yyyymmdd = getYyyyMmDd(). Profile: Studies Syntax getHighest(). def cond = 0 < period . plot b = vol. TPOProfile. This script plots the High price for each weekly Volume profile. profile vol = volumeProfile("startNewProfile" = cond. "onExpansion" = no). def period = Floor(day_number / 7). MonkeyBarsExpanded. getHighest . vol.show().Usage in: MonkeyBars.period[1]. VolumeProfile. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)). MonkeyBarsExpanded. Profile: Studies Syntax getHighestValueArea().Example def yyyymmdd = getYyyyMmDd(). getHighestValueArea This script plots the highest price of each weekly Volume profile's Value Area.getHighestValueArea(). profile vol = volumeProfile("startNewProfile" = cond. TPOProfile.YELLOW).show("va color" = Color.period[1]. vol. def cond = 0 < period . Usage in: MonkeyBars. VolumeProfile. "onExpansion" = no). Description Returns the highest price of the profile's Value Area. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)). plot b = vol. . def period = Floor(day_number / 7). VolumeProfile.getLowest(). getLowest This script plots the Low price for each weekly Volume profile.show().period[1]. Description Returns the lowest price value reached by the instrument within the time period for which the profile is accumulated. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)). Usage in: MonkeyBars. def cond = 0 < period . def period = Floor(day_number / 7). TPOProfile.Example def yyyymmdd = getYyyyMmDd(). MonkeyBarsExpanded. "onExpansion" = no). vol. Profile: Studies Syntax getLowest(). profile vol = volumeProfile("startNewProfile" = cond. . plot b = vol. . Usage in: MonkeyBars.period[1].YELLOW). def cond = 0 < period . Profile: Studies Syntax getLowestValueArea(). MonkeyBarsExpanded.show("va color" = Color. Description Returns the lowest price of the profile's Value Area. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)).getLowestValueArea(). vol. getLowestValueArea This script plots the lowest price of each weekly Volume profile's Value Area.Example def yyyymmdd = getYyyyMmDd(). profile vol = volumeProfile("startNewProfile" = cond. VolumeProfile. plot b = vol. def period = Floor(day_number / 7). "onExpansion" = no). TPOProfile. VolumeProfile. getPointOfControl This script displays the Point of Control plot for weekly TPO profiles. MonkeyBarsExpanded. TPOProfile. tpo. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)).Example def yyyymmdd = getYyyyMmDd(). plot b = tpo.getPointOfControl().show(). Description Returns the price value of the Point of Control level closest to the middle of profile's price range.period[1]. def cond = 0 < period . "onExpansion" = no). profile tpo = timeProfile("startNewProfile" = cond. . Profile: Studies Syntax getPointOfControl(). def period = floor(day_number / 7). Usage in: MonkeyBars. IDataHolder startNewProfile. the monkeyBars function is given a trigger signal to calculate the new profile. int numberOfProfiles. This value can be defined by an actual price range or a PricePerRow constant. the second decade is displayed as digits 0-9 in the second palette color. Note that a named variable must be used for this parameter. The first decade is displayed as digits 0-9 in the first palette color. double pricePerRow. The timeInterval parameter defines an ordinal number of aggregation period. boolean emphasize first digit). Note that a named variable must be used for this parameter. when it is true. double the playground percent. The startNewProfile parameter defines a condition. monkeyBars Description Calculates the Monkey Bars profile with user-defined paramaters. int onExpansion. Default values: • symbol: "<currently selected symbol>" • pricePerRow: PricePerRow. The symbol parameter defines a symbol to calculate Monkey Bars for. The pricePerRow parameter defines the "height" (price range) of each row of Monkey Bars. and so on.0 • emphasize first digit: 0 .Profile: Studies Syntax monkeyBars(IDataHolder timeInterval. String symbol.AUTOMATIC • startNewProfile: all chart • onExpansion: yes • numberOfProfiles: "all" • the playground percent: 70. This script displays Monkey Bars with 1 day aggregation period for the whole chart. profile monkey = monkeyBars(timeInterval. The emphasize first digit parameter defines whether or not to highlight the opening digit of each period in bold. def allchart = 0. The the playground percent parameter sets the percentage of the trading activity for which The Playground is determined. Example def yyyymmdd = getYyyyMmDd(). def timeInterval = getDayOfMonth(yyyymmdd). If onExpansion is set to yes then this parameter is ignored and only one profile is shown. "startNewprofile"=allchart). The numberOfProfiles parameter defines the number of profiles to be displayed if onExpansion is set to no.show(). monkey.The onExpansion parameter defines whether or not to show Monkey Bars on the expansion area of the chart. . Usage in: MonkeyBars. and Monkey Bars profiles. value area). that element is not displayed.CURRENT • close color: Color. The va color parameter defines the color of the Value Area.Profile: Studies Syntax show(CustomColor color. Note that when Color. The poc color parameter defines the color of the Point of Control. double opacity. in percent. The color parameter defines the main color of Time and Volume profile bars. Volume. CustomColor close color). CustomColor open color. show Description Controls visibility and color scheme of Time.0 • open color: Color. CustomColor va color.PLUM • poc color: Color. The open color parameter defines the color of the square marking the Monkey Bars' Open price.CURRENT • va color: Color. Default values: • color: Color.CURRENT is used for any of the elements (profile itself. Note that profiles calculated by the corresponding functions will only be visible if the show function is applied to them. The opacity parameter sets the degree of histogram opacity.CURRENT . CustomColor poc color. point of control.CURRENT • opacity: 50. The close color parameter defines the color of the arrow marking the Monkey Bars' Close price. This script displays weekly Volume profiles with Value Area highlighted in yellow.Usage in: MonkeyBars. VolumeProfile. Example def yyyymmdd = getYyyyMmDd(). MonkeyBarsExpanded.YELLOW).period[1]. "onExpansion" = no). vol. def day_number = daysFromDate(first(yyyymmdd)) + getDayOfWeek(first(yyyymmdd)). profile vol = volumeProfile("startNewProfile" = cond. def period = Floor(day_number / 7).show("va color" = Color. TPOProfile. def cond = 0 < period . . int onExpansion. double pricePerRow. The value area percent parameter sets the percentage of the trading activity for which the Value Area is determined. The symbol parameter defines a symbol to calculate the TPO profile for. double value area percent). The onExpansion parameter defines whether or not the profile is shown on the expansion area of the chart. This value can be defined by an actual price range or a PricePerRow constant. If onExpansion is set to yes then this parameter is ignored and only one profile is shown. int numberOfProfiles. the function is given a trigger signal to calculate the new TPO profile. The pricePerRow parameter defines the "height" (price range) of each row of the profile. The numberOfProfiles parameter defines the number of profiles to be displayed if onExpansion is set to no. timeProfile Description Displays the time price opportunity (TPO) profile with user-defined calculation parameters.AUTOMATIC • startNewProfile: all chart • onExpansion: yes • numberOfProfiles: "all" • value area percent: 70. IDataHolder startNewProfile. Default values: • symbol: "<currently selected symbol>" • pricePerRow: PricePerRow.0 .Profile: Studies Syntax timeProfile(String symbol. when it is true. Note that a named variable must be used for this parameter. The startNewProfile parameter defines a condition. tpo.BLUE).Example def allchart = 0.show("color"=Color. This script plots TPO profile study (colored blue) that aggregates all chart data on the right expansion. Usage in: TPOProfile. . profile tpo = timeProfile("startnewprofile"=allchart). 0 .AUTOMATIC • startNewProfile: all chart • onExpansion: yes • numberOfProfiles: "all" • value area percent: 70.Profile: Studies Syntax volumeProfile(String symbol. volumeProfile Description Displays the volume profile with user-defined calculation parameters. The startNewProfile parameter defines a condition. The onExpansion parameter defines whether or not the profile is shown on the expansion area of the chart. the function is given a trigger signal to calculate the new volume profile. This value can be defined by an actual price range or a PricePerRow constant. If onExpansion is set to yes then this parameter is ignored and only one profile is shown. The value area percent parameter sets the percentage of the trading activity for which the Value Area is determined. double value area percent). The numberOfProfiles parameter defines the number of profiles to be displayed if onExpansion is set to no. Default values: • symbol: "<currently selected symbol>" • pricePerRow: PricePerRow. The pricePerRow parameter defines the "height" (price range) of each row of the profile. The symbol parameter defines a symbol to calculate the volume profile for. IDataHolder startNewProfile. double pricePerRow. int numberOfProfiles. when it is true. Note that a named variable must be used for this parameter. int onExpansion. profile vol = volumeProfile("startnewprofile"=allchart). vol.show("color"=Color. .YELLOW). This script plots Volume profile study (colored yellow) that aggregates all chart data on the right expansion. Usage in: VolumeProfile.Example def allchart = 0. Each of the functions is used as a supplement for technical analysis.This section contains functions not fitting the rest of the sections. o Others Here is the full list: • addOrder • alert • barNumber • between • compoundValue • concat • entryPrice • first • fundamental • getAggregationPeriod • getInterestRate • getSymbolPart • getValue • getYield • if • tickSize • tickValue . The price parameter defines the price at which the order is added. The arrowColor parameter defines the color of arrow.MAGENTA • arrowColor: Color. which means that the order will be added at the Open price of the next bar. . CustomColor tickColor. The tradeSize parameter defines the number of contracts traded.CONDITIONAL • price: open[-1] • tradeSize: specified by strategy settings • tickColor: Color.MAGENTA Description Adds an order of specified side and position effect for the next bar when the condition is true.Profile: Strategies Syntax addOrder(int type. strategy name and current position. Note that the default value of this parameter is open[-1]. IDataHolder price. The condition parameter defines the condition upon which the order is added. Note that this value overrides the trade size specified in Strategy Global Settings. The type parameter defines order side and position effect using the OrderType constants. IDataHolder tradeSize. CustomColor arrowColor). The tickColor parameter defines the color of tick marking the trade price. IDataHolder condition. addOrder Default values: • type: OrderType. VoltyExpanCloseLX. MomentumLE. close > close[1]. ConsBarsDownSE. KeyRevLX. open[2]. SpectrumBarsLE. Usage in: . GapUpLE.BUY_AUTO. PriceZoneOscillatorSX. PriceZoneOscillatorLE. TrailingStopLX. ATRTrailingStopLE. BollingerBandsSE. BollingerBandsLE. the code opens the long position or closes the short one at the Open price of the second bar from the current. PriceZoneOscillatorLX. StopLossSX. 50.ORANGE). PriceZoneOscillatorSE. InsideBarSE. InsideBarLE. ATRTrailingStopSE. ProfitTargetLX.ORANGE.Example addOrder(OrderType. and the signals will be colored orange. The trade size will be equal to 50. KeyRevLE. Color. ThreeBarInsideBarSE. ThreeBarInsideBarLE. ProfitTargetSX. StopLossLX. ConsBarsUpLE. TrailingStopSX. Color. If the current Close price is higher than the previous. GapDownSE. the condition for the alert function is not checked and the local alert cannot be triggered.NoSound • Sound.Chimes • Sound. Note that you can create studies containing only alert function call without defining any plots. String text.ONCE • Alert. int alert type.TICK Valid sound parameters are: • Sound. Default values: • alert type: Alert. then it is not refreshed and thinkScript functions are not recalculated.Ring . String sound). Valid alert type parameters are: • Alert.ONCE • sound: Sound.BAR • Alert. As a result.Ding • Sound. Take the following limitation into consideration: If the chart is inactive (detached window with the chart is minimized or subtab with the chart is not on focus in main window).Syntax alert(IDataHolder condition.NoSound alert Description Shows an alert message with the text and plays the sound when the condition is true.Bell • Sound. BAR).Above). "Tick > 200!". but less than 200 and the second alert . Sound. Average(close. "Closing price crosses over SMA!"). CrossingDirection. average(close.Example 1 alert(Crosses(close. Alert. alert(close >= 200. 15). "Bullish!". Both alerts also display a text and play sound other than default.BAR value for the alert type and default Sound. Sound.Chimes). . alert(condition. Usage in: LBR_SmartADX. 15).for each tick greater than 200. It can be triggered only once and does not play any sound. First alert is triggered for each tick greater than 100. This alert is triggered when the fast average crosses the slow average and shows the corresponding text message. This alert is triggered on the first cross of the closing price over the SMA with the length equal to 15.NoSound value for the sound. CrossingDirection. 30). Alert. because it uses Alert. "100 <= Tick < 200!". It can be triggered once per bar and does not play any sound.Above). Example 2 def condition = Crosses(Average(close.TICK.ONCE and Sound.NoSound for the alert type and sound. Example 3 alert(close >= 100 and close < 200.Ding). Alert.TICK. because it uses default values Alert. plot Data = if barNumber() <= 5 then 100 else if barNumber() == 6 or barNumber() == 7 then 150 else 200. Description Returns the current bar number. The examples draws the Data plot depending on the bar number. Usage in: DarvasBox. TPOProfile. If the number is less or equal to 5 then its value is 100. MonkeyBars. ZigZagPercent. if the number is 5 or 6 then 150. in the rest of the cases its value is 200.barNumber Syntax barNumber(). plot RSquared = Sqr(correlation(barNumber(). length)). The output value of barNumber increments by one on each new bar and represents a linear dependency. input length = 14. Example 2 declare lower. For this reason it can be used to calculate values for the RSquared plot that approximates the price with the linear regression trendline. MonkeyBarsExpanded. VolumeProfile. Example 1 declare lower. DynamicMomentumIndex. SemiCupFormation. . ZigZagSign. close. and 0 (false) if the data is outside of the two parameter values. double value1. The function returns 1 (true) if the data is between the two parameter values. double value2).0. plot Between1 = between(close.between Syntax between(double parameter. plot Between2 = close >= lowLimit and close <= highLimit. Example declare lower. Description Tests if the specified parameter is within the range of value1 and value2 inclusively. input highLimit = 160. . lowLimit. highLimit). The code will return 1 if the closing price is between lowLimit and highLimit.0. and 0 if the closing price is below lowLimit or above highLimit. input lowLimit = 140. The example also shows the alternative solution to the between function implemented using the double inequality. etc. ReverseEngineeringRSI. This function is used to initialize studies with recursion. . MonkeyBarsExpanded. Description Calculates a compound value according to following rule: if a bar number is bigger than length then the visible data value is returned. Starting from the third bar each following number is calculated as the sum of the previous two numbers while the numbers for the first two bars are equal to one. RelativeStrength. The example calculates the Fibonacci sequence. VolumeProfile. HeikinAshiDiff. 5. PositiveVolumeIndex. Usage in: CyberCyclesOscillator.compoundValue Default values: • length: 1 Syntax compoundValue(int length. rec x = compoundValue(2. MovAvgAdaptive. NegativeVolumeIndex. plot FibonacciNumbers = x. IDataHolder visible data. 1. VariableMA. IDataHolder historical data). 3. VWAP. As a result you will get a plot containing values 1. DarvasBox. otherwise the historical data value is returned. 2. MonkeyBars. LegacyEMA. 1). Example declare lower. TPOProfile. x[1] + x[2]. This example displays a constantly visible chart label with the SMA of the given symbol with the length equal to 10 rounded to one decimal place. Usage in: AdvanceDecline. Description Concatenates two string values. concat("SMA (". WoodiesCCI. SemiCupFormation. 10). round(Average(close(symbol). Any value2). concat(". 1))))). concat(symbol. 10): ". Next3rdFriday. If the values' type is not string it is first converted to a string (for doubles it saves four decimal places) Example input symbol = "IBM". AddChartLabel(yes. .concat Syntax concat(Any value1. ProfitTargetSX. Defines a selling strategy for closing a long position when either the closing price is greater than the entry price by 3 for taking profits or less by 9 for safety. Usage in: ProfitTargetLX. Description Returns the price of the entry order. . entryPrice Example declare LONG_EXIT. StopLossSX. addOrder(close > entryPrice() + 3 or close < entryPrice() 9). TrailingStopLX. TrailingStopSX. SpectrumBarsLE. ThreeBarInsideBarLE. For several entry orders in the same direction as the currently held position the function returns the average price for all of them. StopLossLX. ThreeBarInsideBarSE.Profile: Strategies Syntax entryPrice(). Usage in: MonkeyBars. . Description Returns the value of the parameter expression in the first bar. The code calculates the close price percentage move on the analogy of the Percentage View mode for charts. In this example the parameter expression for the first function is close.close1) / close1 * 100. def close1 = first(close). plot Data = (close . MonkeyBarsExpanded. VWAP. This means that the close1 variable always holds close for the first bar. TPOProfile. Example declare lower. VolumeProfile.first Syntax first(IDataHolder data). String priceType). relationWithSecurity).fundamental Syntax fundamental(int fundamentalType.e. def price1 = fundamental(price). This function should be used with one of the Fundamental Type constants to perform as the corresponding fundamental function. Any period.g. Week. aggregation period. . Month. and price type. BID (for Forex symbols only) input price = FundamentalType. i. input relationWithSecurity = "SPX". ASK. def price2 = fundamental(price. You can use both Aggregation Period constants and predefined string values (e. see the Fundamental Type constants section. The full list of the pre-defined string values can be found in the Referencing Secondary Aggregation article. For more information about these constants. Example declare lower. Valid parameters for the price type are: • LAST • MARK. 2 Days.CLOSE. etc. it returns the specified price for the chosen symbol. Day. Default values: • symbol: "<currently selected symbol>" • period: "<current period>" • priceType: "<current type>" Description This function is generalization of fundamental functions. String symbol.) as valid parameters for the aggregation period. SymbolRelation. Relation.plot Relation = if price2 == 0 then Double. Usage in: DailySMA.NaN else price1 / price2.SetDefaultColor(GetColor(1)). This script exemplifies usage of the fundamental function in the Symbol Relation study. . } else { data = Average(close. plot data. For daily and longer aggregations it calculates the average on the lengthDaily period. } The example plots the simple moving average depending on an aggregation period. input lengthDaily = 10. then it calculates the average on the lengthIntraday period. lengthIntraday). lengthDaily). Description Returns the current aggregation period in milliseconds for time charts and in ticks for tick charts. If the aggregation period is shorter than day.DAY { data = Average(close. For more information about the constants see the Constants section. The aggregation period is the number of milliseconds (ticks) required to complete a candle on the current chart time frame. Usage in: VWAP. . Example input lengthIntraday = 20. WoodiesCCI. if getAggregationPeriod() < AggregationPeriod.getAggregationPeriod Syntax getAggregationPeriod(). You can use this function in combination with aggregation period constants. plot Charge = loan * getInterestRate(). Description Returns the global interest rate.getInterestRate Syntax getInterestRate(). AddChartLabel(yes. getInterestRate() * 100)). Example declare lower. . This example draws a charge for the loan at the current interest rate displayed in the chart label. concat("Interest Rate: ". input loan = 1000. The form implies the sorting in the ascending order. getSymbolPart The code calculates the spread between the first and second parts of the composite symbol. if you specify the "KO+GE" composite then it will be represented as "GE+KO" and it's first part will be "GE". Note that the normalized form of representation is used when defining parts a composite index. Default values: • position: 1 Description Returns a part of the composite symbol. plot Spreads = close(getSymbolPart(1)) close(getSymbolPart(2)). not "KO". . For example. PairRatio. as it was during the input. Example declare lower. Usage in: PairCorrelation.Syntax getSymbolPart(int position). 12). GetMaxValueOffset(high. . Usage in: DarvasBox. ZigZagPercent. Example plot ClosingPriceForHighestHigh = getValue(close. Default values: • max offset: 0 Description Returns the value of data with the specified dynamic offset. ZigZagSign. 12).getValue Syntax getValue(IDataHolder data. MESASineWave. RandomWalkIndex. LookUpHighest. SemiCupFormation. The example draws a closing price plot for a bar where the high price was at its maximum for the last 12 bars. PolychromMtm. int max offset). IDataHolder dynamic offset. DynamicMomentumIndex. AbsValue('dynamic offset') should be less or equal than max offset. LookUpLowest. plot CurrentYield = getYield() * 100. . Description Returns the yield of the current stock or the underlying symbol for the current option. Example declare lower. getYield() * close)). AddChartLabel(yes. getYield This script plots the current yield line and places a chart label indicating annual dividends.Syntax getYield(). concat("Annual Dividends: ". g.Syntax if(double condition.DOWNTICK)).UPTICK else Color.UPTICK. double false value). if close > open { Maximum3 = close. The following script will result in compilation error as type CustomColor is not compatible with type double: if Example plot Maximum1 = if(close > open. AssignPriceColor(if(close > open. a true value and a false value. you can use it in a conjunction with else to create more complex conditions. Color. There are two ways to use the function. Note that input arguments can only be numerical of type double.g. double true value. If close is higher than open. Secondly. for CustomColor arguments. then close is drawn. } else { Maximum3 = open. Color constants). } The code draws either close or open value depending on the condition in the if-statement. First. Description Returns true value if condition is true and false value otherwise. plot Maximum2 = if close > open then close else open. use the if-expression. E. otherwise open is drawn. open). If other values are needed (e. you can use it as the right side of an equation with 3 parameters: a condition. . the following code is valid: AssignPriceColor(if close > open then Color. close.DOWNTICK). plot Maximum3. Color. Usage in: DarvasBox. . Maximum2 and Maximum3 plots use alternative solutions such as if-expression and if-statement correspondingly. Syntax tickSize(String symbol); Default values: • symbol: "<currently selected symbol>" Description Returns the minimum possible tick size for the current symbol. tickSize Initially the example draws the OverBought and OverSold plots. The OverBought plot is calculated by adding the given number of ticks to the highest price for the last 12 bars starting from previous bar. The OverSold plot is calculated the same way but by subtracting the ticks from the lowest price. If the close price is out of the area of the first two plots the code displays the BreakOut plot. Usage in: ProfitTargetLX; ProfitTargetSX; StopLossLX; StopLossSX; TrailingStopLX; TrailingStopSX; WoodiesCCI. Example input numberOfTicks = 3; plot OverBought = Highest(high)[1] + numberOfTicks * tickSize(); plot OverSold = Lowest(low)[1] - numberOfTicks * tickSize(); plot BreakOut = if Close >= OverBought then Close else if Close <= OverSold then Close else Double.NaN; Breakout.SetPaintingStrategy(PaintingStrategy.POINTS); Breakout.SetLineWeight(3); Breakout.HideBubble(); tickValue Syntax tickValue(String symbol); Default values: • symbol: "<currently selected symbol>" Description Returns the dollar value of a symbol tick. Example AddChartLabel(yes, concat("Contract size is ", tickValue()/tickSize())); In this example the contract size is calculated using the tick size and value. The thinkscript provides constants in order to be able to use the script more efficiently. For example, you can use aggregation period constants to pick an aggregation for your study. Or you can paint your chart using different color constants. o Constants Choose your constant from the list: • AggregationPeriod • Alert • ChartType • Color • CrossingDirection • Curve • Double • EarningTime • FundamentalType • OrderType • PaintingStrategy • PricePerRow • Sound 257 268 269 273 283 285 289 291 293 297 299 309 310 Aggregation period constants define a specific aggregation period for your studies and strategies. The period length varies from one minute to option expiration. o AggregationPeriod Choose an aggregation period from the list: • MIN • TWO_MIN • THREE_MIN • FOUR_MIN • FIVE_MIN • TEN_MIN • FIFTEEN_MIN • TWENTY_MIN • THIRTY_MIN • HOUR • TWO_HOURS • FOUR_HOURS • DAY • TWO_DAYS • THREE_DAYS • FOUR_DAYS • WEEK • MONTH • OPT_EXP MIN Syntax AggregationPeriod.MIN Description Defines the aggregation period equal to one minute (60,000 milliseconds). Example def agg = AggregationPeriod.MIN; plot data = close(period = agg); This example script draws the Close price plot with aggregation period equal to one minute. Note that aggregation period used in this example cannot be less than chart aggregation period. See also getAggregationPeriod function in the Others section. TWO_MIN Syntax AggregationPeriod.TWO_MIN Description Defines the aggregation period equal to two minutes (120,000 milliseconds). Example def agg = AggregationPeriod.TWO_MIN; plot data = close(period = agg); This example script draws the Close price plot with aggregation period equal to two minutes. Note that aggregation period used in this example cannot be less than chart aggregation period. See also getAggregationPeriod function in the Others section. THREE_MIN Syntax AggregationPeriod.THREE_MIN Description Defines the aggregation period equal to three minutes (180,000 milliseconds). This example script draws the Close price plot with aggregation period equal to three minutes. Note that aggregation period used in this example cannot be less than chart aggregation period. See also getAggregationPeriod function in the Others section. Example def agg = AggregationPeriod.THREE_MIN; plot data = close(period = agg); FOUR_MIN Syntax AggregationPeriod.FOUR_MIN Description Defines the aggregation period equal to four minutes (240,000 milliseconds). Example def agg = AggregationPeriod.FOUR_MIN; plot data = close(period = agg); This example script draws the Close price plot with aggregation period equal to four minutes. Note that aggregation period used in this example cannot be less than chart aggregation period. See also getAggregationPeriod function in the Others section. 000 milliseconds). See also getAggregationPeriod function in the Others section. TEN_MIN Syntax AggregationPeriod.000 milliseconds). This example script draws the Close price plot with aggregation period equal to five minutes. This example script draws the Close price plot with aggregation period equal to ten minutes.FIVE_MIN Syntax AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period. Note that aggregation period used in this example cannot be less than chart aggregation period. . plot data = close(period = agg). Example def agg = AggregationPeriod.FIVE_MIN Description Defines the aggregation period equal to five minutes (300. plot data = close(period = agg).TEN_MIN.FIVE_MIN. Example def agg = AggregationPeriod.TEN_MIN Description Defines the aggregation period equal to ten minutes (600. See also getAggregationPeriod function in the Others section. . Example def agg = AggregationPeriod. This example script draws the Close price plot with aggregation period equal to twenty minutes. TWENTY_MIN Syntax AggregationPeriod.TWENTY_MIN Description Defines the aggregation period equal to twenty minutes (1. Example def agg = AggregationPeriod.000 milliseconds). Note that aggregation period used in this example cannot be less than chart aggregation period.FIFTEEN_MIN Syntax AggregationPeriod.FIFTEEN_MIN. See also getAggregationPeriod function in the Others section. plot data = close(period = agg). plot data = close(period = agg).TWENTY_MIN.200. This example script draws the Close price plot with aggregation period equal to fifteen minutes.000 milliseconds).FIFTEEN_MIN Description Defines the aggregation period equal to fifteen minutes (900. See also getAggregationPeriod function in the Others section. Note that aggregation period used in this example cannot be less than chart aggregation period. THIRTY_MIN Syntax AggregationPeriod.800. See also getAggregationPeriod function in the Others section. Example def agg = AggregationPeriod.600.THIRTY_MIN Description Defines the aggregation period equal to thirty minutes (1.000 milliseconds).THIRTY_MIN.HOUR.000 milliseconds). HOUR Syntax AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period. plot data = close(period = agg). . This example script draws the Close price plot with aggregation period equal to thirty minutes. plot data = close(period = agg). Note that aggregation period used in this example cannot be less than chart aggregation period. This example script draws the Close price plot with aggregation period equal to one hour.HOUR Description Defines the aggregation period equal to one hour (3. See the getAggregationPeriod function in the Others section. Example def agg = AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period.FOUR_HOURS. plot data = close(period = agg). FOUR_HOURS Syntax AggregationPeriod.FOUR_HOURS Description Defines the aggregation period equal to four hours (14.TWO_HOURS Description Defines the aggregation period equal to two hours (7. plot data = close(period = agg). This example script draws the Close price plot with aggregation period equal to two hours. This example script draws the Close price plot with aggregation period equal to four hours.000 milliseconds).400.200. Note that aggregation period used in this example cannot be less than chart aggregation period. Example def agg = AggregationPeriod. See also getAggregationPeriod function in the Others section.TWO_HOURS Syntax AggregationPeriod.000 milliseconds). See also getAggregationPeriod function in the Others section. Example def agg = AggregationPeriod.TWO_HOURS. . 400.DAY. This example script draws the Close price plot with aggregation period equal to two days.DAY Description Defines the aggregation period equal to one day (86. See also getAggregationPeriod function in the Others section.800. See also getAggregationPeriod function in the Others section.DAY Syntax AggregationPeriod. This example script draws the daily Close price plot.TWO_DAYS Description Defines the aggregation period equal to two days (172. .000 milliseconds). TWO_DAYS Syntax AggregationPeriod. plot data = close(period = agg).000 milliseconds). Note that aggregation period used in this example cannot be less than chart aggregation period.TWO_DAYS. Example def agg = AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period. plot data = close(period = agg). Example def agg = AggregationPeriod. THREE_DAYS Syntax AggregationPeriod. plot data = close(period = agg). plot data = close(period = agg).600. This example script draws the Close price plot with aggregation period equal to three days. See also getAggregationPeriod function in the Others section. Example def agg = AggregationPeriod.FOUR_DAYS Description Defines the aggregation period equal to four days (345.THREE_DAYS Description Defines the aggregation period equal to three days (259. Note that aggregation period used in this example cannot be less than chart aggregation period. Note that aggregation period used in this example cannot be less than chart aggregation period.THREE_DAYS. FOUR_DAYS Syntax AggregationPeriod.000 milliseconds). This example script draws the Close price plot with aggregation period equal to four days.FOUR_DAYS.000 milliseconds) Example def agg = AggregationPeriod.200. . See also getAggregationPeriod function in the Others section. WEEK.000 milliseconds). See also getAggregationPeriod function in the Others section. Note that aggregation period used in this example cannot be less than chart aggregation period. .WEEK Syntax AggregationPeriod. plot data = close(period = agg).WEEK Description Defines the aggregation period equal to one week (604. See also getAggregationPeriod function in the Others section. MONTH Syntax AggregationPeriod.000.MONTH. This example script draws the weekly Close price plot.800.MONTH Description Defines the aggregation period equal to one month (2. plot data = close(period = agg).000 milliseconds) Example def agg = AggregationPeriod. This example script draws the Close price plot with aggregation period equal to one month.592. Example def agg = AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period. OPT_EXP Syntax AggregationPeriod. Note that aggregation period used in this example cannot be less than chart aggregation period. Example def agg = AggregationPeriod. This example script draws the Close price plot with aggregation period equal to option expiration.OPT_EXP. See also getAggregationPeriod function in the Others section. .400.OPT_EXP Description Defines the aggregation period equal to option expiration (2.000 milliseconds).678. plot data = close(period = agg). o Alert Choose an alert constant from the list: • BAR • ONCE • TICK .Alert constants represent different types of alerts for the alert function. ONCE Syntax Alert. TICK Syntax Alert.BAR Syntax Alert.ONCE Description Defines the alert that can be triggered only once after adding a study. .BAR Description Defines the alert that can be triggered only once per bar. Example See the alert function in the Others section. Example See the alert function in the Others section. Example See the alert function in the Others section.TICK Description Defines the alert that can be triggered after each tick. Syntax ChartType.In this section you will find information on the constants used in setChartType function. Example See the setChartType article in the Look and Feel functions section.CANDLE Description Used in setChartType function to set the Candle chart type. • BAR • CANDLE • CANDLE_TREND • HEIKIN_ASHI • LINE • AREA o ChartType BAR Example See the setChartType article in the Look and Feel functions section. . CANDLE Syntax ChartType.BAR Description Used in setChartType function to set the Bar chart type. Syntax ChartType.HEIKIN_ASHI Description Used in setChartType function to set the Heikin Ashi chart type.LINE Description Used in setChartType function to set the Line chart type. Example See the setChartType article in the Look and Feel functions section. Syntax ChartType. . CANDLE_TREND Example See the setChartType article in the Look and Feel functions section. HEIKIN_ASHI Syntax ChartType.CANDLE_TREND Description Used in setChartType function to set the Candle Trend chart type. LINE Example See the setChartType article in the Look and Feel functions section. Syntax ChartType. .AREA Example See the setChartType article in the Look and Feel functions section.AREA Description Used in setChartType function to set the Area chart type. .The thinkScript provides the set of constants for colors. o Color Here is the full list of the colors: • BLACK • BLUE • CURRENT • CYAN • DARK_GRAY • DARK_GREEN • DARK_ORANGE • DARK_RED • DOWNTICK • GRAY • GREEN • LIGHT_GRAY • LIGHT_GREEN • LIGHT_ORANGE • LIGHT_RED • LIME • MAGENTA • ORANGE • PINK • PLUM • RED • UPTICK • VIOLET • WHITE • YELLOW Example See the SetDefaultColor function in the Look and Feel functions section. 0). . Sample BLUE Syntax Color. When using the AssignPriceColor function the constant is responsible for price bars color.BLACK Syntax Color. In combintaion with the AssignBackgroundColor function the constant defines the corresponding background color. 255). Its RGB representation is (0. 0.CURRENT Description Refers to the default plot color (or redefined color in case it was changed on the UI).BLUE Description Defines the blue color. 0. Sample CURRENT Syntax Color.BLACK Description Defines the black color. Its RGB representation is (0. 255.CYAN Description Defines the cyan color. Sample DARK_GRAY Syntax Color. 0). 64. Its RGB representation is (64. Its RGB representation is (0.CYAN Syntax Color.DARK_GREEN Description Defines the dark green color. 100. Its RGB representation is (0. Sample . Sample DARK_GREEN Syntax Color. 64).DARK_GRAY Description Defines the dark gray color. 255). DOWNTICK Description Defines the downtick color.DARK_RED Description Defines the dark red color. Sample DARK_RED Syntax Color.DARK_ORANGE Description Defines the dark orange color. 0). Sample . 0). Its RGB representation is (255. 127. 0. 0. Its RGB representation is (128. 0). Sample DOWNTICK Syntax Color.DARK_ORANGE Syntax Color. Its RGB representation is (204. Its RGB representation is (128. Sample . 255.GRAY Description Defines the gray color.GRAY Syntax Color. Sample LIGHT_GRAY Syntax Color. 0).GREEN Description Defines the green color. 192. Its RGB representation is (0. 192). Sample GREEN Syntax Color. 128.LIGHT_GRAY Description Defines the light gray color. 128). Its RGB representation is (192. LIGHT_RED Description Defines the light red color.LIGHT_GREEN Description Defines the light green color. Sample LIGHT_GREEN Syntax Color.LIGHT_GREEN Syntax Color. Sample . 114). 238.LIGHT_GREEN Description Defines the light green color. Its RGB representation is (144. 238. Its RGB representation is (255. 114). Its RGB representation is (144. 0). 63. Sample LIGHT_RED Syntax Color. ORANGE Description Defines the orange color. Its RGB representation is (255. Sample MAGENTA Syntax Color.LIME Syntax Color. Its RGB representation is (191. 200.LIME Description Defines the lime color.MAGENTA Description Defines the magenta color. 0. 255. Sample ORANGE Syntax Color. 0). 255). 0). Sample . Its RGB representation is (255. Description Defines the plum color. 0.RED Description Defines the red color. Sample Sample RED Syntax Color. . Its RGB representation is (128.PINK Syntax Color. 0). 128).PLUM. 175). Sample PLUM Syntax Color. Its RGB representation is (255. 175. 0. Its RGB representation is (255.PINK Description Defines the pink color. Its RGB representation is (153. 255). 153. Sample VIOLET Syntax Color. Sample .VIOLET Description Defines the violet color. Sample WHITE Syntax Color. Its RGB representation is (255. 255).UPTICK Syntax Color. 0). Its RGB representation is (3.WHITE Description Defines the white color.UPTICK Description Defines the uptick color. 128. 255. 0).YELLOW Description Defines the yellow color. Sample . Its RGB representation is (255. 255.YELLOW Syntax Color. CrossingDirection. Choose a crossing direction constant from the list: • Above • Below • Any o CrossingDirection Above Example plot avg = Average(close. 10). Note that this constant can be replaced with reserved word yes.SetPaintingStrategy(PaintingStrategy. avg. This code marks the bars at which the Close price gets higher than its 10 period average.Above Description This constant is used with the Crosses function to find when the first value becomes greater than the second. Syntax CrossingDirection.Above).BOOLEAN_ ARROW_UP). . plot crossing = Crosses(close.Crossing direction constants define a specific switch of the relationship between arguments of the Crosses function. crossing. Below Description This constant is used with the Crosses function to find when the first value becomes less than the second. plot crossing = Crosses(close. This code marks the bars at which the Close price becomes less than its 10 period average.SetPaintingStrategy(PaintingStrategy. Note that this constant can be replaced with reserved word no.BOOLEAN_ ARROW_DOWN). Example plot avg = Average(close. crossing. 10). crossing. Any Syntax CrossingDirection.Any). . CrossingDirection. avg. plot crossing = Crosses(close. 10). Example plot avg = Average(close.Below Syntax CrossingDirection.Below).Any Description Defines the change of relation of two values in the Crosses function irrespective of its direction.BOOLEAN_ ARROW_UP). CrossingDirection. This code marks the bars at which the Close price becomes greater or less than its 10 period average. avg.SetPaintingStrategy(PaintingStrategy. The thinkscript contains the set of constants for curves. o Curve Choose your constant from the list: • FIRM • LONG_DASH • MEDIUM_DASH • SHORT_DASH • POINTS . Sample Example See the SetStyle function in the Look and Feel functions section. LONG_DASH Syntax Curve.FIRM Syntax Curve.FIRM Description Defines the firm style curve constant. .LONG_DASH Description Defines the style of curve with long dashes. Sample Example See the SetStyle function in the Look and Feel functions section. Sample Example See the SetStyle function in the Look and Feel functions section. Sample Example See the SetStyle function in the Look and Feel functions section. . SHORT_DASH Syntax Curve.MEDIUM_DASH Syntax Curve.SHORT_DASH Description Defines the style of curve with short dashes.MEDIUM_DASH Description Defines the style of curve with medium-size dashes. POINTS Description Defines the points style curve constant. Sample Example See the SetStyle function in the Look and Feel functions section.POINTS Syntax Curve. . Choose a constant from the list: • E • NaN • Pi o Double .This section describes mathematical constants such as exponent or pi. E Syntax Double. Example (Price Oscillator) See the exp function in the Mathematical and Trigonometrical functions section. Sin.Pi Description Returns the value of the pi constant.E Description Returns the value of the exponent constant. ACos. and Cos functions in the Mathematical and Trigonometrical functions section.NaN Description Returns the value that indicates that the result of an operation is not a number. Pi Syntax Double. Example (Price Oscillator) See the ASin. Example (Price Oscillator) See the isNaN function in the Mathematical and Trigonometrical functions section. NaN Syntax Double. . or during market hours. BEFORE_MARKET Example See the hasEarnings article in the Corporate Actions functions section. or after market close.ANY Description Used with hasEarnings function to query whether there are announced earnings.BEFORE_MARKET Description Used with hasEarnings function to query whether the earnings announcement takes place before market open.In this section you will find information on the constants used with hasEarnings function. . The announcement can take place before market open. Syntax EarningTime. Example See the hasEarnings article in the Corporate Actions functions section. or at unspecified time. • ANY • BEFORE_MARKET • AFTER_MARKET o EarningTime ANY Syntax EarningTime. AFTER_MARKET Example See the hasEarnings article in the Corporate Actions functions section. Syntax EarningTime.AFTER_MARKET Description Used with hasEarnings function to query whether the earnings announcement takes place after market close. . LOW Description Used with fundamental function to return the Low price.HIGH Description Used with fundamental function to return the High price.In this section you will find information on the constants used in fundamental function. Example See the fundamental function article in the Others section. • HIGH • LOW • CLOSE • OPEN • HL2 • HLC3 • OHLC4 • VWAP • VOLUME • OPEN_INTEREST • IMP_VOLATILITY o FundamentalType HIGH Syntax FundamentalType. Example See the fundamental function article in the Others functions section. . LOW Syntax FundamentalType. Example See the fundamental function article in the Others section. HL2 Syntax FundamentalType. . OPEN Syntax FundamentalType.HL2 Description Used with fundamental function to return the arithmetical mean of High and Low prices.CLOSE Description Used with fundamental function to return the Close price. Example See the fundamental function article in the Others section.CLOSE Syntax FundamentalType. Example See the fundamental function article in the Others section.OPEN Description Used with fundamental function to return the Open price. VWAP Syntax FundamentalType. Low. OHLC4 Syntax FundamentalType. Open. Example See the fundamental function article in the Others section.HLC3 Description Used with fundamental function to return the arithmetical mean of High. .VWAP Description Used with fundamental function to return the volume weighted average price value.HLC3 Syntax FundamentalType. and Close prices. Low. Example See the fundamental function article in the Others section.OHLC4 Description Used with fundamental function to return the arithmetical mean of High. and Close prices. Example See the fundamental function article in the Others section. Example See the fundamental function article in the Others section. IMP_VOLATILITY Syntax FundamentalType.VOLUME Description Used with fundamental function to return the volume value. OPEN_INTEREST Syntax FundamentalType. Example See the fundamental function article in the Others section.OPEN_INTEREST Description Used with fundamental function to return the open interest value. . Example See the fundamental function article in the Others section.IMP_VOLATILITY Description Used with fundamental function to return the implied volatility value.VOLUME Syntax FundamentalType. In this section you will find information on the constants used in addOrder function. see the Strategy Properties article for details.BUY_TO_CLOSE Description Used in addOrder function to add a buying order for closing a short position. BUY_AUTO Syntax OrderType. Example See the addOrder article in the Others section. • BUY_AUTO • BUY_TO_CLOSE • SELL_AUTO • SELL_TO_CLOSE o OrderType Syntax OrderType. see the Strategy Properties article for details.BUY_AUTO Description Used in addOrder function to add a buying order for entering a new long position or closing a short position. Note that you can switch order to BUY_AUTO by customizing strategy properties. BUY_TO_CLOSE . Example See the addOrder article in the Others section. Note that you can switch order to BUY_TO_CLOSE by customizing strategy properties. see the Strategy Properties article for details. Note that you can switch order to SELL_TO_CLOSE by customizing strategy properties. Example See the addOrder article in the Others section. Example See the addOrder article in the Others section.Syntax OrderType.SELL_TO_CLOSE Description Used in addOrder function to add a selling order for closing a long position. Note that you can switch order to SELL_AUTO by customizing strategy properties.SELL_AUTO Description Used in addOrder function to add a selling order for entering a new short position or closing a long position. SELL_AUTO Syntax OrderType. see the Strategy Properties article for details. SELL_TO_CLOSE . The constants in this section define painting strategy styles. o PaintingStrategy Here is the list of the constants: • ARROW_DOWN • ARROW_UP • BOOLEAN_ARROW_DOWN • BOOLEAN_ARROW_UP • BOOLEAN_POINTS • DASHES • HISTOGRAM • HORIZONTAL • LINE • LINE_VS_POINTS • LINE_VS_SQUARES • LINE_VS_TRIANGLES • POINTS • SQUARED_HISTOGRAMadded • SQUARES • TRIANGLES • VALUES_ABOVE • VALUES_BELOW . ARROW_UP Syntax PaintingStrategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.Sample Syntax PaintingStrategy.ARROW_UP Description Defines the arrow up painting strategy. . ARROW_DOWN Example See the SetPaintingStrategy function in the Look and Feel section.ARROW_DOWN Description Defines the arrow down painting strategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.BOOLEAN_ARROW_UP Description Defines the boolean arrow up painting strategy. . It supposes that a plot computes logical values and only true values are displayed as arrows down above the current high price.BOOLEAN_ARROW_DOWN Syntax PaintingStrategy. BOOLEAN_ARROW_UP Syntax PaintingStrategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.BOOLEAN_ARROW_DOWN Description Defines the boolean arrow down painting strategy. It supposes that a plot computes logical values and only true values are displayed as arrows up below the current low price. DASHES Description Defines the dashes painting strategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.BOOLEAN_POINTS Syntax PaintingStrategy. DASHES Syntax PaintingStrategy. . It supposes that a plot computes logical values and only true values are displayed as points at the current closing price. Sample Example See the SetPaintingStrategy function in the Look and Feel section.BOOLEAN_POINTS Description Defines the boolean points painting strategy. HORIZONTAL Description Defines the painting strategy with long segments forming a continuous line when the study has the same value for adjacent bars. and Profile Low plots by profile studies (TPOProfile. Value Area High. Profile High. HORIZONTAL Syntax PaintingStrategy. VolumeProfile. Value Area Low. MonkeyBars). Sample Example This painting strategy is used to draw Point of Control.HISTOGRAM Syntax PaintingStrategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section. .HISTOGRAM Description Defines the histogram painting strategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section. . Syntax PaintingStrategy. Sample LINE_VS_POINTS Example See the SetPaintingStrategy function in the Look and Feel section.LINE Syntax PaintingStrategy.LINE_VS_POINTS Description Defines the line and points painting strategy.LINE Description Defines the line painting strategy. LINE_VS_TRIANGLES Description Defines the line and triangles painting strategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.LINE_VS_SQUARES Syntax PaintingStrategy. LINE_VS_TRIANGLES Syntax PaintingStrategy. . Sample Example See the SetPaintingStrategy function in the Look and Feel section.LINE_VS_SQUARES Description Defines the line and squares painting strategy. Syntax PaintingStrategy. . its adjacent columns are not divided.SQUARED_HISTOGRAM Description Defines the painting strategy where study values are represented as a histogram with wide columns. Unlike the basic HISTOGRAM painting strategy. Sample SQUARED_HISTOGRAM Example See the SetPaintingStrategy function in the Look and Feel section.POINTS Description Defines the points painting strategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.POINTS Syntax PaintingStrategy. Sample Example See the SetPaintingStrategy function in the Look and Feel section.SQUARES Description Defines the painting strategy with squares marking study values. Syntax PaintingStrategy.TRIANGLES Description Defines the painting strategy with triangles marking study values. . Sample TRIANGLES Example See the SetPaintingStrategy function in the Look and Feel section.SQUARES Syntax PaintingStrategy. .VALUES_ABOVE Description Defines a painting strategy which draws numeric plot values above the current high price. Syntax PaintingStrategy.VALUES_BELOW Description Defines a painting strategy which draws numeric plot values below the current low price. For more information about the constant. Sample VALUES_BELOW Example See the SetPaintingStrategy function in the Look and Feel section.VALUES_ABOVE Syntax PaintingStrategy. For more information about the constant. see the Sequential study definition. see the Sequential study definition. Sample Example See the SetPaintingStrategy function in the Look and Feel section. the height of a row is computed to have a total number of rows equal to 50 for Monkey Bars and 85 for others. . the height of a row is equal to the minimal price change for the current symbol.AUTOMATIC Description Defines the "height" (price range) of each row of the profile. o PricePerRow Choose a constant from the list: • AUTOMATIC • TICKSIZE Syntax PricePerRow. When this constant is specified.TICKSIZE Description Defines the "height" (price range) of each row of the profile. AUTOMATIC TICKSIZE Syntax PricePerRow. Note that this constant can only be used in conjunction with the Profile functions. Note that this constant can only be used in conjunction with the Profile functions.The constants described in this section are used in combination with the profile functions to define a price range. When this constant is specified. NoSound Description Defines the no sound constant.The thinkscript provides the set of constants for sounds. The constants can be used in combination with alert constants to create alerts. Example See the alert function in the Others section.Bell Description Defines the bell sound constant. o Sound Choose a sound from the list: • NoSound • Bell • Ding • Ring • Chimes NoSound Syntax Sound. . Bell Syntax Sound. Example See the alert function in the Others section. Ring Description Defines the ring sound constant. Chimes Syntax Sound. . Ring Syntax Sound.Ding Description Defines the ding sound constant.Ding Syntax Sound. Example See the alert function in the Others section. Example See the alert function in the Others section. Example See the alert function in the Others section.Chimes Description Defines the chimes sound constant. Thinkscript functions receive arguments of different data types as parameters. o Data Types Here is the full list of the data types: • Any • boolean • CustomColor • double • IDataHolder • int • String • Data Conversion 313 313 313 313 313 313 314 . for example. o boolean Description Logical value .o Any Description Value of any data type from this section. Double quotes are used to mark text constants. for example 5. "TEXT".true (yes) or false (no). o int Description o String An integer number.RED. for example 1. consisting of floating point values. . for example.02. 0. close or volume. o double Description A floating point number. Color. For example. except for CustomColor. Description A string of text. for example. o CustomColor Description Color value. o IDataHolder Description An array of data.5. Note that you can drop the zero integer part and start the notation from the radix point.02 can also be written as . String Data Accepted - Conversion Rule 0 (0. IDataHolder. no to 0. boolean. IDataHolder equal to that number. int String yes is converted to 1. int.thinkScript enables you to pass a data type value other than the one specified in a function. double. double. Logical int values are preliminary converted to numerical. converted to no (false). boolean.0. In this case the parameter is automatically converted to the desired data type. Non-integer numbers are IDataHolder rounded towards zero.NaN are double. - . other IDataHolder. no to IDataHolder.0. o Data Conversion Any Argument boolean double CustomColor - boolean. int 0.0) and Double. A number is converted to an array whose elements are all boolean. int numbers to yes (true). double. yes is converted to 1. o Operators Here is the full list of the data types: • Arithmetic • Comparison • Conditional • Indexing • Logical • Operator Precedence 316 317 319 320 321 323 .Thinkscript functions receive arguments of different data types as parameters. high. . concat("Day ". getDay())). 25th. day of the year. etc. Example declare hide_on_intraday. 45th..o Arithmetic Description The thinkscript contains the following logical operators: + * / Operator Description subtraction division remainder addition multiplication % All arithmetic operators are binary. Draws a cloud near the 5th. AddChartBubble(getDay() % 20 == 5. crosses above crosses above greater than or equal to crosses below crosses below . Comparison operators can be applied only to numeric data. refer to the crosses reserved word article. crosses above. Example 1 plot uptick = close > close[1]. plot downtick = close < close[1].o Comparison Description The thinkscript contains the following comparison operators: == != < > <> <= >= equals Operator equals equals Description not equals not equals less than between crosses between crosses greater than less than or equal to All of these operators except for between are binary. For information on using crosses. These operators return yes or no depending whether the corresponding condition is satisfied or not. and crosses below operators. plot neutral = close equals close[1]. The x between y and z statement is equal to the y <= x and x <= z statement. if (StudyType == StudyType.SetPaintingStrategy(PaintingStrategy. } Marks bars with different signs depending whether the Close value was less. length).BOOLEAN_AR ROW_DOWN).BOOLEAN_POINTS).uptick. neutral.SetPaintingStrategy(PaintingStrategy.close) <= (high . This example uses a condition operator to choose an averaging function and to set the hiding setting of a label. AddChartLabel(StudyType != StudyType. .SMA) { Avg = Average(price."). plot Avg. Example 2 input price = close. Doji.SetPaintingStrategy(PaintingStrategy.SMA. Example 3 input percent = 5.BOOLEAN_ARRO W_UP). "Exponential moving average is displayed. length). downtick. plot Doji = AbsValue(open . } else { Avg = ExpAverage(price.low) * percent / 100.BOOLEAN_POIN TS).SetPaintingStrategy(PaintingStrategy. input StudyType = {default SMA. This example tests if the difference between the Open and Close prices does not exceed a specific percentage of the price spread. equal or greater than the previous one. EMA}. input length = 12. .the third. Example input price = close. otherwise . if long_average then 26 else 12). If the statement is true. The first operand is interpreted as a logical statement. input long_average = yes. plot SimpleAvg = Average(price. The value passed to the averaging function is defined depending on the long_average parameter.o Conditional Description The conditional operator if-then-else also known as the ifstatement is applied to three values. then the result of the operator equals the second operand. . For more information. plot FuturePrice = price[-shift]. indicator outputs. The square brackets indicate the shift against the current moment.o Indexing Description The indexing operator [] is used to access the previous or future data in an array of data. function outputs. Draws shifted price plots. input shift = 5. etc. variables. Shows the smoothed MACD value 10 bars ago.Avg[10]. see the Referencing Historical Data article. The positive values of the shift represent the values in the past. The indexing operator can be applied to fundamental data. Note that you can also use verbal syntax when referencing historical data. plot PastPrice = price[shift]. Example 2 plot PastMACD = MACD(). Example 1 input price = close. the negative shift values represent the values in the future. Zero(0) is interpreted as a false value.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARRO W_DOWN). Example 1 plot LocalMinimum = low < low[1] and low < low[-1]. LocalMinimum. Highlights local minumums of the lowest price. .SetPaintingStrategy(PaintingStrategy. Highlights moments. signal.BOOLEA N_ARROW_UP). Note that all logic operators except for negation are binary. Example 2 plot signal = open == high or close == high. Logical OR is true when at least one argument is true. Consider the following rules when using the logical operators: Logical NOT is true when the argument is false.o Logical Description The thinkscript contains the following logical operators: ! Operator Description and. && or logical AND logical OR logical NOT Logical operators can be applied only to numeric data. all other values are interpreted as a true value. when the open or close price is the highest. Logical AND is true when both arguments are true. AddChartBubble(bubble and barNumber() == 1. Example 3 input bubble = yes. AddChartLabel(!bubble. . "Displaying a bubble"). "Displaying a label"). high.Draws a cloud or label near the first bar depending on the parameter. The label is displayed when the the bubble parameter is set to no. >=. % +. crosses and. <>. && The between operator has the precedence lower than the addition and subtraction operators and higher than the conditional operator. crosses below. ! or if [].The precedence of thinkScript operators is shown in the following table: o Operator Precedence 1 2 3 4 5 6 7 8 Precedence Operator *. equals. <. from ==. >. . crosses above. /. !=. <=. thinkScript Integration • thinkScript Integration o Conditional Orders o Custom Quotes o Study Alerts o Study Filters 325 327 329 331 .In this section you will find information on thinkScript integration with thinkorswim desktop functionality. Now you are ready to set order rules. constant plots are not included in the Plots list. Rules for the order submission can be set in the Submit at Specified Market Condition form. The Order Rules window will appear.. you can choose triggering direction relative to threshold value. you are not restricted to use a single pre-defined study to place conditional orders. You can also use a combination of studies or implement a new one right away. choose Complex Formula from the Trigger Type list. After typing in the desirable symbol name. Conditional Orders are automatically placed when a studybased condition is fulfilled. 1. For numerical plots. o Conditional Orders How to Find It: . make sure that Trigger Type is Study Value and choose a desirable study from the Study list.g. painting strategies. colors. The editor window will appear. click on the Method cell and choose "STUDY" from the drop-down list." to open the Study Order Condition window. For boolean plots. For that purpose. you can specify whether to submit the order when the value is true or false. Use one of the pre-defined studies from the quick list or choose "Edit. The interface allows you to specify the study plot whose values will be analyzed. input parameters.. However. You can use both pre-defined and custom studies whose values will be analyzed to place the order. If you prefer to use a pre-defined (or previously created) study for that purpose. etc. Note that Look and Feel inputs (e. Click the "gear-and-plus" icon on the right-hand side of the Order Entry form. and aggregation period.3. 2.) are not available in Conditional Orders. such as HighestAll) are not allowed. • rec variables are not allowed. Here is a list of thinkScript usage peculiarities when applied to Conditional Orders: • You are free to use bid and ask functions. • Studies must have exactly one plot. you can use either a regular study or an expression. it checks whether the price is above the 60 period EMA and 14 period ADX value is higher than 18. Specific Usage In Conditional Orders. choose FALSE. 60) and ADX(length = 14) > 18 . which could possibly mean that the market is in strong uptrend. click OK in the lower right corner of the window. choose TRUE from the Trigger If list. If you would like to automatically place an order when this condition fulfills. Once you have set the rules for the conditional order. If you however prefer to place the order when the condition is not satisfied. Example Consider the following script: close > expaverage(close.This condition is used in the Volume Zone Oscillator study. • Range-dependent functions (dealing with data from the whole chart. the interface allows you to specify the study plot whose values will be analyzed.these can be set in the right section of the editor window.. For pre-defined studies. Right-click on the upper row of the watchlist and choose Customize. Also.When watching market quotes. In order to do that. from the menu appeared. click the empty cell in the bottom of the column and type symbol's name in it. make sure you are using a convenient name for the study. Example To add a 60 day simple moving average.. Add as many symbols as you wish to the Symbol column. you can replace it with another one by . and aggregation period . input parameters. use the following script: SimpleMovingAvg() After that. Click the MarketWatch tab and choose Quote from the subtab row. o Custom Quotes 1. Add a Custom item (or several) to the current set .one for each value to be calculated. choose "Day" from the Aggregation list and set the length input parameter equal to 60. which can be specified within the Column name string. Click the "script" icon next to it to call the Custom Quote Formula editor window. aggregation period can be set using the Aggregation list. Note that once a predefined study is added. you might need immediate calculation of certain studies for one or several symbols. 2. 3. You can use thinkScript integration feature in Custom Quotes for that purpose. How to Find It: Now you are ready to create a study whose values will be displayed in your watchlist. For custom studies. 4. • rec variables are not allowed.Momentum(length = period2). def period2 = 10.choosing the corresponding name from the Study list which is now active. This script calculates the difference between 40 and 10 period Momentum values. You can also use a custom study. and AssignBackgroundColor() have specific usage. • Studies must have exactly one plot. and Option view at All Products under the Trade tab. plot a = Momentum(length = period1) . def period1 = 40. Scan results. thinkScript usage is somewhat different from that in studies and strategies. • Range-dependent functions (dealing with data from the whole chart. click OK. the standard thinkScript syntax is also supported in Custom Quotes formulas. Custom Quotes are also available for watchlists in Watchlist gadget. SetDefaultColor(). As you can see. . Once you have set the Custom Quote formula. study values will appear in the column with the corresponding name. Here is the list of peculiarities: • You are free to use bid and ask functions. such as HighestAll) are not allowed. Consider the following example: Specific Usage When in Custom Quotes. Note that you can adjust calculation rules by right-clicking the column name and choosing Edit formula from the menu. • Functions AssignValueColor(). etc. You can also use a combination of studies or implement a new one right away. you are not restricted to using a single pre-defined study to generate alert signals. However. o Study Alerts 1. 60) and ADX(length = 14) > 18 This condition is used in the Volume Zone Oscillator study. input parameters. How to Find It: Now you are ready to set alert rules. The Study Alerts window will appear. Click the Study Alert button. The interface allows you to specify the study plot whose values will be analyzed. If you prefer to use a predefined (or previously created) study for that purpose. it checks whether the price is above the 60 period EMA and 14 period ADX value is higher than 18. Choose the symbol to issue alerts for.g. The thinkScript editor will appear.) are NOT available in "Study Alerts". colors. 2. choose Complex Formula from the Trigger Type list. painting strategies. Example Consider the following script: close > expaverage(close.Study Alerts are signals generated when a study-based condition is fulfilled. You can use both pre-defined and custom studies whose values will be analyzed to issue the alert. Note that Look and Feel inputs (e. you can specify whether to issue the alert when the value is true or false. you can choose triggering direction relative to threshold value. 3. Click the MarketWatch tab and choose Alerts from the subtab row. For numerical plots. For boolean plots. For that purpose. which could possibly mean . and aggregation period. choose a desirable one from the Study list. constant plots are not included in the Plots list. that the market is in strong uptrend. you can use either a regular study or an expression. Specific Usage In Study Alerts. click Create Alert in the lower right corner of the window. If you however prefer to place the order when the condition is not satisfied. • Range-dependent functions (dealing with data from the whole chart. • Studies must have exactly one plot. • rec variables are not allowed. Here is a list of thinkScript usage peculiarities when applied to Study Alerts: • You are free to use bid and ask functions. choose TRUE from the Trigger If list. Once you have set the rules for the alert. . choose FALSE. If you would like to be notified when this condition fulfills. such as HighestAll) are not allowed. The first field of the editor allows you to choose a custom or pre-defined study to filter the results. 60) and ADX(length = 14) > 18 . Click the Add Study Filter button. it checks whether the price is above the 60 period EMA and 14 period ADX value is higher than 18.How to Find It: 1. Example Consider the following script: The Stock Hacker Scanning Tool allows you to search for symbols meeting certain criteria. Study filters are criteria based on study values: adding one or several study filters will help you narrow the search range when looking for symbols. 3. 4. close > expaverage(close. and click Scan afterwards. pre-defined study filters might be insufficient to your search. A new filter editor will appear. Now you are ready to set the custom filter rules using thinkScript. Choose Custom from the study list. 2. this will open the Scanner Custom Filter editor window. Choose the desirable study. Search results will be shown in the watchlist form below the Criteria section. You can use up to ten filters to scan the market. adjust input parameters. o Study Filters This condition is used in the Volume Zone Oscillator study. Click OK save the filter and then press Scan to display all symbols meeting this criterion. However. which could possibly mean that the market is in strong uptrend. Click the Scan tab and choose Stock Hacker from the subtab row. Note that search criteria can be adjusted by pressing the "pencil" icon in the filter. For more information on that. • Scripts using standard thinkScript syntax must have exactly one plot. press the "cross" icon. 15). which means that you can display custom quotes along with standard values. Note also that search results are displayed in the watchlist form. refer to the Custom Quotes article. This example script searches for symbols which were above simple moving average two days ago. Specific Usage When in Stock Hacker. thinkScript usage is somewhat different from that in studies and strategies. but have fallen below since then. . Here is the list of peculiarities: • Secondary aggregation is not allowed: all studies have aggregation period equal to one day. plot condition = close[2] > SMA[2] and close[1] < SMA[1] and close < SMA.You can also use plot values in Study Filters: def SMA = Average(close. To delete a filter. • Getting Started o Writing Your First Script  Defining Plots  Defining Variables  Def Variables  Rec Variables  Rec Enumerations  Using Functions  Formatting Plots  Adjusting Parameters Using Inputs  Accessing Data  Using Strategies o Advanced Topics 19  Concatenating Strings  Creating Local Alerts  Referencing Data  Referencing Secondary Aggregation  Referencing Historical Data  Referencing Other Price Type Data  Referencing Other Studies  Referencing Other Symbol's Data  Past Offset  Using Profiles 4 5 . • o Reserved Words  above   ago   and   bar   bars   below   between   case   crosses   declare  Reference o Declarations  all_for_one  hide_on_daily  hide_on_intraday  lower  on_volume o Functions  Fundamentals  ask  bid  close  high  hl2 def default do else equals fold from if input boolean 35 37  Option Related 92  delta  gamma  getDaysToExpiration  getStrike  getUnderlyingSymbol  isEuropean 78 79  hlc3  imp_volatility  low  ohlc4  open      68 once_per_bar real_size upper weak_volume_dependency zerobase           constant enum float integer price string no or plot profile          rec reference script switch then to while with yes  open_interest  volume  vwap       isOptionable isPut optionPrice rho theta vega .  Technical Analysis  AccumDist  Average  AvgTrueRange  BodyHeight  Ema2  ExpAverage  FastKCustom  GetMaxValueOffset  GetMinValueOffset  Highest  HighestAll  HighestWeighted  IsAscending  Mathematical and Trigonometrical  AbsValue  IsNaN  ACos  lg  ASin  log  ATan  Max  Ceil  Min  Cos  Power  Crosses  Random  exp  round  Floor  roundDown  isInfinite  roundUp  Statistical  correlation  covariance  Inertia  InertiaAll  lindev     156 stdev stdevAll sterr sterrAll 104  IsDescending  IsDoji  IsLongBlack  IsLongWhite  Lowest  LowestAll  LowestWeighted  MidBodyVal  moneyflow  TrueRange  Ulcer  WildersAverage  wma        132 Sign Sin Sqr Sqrt sum Tan TotalSum .  Date and Time 170  countTradingDays  daysFromDate  daysTillDate  getDay  getDayOfMonth  getDayOfWeek  getLastDay  getLastMonth  getLastWeek  Corporate Actions 185  getActualEarnings  getDividend  getEstimatedEarnings  getSplitDenominator          getLastYear getMonth getWeek getYear getYyyyMmDd regularTradingEnd regularTradingStart secondsFromTime secondsTillTime  Look and Feel 191  AddChartBubble  AddChartLabel  AddCloud  AddVerticalLine  AssignBackgroundColor  AssignNormGradientColor  AssignPriceColor  AssignValueColor  color  CreateColor  DefineColor  DefineGlobalColor  EnableApproximation  GetColor  Profiles 220  getHighest  getHighestValueArea  getLowest  getLowestValueArea  getPointOfControl  getSplitNumerator  hasConferenceCall  hasEarnings             globalColor hide HideBubble hidePricePlot HideTitle setChartType SetDefaultColor setHiding SetLineWeight SetPaintingStrategy SetStyle TakeValueColor     monkeyBars show timeProfile volumeProfile . o AggregationPeriod o Constants 256  AggregationPeriod  MIN  TWO_MIN  THREE_MIN  FOUR_MIN  FIVE_MIN  TEN_MIN  FIFTEEN_MIN  TWENTY_MIN  THIRTY_MIN • MIN • TWO_MIN • THREE_MIN • FOUR_MIN • FIVE_MIN • TEN_MIN • FIFTEEN_MIN • TWENTY_MIN • THIRTY_MIN • HOUR  Others 234  addOrder  alert  barNumber  between  compoundValue  concat  entryPrice  first  fundamental         getAggregationPeriod getInterestRate getSymbolPart getValue getYield if tickSize tickValue HOUR TWO_HOURS FOUR_HOURS DAY TWO_DAYS THREE_DAYS FOUR_DAYS WEEK MONTH OPT_EXP           • • • • • • • • • 257  Alert  BAR  ONCE 268  TICK TWO_HOURS FOUR_HOURS DAY TWO_DAYS THREE_DAYS FOUR_DAYS WEEK MONTH OPT_EXP .  Color 273  BLACK  BLUE  CURRENT  CYAN  DARK_GRAY  DARK_GREEN  DARK_ORANGE  DARK_RED  DOWNTICK  GRAY  GREEN  LIGHT_GRAY  LIGHT_GREEN  CrossingDirection  Above  Below  Curve 285  FIRM  LONG_DASH  MEDIUM_DASH  Double  E  NaN  Pi 289 283  ChartType 269  BAR  CANDLE  CANDLE_TREND  HEIKIN_ASHI  LINE  AREA              Any LIGHT_ORANGE LIGHT_RED LIME MAGENTA ORANGE PINK PLUM RED UPTICK VIOLET WHITE YELLOW  SHORT_DASH  POINTS  EarningTime 291  ANY  BEFORE_MARKET  AFTER_MARKET . o OrderType  FundamentalType  HIGH  LOW  CLOSE  OPEN  HL2  HLC3  OHLC4  VWAP • • • • 293          PaintingStrategy 299  ARROW_DOWN  ARROW_UP  BOOLEAN_ARROW_DOWN  BOOLEAN_ARROW_UP  BOOLEAN_POINTS  DASHES  HISTOGRAM  HORIZONTAL  LINE  LINE_VS_POINTS  PricePerRow  AUTOMATIC  TICKSIZE  Sound  NoSound  Bell  Ding 310 309 BUY_AUTO BUY_TO_CLOSE SELL_AUTO SELL_TO_CLOSE 297 VOLUME OPEN_INTEREST IMP_VOLATILITY OrderType BUY_AUTO BUY_TO_CLOSE SELL_AUTO SELL_TO_CLOSE         LINE_VS_SQUARES LINE_VS_TRIANGLES POINTS SQUARED_HISTOGRAM SQUARES TRIANGLES VALUES_ABOVE VALUES_BELOW  Ring  Chimes . o Data Types  Any  boolean  CustomColor  double o Operators  Arithmetic  Comparison  Conditional 312     IDataHolder int String Data Conversion 323 • thinkScript Integration 324 o Conditional Orders o Custom Quotes o Study Alerts o Study Filters 325  Indexing  Logical  Operator Precedence 327 329 331 .
Copyright © 2024 DOKUMEN.SITE Inc.