ounter.new()
// Add 1 to the bars
and ticks
fields. The ticks
field is not subject to rollback on unconfirmed bars.
counter.bars += 1
counter.ticks += 1
// Plot both fields for comparison. plot(counter.bars, “Bar counter”, color.blue, 3) plot(counter.ticks, “Tick counter”, color.purple, 3)
In Pine, the varip keyword is used to indicate that an object's fields persist throughout the script execution and do not roll back on unconfirmed bars.
In the declaration of the Counter type, the bars field does not use the varip keyword, so it rolls back on each unconfirmed bar. The ticks field uses the varip keyword, so it does not roll back on unconfirmed bars.
The counter object is declared using the var keyword, so it persists throughout the script execution.
In each iteration, both the bars field and the ticks field are incremented by 1. The bars field rolls back on each unconfirmed bar, while the ticks field does not roll back.
Finally, by plotting the counter.bars and counter.ticks fields, you can compare the difference between them. The value of counter.bars rolls back on each unconfirmed bar, while the value of counter.ticks continues to increase until the end of the script execution.
**Modify field values**
```pine
type order
float price
float amount
string symbol
if strategy.position_size == 0 and open > close
strategy.entry("long", strategy.long, 1)
order1 = order.new(strategy.opentrades.entry_price(strategy.opentrades - 1), strategy.opentrades.size(strategy.opentrades - 1), syminfo.ticker)
if strategy.position_size != 0
runtime.log(order1)
order1.price := 999
order1.amount := 100
runtime.log(order1)
runtime.error("stop")
The value of an object field can be changed using the :=
reassignment operator.
Object collection
The example declares an empty array that will hold objects of the user-defined order type:
type order
float price
float amount
string symbol
arrOrder = array.new<order>()
order1 = order.new(99, 1, "BTC_USDT")
order2 = order.new(100, 2, "ETH_USDT")
array.push(arrOrder, order1)
array.push(arrOrder, order2)
runtime.log(arrOrder)
runtime.error("stop")
or
type order
float price
float amount
string symbol
var array<order> arrOrder = na
arrOrder := array.new<order>()
order1 = order.new(99, 1, "BTC_USDT")
order2 = order.new(100, 2, "ETH_USDT")
array.push(arrOrder, order1)
array.push(arrOrder, order2)
runtime.log(arrOrder)
runtime.error("stop")
Copy object
In Pine, objects are assigned by reference. When an existing object is assigned to a new variable, both refer to the same object.
//@version=5
indicator("")
type pivotPoint
int x
float y
pivot1 = pivotPoint.new()
pivot1.x := 1000
pivot2 = pivot1
pivot2.x := 2000
// Both plot the value 2000.
plot(pivot1.x)
plot(pivot2.x)
In the following example, we create a pivot1 object and set its x field to 1000. We then declare a pivot2 variable that contains a reference to the pivot1 object, so both of them point to the same instance. Therefore, changing pivot2.x also changes pivot1.x, because both refer to the x field of the same object.
To create a copy that is independent of the original object, in this case we can use the built-in copy() method. In this example, we declare the variable pivot2 to refer to the copied instance of the pivot1 object. Now, changing pivot2.x will not change pivot1.x, because it refers to the x field of a separate object:
//@version=5
indicator("")
type pivotPoint
int x
float y
pivot1 = pivotPoint.new()
pivot1.x := 1000
pivot2 = pivotPoint.copy(pivot1)
pivot2.x := 2000
// Plots 1000 and 2000.
plot(pivot1.x)
plot(pivot2.x)
It should be noted that TradingView’s copy method is a shallow copy. If an object has special types of fields (array, etc.), these fields in the shallow copy of the object will point to the same instance as the object. FMZ platform directly implements deep copying, and no additional processing is required. You can refer to the following example:
Deep copy
//@version=5
indicator("test deepCopy")
type orderInfo
float price
float amount
type labelInfo
orderInfo order
string labelMsg
labelInfo1 = labelInfo.new(orderInfo.new(100, 0.1), "test labelInfo1")
labelInfo2 = labelInfo.copy(labelInfo1)
labelInfo1.labelMsg := "labelInfo1->2" // Modify the base type field of labelInfo1 to see if it affects labelInfo2
labelInfo1.order.price := 999 // Modify the composite type field of labelInfo1 to see if it affects labelInfo2
runtime.log(labelInfo1)
runtime.log(labelInfo2)
runtime.error("stop")
The test results show that labelInfo.copy(labelInfo1) is a deep copy when executed, and modifying any field of labelInfo1 will not affect labelInfo2.
Methods in the Pine language are specialized functions associated with a specific instance of a built-in or user-defined type. In most respects, they are essentially the same as regular functions, but provide a shorter, more convenient syntax. Users can access methods directly on variables using dot notation, just like accessing fields of Pine objects. Pine includes built-in methods for all special types, including arrays, matrices, maps, lines, fill lines, and more. These methods provide users with a more concise way to call specialized programs of these types in scripts.
Built-in methods
For example, a script code like this:
//@version=5
indicator("Custom Sample BB", overlay = true)
float sourceInput = input.source(close, "Source")
int samplesInput = input.int(20, "Samples")
int n = input.int(10, "Bars")
float multiplier = input.float(2.0, "StdDev")
var array<float> sourceArray = array.new<float>(samplesInput)
var float sampleMean = na
var float sampleDev = na
// Identify if `n` bars have passed.
if bar_index % n == 0
// Update the queue.
array.push(sourceArray, sourceInput)
array.shift(sourceArray)
// Update the mean and standard deviaiton values.
sampleMean := array.avg(sourceArray)
sampleDev := array.stdev(sourceArray) * multiplier
// Calculate bands.
float highBand = sampleMean + sampleDev
float lowBand = sampleMean - sampleDev
plot(sampleMean, "Basis", color.orange)
plot(highBand, "Upper", color.lime)
plot(lowBand, "Lower", color.red)
Can be rewritten equivalently as:
//@version=5
indicator("Custom Sample BB", overlay = true)
float sourceInput = input.source(close, "Source")
int samplesInput = input.int(20, "Samples")
int n = input.int(10, "Bars")
float multiplier = input.float(2.0, "StdDev")
var array<float> sourceArray = array.new<float>(samplesInput)
var float sampleMean = na
var float sampleDev = na
// Identify if `n` bars have passed.
if bar_index % n == 0
// Update the queue.
sourceArray.push(sourceInput)
sourceArray.shift()
// Update the mean and standard deviaiton values.
sampleMean := sourceArray.avg()
sampleDev := sourceArray.stdev() * multiplier
// Calculate band values.
float highBand = sampleMean + sampleDev
float lowBand = sampleMean - sampleDev
plot(sampleMean, "Basis", color.orange)
plot(highBand, "Upper", color.lime)
plot(lowBand, "Lower", color.red)
You can see that after PINE supports Methods
, the code array.avg(sourceArray)
can be written in the form of methods: sourceArray.avg()
.
Note that FMZ does not support calls like array.avg
currently.
User defined methods
Pine allows users to define custom methods that work with objects of any built-in or user-defined type. Defining a method is essentially the same as defining a function, with two key differences:
For example, in the following code, the code for calculating the Bollinger indicator is encapsulated as a user-defined method:
//@version=5
indicator("Custom Sample BB", overlay = true)
float sourceInput = input.source(close, "Source")
int samplesInput = input.int(20, "Samples")
int n = input.int(10, "Bars")
float multiplier = input.float(2.0, "StdDev")
var array<float> sourceArray = array.new<float>(samplesInput)
var float sampleMean = na
var float sampleDev = na
// Identify if `n` bars have passed.
if bar_index % n == 0
// Update the queue.
sourceArray.push(sourceInput)
sourceArray.shift()
// Update the mean and standard deviaiton values.
sampleMean := sourceArray.avg()
sampleDev := sourceArray.stdev() * multiplier
// Calculate band values.
float highBand = sampleMean + sampleDev
float lowBand = sampleMean - sampleDev
plot(sampleMean, "Basis", color.orange)
plot(highBand, "Upper", color.lime)
plot(lowBand, "Lower", color.red)
Modified to:
//@version=5
indicator("Custom Sample BB", overlay = true)
float sourceInput = input.source(close, "Source")
int samplesInput = input.int(20, "Samples")
int n = input.int(10, "Bars")
float multiplier = input.float(2.0, "StdDev")
var array<float> sourceArray = array.new<float>(samplesInput)
method maintainQueue(array<float> srcArray, float value, bool takeSample = true) =>
if takeSample
srcArray.push(value)
srcArray.shift()
srcArray
method calcBB(array<float> srcArray, float mult, bool calculate = true) =>
var float mean = na
var float dev = na
if calculate
mean := srcArray.avg()
dev := srcArray.stdev() * mult
[mean, mean + dev, mean - dev]
bool newSample = bar_index % n == 0
[sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample)
plot(sampleMean, "Basis", color.orange)
plot(highBand, "Upper", color.lime)
plot(lowBand, "Lower", color.red)
You can see that the first parameter in the parameter list of the user-defined methods declared with the keyword method: maintainQueue and calcBB is of type array<float>
, which means that the method is a method of a variable of type array<float>
, so you can see that the following code is called to calculate the Bollinger indicator.
[sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample)
Methods overloading
User-defined methods can override and overload existing built-in methods and user-defined methods with the same identifier. This feature allows users to define multiple routines associated with different argument signatures under the same method name. As a simple example, suppose we want to define a method to identify the type of a variable. Since we must explicitly specify the object type associated with a user-defined method, we need to define overloads for each type we want it to recognize. Next we define a getType() method that returns a string representation of a variable’s type and has overloads for the five basic types:
//@version=5
indicator("Type Inspection")
// @function Identifies an object's type.
// @param this Object to inspect.
// @returns (string) A string representation of the type.
method getType(int this) =>
na(this) ? "int(na)" : "int"
method getType(float this) =>
na(this) ? "float(na)" : "float"
method getType(bool this) =>
na(this) ? "bool(na)" : "bool"
method getType(color this) =>
na(this) ? "color(na)" : "color"
method getType(string this) =>
na(this) ? "string(na)" : "string"
a = 1 // a.getType(): float
b = 1.0 // b.getType(): float
c = true // c.getType(): bool
d = color.white // d.getType(): string(na)
e = "1" // e.getType(): string
runtime.log("a.getType():", a.getType())
runtime.log("b.getType():", b.getType())
runtime.log("c.getType():", c.getType())
runtime.log("d.getType():", d.getType())
runtime.log("e.getType():", e.getType())
runtime.error("stop")
The base type of each variable determines which overload of getType()
will be used. On the FMZ platform, since the underlying implementation of PINE scripts is Javascript, the numeric type will be judged as floating point data (float).
When calling a function, you can pass arguments. You can assign argument names to assign values. You can directly pass variables in the corresponding argument positions. Mixed use is also supported. For example:
plot(close, title="test plot") // Pass the argument close directly; specify the argument title and assign the string "test plot"
After specifying the argument name assignment, you can no longer directly pass the variable as an argument, and the subsequent arguments must be written in the form of argument name assignment.
// plot(close, title="test", color.red) // Although the third argument of plot is the color value, but this will report an error
plot(close, title="test", color=color.red) // Correct writing
plot(close, "test", color.red) // Correct writing
Convert the time period passed to the timeframe
argument into seconds.
timeframe.in_seconds(timeframe)
Example
// Get chart timeframe:
i_tf = input.timeframe("1D")
// Convert timeframe to the int value (number of seconds in 1 Day):
tf = timeframe.in_seconds(i_tf)
plot(tf)
Returns
An int representation of the number of seconds in one bar of a timeframe
.
Arguments
- timeframe
(simple string) Timeframe. Optional. The default is timeframe.period.
Remarks
For the timeframe
>= ‘1M’ function calculates number of seconds based on 30.4167 (365⁄12) days in month.
See also
## ticker
### ticker.heikinashi
Creates a ticker identifier for requesting a smoothed average int representation value.
ticker.heikinashi(symbol)
**Example**
```pine
heikinashi_close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_aapl_60_close = request.security(ticker.heikinashi(syminfo.tickerid), "60", close)
plot(heikinashi_close)
plot(heikinashi_aapl_60_close)
Returns String value of the stock code that can be supplied to request.security function.
Arguments
- symbol
(simple string) product code identifier.
See also
## request
### request.data
Request external data.
request.data(url, attribute)
**Example**
```pine
/*backtest
start: 2024-09-01 16:00:00
end: 2024-10-10 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
args: [["RunMode",1,358374],["ZPrecision",0,358374]]
*/
var chart_data = "https://www.datadata.com/api/v1/query/ebe46218-c5c6-4366-8c72-413694417976/data"
spotPrice = request.data(chart_data, "$.spot_close_price")
futuresPrice = request.data(chart_data, "$.future_close_price")
diff = futuresPrice - spotPrice
plot(diff, "perpetual-spot difference")
plot(futuresPrice, "futures prices", overlay=true)
plot(spotPrice, "spot prices", overlay=true)
if diff > 80 and strategy.position_size >= 0
runtime.log("diff > 80")
strategy.entry("Enter Short", strategy.short)
if diff < 60 and strategy.position_size <= 0
runtime.log("diff < 60")
strategy.entry("Enter Short", strategy.long)
Return value The attribute argument specifies the data series.
Arguments
- url
(simple string) The requested data source url and the data format of the data source response must meet the requirements (including at least the time and data attributes): {"data": [], "schema": ["time", "data"]}
. You can refer to the data format in the example:
{
"data": [
[1720051200000, "{\"spot_close_price\" : 57050.01, \"future_close_price\" : 57045.9}"],
[1720137600000, "{\"spot_close_price\" : 56628.79, \"future_close_price\" : 56604.9}"],
// ...
],
"schema": ["time", "data"]
}
attribute
(simple string) specifies the attribute name and returns the required data. For example: "$.spot_close_price"
, use $.
as the prefix, and the attribute name is consistent with the attribute in the data field in the data in the response when requesting the data sourceIf an error is prompted, you need to check whether the time range requested by request.data
is consistent with the time range set for the backtest. If no data can be queried in the backtest time series, an error will be reported.
The data-data data query SQL statement in this example is:
WITH latest_data AS (
SELECT
klines.spot_1d.Time AS time,
CONCAT('{\"spot_close_price\" : ', klines.spot_1d.Close, ', \"future_close_price\" : ', klines.future_1d.Close, '}') AS data
FROM
klines.spot_1d
JOIN
klines.future_1d
ON
klines.spot_1d.Time = klines.future_1d.Time
WHERE
klines.spot_1d.Symbol = 'btc_usdt'
AND
klines.future_1d.Symbol = 'btc_usdt.swap'
AND
klines.spot_1d.Exchange = 'Binance'
AND
klines.future_1d.Exchange = 'Binance'
ORDER BY
klines.spot_1d.Time DESC
LIMIT 100
)
SELECT * FROM latest_data
ORDER BY time ASC;
You can query and create data links on the Data Exploration page of the FMZ platform, which is the https://www.datadata.com/api/v1/query/ebe46218-c5c6-4366-8c72-413694417976/data
used in the example.
Ask for another variety/resolution.
request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency)
Example
s = request.security(syminfo.tickerid, "D", close) // 1 Day
plot(s)
expr = ta.sma(close, 10)
s1 = request.security(syminfo.tickerid, "240", expr) // 240 Minutes
plot(s1)
// To avoid difference in calculation on history/realtime you can request not latest values and use merge strategy flags as follows:
s2 = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(s2)
f() => [open, high]
[o, h] = request.security(syminfo.tickerid, "D", f())
[l, c] = request.security(syminfo.tickerid, "D", [low, close])
plot((o + h + l + c) / 4)
Returns Requested series
Arguments
- symbol
(simple string) Symbol.
- timeframe
(simple string) Time Period. An empty string is interpreted as the current resolution of the chart.
- expression
(series int/float/bool/color) An expression can be calculated and returned from the request.security call. It can be a series or a tuple containing elements that can be cast to series.
- gaps
(barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the main series OHLC data). Possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
- lookahead
(barmerge_lookahead) Merge strategy for the requested data position. Possible values: barmerge.lookahead_on, barmerge.lookahead_off. Default value is barmerge.lookahead_off starting from version 3. Note that behavour is the same on real-time, and differs only on history.
- ignore_invalid_symbol
(const bool) An optional argument. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. The default value is false.
- currency
(simple string) Currency into which the symbol’s currency-related values (e.g. OHLC) are to be converted. The expression
is then calculated based on the converted values. The conversion rates used are based on the FX_IDC pairs’ daily rates of the previous day (relative to the bar where the calculation is done). Optional. The default is syminfo.currency. Possible values: a three-letter string with the currency code in the ISO 4217 format (e.g. “USD”) or one of the constants in the currency.* namespace, e.g. currency.USD.
Remarks PineScript code that uses this function could calculate differently on history and real-time data. If you want to specify additional arguments for the requested symbol, e.g. session or adjustment type, you can use the ticker.new() function. It is not possible to pass a spread to this function using the ‘ticker’ variable. You can use the ‘ticker.new’ variable or a string representation of the ticker, e.g. “AAPL+MSFT*TSLA”. At the moment, up to 40 request.security calls can be present in a script. Please note that using this variable/function can cause indicator repainting.
The resolution argument allowable values are: 1S, 5S, 15S, 30S - for seconds intervals (chart resolution should be less than or equal to the requested resolution) from 1 to 1440 for minutes from 1D to 365D for days from 1W to 52W for weeks from 1M to 12M for months
See also
## str
### str.contains
Returns true if the ```source``` string contains the ```str``` substring, false otherwise.
str.contains(source, str)
**Example**
```pine
// If the current chart is a continuous futures chart, e.g "BTC1!", then the function will return true, false otherwise.
var isFutures = str.contains(syminfo.tickerid, "!")
plot(isFutures ? 1 : 0)
Returns
True if the str
was found in the source
string, false otherwise.
Arguments
- source
(series string) Source string.
- str
(series string) The substring to search for.
See also
### str.endswith
Returns true if the ```source``` string ends with the substring specified in ```str```, false otherwise.
str.endswith(source, str)
**Returns**
True if the ```source``` string ends with the substring specified in ```str```, false otherwise.
**Arguments**
- ```source``` (series string) Source string.
- ```str``` (series string) The substring to search for.
**See also**
```str.startswith```
### str.startswith
Returns true if the ```source``` string starts with the substring specified in ```str```, false otherwise.
str.startswith(source, str)
**Returns**
True if the ```source``` string starts with the substring specified in ```str```, false otherwise.
**Arguments**
- ```source``` (series string) Source string.
- ```str``` (series string) The substring to search for.
**See also**
```str.endswith```
### str.substring
Returns a new string that is a substring of the ```source``` string. The substring begins with the character at the index specified by ```begin_pos``` and extends to 'end_pos - 1' of the ```source``` string.
str.substring(source, begin_pos)
str.substring(source, begin_pos, end_pos)
**Example**
```pine
sym= "EXCHANGE_NAME:SYMBOL_NAME"
pos = str.pos(sym, ":") // Get position of ":" character
tkr= str.substring(sym, pos+1) // "SYMBOL_NAME"
if barstate.islastconfirmedhistory
runtime.log(tkr)
Returns The substring extracted from the source string.
Arguments
- source
(series string) Source string from which to extract the substring.
- begin_pos
(series int) The beginning position of the extracted substring. It is inclusive (the extracted substring includes the character at that position).
- end_pos
(series int) The ending position. It is exclusive (the extracted string does NOT include that position’s character). Optional. The default is the length of the source
string.
Remarks
Strings indexing starts from 0. If begin_pos
is equal to end_pos
, the function returns an empty string.
See also
### str.tonumber
str.tonumber(string)
**Returns**
A float version of the string if it contains a valid number, na otherwise.
**Arguments**
- ```string``` (series string) String representation of an int or float.
### str.format
Converts the formatting string and value(s) into a formatted string. The formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted. Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional format specifier. The index represents the position of that argument in the str.format argument list.
str.format(formatString, arg0, arg1, …)
**Example**
```pine
// The format specifier inside the curly braces accepts certain modifiers:
// - Specify the number of decimals to display:
s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3
runtime.log(s1)
// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1
runtime.log(s2)
// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34
runtime.log(s3)
// - Display a number as a percentage:
s4 = str.format("{0,number,percent}", 0.5) // returns: 50%
runtime.log(s4)
// EXAMPLES WITH SEVERAL ARGUMENTS
// returns: Number 1 is not equal to 4
s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
runtime.log(s5)
// returns: 1.34 != 1.3
s6 = str.format("{0} != {0, number, #.#}", 1.34)
runtime.log(s6)
// returns: 1 is equal to 1, but 2 is equal to 2
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52)
runtime.log(s7)
// returns: The cash turnover amounted to $1,340,000.00
s8 = str.format("The cash turnover amounted to {0, number, currency}", 1340000)
runtime.log(s8)
// returns: Expected return is 10% - 20%
s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
runtime.log(s9)
Returns The formatted string.
Arguments
- formatString
(series string) Format string.
- arg0, arg1, ...
(series int/float/bool/string/na/int[]/float[]/bool[]/string[]) Values to format.
Remarks Any curly braces within an unquoted pattern must be balanced. For example, “ab {0} de” and “ab ‘}’ de” are valid patterns, but “ab {0’}’ de”, “ab } de” and “”{“” are not.
Returns an integer corresponding to the amount of chars in that string.
str.length(string)
Returns The number of chars in source string.
Arguments
- string
(series string) Source string.
Returns a new string with all letters converted to lowercase.
str.lower(source)
Returns A new string with all letters converted to lowercase.
Arguments
- source
(series string) String to be converted.
See also
### str.upper
Returns a new string with all letters converted to uppercase.
str.upper(source)
**Returns**
A new string with all letters converted to uppercase.
**Arguments**
- ```source``` (series string) String to be converted.
**See also**
```str.lower```
### str.match
Returns the new substring of the ```source``` string if it matches a ```regex``` regular expression, 'na' otherwise.
str.match(source, regex)
**Example**
```pine
s = input.string("It's time to sell some EXCHANGE_NAME:SYMBOL_NAME!")
// finding first substring that matches regular expression "[\w]+:[\w]+"
var string tickerid = str.match(s, "[\\w]+:[\\w]+")
if barstate.islastconfirmedhistory
runtime.log(tickerid) // "EXCHANGE_NAME:SYMBOL_NAME"
Returns
The new substring of the source
string if it matches a regex
regular expression, ‘na’ otherwise.
Arguments
- source
(series string) Source string.
- regex
(series string) The regular expression to which this string is to be matched.
Remarks
Function returns first occurrence of the regular expression in the source
string.
The backslash “\” symbol in the regex
string needs to be escaped with additional backslash, e.g. “\d” stands for regular expression “\d”.
See also
### str.pos
Returns the position of the first occurrence of the ```str``` string in the ```source``` string, 'na' otherwise.
str.pos(source, str)
**Returns**
Position of the ```str``` string in the ```source``` string.
**Arguments**
- ```source``` (series string) Source string.
- ```str``` (series string) The substring to search for.
**Remarks**
Strings indexing starts at 0.
**See also**
```str.contains``` ```str.match``` ```str.substring```
### str.replace
Returns a new string with the N+1th occurrence of the ```target``` string and the previous occurrence of ```target``` string replaced by the ```replacement``` string, where N is specified in ```occurrence```. N is the matching index of the target string to be replaced in the source string.
str.replace(source, target, replacement, occurrence)
**Example**
```pine
var source = "EXCHANGE1:SYMBOL1 / EXCHANGE1:SYMBOL2"
// Replace first occurrence of "EXCHANGE1" with "EXCHANGE2" replacement string
var newSource = str.replace(source, "EXCHANGE1", "EXCHANGE2", 0)
if barstate.islastconfirmedhistory
// Display "EXCHANGE1:SYMBOL1 / EXCHANGE1:SYMBOL2"
runtime.log(newSource)
Returns Processed string.
Arguments
- source
(series string) Source string.
- target
(series string) String to be replaced.
- replacement
(series string) String to be inserted instead of the target string.
- occurrence
(series int) The matching index of the occurrence of the target string to be replaced in the source string Indexing starts at 0 for the first match. Optional. Default value is 0.
See also
### str.replace_all
Replaces each occurrence of the target string in the source string with the replacement string.
str.replace_all(source, target, replacement)
**Returns**
Processed string.
**Arguments**
- ```source``` (series string) Source string.
- ```target``` (series string) String to be replaced.
- ```replacement``` (series string) String to be substituted for each occurrence of target string.
### str.split
Divides a string into an array of substrings and returns its array ID.
str.split(string, separator)
**Returns**
The ID of an array of strings.
**Arguments**
- ```string``` (series string) Source string.
- ```separator``` (series string) The string separating each substring.
### str.tostring
str.tostring(value)
str.tostring(value, format)
str.tostring(value[])
str.tostring(value[], format)
**Returns**
The string representation of the ```value``` argument.
If the ```value``` argument is a string, it is returned as is.
When the ```value``` is na, the function returns the string "NaN".
**Arguments**
- ```value``` (series int/float/bool/string/int[]/float[]/bool[]/string[]) Value or array ID whose elements are converted to a string.
- ```format``` (series string) Format string. Accepts these format.* constants: format.mintick, format.percent, format.volume. Optional. The default value is '#.##########'.
**Remarks**
The formatting of float values will also round those values when necessary, e.g. str.tostring(3.99, '#') will return "4".
To display trailing zeros, use '0' instead of '#'. For example, '#.000'.
When using format.mintick, the value will be rounded to the nearest number that can be divided by syminfo.mintick without the remainder. The string is returned with trailing zeroes.
If the x argument is a string, the same string value will be returned.
Bool type arguments return "true" or "false".
When x is na, the function returns "NaN".
## color
### color.new
Function color applies the specified transparency to the given color.
color.new(color, transp)
**Example**
```pine
plot(close, color=color.new(color.red, 50))
Returns Color with specified transparency.
Arguments
- color
(series color)
- transp
(series int/float) Possible values are from 0 (not transparent) to 100 (invisible).
Remarks Using arguments that are not constants (e.g., ‘simple’, ‘input’ or ‘series’) will have an impact on the colors displayed in the script’s “Settings/Style” tab. See the User Manual for more information.
Creates a new color with transparency using the RGB color model.
color.rgb(red, green, blue, transp)
Example
plot(close, color=color.rgb(255, 0, 0, 50))
Returns Color with specified transparency.
Arguments
- red
(series int/float) Red color component. Possible values are from 0 to 255.
- green
(series int/float) Green color component. Possible values are from 0 to 255.
- blue
(series int/float) Blue color component. Possible values are from 0 to 255.
- transp
(series int/float) Optional. Color transparency. Possible values are from 0 (opaque) to 100 (invisible). Default value is 0.
Remarks Using arguments that are not constants (e.g., “simple”, “input” or “series”) will have an impact on the colors displayed in the script’s “Settings/Style” tab. See the User Manual for more information.
Print variable information to the console.
FMZ PINE language specific functions, runtime.debug(value)
, with only an argument.
Output content in the log.
FMZ PINE language specific functions, runtime.log(1, 2, 3, close, high, ...)
, you can pass multiple arguments.
When called, causes a runtime error with the error message specified in the message
argument.
runtime.error(message)
Arguments message (series string) Error message.
Adds an input to the Inputs tab of your script’s Settings, which allows you to provide configuration options to script users. This function automatically detects the type of the argument used for “defval” and uses the corresponding input widget.
input(defval, title, tooltip, inline, group)
input(defval, title, inline, group, tooltip)
Example
i_switch = input(true, "On/Off") // Set true, the default is checked.
plot(i_switch ? open : na)
i_len = input(7, "Length")
i_src = input(close, "Source") // Drop-down box, select close by default.
plot(ta.sma(i_src, i_len))
i_col = input(color.red, "Plot Color")
plot(close, color=i_col)
i_text = input("Hello!", "Message")
runtime.log(i_text)
Returns Value of input variable.
Arguments
- defval
(const int/float/bool/string/color or source-type built-ins) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where script users can change it. Source-type built-ins are built-in series float variables that specify the source of the calculation: close
, hlc3
, etc.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
Remarks Result of input function always should be assigned to a variable, see examples above.
See also
### input.source
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a dropdown that allows the user to select a source for the calculation, e.g. close, hl2, etc. If the script includes only one input.source() call, the user can also select an output from another indicator on their chart as the source.
input.source(defval, title, tooltip, inline, group)
**Example**
```pine
i_src = input.source(close, "Source")
plot(i_src)
Returns Value of input variable.
Arguments
- defval
(series int/float) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where the user can change it.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
Remarks Result of input.source function always should be assigned to a variable, see examples above.
See also
### input.string
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a field for a string input to the script's inputs.
input.string(defval, title, options, tooltip, inline, group, confirm)
**Example**
```pine
i_text = input.string("Hello!", "Message")
runtime.log(i_text)
Returns Value of input variable.
Arguments
- defval
(const string) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where the user can change it. When a list of values is used with the options
argument, the value must be one of them.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- options
(List of constants: [<type>…]) A list of options to choose from.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
Remarks Result of input.string function always should be assigned to a variable, see examples above.
See also
### input.bool
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a checkmark to the script's inputs.
input.bool(defval, title, tooltip, inline, group, confirm)
**Example**
```pine
i_switch = input.bool(true, "On/Off")
plot(i_switch ? open : na)
Returns Value of input variable.
Arguments
- defval
(const bool) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where the user can change it.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
Remarks Result of input.bool function always should be assigned to a variable, see examples above.
See also
### input.int
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a field for an integer input to the script's inputs.
input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm)
input.int(defval, title, options, tooltip, inline, group, confirm)
**Example**
```pine
i_len1 = input.int(10, "Length 1", minval=5, maxval=21, step=1)
plot(ta.sma(close, i_len1))
i_len2 = input.int(10, "Length 2", options=[5, 10, 21])
plot(ta.sma(close, i_len2))
Returns Value of input variable.
Arguments
- defval
(const int) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where script users can change it. When a list of values is used with the options
argument, the value must be one of them.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- minval
(const int) Minimal possible value of the input variable. Optional.
- maxval
(const int) Maximum possible value of the input variable. Optional.
- step
(const int) Step value used for incrementing/decrementing the input. Optional. The default is 1.
- options
(tuple of const int values: [val1, val2, …]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, …]. When using this argument, the minval
, maxval
and step
arguments cannot be used.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
Remarks Result of input.int function always should be assigned to a variable, see examples above.
See also
### input.float
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a field for a float input to the script's inputs.
input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm)
input.float(defval, title, options, tooltip, inline, group, confirm)
**Example**
```pine
i_angle1 = input.float(0.5, "Sin Angle", minval=-3.14, maxval=3.14, step=0.02)
plot(math.sin(i_angle1) > 0 ? close : open, "sin", color=color.green)
i_angle2 = input.float(0, "Cos Angle", options=[-3.14, -1.57, 0, 1.57, 3.14])
plot(math.cos(i_angle2) > 0 ? close : open, "cos", color=color.red)
Returns Value of input variable.
Arguments
- defval
(const int/float) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where script users can change it. When a list of values is used with the options
argument, the value must be one of them.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- minval
(const int/float) Minimal possible value of the input variable. Optional.
- maxval
(const int/float) Maximum possible value of the input variable. Optional.
- step
(const int/float) Step value used for incrementing/decrementing the input. Optional. The default is 1.
- options
(tuple of const int/float values: [val1, val2, …]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, …]. When using this argument, the minval
, maxval
and step
arguments cannot be used.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
Remarks Result of input.float function always should be assigned to a variable, see examples above.
See also
### input.color
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users. This function adds a color picker that allows the user to select a color and transparency, either from a palette or a hex value.
input.color(defval, title, tooltip, inline, group, confirm)
**Example**
```pine
i_col = input.color(color.red, "Plot Color")
plot(close, color=i_col)
Returns Value of input variable.
Arguments
- defval
(const color) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where the user can change it.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
Remarks Result of input.color function always should be assigned to a variable, see examples above.
See also
### input.price
Adds a price input to the script's "Settings/Inputs" tab. Using ```confirm = true``` activates the interactive input mode where a price is selected by clicking on the chart.
input.price(defval, title, tooltip, inline, group, confirm)
**Example**
```pine
price1 = input.price(title="Date", defval=42)
plot(price1)
price2 = input.price(54, title="Date")
plot(price2)
Returns Value of input variable.
Arguments
- defval
(const int/float) Determines the default value of the input variable proposed in the script’s “Settings/Inputs” tab, from where the user can change it.
- title
(const string) Title of the input. If not specified, the variable name is used as the input’s title. If the title is specified, but it is empty, the name will be an empty string.
- tooltip
(const string) The string that will be shown to the user when hovering over the tooltip icon.
- inline
(const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
- group
(const string) Creates a header above all inputs using the same group argument string. The string is also used as the header’s text.
- confirm
(const bool) If true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. Optional. The default is false.
Remarks
When using interactive mode, a time input can be combined with a price input if both function calls use the same argument for their inline
argument.
See also
input.bool
input.int
input.float
input.string
“`input.resoluti