How to Call Another Script in TradingView Pine Script?

Calling another script in Pine Script allows you to reuse code, access data from different indicators, or modularize complex strategies. This capability is essential for building sophisticated trading tools. This article explores the primary methods for achieving this, focusing on practical applications and best practices.

Why Call Another Script?

Calling another script offers several advantages:

  • Code Reusability: Avoid duplicating code by creating reusable functions or libraries.
  • Data Aggregation: Combine data from multiple indicators or strategies.
  • Modular Design: Break down complex algorithms into manageable modules.
  • Improved Performance: Optimize resource usage by calling specific calculations only when needed.

Limitations and Considerations

Before diving into the implementation details, it’s important to acknowledge a few limitations:

  • Scope: Scripts operate in their own scope, meaning direct variable access is not possible. Data must be explicitly passed.
  • Performance: Excessive use of request.security() can impact script performance, especially on higher timeframes.
  • Repainting: Be aware of repainting issues when using data from scripts that recalculate historical values. Use request.security with caution.
  • Security: Be aware of security implications when using request.security, do not share sensitive data.

Using request.security() to Access Data from Another Script

The most common way to call another script is by using the built-in function request.security(). This function allows you to request data from another symbol, timeframe, or even another script on the same chart.

Understanding request.security()

request.security() fetches data from a specified symbol and timeframe. It can also access the output of another indicator or strategy.

Syntax and Parameters

The general syntax is as follows:

request.security(symbol, timeframe, expression, lookahead)
  • symbol (string): The symbol to fetch data from (e.g., “AAPL”, “BTCUSDT”).
  • timeframe (string): The timeframe to use (e.g., “D”, “60”, “5”).
  • expression *(series): The expression to calculate on the fetched data (e.g.,close,sma(close, 20)`).
  • lookahead (barmerge.lookahead_) : Optional argument to prevent repainting (e.g., barmerge.lookahead_on, barmerge.lookahead_off).

Example: Fetching Moving Average from Another Script

This example demonstrates how to fetch the 200-day simple moving average (SMA) from the SPY ETF and plot it on your current chart.

//@version=5
indicator(title="Fetch SMA from SPY", overlay=true)

sma_spy = request.security("SPY", "D", ta.sma(close, 200))

plot(sma_spy, color=color.red, title="SPY 200 SMA")

In this example, request.security() fetches the 200-day SMA of the closing price from the SPY ETF. The resulting sma_spy series is then plotted on the chart.

Implementing Custom Functions and Libraries

While request.security() is useful for accessing data, custom functions and libraries provide a more structured way to reuse code.

Creating Reusable Functions

You can define custom functions within your script to encapsulate reusable logic.

//@version=5
indicator(title="Custom Function Example", overlay=true)

// Custom function to calculate the average of high and low
avg_hl(high, low) =>
    (high + low) / 2

avg = avg_hl(high, low)

plot(avg, color=color.blue, title="Average High Low")

Publishing and Using Libraries

For more extensive code reuse, you can create and publish libraries. Libraries are separate scripts that contain functions and variables that can be imported into other scripts.

  1. Create a Library: Create a new Pine Script and select the “Library” type.

    //@version=5
    library("MyIndicatorLibrary")
    
    // Function to calculate the Relative Strength Index (RSI)
    rsi(source, length) =>
        ta.rsi(source, length)
    
  2. Publish the Library: Publish the library with appropriate visibility settings.

  3. Use the Library: In your main script, import the library using the import statement.

    //@version=5
    indicator(title="Using Library", overlay=true)
    
    import MyIndicatorLibrary
    
    rsi_value = MyIndicatorLibrary.rsi(close, 14)
    
    plot(rsi_value, color=color.green, title="RSI from Library")
    

Example: Creating a Custom Indicator Library

Let’s create a library containing several common indicator functions.

Library Script (MyIndicatorLibrary):

//@version=5
library("MyIndicatorLibrary")

// Function to calculate Simple Moving Average (SMA)
sma(source, length) =>
    ta.sma(source, length)

// Function to calculate Relative Strength Index (RSI)
rsi(source, length) =>
    ta.rsi(source, length)

// Function to calculate Bollinger Bands
bb(source, length, mult) =>
    basis = ta.sma(source, length)
    dev = mult * ta.stdev(source, length)
    upper = basis + dev
    lower = basis - dev
    [upper, lower]

Main Script (Using the Library):

//@version=5
indicator(title="Using Indicator Library", overlay=true)

import MyIndicatorLibrary

sma20 = MyIndicatorLibrary.sma(close, 20)
rsi14 = MyIndicatorLibrary.rsi(close, 14)
bb_values = MyIndicatorLibrary.bb(close, 20, 2)
bb_upper = bb_values[0]
bb_lower = bb_values[1]

plot(sma20, color=color.blue, title="SMA 20")
plot(rsi14, color=color.green, title="RSI 14")
plot(bb_upper, color=color.red, title="Bollinger Upper")
plot(bb_lower, color=color.red, title="Bollinger Lower")

Advanced Techniques and Best Practices

Handling Timeframes and Resolutions

When calling scripts with different timeframes, be mindful of how data is aggregated. request.security() automatically merges data, but you should understand the implications for your calculations. For example, if you request daily data from a script running on a 15-minute chart, the daily values will be repeated for each 15-minute bar within that day.

Error Handling and Debugging

When an error occurs within a called script, it can be difficult to pinpoint the cause. Use try...catch blocks where necessary, and log relevant data to the console using runtime.log to help diagnose issues.

Optimizing Performance

Excessive use of request.security() can significantly impact script performance. Consider these optimization techniques:

  • Minimize Calls: Avoid calling request.security() within loops or frequently executed blocks of code.
  • Cache Results: Store the results of request.security() in variables and reuse them whenever possible.
  • Use Lower Timeframes: If possible, request data from lower timeframes to reduce the amount of data that needs to be processed.
  • Avoid Repainting: Use the lookahead argument to prevent repainting, but be aware of the trade-offs.

Conclusion

Summary of Methods

  • request.security(): Used to fetch data from other symbols, timeframes, or scripts. Essential for aggregating data from multiple sources.
  • Custom Functions: Encapsulate reusable logic within a single script.
  • Libraries: Create and publish reusable code modules that can be imported into other scripts. Ideal for building complex indicators and strategies.

Further Learning Resources

  • TradingView Pine Script Reference Manual
  • TradingView PineCoders community resources

Leave a Reply