As seasoned Pine Script developers, we’re constantly refining our tools to build more robust, flexible, and user-friendly indicators and strategies. A key element in achieving this flexibility is the proper use of inputs. While the traditional input() function served its purpose, Pine Script v5 introduced a more structured and powerful way to handle script parameters: inline inputs.
Introduction to Inline Inputs in Pine Script
Let’s dive into what inline inputs are and why they are a superior approach for professional-grade scripts.
What are Inline Inputs?
Inline inputs, introduced with Pine Script v5, refer to the family of functions like input.int(), input.float(), input.string(), input.bool(), input.color(), input.time(), input.price(), and input.symbol(). Unlike the older input() function which required a separate declaration and then usage of its returned value, inline inputs define the input and return its value in a single, concise line of code.
This syntax streamlines script development, making it easier to see where a specific input is defined and used. It ties the input definition directly to the variable it controls, improving code readability and maintainability, especially in complex scripts.
Benefits of Using Inline Inputs
Migrating to or starting with inline inputs offers significant advantages for experienced Pine Script developers:
- Improved Readability: The variable assignment happens directly at the point of input definition, making the code flow clearer.
- Enhanced Organization: The introduction of mandatory
groupandtitlearguments allows for much cleaner categorization and labeling of inputs within the script’s settings dialog. - Strong Type Safety: Each input function is type-specific (
input.intreturns an integer,input.floata float, etc.), reducing potential runtime errors caused by unexpected data types. - Mandatory Documentation: The requirement for
titleand encourages better practices in documenting script parameters directly within the code.
For large scripts with numerous parameters, proper use of group and title with inline inputs transforms a potentially chaotic settings dialog into a well-organized control panel, significantly improving the user experience.
Basic Syntax and Structure
The fundamental structure of an inline input call is:
variableName = input.type(defaultValue, title='Input Title', group='Input Group', options=..., minval=..., maxval=...)
Here, input.type is one of the specific input functions (e.g., input.int, input.float).
variableName: The variable that will hold the value selected by the user in the settings.defaultValue: The initial value of the input when the script is added to the chart.title: (Mandatory) The label shown next to the input field in the settings dialog.group: (Mandatory) The name of the section where this input will appear in the settings dialog.- Other arguments like
options,minval,maxvaldepend on the input type and provide further control and validation.
This structure is consistent across all inline input types, making them easy to learn and implement.
Implementing Inline Inputs in Pine Script
Effective implementation of inline inputs goes beyond just syntax; it involves leveraging the available arguments to create a logical and intuitive settings interface for your script users.
Defining Input Options with input.string, input.int, input.float, input.bool
Each input function is tailored for a specific data type:
input.int(): For integer values (e.g., lengths of periods, counts).input.float(): For floating-point numbers (e.g., percentage thresholds, multipliers).input.bool(): For boolean true/false values (e.g., toggling features).input.string(): For text input. This is often used with theoptionsargument to provide a dropdown selection.input.color(): For selecting colors.input.time(): For specifying time durations or points.input.price(): For specific price levels.input.symbol(): For selecting a different symbol.
Here’s an example showing different types:
length = input.int(14, title='Lookback Period', group='Indicator Settings', minval=1)
threshold = input.float(50.5, title='Signal Threshold', group='Alert Levels', step=0.1)
enableFeature = input.bool(true, title='Enable Custom Feature', group='General Options')
maType = input.string('SMA', title='Moving Average Type', group='Indicator Settings', options=['SMA', 'EMA', 'WMA'])
Note the use of type-specific arguments like minval for input.int and step for input.float, and options for input.string to provide predefined choices.
Grouping Inline Inputs with group Argument
The group argument is crucial for organizing inputs. All inputs with the same group string will appear under a collapsible section with that name in the script’s settings dialog. This prevents a long, flat list of inputs, especially in complex scripts.
Consider a script with inputs for multiple components:
// --- Moving Average Group ---
maLength = input.int(20, title='Length', group='Moving Average')
maColor = input.color(color.blue, title='Color', group='Moving Average')
// --- RSI Group ---
rsiLength = input.int(14, title='Length', group='RSI')
rsiLevel = input.float(70, title='Overbought Level', group='RSI')
// --- General Settings Group ---
showPlot = input.bool(true, title='Show Indicator Plot', group='General Settings')
This simple use of group creates distinct sections in the settings for ‘Moving Average’, ‘RSI’, and ‘General Settings’, greatly improving navigability.
Adding Input Titles Using the title Argument
The title argument provides the human-readable label for each input field in the settings dialog. It is mandatory and should be descriptive enough for a user to understand what the input controls.
Choose clear and concise titles.
- Instead of
len, useLookback PeriodorMA Length. - Instead of
th, useEntry ThresholdorStop Loss Percentage.
A good title, combined with effective grouping, makes your script’s settings intuitive and easy to configure.
Advanced Techniques and Customization
Let’s explore how inline inputs integrate into more advanced Pine Script patterns and functionalities.
Conditional Input Display Based on Other Input Values
While Pine Script’s input system within the settings pane itself doesn’t natively support dynamic display (e.g., hiding one input based on the value of another checkbox directly in the UI), you can use input values to conditionally apply or ignore settings within your script’s logic.
For instance, you can have a boolean input to enable a feature and then use an if statement based on that boolean’s value to process other related inputs:
enableFeatureX = input.bool(true, title='Enable Feature X', group='Features')
featureX_param = input.int(10, title='Parameter for X', group='Features', inline='featureX_params') // Use inline for horizontal layout
featureX_param2 = input.float(1.5, title='Multiplier', group='Features', inline='featureX_params') // Same inline value groups horizontally
result = if enableFeatureX
// Use featureX_param and featureX_param2 here
close * featureX_param2 + featureX_param
else
// Feature X is disabled, perhaps use a default value or zero
close
plot(result)
Here, featureX_param and featureX_param2 are always visible in settings, but their values are only used if enableFeatureX is true. The inline='...' argument is used here to visually group inputs horizontally in the settings dialog, which is a separate but related organization feature.
Using Inline Inputs with Security Function
Inline inputs can be used directly within the security() function call. This allows parameters defined by the user on the main chart’s script to influence calculations performed on data from other symbols or timeframes.
secondarySymbol = input.symbol('NASDAQ:AAPL', title='Analyze Symbol', group='Multi-Symbol')
secondaryTimeframe = input.time('D', title='Timeframe', group='Multi-Symbol')
maLengthOther = input.int(50, title='MA Length (Other Symbol)', group='Multi-Symbol', minval=1)
[otherClose, otherMA] = request.security(
secondarySymbol,
secondaryTimeframe,
[close, ta.sma(close, maLengthOther)] // Use the input maLengthOther here
)
plot(otherMA, color=color.purple, title='MA on Other Symbol')
This pattern is extremely powerful for building multi-symbol or multi-timeframe strategies and indicators where the user needs control over the parameters applied to the auxiliary data.
Combining Inline Inputs with Strategy Backtesting
Inline inputs are fundamental to making strategy backtesting parameters easily tunable. Each input represents a parameter that can be manually adjusted to see its effect on the strategy’s performance metrics. Furthermore, these inline inputs are precisely what is used by TradingView’s built-in Optimizer.
When defining inputs for a strategy:
entryLength = input.int(10, title='Entry MA Length', group='Strategy Parameters', minval=1)
exitLength = input.int(20, title='Exit MA Length', group='Strategy Parameters', minval=1)
qty = input.float(0.1, title='Order Quantity', group='Strategy Parameters', minval=0.01, step=0.01)
These inputs appear directly in the strategy’s settings. The Optimizer tool can then iterate through ranges of values for entryLength, exitLength, and qty (or any other input), allowing users to find potentially optimal parameter sets based on historical data. Well-defined inline inputs with appropriate minval, maxval, and step arguments are essential for effective optimization.
Practical Examples of Inline Inputs
Let’s solidify our understanding with a few practical code examples demonstrating inline inputs in action.
Creating a Moving Average Strategy with Adjustable Length via Inline Input
A simple crossover strategy where the MA length is controlled by an input.
//@version=5
strategy('MA Crossover Strategy', overlay=true)
// --- Strategy Inputs ---
maLength = input.int(20, title='Moving Average Length', group='Strategy Parameters', minval=1)
// --- Calculation ---
smaValue = ta.sma(close, maLength)
// --- Strategy Logic ---
longCondition = ta.crossover(close, smaValue)
shortCondition = ta.crossunder(close, smaValue)
if longCondition
strategy.entry('Long', strategy.long)
if shortCondition
strategy.close('Long')
// --- Plotting ---
plot(smaValue, color=color.blue, title='SMA')
Users can easily change the maLength input in the strategy’s settings to test different moving average periods.
Implementing a Relative Strength Index (RSI) Indicator with Customizable Parameters
An RSI indicator where the period, overbought, and oversold levels are inputs.
//@version=5
indicator('Customizable RSI', shorttitle='RSI', overlay=false)
// --- Indicator Inputs ---
rsiLength = input.int(14, title='RSI Length', group='RSI Settings', minval=1)
src = input.source(close, title='Source', group='RSI Settings')
// --- Level Inputs ---
overboughtLevel = input.float(70.0, title='Overbought Level', group='Levels', step=0.1)
oversoldLevel = input.float(30.0, title='Oversold Level', group='Levels', step=0.1)
// --- Calculation ---
rsiValue = ta.rsi(src, rsiLength)
// --- Plotting ---
plot(rsiValue, color=color.purple, title='RSI')
hline(overboughtLevel, color=color.red, title='Overbought Level')
hline(oversoldLevel, color=color.green, title='Oversold Level')
// --- Background Colors (Optional) ---
bgColor = if rsiValue >= overboughtLevel
color.new(color.red, 90)
else if rsiValue <= oversoldLevel
color.new(color.green, 90)
else
na
bgcolor(bgColor)
This example shows inputs for integer, float, and source types, organized into different groups.
Developing a Volume-Based Alert System with Inline Input Thresholds
A simple alert script that triggers when volume exceeds a user-defined threshold.
//@version=5
indicator('Volume Threshold Alert', overlay=true)
// --- Alert Input ---
volumeThreshold = input.int(1000000, title='Volume Threshold', group='Alert Settings', minval=0)
// --- Alert Condition ---
alertCondition = volume > volumeThreshold
// --- Plotting (Optional Visual Aid) ---
barcolor(alertCondition ? color.yellow : na)
// --- Alert Function ---
alert(alertCondition, 'Volume exceeded threshold! Current Volume: {{volume}} Threshold: ' + str.tostring(volumeThreshold), alert.freq_once_per_bar)
The volumeThreshold input allows users to easily set the desired alert level without modifying the script code itself.
Best Practices and Common Mistakes
Mastering inline inputs involves not just knowing the syntax but also following best practices to create usable and maintainable scripts.
Optimizing User Experience with Clear Labels and Descriptions
- Use Descriptive Titles: The
titleshould clearly state the purpose of the input (e.g., ‘Fast MA Length’, ‘Stop Loss Percentage’, ‘Enable Alerts’). Avoid abbreviations unless they are universally understood (like RSI, MACD). - Group Logically: Use the
groupargument to bundle related inputs together. Common groups include ‘Strategy Parameters’, ‘Indicator Settings’, ‘Alerts’, ‘Plotting Styles’, ‘Time Management’, etc. - Set Sensible Defaults: The
defaultValueshould be a value that makes sense for the typical use case of the script. - Specify Ranges/Steps: Use
minval,maxval, andsteparguments where appropriate, especially for numerical inputs, to guide the user and prevent invalid configurations (e.g., a length of 0 or a percentage over 100).
Well-organized and clearly labeled inputs significantly enhance the user experience, making your script easier to configure and understand.
Avoiding Common Errors When Defining Inline Inputs
- Missing
titleorgroup: These are mandatory arguments in v5 inline inputs. Forgetting them will result in compilation errors. - Type Mismatches: Ensure the variable receiving the input value is compatible with the input function’s return type (e.g., don’t assign
input.floatto a variable intended for integers without explicit conversion, although Pine Script is relatively flexible here, it’s best practice for clarity). - Incorrect Argument Usage: Using arguments specific to one input type (like
optionsforinput.string) with another type will cause errors. - Excessive Inputs: While inputs are great, too many can overwhelm the user. Consider combining related settings where possible or using boolean toggles to reveal/hide groups of related logic (even if inputs remain visible).
Pay close attention to the compiler’s error messages; they are usually quite informative regarding input definition issues.
Troubleshooting and Debugging Tips
When troubleshooting issues potentially related to inputs:
- Check Input Values: Temporarily
plot()orlabel.new()the values of your inputs at key points in your script to confirm they hold the expected values after configuration in the settings. - Verify Types: Use
typeof()to check the actual data type of the variable holding the input value if you suspect a type-related issue. - Isolate Inputs: If a script is behaving unexpectedly, temporarily hardcode the values that are normally controlled by inputs to rule out configuration errors or issues with the input definition itself.
- Review Grouping/Titles: Ensure your
groupandtitlestrings are consistent if you expect inputs to appear in the same section or have specific labels.
Debugging input-related problems is often a process of verifying that the value selected by the user is correctly read by the script and used in calculations or logic as intended.
By embracing inline inputs and following these guidelines, you can create Pine Script indicators and strategies that are not only powerful under the hood but also intuitive and easy for anyone to configure and use.