### Example Alert Script Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-A---Creating-Local-Alerts A practical example that triggers an alert when the open price exceeds 400. ```thinkScript Alert(open > 400, "Open is greater than 400! Current value is" + open, alert.ONCE, Sound.Ring); ``` -------------------------------- ### Calculate Major Gann Levels using LowestAll Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/LowestAll This example demonstrates how to use LowestAll along with HighestAll to calculate Major Gann Levels. It requires no specific setup beyond standard thinkScript usage. ```thinkScript def HH = HighestAll(high); def LL = LowestAll(low); plot G1 = HH / 2; plot G2 = (HH + LL) / 2; plot G3 = HH / 4; plot G4 = (HH - LL) / 4 + LL; ``` -------------------------------- ### FastKCustom Usage Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/FastKCustom Example demonstrating how to use FastKCustom to dynamically color a plot based on price normalization. ```thinkScript declare lower; input colorNormLength = 14; plot Price = close; def abs = AbsValue(Price); def normVal = FastKCustom(abs, colorNormLength); Price.AssignValueColor( CreateColor(255, 2.55 * normVal, 0) ); ``` -------------------------------- ### AddOrder Example Usage Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/AddOrder Demonstrates how to use the AddOrder function to place a buy order when the current closing price is higher than the previous one. This example specifies the order type, condition, price, trade size, and colors for signals. ```thinkScript AddOrder(OrderType.BUY_AUTO, close > close[1], open[-1], 50, Color.ORANGE, Color.ORANGE, "Sample buy @ " + open[-1]); ``` -------------------------------- ### Get Entry Price for Sell Order Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/EntryPrice Use EntryPrice() to define conditions for closing a long position. This example sets a profit target 3 points above entry and a stop-loss 9 points below. ```thinkScript AddOrder(OrderType.SELL_TO_CLOSE, close > EntryPrice() + 3 or close < EntryPrice() - 9); ``` -------------------------------- ### thinkScript SecondsTillTime Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/SecondsTillTime This example draws the close price when the remaining seconds are within a defined duration and before a specified close time in EST. Ensure the chart aggregation period is less than one day for accurate results. ```thinkScript input CloseTime = 1600; input DurationHours = 1; def durationSec = DurationHours * 60 * 60; def secondsRemained = SecondsTillTime(closeTime); plot Price = if secondsRemained >= 0 and secondsRemained <= durationSec then close else double.NaN; ``` -------------------------------- ### LowestWeighted Function Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/LowestWeighted This example demonstrates how the LowestWeighted function is constructed by taking the minimum of several values. The two plots generated by the built-in function and the manual calculation coincide. ```thinkScript declare lower; input price1 = close; input price2 = open; def delta = price2 - price1; plot LWBuiltin = LowestWeighted(price1, 3, delta); plot LW = Min(Min(price1, price1[1] + delta), price1[2] + 2 * delta); ``` -------------------------------- ### Define basic script variables Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-3---Defining-Inputs Initial script examples showing variable definition using close and open prices. ```thinkScript def val = close/open; def data1 = Exp(val); def data2 = Power(Double.E, val); ``` ```thinkScript def val = close/open; def data1 = Exp(val); ``` -------------------------------- ### Get Split Numerator and Denominator for Position Calculation Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetSplitNumerator This example demonstrates how to use GetSplitNumerator and GetSplitDenominator to calculate the current trader position, accounting for stock splits. It initializes the position and updates it based on split ratios. ```thinkScript declare lower; input initialPosition = 100; def position = CompoundValue(1, if !IsNaN(GetSplitDenominator()) then position[1] * GetSplitNumerator() / GetSplitDenominator() else position[1], initialPosition); plot CurrentPosition = position; ``` -------------------------------- ### If Function and Expression Examples Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/If Shows various ways to implement conditional logic using the If function, if-expressions, and if-statements. ```thinkScript plot Maximum1 = If(close > open, close, open); plot Maximum2 = if close > open then close else open; plot Maximum3; if close > open { Maximum3 = close; } else { Maximum3 = open; } ``` -------------------------------- ### FastKCustom Function Reference Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/FastKCustom Reference for the FastKCustom function, detailing its parameters, calculation, and an example of its implementation in thinkScript. ```APIDOC ## FastKCustom Function ### Description Returns values from `0` through `100` depending on a price. If the price is the lowest for the last `length` bars then `0` is returned. If the price is the highest for the last `length` bars then `100` is returned. The function is calculated according to the following algorithm: `FastKCustom = if Highest(close, 12) - Lowest(close, 12) > 0 then (close - Lowest(close, 12)) / (Highest(close, 12) - Lowest(close, 12))*100 else 0` ### Input Parameters | Parameter | Default value | Description | |---|---|---| | data | - | Defines data for which the FastK is found. | | length | 14 | Defines the period on which the prices are translated into 0..100 range. | ### Example ``` declare lower; input colorNormLength = 14; plot Price = close; def abs = AbsValue(Price); def normVal = FastKCustom(abs, colorNormLength); Price.AssignValueColor( CreateColor(255, 2.55 * normVal, 0) ); ``` The example plots the EMA using the manual thinkScript® implementation and the built-in function. The resulting plots coincide forming a single curve. The `FastKCustom` function is used to assign a `normVal` value to each bar depending on its price. Zero value is assigned if the current closing price is the lowest on the last `14` bars, `100` is assigned if the current closing price is the highest on the last 14 bars. The `normVal` is used in the `AssignValueColor` function to paint a plot with colors ranging from red `(255, 0,0)` to yellow `(255, 255, 0)`. The green component of the color varies depending on the current value of `normVal`. ``` -------------------------------- ### GetEventOffset Function Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetEventOffset This example script displays a chart bubble indicating the number of bars since the most recent conference call using the GetEventOffset function. ```thinkScript AddChartBubble( HasConferenceCall(), high, "The last conference call was " + GetEventOffset(Events.CONFERENCE_CALL, -1) + " bars ago"); ``` -------------------------------- ### Average Function Reference Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Average Details on the Average function syntax, parameters, and usage examples. ```APIDOC ## Average(data, length) ### Description Returns the average value of a set of data for the last `length` bars. If the length of the data set is not specified, the default value of 12 is used. ### Parameters #### Input Parameters - **data** (IDataHolder) - Required - Defines data for which the average is found. - **length** (int) - Optional (Default: 12) - Defines period on which the average value is found. ### Example 1 ``` script AverageTS { input data = close; input length = 12; plot AverageTS = Sum(data, length) / length; } input price = close; input length = 12; plot SMA1 = Average(price, length); plot SMA2 = AverageTS(price, length); ``` ### Example 2 ``` plot SMA = Average(close, 20); ``` ``` -------------------------------- ### Calculate and Display P/E Ratio using GetActualEarnings Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetActualEarnings Calculates and displays the Price-Earnings Ratio using diluted earnings over approximately twelve months. This example is specific to daily charts. ```thinkScript declare lower; def AE = if IsNaN(GetActualEarnings()) then 0 else GetActualEarnings(); plot EPS_TTM = Sum(AE, 252); def pe = close / EPS_TTM; AddLabel(yes, "P/E Ratio: " + pe); ``` -------------------------------- ### HighestWeighted Function Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/HighestWeighted Demonstrates how to use the HighestWeighted function and construct it manually by taking the maximum of several values. The two plots should coincide. ```thinkScript declare lower; input price1 = close; input price2 = open; def delta = price2 - price1; plot HWBuiltin = HighestWeighted(price1, 3, delta); plot HW = Max(Max(price1, price1[1] + delta), price1[2] + 2 * delta); ``` -------------------------------- ### GetYear Function Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYear Use this function to retrieve the current bar's year in the CST timezone. The example plots the 'open' price for the last three years. ```thinkScript plot Price = if GetYear() > GetLastYear() - 3 then open else Double.NaN; ``` -------------------------------- ### Calculate and Plot Vega Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/Vega This example demonstrates how to approximate Vega by calculating the change in option price relative to a change in implied volatility. It then plots both the approximate Vega and the direct Vega calculation. ```thinkScript declare lower; def epsilon = 0.01 * imp_volatility(GetUnderlyingSymbol()); plot approxVega = (OptionPrice(Volatility = imp_volatility(GetUnderlyingSymbol()) + epsilon) - OptionPrice()) / epsilon / 100; plot Vega = vega(); ``` -------------------------------- ### Use Floor and Ceil Functions in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Floor This example demonstrates how to use the Floor and Ceil functions to draw a channel at integer levels that encompasses the high and low prices. Ensure the Floor and Ceil functions are available in your thinkScript environment. ```thinkScript plot Lower = Floor(low); plot Upper = Ceil(high); ``` -------------------------------- ### Define Boolean Input Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input/boolean Syntax and usage example for defining a boolean input parameter in thinkScript. ```APIDOC ## boolean input ### Description Defines a boolean input parameter. The default value can be set to "yes" or "no". ### Syntax `input =;` ### Example ``` input useHighLow = yes; plot HighPrice = if useHighLow then Highest(high, 10) else Highest(close, 10); plot LowPrice = if useHighLow then Lowest(low, 10) else Lowest(close, 10); ``` ### Usage This example draws a channel based on the highest and lowest price for a length of 10. The `useHighLow` input determines whether to use high/low prices or closing prices, defaulting to "yes". ``` -------------------------------- ### Using Assert to Validate Input Parameters Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/Assert This example demonstrates how to use the Assert function to check if an input 'percent' is positive. If the condition is false, an error message is displayed, and the study plots are not shown. ```thinkScript input percent = 5.0; Assert(percent > 0.0, "percent must be positive"); plot UpperBand = (1 + percent / 100 ) * close ; plot LowerBand = (1 - percent / 100 ) * close ; ``` -------------------------------- ### Sum Function Reference Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Sum Provides details on the Sum function, including its parameters, default values, and usage examples. ```APIDOC ## Sum Function ### Description Returns the sum of values for the specified number of bars. The default value of `length` is `12`. ### Syntax `Sum(IDataHolder data, int length)` ### Parameters #### Input Parameters - **data** (IDataHolder) - Required - Defines values to be summed. - **length** (int) - Optional - Default value: 12. Defines the number of bars for which the values are summed. ### Examples #### Example 1: Sum of closing prices over 20 bars ``` declare lower; plot data = Sum(close, 20); ``` This example displays a line that is the sum of the last 20 days' closing prices. #### Example 2: 20-day moving average ``` plot data = Sum(close, 20) / 20; ``` This example returns the sum of the last 20 days' closing prices divided by 20, which is the 20-day moving average. ``` -------------------------------- ### SetLineWeight usage example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/SetLineWeight Sets the thickness of the 'Price' plot to 5 pixels. The value must be between 1 and 5. ```thinkScript plot Price = close; Price.SetLineWeight(5); ``` -------------------------------- ### Plotting Bands with Float Input in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input/float This example demonstrates using a float input to calculate and plot upper and lower bands based on the closing price. The percentShift input controls the band's width. ```thinkScript plot UpperBand = close * (1 + percentShift / 100); plot LowerBand = close * (1 - percentShift / 100); ``` -------------------------------- ### Calculate Cumulative Pre-Market Volume Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetTime Uses GetTime to determine if the current bar occurs before the regular trading session start time. ```thinkScript def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1]; def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD()); def vol = if isRollover and beforeStart then volume else if beforeStart then vol[1] + volume else Double.NaN; plot PreMarketVolume = vol; ``` -------------------------------- ### Calculate Aroon Oscillator using GetMinValueOffset Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/GetMinValueOffset This example calculates the Aroon Oscillator by finding the offset of the minimum value using GetMinValueOffset and the offset of the maximum value using GetMaxValueOffset. It requires the 'high' and 'low' data and a specified length. ```thinkScript declare lower; input length = 25; def upIndex = GetMaxValueOffset(high, length); def downIndex = GetMinValueOffset(low, length); plot AroonOsc = (downIndex - upIndex) * 100.0 / length; ``` -------------------------------- ### Enumeration Type Compatibility Check Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/def Example showing type compatibility rules for enumerations. Note that attempting to compare different enumeration types or assign incompatible values will result in errors. ```thinkscript def a = {q, w, e, default r, t, y}; def b = {q, w, e, default r, t, y}; a = a.q; b = b.q; plot z = a[1] == a.q; plot x = a == z; plot y = a != if (1==2) then a else a.q; plot w = if (1==2) then a else a.q != if (1==2) then b else b.q; ``` -------------------------------- ### Conditional Chart Bubble or Label Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Operators/Logical This example conditionally displays a chart bubble or a label based on a 'bubble' input parameter. The label is shown when the 'bubble' parameter is false, demonstrating the use of logical AND with a function and logical NOT implicitly. ```thinkScript input bubble = yes; AddChartBubble(bubble and barNumber() == 1, high, "Displaying a bubble"); AddLabel(!bubble, "Displaying a label"); ``` -------------------------------- ### Reference study variables Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/reference Example of referencing def variables from the ATRTrailingStop study to assign price colors and add vertical lines. ```thinkScript def st = ATRTrailingStop().state; AssignPriceColor(if st == 1 then GetColor(1) else if st == 2 then GetColor(0) else Color.CURRENT); def bs = !IsNaN(close) and ATRTrailingStop().BuySignal == yes; def ss = !IsNaN(close) and ATRTrailingStop().SellSignal == yes; AddVerticalLine(bs or ss, if bs then "Buy!" else "Sell!", if bs then GetColor(0) else GetColor(1)); ``` -------------------------------- ### Convert Number to String with AsText Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/AsText Use AsText to format a number as a string with specified decimal places. This example displays the Rate of Change in Close price. ```thinkScript input length = 9; AddLabel(yes, AsText((close - close[length]) / close[length], NumberFormat.TWO_DECIMAL_PLACES)); ``` -------------------------------- ### Lowest Function Usage in Williams %R Calculation Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Lowest This example demonstrates how to use the Lowest function to find the minimum low over a specified length, as part of the Williams %R indicator calculation. Ensure the 'high', 'low', and 'close' data are available. ```thinkScript declare lower; input length = 10; def HH = Highest(high, length); def LL = Lowest(low, length); plot "Williams %R" = if HH == LL then -100 else (HH - close) / (HH - LL) * (-100); ``` -------------------------------- ### RegularTradingStart Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/RegularTradingStart This function returns the number of milliseconds elapsed since the epoch until the start of the regular trading hours on a given day for the current symbol. The trading day is specified using the YYYYMMDD format. ```APIDOC ## RegularTradingStart ### Description Returns the number of milliseconds elapsed since the epoch (January 1, 1970, 00:00:00 GMT) till the start of the regular trading hours on a given day for the current symbol. The trading day is to be specified using the YYYYMMDD format. ### Input parameters #### Path Parameters - **yyyyMmDd** (int) - Required - Defines the trading day in the YYYYMMDD format. ### Request Example ```thinkscript def rth = (RegularTradingEnd(GetYYYYMMDD()) - RegularTradingStart(GetYYYYMMDD())) / AggregationPeriod.HOUR; AddLabel(yes, "RTH duration (hrs): " + rth); ``` ### Response #### Success Response (200) - **milliseconds** (int) - The number of milliseconds elapsed since the epoch until the start of regular trading hours. ``` -------------------------------- ### Calculate Rho Option Greek in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/Rho This example demonstrates an approximate calculation of rho using changes in option price and interest rates. It requires the OptionPrice and Rho functions. ```thinkScript declare lower; def epsilon = 0.0001; plot approxRho = (OptionPrice(interestRate = GetInterestRate() + epsilon) - OptionPrice()) / epsilon / 100; plot Rho = Rho(); ``` -------------------------------- ### Use GetValue to Plot Closing Price for Highest High Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/GetValue This example plots the closing price of the bar that corresponds to the highest high within the last 12 bars. Ensure the 'high' and 'close' data are available for the specified offset. ```thinkScript plot ClosingPriceForHighestHigh = GetValue(close, GetMaxValueOffset(high, 12), 12); ``` -------------------------------- ### Fundamental Function Usage Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/Fundamental This script demonstrates how to use the Fundamental function to calculate the relation between two symbols based on their fundamental prices. Ensure the 'FundamentalType' and 'relationWithSecurity' inputs are correctly set. ```thinkScript declare lower; input price = FundamentalType.CLOSE; input relationWithSecurity = "SPX"; def price1 = Fundamental(price); def price2 = Fundamental(price, relationWithSecurity); plot Relation = if price2 == 0 then Double.NaN else price1 / price2; Relation.SetDefaultColor(GetColor(1)); ``` -------------------------------- ### AddLabel with Row Ownership and Conditional Coloring Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddLabel This example demonstrates adding a label that displays average price, with its color changing based on the trend. It utilizes the 'row ownership = yes' parameter to ensure the label occupies its own row, preventing overlap with other labels. The label's text and color are dynamically set based on whether the current close price is above the average close. ```thinkScript def avgPrice = GetAveragePrice(); def trendUp = close > Average(close); AddLabel(yes, "My Avg Price: " + avgPrice, if trendUp then Color.GREEN else Color.RED, location = Location.TOP_LEFT, size = FontSize.SMALL, "row ownership" = yes); ``` -------------------------------- ### Get First Bar Close Price in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/First Calculates the percentage change of the close price from the first bar. Use this to establish a baseline for price movement analysis. ```thinkScript declare lower; def close1 = First(close); plot Data = (close - close1) / close1 * 100; ``` -------------------------------- ### Using Equality and Inequality Operators Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions Demonstrates the use of comparison operators to test equality and inequality between price data points. ```thinkScript def a = close==open; def b = close!=open; def c = close<>open; ``` -------------------------------- ### Compare Conditional Expression Methods Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-5---Conditional-Expressions Demonstrates the equivalent functionality of If-function, if-expression, and if-statement for plotting the higher of open or close prices. ```thinkScript plot Maximum1 = If(close > open, close, open); plot Maximum2 = if close > open then close else open; plot Maximum3; if close > open { Maximum3 = close; } else { Maximum3 = open; } ``` -------------------------------- ### AssignNormGradientColor Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignNormGradientColor This example demonstrates how to use AssignNormGradientColor to color a Price Oscillator plot. The plot will be colored yellow for the biggest positive difference and light red for the smallest difference over the last 14 bars, with intermediate colors for values in between. ```thinkScript declare lower; input colorNormLength = 14; input fastLength = 9; input slowLength = 18; plot PriceOsc = Average(close, fastLength) - Average(close, slowLength); PriceOsc.AssignNormGradientColor(colorNormLength, Color.LIGHT_RED, Color.YELLOW); ``` -------------------------------- ### GET Double.Pi Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/Double/Double-Pi Returns the mathematical constant pi. ```APIDOC ## Double.Pi ### Description Returns the value of the pi constant. ### Syntax `Double.Pi` ``` -------------------------------- ### Reference study with parameters Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/reference Illustrates full and compact forms for referencing studies with multiple input parameters. ```thinkScript plot MyBB2 = BollingerBandsSMA(price = open, displace = 0, length = 30); ``` ```thinkScript plot MyBB = BollingerBandsSMA(open, 0, 30); ``` -------------------------------- ### Get Next OTM Option Code Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/GetNextOTMOption Use this function to get the option code of the next strike in the same series. For puts, it returns the code for a lower strike; for calls, it returns the code for a higher strike. The returned code is for the next option in the out-of-the-money direction. ```thinkScript AddLabel(yes, "Next OTM option is" + GetNextOTMOption(".GOOG120317C580")); ``` -------------------------------- ### Calculate Cumulative Volume using rec Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/rec Demonstrates how to use recursion to maintain a running total of volume over time. ```thinkScript rec C = C[1] + volume; plot CumulativeVolume = C; ``` -------------------------------- ### AddVerticalLine Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddVerticalLine Documentation for the AddVerticalLine function, including parameters and usage examples. ```APIDOC ## AddVerticalLine ### Description Adds a vertical line with specified text to the chart. ### Parameters - **visible** (boolean) - Required - Defines condition upon which the line is displayed. - **text** (Any) - Optional - Defines text to be displayed next to the line. Default: "" - **color** (CustomColor) - Optional - Defines color of the line. Default: Color.RED - **stroke** (int) - Optional - Defines style of the line. Default: Curve.SHORT_DASH ### Request Example input period = {WEEK, default MONTH}; AddVerticalLine((period == period.WEEK and GetWeek() <> GetWeek()[1]) or (period == period.MONTH and GetMonth() <> GetMonth()[1]), "", Color.ORANGE, curve.SHORT_DASH); ``` -------------------------------- ### TotalSum Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/TotalSum Calculates the cumulative sum of a data series from the start of the chart. ```APIDOC ## TotalSum ### Description Returns the sum of all values from the first bar to the current. ### Parameters #### Input Parameters - **data** (IDataHolder) - Required - Defines values to be summed. ### Request Example ``` declare lower; plot data = TotalSum(volume); ``` ### Response - **Result** (Numeric) - The total accumulated value for the time frame of the current chart. ``` -------------------------------- ### Comparing Current and Past Prices with AddCloud Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddCloud Visualizes the relationship between current price and a historical price point using violet and pink color fills. ```thinkScript plot CurrentPrice = close; plot PastPrice = close[10]; AddCloud(CurrentPrice, PastPrice, Color.VIOLET, Color.PINK); ``` ```thinkScript plot CurrentPrice = close; plot PastPrice = close[10]; AddCloud(PastPrice, CurrentPrice, Color.VIOLET, Color.PINK); ``` -------------------------------- ### EMA2 Function Reference Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/EMA2 Documentation for the EMA2 function, including parameters and usage examples. ```APIDOC ## EMA2 ### Description Returns the exponential moving average (EMA) of `data` with a `smoothing factor`. The `prefetch` parameter controls the number of historical data points used to initialize the EMA for the first bar. The `First Bar` parameter is deprecated. ### Syntax `EMA2(IDataHolder data, int prefetch, double smoothing factor, int First Bar)` ### Parameters - **data** (IDataHolder) - Required - Defines data for which the average is found. - **prefetch** (int) - Optional (Default: 0) - Defines the number of historical data points used to initialize EMA for the first bar. - **smoothing factor** (double) - Required - Defines smoothing factor for calculation of the average. - **First Bar** (int) - Optional (Default: 0) - Deprecated parameter. ### Example ``` input additionalBars = 0; plot ExpAvg = EMA2(close, additionalBars, 0.2); ``` ``` -------------------------------- ### Visualizing infinite bounds with AddCloud Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-D---Using-NaN-and-Infinity-Constants Demonstrates using infinite values to create conditional color-filled stripes between bounds without triggering chart re-scaling. ```thinkScript def hiLevel = if close >= Average(close) then Double.POSITIVE_INFINITY else Double.NEGATIVE_INFINITY; AddCloud(hiLevel, -hiLevel, Color.LIGHT_GREEN, Color.LIGHT_RED); ``` -------------------------------- ### AddLabel Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddLabel This snippet details the AddLabel function, its parameters, and provides examples of its usage in thinkScript. ```APIDOC ## AddLabel Function ### Description Adds a text label to the specified location on the chart. This function can also be used to display text in custom quotes. The `row ownership` parameter allows a label to claim exclusive use of its row, pushing other labels to adjacent rows. **Note**: When `AddLabel()` calls another function, it only uses the value of that function at the last real bar. **Tip**: Enable **Fit study markers** in chart settings to avoid label overlap with chart elements. ### Method `AddLabel` ### Parameters #### Path Parameters - **visible** (boolean) - Required - Defines the condition upon which the label is displayed. - **text** (Any) - Required - Defines the text to be displayed in the label. - **color** (CustomColor) - Optional - Defines the color of the label. Defaults to `Color.RED`. - **location** (int) - Optional - Defines the location of the label. Defaults to `Location.TOP_LEFT`. - **size** (int) - Optional - Defines the font size of the label. Defaults to `FontSize.SMALL`. - **row ownership** (boolean) - Optional - If set to `yes`, this label claims ownership of the entire chart row. Defaults to `no`. ### Request Example ```thinkscript def avgPrice = GetAveragePrice(); def trendUp = close > Average(close); AddLabel(yes, "My Avg Price: " + avgPrice, if trendUp then Color.GREEN else Color.RED, location = Location.TOP_LEFT, size = FontSize.SMALL, "row ownership" = yes); AddLabel(yes, if close > Average(close, 20) then "Uptrend" else "Downtrend", location = Location.TOP_RIGHT, size = FontSize.X_LARGE); ``` ### Response #### Success Response (200) This function does not return a value directly but modifies the chart by adding a label. #### Response Example (No direct response body, labels are rendered on the chart.) ``` -------------------------------- ### GET /thinkScript/GrossProfitMargin Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals/GrossProfitMargin Calculates the gross profit margin ratio for a specified symbol and fiscal period. ```APIDOC ## GET /thinkScript/GrossProfitMargin ### Description The `GrossProfitMargin` function returns the ratio of a company's gross income to its net sales or revenues. ### Parameters #### Path Parameters - **symbol** (Symbol) - Optional - The symbol to analyze. Defaults to the current symbol. - **fiscalPeriod** (int) - Optional - The fiscal period for the data. Defaults to FiscalPeriod.YEAR. Use FiscalPeriod.QUARTER for quarterly data. ``` -------------------------------- ### LOW Syntax and Usage Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/FundamentalType/FundamentalType-LOW Provides information on how to use the LOW syntax within the Fundamental function to access the Low price. ```APIDOC ## LOW ### Syntax `FundamentalType.LOW` ### Description Used with Fundamental function to return the Low price. ### Example See the Fundamental function article in the Others functions section. ``` -------------------------------- ### GET FreeCashFlowPerShare Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals/FreeCashFlowPerShare Retrieves the free cash flow per share for a specified symbol and fiscal period. ```APIDOC ## GET FreeCashFlowPerShare ### Description The FreeCashFlowPerShare function returns the ratio of free cash flow to the number of outstanding shares for the specified symbol. Free cash flow is calculated as cash flow from operating activities minus capital expenditures and total dividends paid. ### Method GET ### Parameters #### Path Parameters - **symbol** (Symbol) - Optional - The ticker symbol to analyze. Defaults to the current symbol. - **fiscalPeriod** (int) - Optional - The fiscal period for the calculation. Defaults to FiscalPeriod.YEAR. Note: FiscalPeriod.QUARTER is not supported. ### Response - **value** (double) - The calculated free cash flow per share. ``` -------------------------------- ### GET GetTime() Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetTime Retrieves the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). ```APIDOC ## GET GetTime() ### Description Returns the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). ### Method GET ### Endpoint GetTime() ### Request Example GetTime(); ### Response - **value** (Integer) - The number of milliseconds since the epoch. ``` -------------------------------- ### Create a TPO Profile Study Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-B---Using-Profiles Aggregates all chart data on the right expansion and displays it in blue. ```thinkScript def allchart = 0; profile tpo = timeProfile("startnewprofile" = allchart); tpo.show("color" = Color.BLUE); ``` -------------------------------- ### GetMinValueOffset Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/GetMinValueOffset This snippet details the GetMinValueOffset function, its parameters, and provides an example of its usage in calculating the Aroon Oscillator. ```APIDOC ## GetMinValueOffset ### Description Returns the offset of the lowest value of `data` for the last `length` bars. ### Method `GetMinValueOffset(IDataHolder data, int length)` ### Parameters #### Input Parameters - **data** (IDataHolder) - Required - Defines data for which the lowest value is found. - **length** (int) - Optional - Default value: 25. Defines period on which the lowest value is found. ### Example ```thinkscript declare lower; input length = 25; def upIndex = GetMaxValueOffset(high, length); def downIndex = GetMinValueOffset(low, length); plot AroonOsc = (downIndex - upIndex) * 100.0 / length; ``` ### Example Explanation The example calculates the Aroon Oscillator. 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. Then the `downIndex` value and the `upIndex` values are used to draw the resulting `AroonOsc` plot. ``` -------------------------------- ### Calculate and Plot P/L Percentage Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio/GetOpenPL This script calculates and plots the P/L% using GetOpenPL, GetQuantity, and GetAveragePrice. It's based on the execution price and colors the plot green for positive values and red for negative. Note: Manual P/L calculation is only valid for symbols with a dollar value of 1; otherwise, OpenCost needs to be multiplied by the dollar value. ```thinkScript declare lower; def openCost = GetQuantity() * GetAveragePrice(); plot PercentPL = GetOpenPL() / AbsValue(openCost) * 100; PercentPL.AssignValueColor(if PercentPL >= 0 then Color.UPTICK else Color.DOWNTICK); ``` -------------------------------- ### Valid Input Definition with Underscores Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input Demonstrates the correct way to define an input name with visual spacing using underscores. ```thinkScript input input_name_with_spaces = "OK"; ``` -------------------------------- ### AddOrder Function: Full Syntax Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-7---Creating-Strategies Illustrates the complete syntax for the AddOrder function, including parameters for order type, condition, price, trade size, tick color, arrow color, and name. This allows for detailed customization of trading orders. ```thinkscript AddOrder(type, condition, price, tradeSize, tickColor, arrowColor, name); ``` -------------------------------- ### Compare Custom and Built-in Average Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Average Demonstrates how a custom script implementation compares to the built-in Average function by plotting both on the same chart. ```thinkScript script AverageTS { input data = close; input length = 12; plot AverageTS = Sum(data, length) / length; } input price = close; input length = 12; plot SMA1 = Average(price, length); plot SMA2 = AverageTS(price, length); ``` -------------------------------- ### HidePricePlot Usage Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/HidePricePlot Hides the price plot for the current symbol by setting the hide price parameter to yes. ```thinkScript plot closeOnly = close; HidePricePlot(yes); ``` -------------------------------- ### AddVerticalLine Usage Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddVerticalLine Draws orange short-dashed vertical lines on a chart based on the selected period frequency. ```thinkScript input period = {WEEK, default MONTH}; AddVerticalLine((period == period.WEEK and GetWeek() <> GetWeek()[1]) or (period == period.MONTH and GetMonth() <> GetMonth()[1]), "", Color.ORANGE, curve.SHORT_DASH); ``` -------------------------------- ### Calculating Power and Logarithmic Values Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions Shows how to perform exponentiation, square roots, and logarithmic calculations using built-in thinkScript functions. ```thinkScript def val = close/open; def data1 = Sqr(val); def data2 = Sqrt(val); def data3 = Power(val, 3); def data4 = Exp(val); def data5 = Lg(val); def data6 = Log(val); ``` -------------------------------- ### WMA Function Reference Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/WMA Provides details on the Weighted Moving Average (WMA) function, including its parameters and a usage example. ```APIDOC ## WMA Function ### Description Returns Weighted Moving Average value. The Weighted Moving Average is calculated by multiplying each of the previous days' data by a weight factor. That factor is equal to the number of days past the first day. The total is then divided by the sum of the factors. ### Syntax `WMA(IDataHolder data, int length)` ### Parameters #### Input Parameters - **data** (IDataHolder) - Required - Defines data for which the average is found. - **length** (int) - Optional - Default value: 9. Defines period on which the average value is found. ### Example ``` plot WMA = WMA(close, 20); ``` The example displays the weighted moving average for the last 20 closing prices. ``` -------------------------------- ### Plotting Price Bands with RoundUp and RoundDown Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/RoundUp Demonstrates using RoundUp and RoundDown to create price bands based on a specified number of digits. ```thinkScript input price = close; input digits = 0; plot ceiling = RoundUp(price, digits); plot floor = RoundDown(price, digits); ``` -------------------------------- ### Calculate Arc Cosine in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/ACos This example demonstrates using ACos to compare a calculated value against pi/3, resulting in a boolean plot. ```thinkScript declare lower; plot Data = Acos(0.5) == Double.Pi / 3; ``` -------------------------------- ### Rounding Numerical Values Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions Demonstrates various rounding functions including Ceil, Floor, and specific precision rounding. ```thinkScript def data1 = Ceil(Double.E); def data2 = Floor(Double.E); def data3 = RoundUp(Double.E, 3); def data4 = RoundDown(Double.E, 3); def data5 = Round(Double.E, 3); ``` -------------------------------- ### Show Function Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Profiles/Show Controls the visibility and color scheme of Time, Volume, and Monkey Bars profiles. Profiles are only visible if the Show function is applied to them. ```APIDOC ## Show Function ### Description This function controls visibility and color scheme of Time, Volume, and Monkey Bars profiles. Note that profiles calculated by the corresponding functions will only be visible if the `Show` function is applied to them. ### Method N/A (This is a function call within thinkScript) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```thinkscript def bn = BarNumber(); def start = 0; profile mb = MonkeyBars(timeInterval = bn, startNewProfile = start, volumeProfileShowStyle = MonkeyVolumeShowStyle.ALL); mb.Show("volume color" = Color.RED, "volume va color" = Color.WHITE, "volume poc color" = Color.GREEN); ``` ### Response #### Success Response (200) N/A (This function modifies visual display, it does not return a value in the traditional API sense) #### Response Example N/A ### Input Parameters Details - **color** (CustomColor) - Optional - Default: `Color.PLUM` - Defines the main color of Time and Volume profile bars. - **poc color** (CustomColor) - Optional - Default: `Color.CURRENT` - Defines the color of the Point of Control. - **va color** (CustomColor) - Optional - Default: `Color.CURRENT` - Defines the color of the Value Area. - **opacity** (double) - Optional - Default: `50.0` - Defines the degree of histogram opacity, in percent. - **open color** (CustomColor) - Optional - Default: `Color.CURRENT` - Defines the color of the square marking the Monkey Bars' Open price. - **close color** (CustomColor) - Optional - Default: `Color.CURRENT` - Defines the color of the arrow marking the Monkey Bars' Close price. - **ib color** (CustomColor) - Optional - Default: `Color.CURRENT` - Only affects MonkeyBars function. It defines the color of Initial Balance bracket. - **volume color** (CustomColor) - Optional - Default: `Color.PLUM` - Only affects MonkeyBars function. It defines the color of Volume Profile if you chose to complement Monkey Bars with it. - **volume va color** (CustomColor) - Optional - Default: `Color.CURRENT` - Only affects MonkeyBars function. It defines the color of the Value Area of Volume Profile if you chose to complement Monkey Bars with it. - **volume poc color** (CustomColor) - Optional - Default: `Color.CURRENT` - Only affects MonkeyBars function. It defines the color of the Point of Control of Volume Profile if you chose to complement Monkey Bars with it. **Note**: `Color.CURRENT` is used for any of the elements (profile itself, point of control, value area), that element is not displayed. ``` -------------------------------- ### Apply zerobase to a study Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/zerobase Use this declaration to ensure the study axis starts at zero when plotting non-negative data like volume. ```thinkScript declare zerobase; declare lower; plot Vol = Volume; ``` -------------------------------- ### Calculate Linear Regression with Inertia Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/Inertia Demonstrates the manual implementation of the linear regression formula compared against the built-in Inertia function. ```thinkScript script inertiaTS { input y = close; input n = 20; def x = x[1] + 1; def a = (n * Sum(x * y, n) - Sum(x, n) * Sum(y, n) ) / ( n * Sum(Sqr(x), n) - Sqr(Sum(x, n))); def b = (Sum(Sqr(x), n) * Sum(y, n) - Sum(x, n) * Sum(x * y, n) ) / ( n * Sum(Sqr(x), n) - Sqr(Sum(x, n))); plot InertiaTS = a * x + b; } input length = 20; plot LinReg1 = Inertia(close, length); plot LinReg2 = InertiaTS(close, length); ``` -------------------------------- ### Draw Vertical Line with Month Change using '+' Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Advanced/Chapter-14---Concatenating-Strings Achieves the same result as the Concat example by using the '+' operator for string concatenation. ```thinkscript AddVerticalLine(getMonth() <> getMonth()[1], "Open: " + open); ``` -------------------------------- ### FastKCustom Algorithm Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/FastKCustom The mathematical implementation of the FastKCustom function. ```thinkScript FastKCustom = if Highest(close, 12) - Lowest(close, 12) > 0 then (close - Lowest(close, 12)) / (Highest(close, 12) - Lowest(close, 12))*100 else 0 ``` -------------------------------- ### Use Max Function in thinkScript Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Max This example plots the higher value between the closing price and the simple moving average. Ensure SimpleMovingAvg() is defined or imported. ```thinkScript def SMA = SimpleMovingAvg(); plot data = Max(close, SMA); ``` -------------------------------- ### AssignBackgroundColor Usage Example Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignBackgroundColor Sets the background color of a quote cell to dark orange when the ADX value exceeds 20, otherwise sets it to black. ```thinkScript plot ADX = ADX(); AssignBackgroundColor(if ADX > 20 then Color.DARK_ORANGE else Color.BLACK); ``` -------------------------------- ### DASHES Syntax and Description Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/PaintingStrategy/PaintingStrategy-DASHES Information about the DASHES syntax and its purpose in defining painting strategies. ```APIDOC ## DASHES ### Syntax `PaintingStrategy.DASHES` ### Description Defines the dashes painting strategy. ### Example See the `SetPaintingStrategy` function in the Look and Feel section. ``` -------------------------------- ### AddLabel to Bottom Right Corner Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/Location/Location-BOTTOM-RIGHT Use `Location.BOTTOM_RIGHT` with `AddLabel()` to display text in the bottom-right corner of the chart. This example shows the current symbol name. ```thinkScript AddLabel(yes, "Current symbol: " + GetSymbol(), location = Location.BOTTOM_RIGHT); ``` -------------------------------- ### Plotting Open Price with open() Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals/open Use this script to plot the daily Open price for a specified symbol and price type. Ensure the symbol, period, and price_type are correctly defined. ```thinkScript input symbol = "EUR/USD"; input period = AggregationPeriod.MONTH; input price_type = {default "LAST", "BID", "ASK", "MARK"}; plot Data = open(symbol, period, price_type); ``` -------------------------------- ### Calculate Total Sum of Volume Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/TotalSum Use TotalSum to get the accumulated volume for the chart's time frame. Ensure the 'volume' data is available. ```thinkScript declare lower; plot data = TotalSum(volume); ``` -------------------------------- ### Use GetDayOfWeek to Add Chart Bubbles Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetDayOfWeek Displays bubbles with text for a certain day of week. Requires the GetYYYYMMDD() function to get the current date. ```thinkScript declare hide_on_intraday; input day_of_week = {default Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; AddChartBubble(GetDayofWeek(GetYYYYMMDD()) == day_of_week + 1, high, "Here it is"); ``` -------------------------------- ### Calculate Bid-Ask Difference and Assign Color Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals/bid This script calculates the percentage difference between the bid and ask prices and the close price, then assigns a background color based on the result. It is intended for use as a custom quote and cannot reference historical data. ```thinkScript plot "Diff, %" = round(100 * ((bid + ask) / 2 - close) / close, 2); AssignBackgroundColor(if "Diff, %" > 0 then Color.UPTICK else if "Diff, %" < 0 then Color.DOWNTICK else Color.GRAY); ``` -------------------------------- ### Plot Closing Price in thinkScript® Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Overview This is a basic thinkScript® command to plot the closing price of a symbol. It serves as a starting point for creating custom studies. ```thinkScript plot Data = close; ``` -------------------------------- ### Plot Simple Moving Average Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/plot Renders a simple moving average on the chart using the Average function. Requires no special setup beyond this declaration. ```thinkScript plot SMA = Average(close, 12); ``` -------------------------------- ### Calculate Bid-Ask Spread and Color Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals/ask This script calculates the bid-ask spread and assigns a background color based on the spread's value. It is intended for use as a custom quote. Historical data cannot be referenced with the 'ask' function. ```thinkScript plot spread = ask - bid; AssignBackgroundColor(if spread < 0.05 then Color.GREEN else if spread < 0.25 then Color.YELLOW else Color.RED); ``` -------------------------------- ### Plotting a Cloud Between Open and Close Prices Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddCloud Highlights the difference between open and close prices with color-coded regions for bull and bear candles. ```thinkScript def OpenPrice = open; def ClosePrice = close; AddCloud(OpenPrice, ClosePrice, color.RED, color.GREEN, yes); ```