Skip to main content

Open Scripts

The Open Scripts feature lets you create your own custom technical indicators and trading strategies right inside the charting application—no coding experience required! Think of it as your personal toolkit for building custom analysis tools that work exactly the way you want them to.

What Can You Do With Open Scripts?

Create Custom Indicators

Build your own technical indicators to analyze price patterns, momentum, volatility, and more. Examples include:

  • Custom RSI indicators with your preferred overbought/oversold levels
  • Bollinger Band variations with different settings
  • Support and resistance lines based on your favorite timeframes
  • Price channel analysis to identify trends and breakouts

Test Trading Strategies

Develop and test your own trading strategies before risking real money:

  • Moving average crossovers (like the classic 50-day/200-day strategy)
  • RSI-based entry/exit rules for overbought and oversold conditions
  • MACD confirmation strategies that combine multiple signals
  • Multi-indicator combinations that give you higher-confidence trade setups

Visualize Your Ideas

Add custom visual elements to your charts:

  • Trendlines and channels that automatically adjust to price movements
  • Custom labels and annotations that highlight important price levels
  • Drawing shapes like rectangles and boxes to mark key areas
  • Fill areas between plots to visualize ranges and bands

How to Get Started (Step-by-Step)

1. Opening the Script Editor

  1. Look for the "Open Scripts" button in the right sidebar of your chart
  2. Click it to open the script editor panel
  3. You'll see three tabs: Script, Saved, and GPT

2. Creating Your First Script

Option A: Start with a Template

  • Click the "Open script" button at the top of the editor
  • Choose from built-in templates like "Indicator", "Fill Bands", or "Strategy"
  • The template code will appear in the editor

Option B: Write from Scratch

  • Simply start typing in the editor
  • Use simple, intuitive commands (no complex programming needed)

3. Understanding the Basics

All scripts follow this simple pattern:

// Declare what type of script you're creating
indicator("My Custom Indicator")

// Calculate values using built-in functions
value = sma(close, 20)

// Display the results on your chart
plot(value)

Common building blocks you'll use:

  • sma(), ema(), rsi(), macd() - For calculating technical indicators
  • plot() - To display lines on your chart
  • fill() - To color areas between plots
  • alertcondition() - To get notified when conditions are met

4. Saving Your Work

  • Click "Save" to save a new script
  • Click "Update" to save changes to an existing script
  • All your scripts are automatically saved to your browser (they'll be there next time you log in)

5. Applying Your Script to the Chart

  • Click the "Apply" button to instantly add your custom indicator to the chart
  • Your script will run automatically as new price data comes in
  • You can have multiple custom indicators running simultaneously

Practical Examples

Simple Moving Average

indicator("20-Day SMA")
sma20 = sma(close, 20)
plot(sma20, color="blue")

RSI with Alerts

indicator("RSI Alert")
rsiValue = rsi(close, 14)
plot(rsiValue, color="purple")
plot(70, color="red")
plot(30, color="green")
alertcondition(rsiValue > 70, "RSI Overbought", "RSI crossed above 70")

Basic Trading Strategy

strategy("SMA Crossover")
fast = sma(close, 10)
slow = sma(close, 20)
if fast > slow
strategy.entry("Long", strategy.long)
if fast < slow
strategy.entry("Short", strategy.short)

Customizing Your Scripts

Adjustable Settings

You can make your scripts flexible by adding customizable inputs:

// This creates a slider in the indicator settings
length = input(20, "Lookback Period", min=5, max=100, step=5)

// This creates a dropdown menu for choosing data sources
source = input(close, "Data Source")

When you apply the script, you'll see these options in the indicator's settings panel where you can adjust them without editing code.

What's Possible (and What's Not)

✅ What Works Great

  • Creating custom technical indicators and trading strategies
  • Real-time calculation as new price data arrives
  • Saving and organizing your favorite scripts
  • Getting alerts when your custom conditions are met
  • Combining multiple indicators in one script
  • Visualizing your ideas with lines, colors, and shapes

❌ What's Not Supported

  • Importing scripts from external files or websites
  • Making web requests or connecting to external services
  • Running scripts in the background when the chart isn't open
  • Complex programming features like loops or custom functions
  • Sharing scripts directly with other users (they need to copy/paste)

Available Building Blocks

Here's a complete list of all the functions you can use in your Open Scripts, organized by category:

Technical Indicators

FunctionDescription
sma(source, length)Simple Moving Average - calculates the average price over a specified number of periods
ema(source, length)Exponential Moving Average - gives more weight to recent prices
wma(source, length)Weighted Moving Average - weights recent prices more heavily
vwma(source, length)Volume-Weighted Moving Average - weights prices by trading volume
rma(source, length)Wilder's Moving Average - exponential smoothing with Wilder's method
hma(source, length)Hull Moving Average - reduces lag while maintaining smoothness
tema(source, length)Triple Exponential Moving Average - reduces lag further
dema(source, length)Double Exponential Moving Average - reduces lag
kama(source, length)Kaufman Adaptive Moving Average - adapts to market volatility
frama(source, length)Fractal Adaptive Moving Average - adapts to market fractals
lsma(source, length)Least Squares Moving Average - linear regression-based
smma(source, length)Smoothed Moving Average - modified EMA
trima(source, length)Triangular Moving Average - double-smoothed SMA
t3(source, length)T3 Moving Average - triple EMA with additional smoothing
rsi(source, length)Relative Strength Index - measures momentum on a scale of 0-100
stoch(k_length, d_length)Stochastic Oscillator - compares closing price to price range
stoch_rsi(source, length)Stochastic RSI - applies stochastic to RSI values
cci(length)Commodity Channel Index - identifies cyclical trends
mom(source, length)Momentum - measures rate of change
roc(source, length)Rate of Change - percentage change over period
trix(source, length)Triple Exponential Average - smooth trend indicator
dmi(length)Directional Movement Index - measures trend direction
adx(length)Average Directional Index - measures trend strength
supertrend(period, multiplier)SuperTrend - trend-following indicator
parabolic_sar(step, max)Parabolic SAR - trend reversal indicator
ultimate_oscillator(short, medium, long)Ultimate Oscillator - multi-timeframe momentum
awesome_oscillator(short, long)Awesome Oscillator - momentum comparison
williams_r(length)Williams %R - overbought/oversold oscillator
balance_of_power()Balance of Power - compares buying/selling pressure
fisher_transform(source, length)Fisher Transform - converts prices to Gaussian distribution
true_strength_index(source, short, long)True Strength Index - smoothed RSI
chande_momentum_oscillator(source, length)Chande Momentum Oscillator - bounded momentum
detrended_price_oscillator(source, length)Detrended Price Oscillator - removes trend component
atr(length)Average True Range - measures market volatility
true_range()True Range - greatest of high-low, high-close, low-close
stdev(source, length)Standard Deviation - measures price dispersion around the mean
stddev(source, length)Standard Deviation - alternative name for stdev
variance(source, length)Variance - square of standard deviation
sum(source, length)Sum of values over specified period
avg(source, length)Average of values over specified period
median(source, length)Median value over specified period
highest(source, length)Highest value over specified period
lowest(source, length)Lowest value over specified period
highestbars(source, length)Bars since highest value
lowestbars(source, length)Bars since lowest value
change(source, length)Price change over specified period
percent_change(source, length)Percentage change over specified period
hl2High-Low Average - (high + low) / 2
hlc3High-Low-Close Average - (high + low + close) / 3
ohlc4Open-High-Low-Close Average - (open + high + low + close) / 4
typical_priceTypical Price - (high + low + close) / 3
median_priceMedian Price - (high + low) / 2
weighted_closeWeighted Close - (high + low + 2 * close) / 4
vwap(source)Volume Weighted Average Price - average price weighted by volume
obv()On-Balance Volume - cumulative volume flow indicator
mfi(length)Money Flow Index - volume-weighted RSI
accdist()Accumulation/Distribution - money flow indicator
money_flow_index(length)Money Flow Index - alternative name for mfi
accumulation_distribution()Accumulation/Distribution - alternative name for accdist
chaikin_money_flow(length)Chaikin Money Flow - volume-weighted accumulation
chaikin_oscillator(short, long)Chaikin Oscillator - difference between EMAs
volume_oscillator(short, long)Volume Oscillator - compares volume EMAs
volume_profile()Volume Profile - displays volume at price levels
ease_of_movement()Ease of Movement - relates price change to volume
price_volume_trend()Price Volume Trend - cumulative volume flow
pivot_points()Pivot Points - key support/resistance levels
fibonacci_retracement()Fibonacci Retracement - key retracement levels
fibonacci_extension()Fibonacci Extension - extension levels
linear_regression(source, length)Linear Regression - trend line calculation
linear_regression_slope(source, length)Linear Regression Slope - trend strength
linear_regression_channel(source, length)Linear Regression Channel - trend channel
bollinger(source, length, mult)Bollinger Bands - price bands based on standard deviation
bb(source, length, mult)Bollinger Bands - alternative name for bollinger
bollinger_bands(source, length, mult)Bollinger Bands - alternative name for bollinger
bollinger_bandwidth(source, length, mult)Bollinger Bandwidth - width as percentage
keltner(source, length, mult)Keltner Channels - volatility-based channels
keltner_channels(source, length, mult)Keltner Channels - alternative name
donchian(source, length)Donchian Channels - highest high/lowest low
donchian_channels(source, length)Donchian Channels - alternative name
donchian_channel(source, length)Donchian Channel - alternative name
keltner_channel(source, length, mult)Keltner Channel - alternative name
price_channel(source, length)Price Channel - highest high/lowest low
moving_average_envelope(source, length, mult)Moving Average Envelope - bands around MA
choppiness_index(length)Choppiness Index - measures market chop
historical_volatility(source, length)Historical Volatility - standard deviation of returns
standard_deviation(source, length)Standard Deviation - alternative name for stdev
zscore(source, length)Z-Score - standard deviations from mean
covariance(a, b, length)Covariance - relationship between two series
beta(a, b, length)Beta - sensitivity to market movements
mode(source, length)Mode - most frequent value
correlation(a, b, length)Correlation - linear relationship between two series
correlation_matrix(a, b, c, length)Correlation Matrix - correlations between multiple series
skewness(source, length)Skewness - asymmetry of distribution
kurtosis(source, length)Kurtosis - peakedness of distribution
heikin_ashi()Heikin-Ashi - smoothed candlestick pattern
renko()Renko - brick-based chart
kagi()Kagi - line-based chart
line_break()Line Break - three-line break chart
point_and_figure()Point and Figure - column-based chart
relative_vigor_index(source, length)Relative Vigor Index - momentum oscillator
elder_ray(source, length)Elder Ray - bull/bear power indicator
bull_power(source, length)Bull Power - buying pressure
bear_power(source, length)Bear Power - selling pressure
commodity_selection_index()Commodity Selection Index - momentum comparison
force_index(source, length)Force Index - price change × volume
stochastic_oscillator(k_length, d_length)Stochastic Oscillator - alternative name for stoch
stochastic_fast(k_length, d_length)Stochastic Fast - faster stochastic
stochastic_slow(k_length, d_length)Stochastic Slow - slower stochastic
advance_decline()Advance/Decline - market breadth indicator
trin()TRIN - market sentiment indicator
mcclellan_oscillator(short, long)McClellan Oscillator - market breadth
mcclellan_summation(short, long)McClellan Summation - cumulative oscillator
volatility_stop(source, length, mult)Volatility Stop - trailing stop
zigzag(source, percent)Zig Zag - significant price movements
fractals()Fractals - swing high/low patterns
pivot_high()Pivot High - swing high points
pivot_low()Pivot Low - swing low points
market_structure()Market Structure - trend identification
security(symbol, timeframe, series)Security - multi-timeframe data access
willr(length)Williams %R - alternative name for williams_r
ultimate_osc(short, medium, long)Ultimate Oscillator - alternative name
awesome_osc(short, long)Awesome Oscillator - alternative name
bb_percent_b(source, length, mult)Bollinger %B - position within bands
bb_width(source, length, mult)Bollinger Width - band width
fisher(source, length)Fisher Transform - alternative name
elder_force_index(source, length)Elder Force Index - alternative name
efi(source, length)Elder Force Index - alternative name
ease_of_movement(source, length)Ease of Movement - alternative name
eom(source, length)Ease of Movement - alternative name
vortex(source, length)Vortex Indicator - trend identification
vortex_pos(source, length)Vortex Positive - positive trend component
vortex_indicator(source, length)Vortex Indicator - alternative name
coppock(source, length)Coppock Curve - long-term momentum
coppock_curve(source, length)Coppock Curve - alternative name
cmo(source, length)Chande Momentum Oscillator - alternative name
chande_momentum(source, length)Chande Momentum - alternative name
tsi(source, short, long)True Strength Index - alternative name
smi(source, short, long)Stochastic Momentum Index - momentum oscillator
kst(source, roc1, roc2, roc3, roc4, sma1, sma2, sma3, sma4)Know Sure Thing - momentum composite
know_sure_thing(source, roc1, roc2, roc3, roc4, sma1, sma2, sma3, sma4)Know Sure Thing - alternative name
dpo(source, length)Detrended Price Oscillator - alternative name
detrended_price_oscillator(source, length)Detrended Price Oscillator - alternative name
aroon_up(source, length)Aroon Up - uptrend strength
aroon_down(source, length)Aroon Down - downtrend strength
aroon_osc(source, length)Aroon Oscillator - difference between up/down
ichimoku()Ichimoku Cloud - comprehensive trend indicator
ichimoku_tenkan()Ichimoku Tenkan - conversion line
ichimoku_kijun()Ichimoku Kijun - base line
ichimoku_senkou_a()Ichimoku Senkou A - leading span A
ichimoku_senkou_b()Ichimoku Senkou B - leading span B
cmf(source, length)Chaikin Money Flow - alternative name
chaikin_money_flow(source, length)Chaikin Money Flow - alternative name
accelerator(source, length)Accelerator Oscillator - momentum change
ac(source, length)Accelerator Oscillator - alternative name
chaikin_vol(source, length)Chaikin Volatility - volatility measure
hv(source, length)Historical Volatility - alternative name
volume(source, length)Volume - alternative name for volume
vol(source, length)Volume - alternative name for volume
bbp(source, length)Bull/Bear Power - momentum measure
bop(source, length)Balance of Power - alternative name
price_channel_upper(source, length)Price Channel Upper - upper boundary
price_channel_lower(source, length)Price Channel Lower - lower boundary
envelope(source, length, mult)Moving Average Envelope - alternative name
envelope_upper(source, length, mult)Envelope Upper - upper boundary
envelope_lower(source, length, mult)Envelope Lower - lower boundary
keltner_upper(source, length, mult)Keltner Upper - upper boundary
keltner_lower(source, length, mult)Keltner Lower - lower boundary
choppiness(source, length)Choppiness Index - alternative name
chop(source, length)Choppiness Index - alternative name
choppiness_index(source, length)Choppiness Index - alternative name
adr(source, length)Average Daily Range - volatility measure
average_daily_range(source, length)Average Daily Range - alternative name

Math Functions

FunctionDescription
abs(x)Absolute value - removes negative sign
sqrt(x)Square root - finds the square root of a number
pow(x, y)Power - raises x to the power of y
log(x)Natural logarithm - log base e of x
exp(x)Exponential - e raised to the power of x
floor(x)Round down - rounds to the nearest lower integer
ceil(x)Round up - rounds to the nearest higher integer
round(x)Round to nearest - rounds to the nearest integer
min(a, b)Minimum - returns the smaller of two values
max(a, b)Maximum - returns the larger of two values

Signal Detection

FunctionDescription
cross(a, b)Cross detection - true when series cross either direction
crossover(a, b)Crossover detection - true when first series crosses above second
crossunder(a, b)Crossunder detection - true when first series crosses below second
rising(source, length)Rising detection - true when series is strictly rising
falling(source, length)Falling detection - true when series is strictly falling

Plotting & Drawing

FunctionDescription
plot(series, title, color, linewidth, opacity, style)Plot a line on your chart
plotshape(series, title, color, style)Plot shapes (dots, triangles, etc.) on your chart
plotbar(open, high, low, close, color)Plot OHLC bars on your chart
bgcolor(color, opacity)Set background color for your chart
fill(series1, series2, color, opacity)Fill area between two plots
hline(value, title, color, linestyle)Horizontal line at specific price level
line.new(x1, y1, x2, y2, color, width)Draw a trendline
line.set_xy(line, x, y)Move a trendline to new coordinates
line.delete(line)Delete a trendline
label.new(x, y, text, color)Add a text label to your chart
label.set_text(label, text)Update a label's text
box.new(left, top, right, bottom, bgcolor, bordercolor)Draw a rectangular box

Strategy Functions

FunctionDescription
strategy.entry(id, direction, qty)Open a new position (long or short)
strategy.exit(id, stop, limit)Set exit conditions (stop loss/take profit)
strategy.close(id)Close an existing position

Alert Functions

FunctionDescription
alertcondition(condition, title, message, id)Trigger an alert when condition is met

Input Configuration

FunctionDescription
input(defval, title, min, max, step, description)Create customizable input parameters for your script

Declaration Functions

FunctionDescription
indicator(title, overlay)Declare a custom indicator
strategy(title)Declare a trading strategy
input(defval, title, min, max, step, description)Create customizable input parameters

Multi-Timeframe Functions

FunctionDescription
security(symbol, timeframe, series)Access data from different timeframes

Miscellaneous Functions

FunctionDescription
naNot available - represents missing data
NaNNot a Number - represents invalid numeric value
bar_indexCurrent bar index - position in the data series