### Example alert script
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-A---Creating-Local-Alerts
A practical example that triggers a ring sound alert once when the open price exceeds 400.
```thinkScript
Alert(open > 400, "Open is greater than 400! Current value is" + open, alert.ONCE, Sound.Ring);
```
--------------------------------
### Basic Variable Definition
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-3---Defining-Inputs
Initial script examples defining variables using price data.
```thinkScript
def val = close/open;
def data1 = Exp(val);
def data2 = Power(Double.E, val);
```
```thinkScript
def val = close/open;
def data1 = Exp(val);
```
--------------------------------
### GetLowest Weekly Volume Profile Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Profiles/GetLowest
Plots the lowest price for each weekly volume profile using a conditional start trigger.
```thinkScript
def yyyymmdd = GetYYYYMMDD();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));
def period = Floor(day_number / 7);
def cond = 0 < period - period[1];
profile vol = VolumeProfile("startNewProfile" = cond, "onExpansion" = no);
vol.Show();
plot b = vol.GetLowest();
```
--------------------------------
### HighestWeighted Construction Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/HighestWeighted
Demonstrates the construction of HighestWeighted by comparing it to a manual calculation using the Max function.
```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);
```
--------------------------------
### FastKCustom Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/FastKCustom
Demonstrates using FastKCustom to dynamically color a plot based on normalized price values.
```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) );
```
--------------------------------
### Calculate Price Based on Time Duration
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/SecondsFromTime
This example plots the closing price only during a specified duration starting from a defined time.
```thinkScript
input OpenTime = 0930;
input DurationHours = 1;
def durationSec = DurationHours * 60 * 60;
def secondsPassed = SecondsFromTime(OpenTime);
plot Price = if secondsPassed >= 0 and secondsPassed <= durationSec then close else double.NaN;
```
--------------------------------
### LowestWeighted Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/LowestWeighted
Demonstrates the usage of LowestWeighted and compares it to a manual calculation using the Min function.
```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);
```
--------------------------------
### Calculate Days from a Specific Date in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/DaysFromDate
This example plots the closing price for bars within a 50-day window starting from the defined BeginDate.
```thinkScript
input BeginDate = 20090101;
plot Price = if DaysFromDate(BeginDate) >= 0 and DaysFromDate(BeginDate) <= 50 then close else double.NaN;
```
--------------------------------
### Calculate Major Gann Levels using LowestAll
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/LowestAll
This example demonstrates using HighestAll and LowestAll to determine global high and low values for calculating Gann levels.
```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;
```
--------------------------------
### AccumDist Function Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/AccumDist
Demonstrates the use of the built-in AccumDist function alongside a custom script implementation to calculate Accumulation/Distribution.
```thinkScript
script AccumDistTS {
input high = high;
input close = close;
input low = low;
input open = open;
input volume = volume;
plot AccumDistTS = TotalSum(if high - low > 0 then (close - open) / (high - low) * volume else 0);
}
declare lower;
plot AccumDist1 = AccumDist(high, close, low, open, volume);
plot AccumDist2 = AccumDistTS(high, close, low, open, volume);
```
--------------------------------
### 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.
```thinkScript
plot Price = close;
Price.SetLineWeight(5);
```
--------------------------------
### GetNextOTMOption Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/GetNextOTMOption
Displays the next option code in a series using a chart label.
```thinkScript
AddLabel(yes, "Next OTM option is" + GetNextOTMOption(".GOOG120317C580"));
```
--------------------------------
### Plotting based on month using GetMonth
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetMonth
This example plots the closing price only during the first six months of the year.
```thinkScript
plot Price = if GetMonth() <= 6 then close else Double.NaN;
```
--------------------------------
### GetYear Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYear
Plots the open price for bars occurring within the last three years.
```thinkScript
plot Price = if GetYear() > GetLastYear() - 3 then open else Double.NaN;
```
--------------------------------
### Plotting based on GetWeek
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetWeek
This example plots the closing price only during odd-numbered weeks of the year.
```thinkScript
plot Price = if GetWeek() % 2 == 1 then close else Double.NaN;
```
--------------------------------
### AssignPriceColor usage example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignPriceColor
Demonstrates coloring price bars based on MoneyFlowIndex levels. Uses Color.CURRENT to maintain existing colors when conditions are not met.
```thinkScript
declare lower;
plot MFI = MoneyFlowIndex();
plot OverBought = 80;
plot OverSold = 20;
MFI.DefineColor("OverBought", Color.ORANGE);
MFI.DefineColor("OverSold", Color.BLUE);
OverBought.SetDefaultColor(Color.GRAY);
OverSold.SetDefaultColor(Color.GRAY);
AssignPriceColor(if MFI >= OverBought then MFI.color("OverBought") else if MFI <= OverSold then MFI.color("OverSold") else Color.CURRENT);
```
--------------------------------
### AddLabel Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddLabel
Displays labels on a chart with conditional coloring and row ownership management.
```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);
```
--------------------------------
### HidePricePlot Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/HidePricePlot
Demonstrates how to hide the price plot by setting the parameter to yes.
```thinkScript
plot closeOnly = close;
HidePricePlot(yes);
```
--------------------------------
### GetLastYear Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetLastYear
Plots the closing price only for bars occurring in the current year.
```thinkScript
plot Price = if GetLastYear() == GetYear() then close else Double.NaN;
```
--------------------------------
### Calculate Pre-Market Volume using GetTime
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;
```
--------------------------------
### RegularTradingStart(int yyyyMmDd)
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/RegularTradingStart
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.
```APIDOC
## RegularTradingStart(int yyyyMmDd)
### 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.
### Parameters
- **yyyyMmDd** (int) - Required - Defines the trading day in the YYYYMMDD format.
### Example
```
def rth = (RegularTradingEnd(GetYYYYMMDD()) - RegularTradingStart(GetYYYYMMDD())) / AggregationPeriod.HOUR;
AddLabel(yes, "RTH duration (hrs): " + rth);
```
```
--------------------------------
### AddOrder Execution Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/AddOrder
Executes a buy order when the current close is higher than the previous close, using a fixed trade size of 50 and custom orange styling.
```thinkScript
AddOrder(OrderType.BUY_AUTO, close > close[1], open[-1], 50, Color.ORANGE, Color.ORANGE, "Sample buy @ " + open[-1]);
```
--------------------------------
### Non-recursive usage example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/if
Demonstrates using if-expressions and if-statements to control moving average parameters.
```thinkScript
input price = close;
input long_average = yes;
plot SimpleAvg = Average(price, if long_average then 26 else 12);
plot ExpAvg;
if long_average {
ExpAvg = ExpAverage(price, 26);
} else {
ExpAvg = ExpAverage(price, 12);
}
```
--------------------------------
### Define an uppercase input parameter
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input
Example of defining an input variable with an uppercase name.
```thinkScript
input TEST = "test in uppercase";
```
--------------------------------
### Calculate Martin Ratio using Ulcer Index
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Ulcer
This example demonstrates how to use the Ulcer function to calculate the Martin Ratio for a financial instrument.
```thinkScript
declare lower;
input length = 100;
input risk_free_rate = 0.01;
def somedate = 20000101;
def growth = close - close[length];
def days = DaysFromDate(somedate) - DaysFromDate(somedate)[length];
def annualreturn = growth / close[length] * 365 / days;
plot MartinRatio = (annualreturn - risk_free_rate) * 100 / Ulcer(close, length);
```
--------------------------------
### Correlation Calculation Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/Correlation
Demonstrates the use of the built-in Correlation function alongside a custom implementation using Covariance and StDev to verify identical results.
```thinkScript
script correlationTS {
input data1 = close;
input data2 = close;
input length = 12;
plot CorrelationTS = Covariance(data1, data2, length) / ( StDev(data1, length) * StDev(data2, length) );
}
declare lower;
input length = 10;
input secondSymbol = "SPX";
plot Correlation1 = Correlation(close, close(secondSymbol), length);
plot Correlation2 = CorrelationTS(close, close(secondSymbol), length);
```
--------------------------------
### Plotting the base-10 logarithm of close prices
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Lg
This example demonstrates how to use the Lg function to plot the base-10 logarithm of the close price on a lower study.
```thinkScript
declare lower;
plot data = Lg(close);
```
--------------------------------
### Basic Technical Indicator Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-7---Creating-Strategies
A simple script that plots a 20-period Simple Moving Average of the closing price.
```thinkScript
input price = close;
input length = 20;
plot avg = Average(price, length);
```
--------------------------------
### Fundamental Function Usage
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/Fundamental
Example demonstrating the use of the Fundamental function to calculate a ratio between the current symbol's price and a related security.
```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));
```
--------------------------------
### Apply real_size to a lower study
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/real-size
This example demonstrates the use of real_size within a custom ADX indicator script.
```thinkscript
declare lower;
declare real_size;
input length = 14;
input averageType = AverageType.WILDERS;
plot ADX = DMI(length, averageType).ADX;
```
--------------------------------
### Plotting a Standard Error Channel
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/StErrAll
This example demonstrates how to use StErrAll to create a linear regression channel based on the standard error of the closing price.
```thinkScript
input price = close;
def regression = InertiaAll(price);
def stdError = StErrAll(price);
plot UpperLine = regression + stdError;
plot LowerLine = regression - stdError;
```
--------------------------------
### Apply weak_volume_dependency in Keltner Channels
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/weak-volume-dependency
This example demonstrates using the declaration to allow the study to switch subgraphs based on the presence of volume data.
```thinkScript
declare weak_volume_dependency;
input factor = 1.5;
input length = 20;
input price = close;
def shift = factor * AvgTrueRange(high, close, low, length);
def average = Average(price, length);
plot Avg = average;
plot Upper_Band = average + shift;
plot Lower_Band = average - shift;
```
--------------------------------
### GetSplitNumerator Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetSplitNumerator
Calculates adjusted position size by accounting for stock splits using GetSplitNumerator and GetSplitDenominator.
```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;
```
--------------------------------
### Using once_per_bar in a study
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/once-per-bar
This example demonstrates applying the declaration to a study that plots a vertical line at a specific time, where per-tick recalculation is redundant.
```thinkScript
declare once_per_bar;
input time = 0930;
AddVerticalLine(secondsFromTime(time)[1] < 0 && secondsFromTime(time) >= 0, time);
```
--------------------------------
### AddCloud with Price Comparison
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddCloud
Draws a cloud based on the relationship between current and past prices, demonstrating how argument order affects coloring logic.
```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);
```
--------------------------------
### Plotting the last bar day of the year
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetLastDay
This example plots the closing price only for bars that occur on the last day of the current year.
```thinkScript
plot Price = if GetLastDay() == GetDay() and GetLastYear() == GetYear() then close else Double.NaN;
```
--------------------------------
### 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 no negative values are present in the plots.
```thinkScript
declare zerobase;
declare lower;
plot Vol = Volume;
```
--------------------------------
### Using EntryPrice in AddOrder
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/EntryPrice
Demonstrates using EntryPrice to set profit-taking and stop-loss conditions for a Sell order.
```thinkScript
AddOrder(OrderType.SELL_TO_CLOSE, close > EntryPrice() + 3 or close < EntryPrice() - 9);
```
--------------------------------
### Using hide_on_intraday in a study
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/hide-on-intraday
This example demonstrates how to use the declaration to hide a study that relies on data only available for daily or higher aggregations.
```thinkScript
declare hide_on_intraday;
declare lower;
plot OpenInterest = open_interest();
```
--------------------------------
### Compare conditional syntax methods
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-5---Conditional-Expressions
Demonstrates the three different ways to implement the same conditional logic in thinkScript.
```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;
}
```
--------------------------------
### Calculating P/E Ratio
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetActualEarnings
Aggregates earnings over a 252-bar period to calculate a trailing twelve-month P/E ratio. This example is intended for 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);
```
--------------------------------
### Calculate Open Profit/Loss using GetQuantity
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio/GetQuantity
Demonstrates calculating Open P/L manually by multiplying quantity by price differences. Note that this specific formula is valid only for instruments with a dollar value of 1.
```thinkScript
declare lower;
def qty = GetQuantity();
def openCost = qty * GetAveragePrice();
def netLiq = qty * close;
plot ManualOpenPL = netLiq - openCost;
plot AutoOpenPL = GetOpenPL();
```
--------------------------------
### Reference study variables
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/reference
Example of referencing internal variables (def) from the ATRTrailingStop study.
```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));
```
--------------------------------
### Display Trading Days Since Year Start
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/CountTradingDays
Calculates and displays the number of trading days from January 1st of the current year to the present date in a chart label.
```thinkScript
def yearstart = GetYear() * 10000 + 101;
AddLabel(yes, CountTradingDays(yearstart, GetYYYYMMDD()) + " trading days since year start");
```
--------------------------------
### Define a lowercase input parameter
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input
Example of defining an input variable with a lowercase name.
```thinkScript
input test = "test in lowercase";
```
--------------------------------
### Reference study with parameters
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/reference
Illustrates full and compact forms for passing parameters to a study.
```thinkScript
plot MyBB2 = BollingerBandsSMA(price = open, displace = 0, length = 30);
```
```thinkScript
plot MyBB = BollingerBandsSMA(open, 0, 30);
```
--------------------------------
### Comparing Built-in and Custom LinDev
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/LinDev
Demonstrates the equivalence between the built-in LinDev function and a manual implementation using a script block.
```thinkScript
script LinDevTS {
input data = close;
input length = 12;
def avgData = Average(data, length);
plot LinDevTS = ( fold i = 0 to length with LD do LD + AbsValue(avgData - GetValue(data, i)) ) / length;
}
declare lower;
input length = 12;
plot LinDev1 = LinDev(close, length);
plot LinDev2 = LinDevTS(close, length);
```
--------------------------------
### Construct Logical Expressions
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-6---Human-Readable-Syntax
Demonstrates building complex logical conditions using natural language keywords like 'is equal to', 'is greater than', and 'is false'.
```thinkScript
def condition1 = open is equal to close;
def condition2 = close is greater than Average(close,9);
def condition3 = condition1 is false and condition2 is false;
```
--------------------------------
### Calculate Open Profit/Loss using GetAveragePrice
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio/GetAveragePrice
Demonstrates manual calculation of Open Profit/Loss by combining GetAveragePrice and GetQuantity, compared against the built-in GetOpenPL function.
```thinkScript
declare lower;
def qty = GetQuantity();
def openCost = qty * GetAveragePrice();
def netLiq = qty * close;
plot ManualOpenPL = netLiq - openCost;
plot AutoOpenPL = GetOpenPL();
```
--------------------------------
### Recursive usage example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/if
Demonstrates using an if-statement to track the highest high value recursively.
```thinkScript
def myHigh;
if high > myHigh[1] {
myHigh = high;
} else {
myHigh = myHigh[1];
}
plot H = myHigh;
```
--------------------------------
### Calculate Vega and Approximate Vega
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/Vega
Demonstrates the built-in Vega function alongside a manual approximation method using a small change in implied volatility.
```thinkScript
declare lower;
def epsilon = 0.01 * imp_volatility(GetUnderlyingSymbol());
plot approxVega = (OptionPrice(Volatility = imp_volatility(GetUnderlyingSymbol()) + epsilon) - OptionPrice()) / epsilon / 100;
plot Vega = vega();
```
--------------------------------
### Invalid If Function Usage
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/If
Example of a compilation error caused by passing non-double types to the If function.
```thinkScript
AssignPriceColor(if(close > open, Color.UPTICK, Color.DOWNTICK));
```
--------------------------------
### Defining Study and Input Hints
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-C---Customizing-Study-Hints
Use the #hint prefix before declarations to provide descriptive text for the study or specific inputs.
```thinkScript
#hint: Hints
This study demonstrates hints.
And hints for inputs as well.
#hint length: Nothing depends on this parameter.
input price = close;
input length = 12;
plot Data = price;
```
--------------------------------
### SetPaintingStrategy usage example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/SetPaintingStrategy
Sets the plot style to a histogram format using the PaintingStrategy constant.
```thinkScript
plot Data = open;
Data.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
```
--------------------------------
### Compare Composite Symbol Parts
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/GetSymbolPart
Demonstrates how to perform string comparisons on symbol parts by including the namespace.
```thinkScript
AddLabel(GetSymbolPart(1) == "/ES:XCME" or GetSymbolPart(2) == "/ES:XCME", "Composite symbol contains /ES!");
```
--------------------------------
### Plotting Open Price with open Function
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Fundamentals/open
Demonstrates how to define inputs for symbol, period, and price type to plot the opening price of a currency pair.
```thinkscript
input symbol = "EUR/USD";
input period = AggregationPeriod.MONTH;
input price_type = {default "LAST", "BID", "ASK", "MARK"};
plot Data = open(symbol, period, price_type);
```
--------------------------------
### Compare Custom and Built-in Average Implementation
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Average
Demonstrates how a custom script implementation of an average compares to the built-in Average function.
```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);
```
--------------------------------
### AssignValueColor Plot Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignValueColor
Applies conditional coloring to a plot based on whether the price difference is positive or negative.
```thinkscript
plot Diff = close - close[1];
Diff.AssignValueColor(if Diff >= 0 then Color.UPTICK else Color.DOWNTICK);
```
--------------------------------
### Calculate cumulative volume using rec
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/rec
Demonstrates how to use rec to create a running total of volume over time.
```thinkScript
rec C = C[1] + volume;
plot CumulativeVolume = C;
```
--------------------------------
### GetValue Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/GetValue
Retrieves the closing price of the bar where the highest high occurred within the last twelve bars.
```thinkScript
plot ClosingPriceForHighestHigh = GetValue(close, GetMaxValueOffset(high, 12), 12);
```
--------------------------------
### Using PriceType.ASK in a script
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/PriceType/PriceType-ASK
Demonstrates how to assign PriceType.ASK to an input and use it within a function to plot the ask price.
```thinkScript
input priceType = PriceType.ASK;
plot AskPrice = open(priceType = priceType);
```
--------------------------------
### Plotting a TPO Profile
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Profiles/TimeProfile
Displays a TPO profile study on the chart expansion area using a custom start condition.
```thinkScript
def allchart = 0;
profile tpo = TimeProfile("startnewprofile"=allchart);
tpo.Show("color"=Color.BLUE);
```
--------------------------------
### Using the Between Function
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/Between
Demonstrates the usage of the Between function compared to a manual double inequality implementation.
```thinkScript
declare lower;
input lowLimit = 140.0;
input highLimit = 160.0;
plot Between1 = Between(close, lowLimit, highLimit);
plot Between2 = close >= lowLimit and close <= highLimit;
```
--------------------------------
### Using Equality and Inequality Operators
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions
Demonstrates the use of equality (==) and inequality (!=, <>) operators for comparing bar data.
```thinkScript
def a = close==open;
def b = close!=open;
def c = close<>open;
```
--------------------------------
### ReturnOnEquity Function Syntax
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals/ReturnOnEquity
The basic syntax for the ReturnOnEquity function, showing the required parameters for symbol and fiscal period.
```thinkScript
ReturnOnEquity ( Symbol symbol , int fiscalPeriod );
```
--------------------------------
### HideTitle Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/HideTitle
Demonstrates hiding the titles of specific plots in a Price Oscillator study to simplify the graph title display.
```thinkScript
declare lower;
plot PriceOsc = Average(close, 9) - Average(close, 18);
plot PriceOscLine = PriceOsc;
plot ZeroLine = 0;
PriceOsc.SetDefaultColor(Color.VIOLET);
PriceOsc.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
PriceOscLine.SetDefaultColor(Color.LIGHT_GRAY);
PriceOscLine.HideTitle();
ZeroLine.SetDefaultColor(Color.PINK);
ZeroLine.HideTitle();
```
--------------------------------
### Using IsInfinite for Division Error Handling
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/IsInfinite
Demonstrates using IsInfinite to detect infinite results from division by zero and assigning a default value.
```thinkScript
declare lower;
input dividend = 10;
input divisor = 0;
def tempResult = dividend / divisor;
plot Result = if IsInfinite(tempResult) then 0 else tempResult;
```
--------------------------------
### Applying Power and Logarithmic Functions
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions
Calculates various power and logarithmic values based on the ratio of close to open prices.
```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);
```
--------------------------------
### GetSplitDenominator Usage Example
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetSplitDenominator
Draws a vertical line on the chart to label stock splits or reverse splits based on the relationship between the numerator and denominator.
```thinkScript
AddVerticalLine(!IsNaN(GetSplitDenominator()), if GetSplitNumerator() > GetSplitDenominator()
then "Split!"
else "Reverse Split!", Color.GRAY);
```
--------------------------------
### Calculate Delta and Approximate Delta in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/Delta
Demonstrates the built-in Delta function alongside a manual approximation method using OptionPrice changes.
```thinkScript
declare lower;
def epsilon = 0.01 * close(GetUnderlyingSymbol());
plot approxDelta = (OptionPrice(underlyingPrice = close(GetUnderlyingSymbol()) + epsilon) - OptionPrice()) / epsilon;
plot Delta = Delta();
```
--------------------------------
### String Comparison in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Operators/Comparison
Demonstrates applying equality and inequality operators to string data returned by getSymbolPart.
```thinkScript
def a = getSymbolPart(1) == "SPX";
def b = getSymbolPart(1) != "GOOG";
```
--------------------------------
### Plotting Weekly Volume Profile Highs
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Profiles/GetHighest
Calculates and plots the highest price for each weekly volume profile using a conditional start trigger.
```thinkScript
def yyyymmdd = GetYYYYMMDD();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));
def period = Floor(day_number / 7);
def cond = 0 < period - period[1];
profile vol = VolumeProfile("startNewProfile" = cond, "onExpansion" = no);
vol.Show();
plot b = vol.GetHighest();
```
--------------------------------
### Show(color, poc color, va color, opacity, open color, close color, ib color, volume color, volume va color, volume poc color)
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Profiles/Show
The Show function controls the visibility and color scheme of Time, Volume, and Monkey Bars profiles. Profiles calculated by corresponding functions are only visible if the Show function is applied to them.
```APIDOC
## Show
### Description
Controls the visibility and color scheme of Time, Volume, and Monkey Bars profiles. Profiles are only visible when this function is applied to them.
### Parameters
- **color** (CustomColor) - Optional - Defines the main color of Time and Volume profile bars. Default: Color.PLUM
- **poc color** (CustomColor) - Optional - Defines the color of the Point of Control. Default: Color.CURRENT
- **va color** (CustomColor) - Optional - Defines the color of the Value Area. Default: Color.CURRENT
- **opacity** (double) - Optional - Sets the degree of histogram opacity, in percent. Default: 50.0
- **open color** (CustomColor) - Optional - Defines the color of the square marking the Monkey Bars' Open price. Default: Color.CURRENT
- **close color** (CustomColor) - Optional - Defines the color of the arrow marking the Monkey Bars' Close price. Default: Color.CURRENT
- **ib color** (CustomColor) - Optional - Defines the color of the Initial Balance bracket (affects MonkeyBars). Default: Color.CURRENT
- **volume color** (CustomColor) - Optional - Defines the color of the Volume Profile (affects MonkeyBars). Default: Color.PLUM
- **volume va color** (CustomColor) - Optional - Defines the color of the Value Area of Volume Profile (affects MonkeyBars). Default: Color.CURRENT
- **volume poc color** (CustomColor) - Optional - Defines the color of the Point of Control of Volume Profile (affects MonkeyBars). Default: Color.CURRENT
### Example
```
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);
```
```
--------------------------------
### Calculate Variance using Sqr
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Sqr
Demonstrates calculating the variance of the closing price by squaring the standard deviation.
```thinkScript
declare lower;
plot Data = Sqr(StDev(close, 10));
```
--------------------------------
### Rounding Values with thinkScript Functions
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-2---Mathematical-Functions
Demonstrates rounding, ceiling, and floor functions using the Double.E constant.
```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);
```
--------------------------------
### Hide study on daily charts
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Declarations/hide-on-daily
This example demonstrates using hide_on_daily to prevent a Simple Moving Average plot from appearing on daily aggregation periods.
```thinkScript
declare hide_on_daily;
plot SMA = average(close);
SMA.AssignValueColor(GetColor(secondsFromTime(0) / 3600));
```
--------------------------------
### Calculate Money Flow in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/MoneyFlow
Demonstrates a custom implementation of money flow alongside the built-in MoneyFlow function.
```thinkScript
script moneyflowTS {
input high = high;
input close = close;
input low = low;
input volume = volume;
input length = 14;
def price = high + close + low;
def moneyFlow = price * volume;
def positiveMoneyFlow = Sum(if price >price[1] then MoneyFlow else 0, length);
def totalMoneyFlow = Sum(MoneyFlow, length);
plot moneyflowTS = if totalMoneyFlow != 0 then 100 * positiveMoneyFlow / totalMoneyFlow else 0;
}
declare lower;
input length = 14;
plot moneyflow1 = MoneyFlow(high, close, low, volume, length);
plot moneyflow2 = MoneyFlowTS(high, close, low, volume, length);
```
--------------------------------
### Correct Multi-Aggregation Handling
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Advanced/Chapter-11---Referencing-Secondary-Aggregation
Shows the correct approach to combining different secondary aggregation periods by splitting them into separate variables.
```thinkScript
def a = close(period = AggregationPeriod.MONTH);
def b = close(period = AggregationPeriod.WEEK);
plot Data = a + b;
```
--------------------------------
### Rounding Price Data with RoundUp
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/RoundUp
Demonstrates using RoundUp and RoundDown to plot price bands rounded to a specific number of digits.
```thinkScript
input price = close;
input digits = 0;
plot ceiling = RoundUp(price, digits);
plot floor = RoundDown(price, digits);
```
--------------------------------
### Calculate Price Plot Based on Time Duration
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/SecondsTillTime
This example plots the closing price when the remaining time until the specified close time is within the defined duration.
```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;
```
--------------------------------
### GetNextITMOption(String optionCode)
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Option-Related/GetNextITMOption
Returns the code of the next option in the same series as the input one. For a Put option, it returns the next option with a higher strike; for a Call option, it returns the next option with a lower strike.
```APIDOC
## GetNextITMOption
### Description
Returns the code of the next option in the same series as the input one. For a Put option, the code of the next option with higher strike will be returned; for a Call option, this function will return the code of the next option with lower strike.
### Signature
`GetNextITMOption(String optionCode)`
### Parameters
- **optionCode** (String) - Required - The input option code.
### Example
`AddLabel(yes, "Next ITM option is" + GetNextITMOption(".GOOG120317C580"));`
```
--------------------------------
### Identify Three Consecutive Doji Candles
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/IsDoji
This example plots a boolean point when three consecutive candles meet the Doji criteria using a custom length of 25.
```ThinkScript
input length = 25;
def IsDoji = IsDoji(length);
plot ThreeDoji = IsDoji[2] and
IsDoji[1] and
IsDoji;
ThreeDoji.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
```
--------------------------------
### Hide a plot in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/Hide
Use this function to set a plot's default visibility to hidden. The example demonstrates hiding the PriceOpen plot while keeping PriceClose visible.
```thinkScript
plot PriceClose = close;
plot PriceOpen = open;
PriceOpen.Hide();
```
--------------------------------
### Plotting the high of the last week in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetLastWeek
This example uses GetLastWeek in conjunction with GetWeek and GetYear to isolate and plot the high price of the final week of the current year.
```thinkScript
plot Price = if GetLastWeek() == GetWeek() and GetLastYear() == GetYear() then high else Double.NaN;
```
--------------------------------
### Compare Price and Moving Average using Max
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Max
Compares the closing price with a simple moving average and plots the higher of the two values.
```thinkScript
def SMA = SimpleMovingAvg();
plot data = Max(close, SMA);
```
--------------------------------
### Calculate Williams %R using Lowest
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Lowest
Demonstrates the use of the Lowest function to determine the minimum low value over a specified period for the Williams %R indicator.
```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);
```
--------------------------------
### Demonstrate Parameter Order Independence in thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions
Shows that the average function produces the same result regardless of the order in which data and length parameters are provided.
```thinkScript
plot SMA = average(data = close, length = 50)
```
```thinkScript
plot SMA = average(length = 50, data = close)
```
--------------------------------
### StDevAll(data, length, startDate, startTime, extendToLeft, extendToRight)
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/StDevAll
Calculates the standard deviation of the provided data. If length is not specified, it calculates for the entire plot. startDate and startTime can be used to define a specific starting point for the calculation.
```APIDOC
## StDevAll(data, length, startDate, startTime, extendToLeft, extendToRight)
### Description
Returns the standard deviation of `data` for the entire plot or for the interval of the last bars defined by the `length` parameter. Unlike `StDev`, the output result for the last bar is used for the whole interval calculated.
### Parameters
- **data** (IDataHolder) - Required - The variable for which the standard deviation is calculated.
- **length** (int) - Optional (Default: all chart) - Number of the last bars for which the curve is plotted.
- **startDate** (int) - Optional (Default: 0) - Starting date in YYYYMMDD format.
- **startTime** (int) - Optional (Default: 0) - Starting time in HHMM format.
- **extendToLeft** (double) - Optional (Default: No) - Defines whether to extend the curve to the left.
- **extendToRight** (double) - Optional (Default: No) - Defines whether to extend the curve to the right.
### Example
```
input price = close;
def regression = InertiaAll(price, 30);
def stdDeviation = StDevAll(price, 30);
plot UpperLine = regression + stdDeviation;
plot LowerLine = regression - stdDeviation;
```
```
--------------------------------
### Visualizing Infinite Bounds with AddCloud
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-D---Using-NaN-and-Infinity-Constants
Assigns infinite values to variables to create colored stripes based on price conditions 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);
```
--------------------------------
### Calculate Donchian Channels using Highest
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/Highest
Demonstrates calculating the upper and lower bands of a Donchian Channel by finding the highest high and lowest low of the previous bars.
```thinkScript
input length = 20;
plot LowerBand = Lowest(low[1], length);
plot UpperBand = Highest(high[1], length);
plot MiddleBand = (LowerBand + UpperBand) / 2;
```
--------------------------------
### QuickRatio(Symbol symbol, int fiscalPeriod)
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals/QuickRatio
Calculates the quick ratio for a specified symbol and fiscal period.
```APIDOC
## QuickRatio(Symbol symbol, int fiscalPeriod)
### Description
The `QuickRatio` function returns the ratio of a company's cash, short-term investments, and net receivables to its total current liabilities. The value is calculated based on annual fiscal data.
### Parameters
- **symbol** (Symbol) - Optional - The symbol to calculate the ratio for. Defaults to the current symbol.
- **fiscalPeriod** (int) - Optional - The fiscal period for the calculation. Defaults to `FiscalPeriod.YEAR`. Note: `FiscalPeriod.QUARTER` is not supported.
```
--------------------------------
### GetNetLiq()
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio/GetNetLiq
Returns the net liquidation value for the currently selected account.
```APIDOC
## GetNetLiq()
### Description
The `GetNetLiq` function returns the net liquidation value for the currently selected account. It represents the current account value if all positions on that account were to be closed at the current market price.
### Syntax
`GetNetLiq()`
### Notes
Studies using this function will return N/A if the 'Show Extended-Hours Trading session' chart property is deactivated. Ensure this is enabled in Style -> Settings under the relevant security tab (Equities, Options, or Futures) in the Axis area.
```
--------------------------------
### Calculate Fibonacci Sequence with CompoundValue
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/CompoundValue
Demonstrates using recursion to calculate Fibonacci numbers where the first two bars are initialized to 1 and subsequent bars are the sum of the previous two.
```thinkScript
declare lower;
def x = CompoundValue(2, x[1] + x[2], 1);
plot FibonacciNumbers = x;
```
--------------------------------
### TotalAssetTurnover Function Syntax
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Stock-Fundamentals/TotalAssetTurnover
The standard syntax for calling the TotalAssetTurnover function with symbol and fiscal period parameters.
```thinkScript
TotalAssetTurnover ( Symbol symbol , int fiscalPeriod );
```
--------------------------------
### Converting an Indicator to a Strategy
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-7---Creating-Strategies
Demonstrates using the AddOrder function to trigger buy and sell signals when the price crosses the moving average.
```thinkScript
input price = close;
input length = 20;
def avg = Average(price, length);
AddOrder(OrderType.BUY_AUTO, price crosses above avg);
AddOrder(OrderType.SELL_AUTO, price crosses below avg);
```
--------------------------------
### Implementing Secondary Aggregation in a Stochastic Study
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Advanced/Chapter-11---Referencing-Secondary-Aggregation
This script demonstrates how to rewrite a Stochastic Full study to support a secondary aggregation period using FundamentalType and the Fundamental function.
```thinkScript
declare lower;
input over_bought = 80;
input over_sold = 20;
input KPeriod = 10;
input DPeriod = 10;
input priceH = FundamentalType.HIGH;
input priceL = FundamentalType.LOW;
input priceC = FundamentalType.CLOSE;
input aggregationPeriod = AggregationPeriod.DAY;
input slowing_period = 3;
input smoothingType = {Default SMA, EMA};
def lowest_k = Lowest(Fundamental(priceL, period = aggregationPeriod), KPeriod);
def c1 = Fundamental(priceC, period = aggregationPeriod) - lowest_k;
def c2 = Highest(Fundamental(priceH, period = aggregationPeriod), KPeriod) - lowest_k;
def FastK = if c2 != 0 then c1 / c2 * 100 else 0;
plot FullK;
plot FullD;
switch(smoothingType) {
case SMA:
FullK = Average(FastK, slowing_period);
FullD = Average(FullK, DPeriod);
case EMA:
FullK = ExpAverage(FastK, slowing_period);
FullD = ExpAverage(FullK, DPeriod);
}
plot OverBought = over_bought;
plot OverSold = over_sold;
```
--------------------------------
### AddCloud with Infinite Bounds
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddCloud
Highlights chart areas using infinite bounds to create vertical stripes based on price averages.
```thinkScript
def hiLevel = if close >= Average(close) then Double.POSITIVE_INFINITY else Double.NEGATIVE_INFINITY;
AddCloud(hiLevel, -hiLevel, Color.LIGHT_GREEN, Color.LIGHT_RED);
```
--------------------------------
### Calculating Dividend Yield with thinkScript
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetDividend
Calculates an annual dividend projection and displays the yield percentage as a chart label.
```thinkScript
declare lower;
def DCont = if IsNaN(GetDividend()) then DCont[1] else GetDividend();
plot DivA = if DCont <> 0 then DCont * 4 else Double.NaN;
def yield = DivA / close * 100;
AddLabel(yes, yield + "% Yield", DivA.TakeValueColor());
```
--------------------------------
### Calculate and Plot P/L Percentage
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio/GetOpenPL
Calculates the percentage of Open Profit/Loss using GetOpenPL, GetQuantity, and GetAveragePrice. Note that this manual calculation is valid only for symbols with a dollar value of 1.
```thinkScript
declare lower;
def openCost = GetQuantity() * GetAveragePrice();
plot PercentPL = GetOpenPL() / AbsValue(openCost) * 100;
PercentPL.AssignValueColor(if PercentPL >= 0 then Color.UPTICK else Color.DOWNTICK);
```
--------------------------------
### Accessing Past and Future Price Data
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Operators/Indexing
Demonstrates shifting price data using positive and negative indices.
```thinkscript
input price = close;
input shift = 5;
plot PastPrice = price[shift];
plot FuturePrice = price[-shift];
```
--------------------------------
### Conditional Logic with Comparison Operators
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Operators/Comparison
Demonstrates using equality and inequality operators to select an averaging function and control label visibility.
```thinkScript
input price = close;
input length = 12;
input StudyType = {default SMA, EMA};
plot Avg;
if (StudyType == StudyType.SMA) {
Avg = Average(price, length);
} else {
Avg = ExpAverage(price, length);
}
AddLabel(StudyType != StudyType.SMA, "Exponential moving average is displayed.");
```
--------------------------------
### Full AddOrder Function Syntax
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-7---Creating-Strategies
The complete syntax for the AddOrder function, allowing for customization of trade size, colors, and labels.
```thinkScript
AddOrder(type, condition, price, tradeSize, tickColor, arrowColor, name);
```
--------------------------------
### AddCloud with Border Visibility
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddCloud
Draws a translucent cloud between open and close prices with a visible border.
```thinkScript
def OpenPrice = open;
def ClosePrice = close;
AddCloud(OpenPrice, ClosePrice, color.RED, color.GREEN, yes);
```
--------------------------------
### Defining Price Inputs
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Basic/Chapter-3---Defining-Inputs
Using the input keyword to allow users to change price data ratios dynamically.
```thinkScript
input val1 = close;
input val2 = open;
def data = Exp (val1/val2);
```
--------------------------------
### Using equals for Doji Pattern Detection
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/equals
This snippet plots points on bars where the open and close prices are equal, identifying the Doji pattern.
```thinkScript
plot Doji = open equals close;
Doji.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
```
--------------------------------
### Define and use a price input
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/input/price
Sets a default price input to close and uses it to calculate an Exponential Moving Average.
```thinkScript
input price = close;
plot EMA = ExpAverage(price, 10);
```
--------------------------------
### Highlight Local Minimums
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/Operators/Logical
Uses the logical AND operator to identify and plot local minimums based on price comparisons.
```thinkScript
plot LocalMinimum = low < low[1] and low < low[-1];
LocalMinimum.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
```
--------------------------------
### Basic alert function syntax
Source: https://toslc.thinkorswim.com/center/reference/thinkScript/tutorials/Appendices/Appendix-A---Creating-Local-Alerts
The standard syntax for defining a local alert in thinkScript.
```thinkScript
alert(condition, text, alert type, sound);
```