nineLivesUtilLibLibrary "nineLivesUtilLib"
isDateInRange(currentTime, useTimeFilter, startDate, endDate)
Checks if the current time is within the specified date range.
Parameters:
currentTime (int) : The current bar's time (time).
useTimeFilter (bool) : Bool 📅: Enable the date range filter.
startDate (int) : Timestamp 📅: The start date for the filter.
endDate (int) : Timestamp 📅: The end date for the filter.
Returns: True if the current time is within the range or filtering is disabled, false otherwise.
@example
inDateRange = nineLivesUtilLib.isDateInRange(time, useTimeFilter, startDate, endDate)
if inDateRange
// Execute trading logic
checkVolumeCondition(currentVolume, useVolumeFilter, volumeThresholdMultiplier, volumeLength)
Checks if the current volume meets the threshold condition.
Parameters:
currentVolume (float) : The current bar's volume (volume).
useVolumeFilter (bool) : Bool 📊: Enable the volume filter.
volumeThresholdMultiplier (float) : Float 📊: Volume threshold relative to average (e.g., 1.5 for 1.5x average).
volumeLength (int) : Int 📊: Lookback length for the volume average.
Returns: True if the volume condition is met or filtering is disabled, false otherwise.
@example
volumeOk = nineLivesUtilLib.checkVolumeCondition(volume, useVolumeFilter, volumeThreshold, volumeLength)
if volumeOk
// Proceed with trading logic
checkMultiTimeframeCondition(currentClose, currentOpen, htfClose, htfOpen, useMultiTimeframe, alignment)
Checks alignment with higher timeframe direction.
Parameters:
currentClose (float) : Float: The current bar's closing price (close).
currentOpen (float) : Float: The current bar's opening price (open).
htfClose (float) : Float: The closing price from the higher timeframe (must be fetched by the calling script using request.security).
htfOpen (float) : Float: The opening price from the higher timeframe (must be fetched by the calling script using request.security).
useMultiTimeframe (bool) : Bool ⏱️: Enable multi-timeframe analysis.
alignment (string) : String ⏱️: Desired alignment ("same", "opposite", "any").
Returns: True if the timeframe alignment condition is met or analysis is disabled, false otherwise.
@example
// In the calling script:
= request.security(syminfo.tickerid, higherTimeframe, )
tfOk = nineLivesUtilLib.checkMultiTimeframeCondition(close, open, htfClose, htfOpen, useMultiTimeframe, tfAlignment)
if tfOk
// Proceed with trading logic
checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode)
Detects the market regime (trending or ranging) and checks if trading is allowed.
Parameters:
useMarketRegime (bool) : Bool 🔍: Enable market regime detection.
regimeIndicator (string) : String 🔍: Indicator to use ("ADX" or "Volatility").
regimeThreshold (int) : Int 🔍: Threshold for trend strength/volatility.
regimeLength (simple int) : Int 🔍: Lookback length for the indicator.
regimeMode (string) : String 🔍: Trading mode based on regime ("trend_only", "range_only", "adaptive").
Returns: A tuple containing:
: conditionMet (bool) - True if trading is allowed based on the regime mode and detection, false otherwise.
: inTrendingRegime (bool) - True if the current regime is trending based on the indicator and threshold.
@example
= nineLivesUtilLib.checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode)
if regimeOk
// Proceed with trading logic
applyCooldown(buySignal, sellSignal, cooldownBars)
Applies a cooldown period after a signal.
Parameters:
buySignal (bool) : Bool: Buy signal (potentially after primary entry logic).
sellSignal (bool) : Bool: Sell signal (potentially after primary entry logic).
cooldownBars (int) : Int ⏳: The number of bars to wait after a signal before allowing another.
Returns: A tuple containing:
: cooldownFilteredBuy (bool) - Buy signal after cooldown filter.
: cooldownFilteredSell (bool) - Sell signal after cooldown filter.
@example
= nineLivesUtilLib.applyCooldown(rawBuySignal, rawSellSignal, iCool)
applyAllFilters(rawBuy, rawSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, drawdownOk, cooldownOkBuy, cooldownOkSell)
Applies all filtering conditions to the buy and sell signals.
Parameters:
rawBuy (bool) : Bool: The initial buy signal candidate (from primary entry logic, e.g., after cooldown).
rawSell (bool) : Bool: The initial sell signal candidate (from primary entry logic, e.g., after cooldown).
inDateRange (bool) : Bool 📅: Result from isDateInRange.
tradeDirection (string) : String 🔄: Overall trade direction preference ("longs_only", "shorts_only", "both").
volumeOk (bool) : Bool 📊: Result from checkVolumeCondition.
tfOk (bool) : Bool ⏱️: Result from checkMultiTimeframeCondition.
regimeOk (bool) : Bool 🔍: Result from checkMarketRegime.
drawdownOk (bool) : Bool 📉: Result from checkDrawdownExceeded (or equivalent).
cooldownOkBuy (bool) : Bool ⏳: Result from applyCooldown for buy.
cooldownOkSell (bool) : Bool ⏳: Result from applyCooldown for sell.
Returns: A tuple containing:
: finalBuySignal (bool) - The final buy signal after all filters.
: finalSellSignal (bool) - The final sell signal after all filters.
@example
= nineLivesUtilLib.applyAllFilters(cooldownBuy, cooldownSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, !drawdownExceeded, cooldownBuy, cooldownSell)
NOTE: This function filters signals generated by your primary entry logic (e.g., EMA crossover).
checkDrawdownExceeded(currentEquity, useMaxDrawdown, maxDrawdownPercent)
Tracks maximum equity and checks if current drawdown exceeds a threshold.
Parameters:
currentEquity (float) : Float: The strategy's current equity (strategy.equity).
useMaxDrawdown (bool) : Bool 📉: Enable max drawdown protection.
maxDrawdownPercent (float) : Float 📉: The maximum allowed drawdown as a percentage.
Returns: True if drawdown protection is enabled and the current drawdown exceeds the threshold, false otherwise.
@example
drawdownExceeded = nineLivesUtilLib.checkDrawdownExceeded(strategy.equity, useMaxDrawdown, maxDrawdownPercent)
if drawdownExceeded
// Consider stopping entries or exiting positions in the strategy script
calculateExitPrice(positionAvgPrice, percentage, isStop, isLong)
Calculates a stop loss or take profit price based on a percentage from the average entry price.
Parameters:
positionAvgPrice (float) : Float: The average price of the current position (strategy.position_avg_price).
percentage (float) : Float: The stop loss or take profit percentage (e.g., 2.0 for 2%).
isStop (bool) : Bool: True if calculating a stop loss price, false if calculating a take profit price.
isLong (bool) : Bool: True if the position is long, false if short.
Returns: The calculated stop price or take profit price, or na if no position or percentage is invalid.
@example
longSL = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, stopLossPercent, true, true)
shortTP = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, takeProfitPercent, false, false)
calculateTrailingStopLevel(positionAvgPrice, trailOffsetPercent, trailPercent, currentHigh, currentLow, isLong)
Calculates the current trailing stop level for a position.
Parameters:
positionAvgPrice (float) : Float: The average price of the current position (strategy.position_avg_price).
trailOffsetPercent (float) : Float 🔄: The percentage price movement to activate the trailing stop.
trailPercent (float) : Float 🔄: The percentage distance the stop trails behind the price.
currentHigh (float) : Float: The current bar's high (high).
currentLow (float) : Float: The current bar's low (low).
isLong (bool) : Bool: True if the position is long, false if short.
Returns: The calculated trailing stop price if active, otherwise na.
@example
longTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, true)
shortTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, false)
if not na(longTrailStop)
strategy.exit("Long Trail", from_entry="Long", stop=longTrailStop)
Pine yardımcı programları
JsonAlertJsonAlert Library – Convert TradingView Alerts to JSON for Server Processing! 📡
🚀 The JsonAlert library makes it easy to send TradingView alerts as structured JSON to your server, allowing seamless integration with automated trading systems, databases, or webhook-based services.
📌 Features:
✅ Converts TradingView alert data into JSON format
✅ Supports custom key-value pairs for flexibility
✅ Allows frequency control (once per bar, once per bar close, every update)
✅ Easy to integrate with server-side PHP or other languages
Note that you have to pass one string array for keys and one string array for values , also you should pass alert frequency .
📖 Example Usage in Pine Script:
//@version=6
indicator("My script" , overlay = true)
import Penhan/JsonAlert/1 as alrt
if high > low
var array keys = array.from("ticker", "timeframe", "pattern")
var array values = array.from( syminfo.ticker , timeframe.period , str.tostring(123.45) )
alrt.alarm (keys, values , alert.freq_once_per_bar)
📡 Json Output Example:
{"ticker": "BTCUSDT","timeframe": "1","pattern": "123.45"}
🖥️ Server-Side PHP Example:
There you can integrate JsonAlert with your server in seconds! :)
DateTimeLibrary with enums that can be used as script inputs to allow users to set their preferred date and/or time formats. The user-selected formats can be passed to the library functions (which use 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎() under the hood) to get formatted date and time strings from a UNIX time.
PREFACE
The target audience of this publication is users creating their own indicators/strategies.
Sometimes a date and/or time needs to be displayed to the user. As a Pine Coder, it is natural to focus our initial attention on the primary calculations or functions of a script, which can lead to the display format of dates and times being an afterthought. While it may not be crucial for the main use case of a script, increased customizability can help push indicators/strategies to the next level in the eyes of the user.
The purpose of this library is to provide an easy-to-use mechanism for allowing script users to choose the formats of dates and times that are displayed to them. Not only is this helpful for users from around the world who may be accustomed to different date/time formats, but it also makes it easier for the script author because it offloads the date/time formatting decision from the author to the user.
HOW TO USE
Step 1
Import the library. Replace with the latest available version number for this library.
//@version=6
indicator("Example")
import n00btraders/DateTime/ as dt
Step 2
Select a date format and/or time format enum to be used as an input.
dateFormatInput = input.enum(dt.DateFormat.FORMAT_3, "Date format")
timeFormatInput = input.enum(dt.TimeFormat.TWENTY_FOUR_HOURS, "Time hours format")
Step 3
Pass the user's selection as the `format` parameter in the formatting functions from this library. The `timestamp` & `timezone` parameters can be any value that would otherwise be used in 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎(𝚝𝚒𝚖𝚎, 𝚏𝚘𝚛𝚖𝚊𝚝, 𝚝𝚒𝚖𝚎𝚣𝚘𝚗𝚎).
string formattedDate = dt.formatDate(timestamp, dateFormatInput, timezone)
string formattedTime = dt.formatTime(timestamp, timeFormatInput, timezone)
LIMITATIONS
The library's ease-of-use comes at a few costs:
Fixed date/time formats.
Using the library's pre-defined date & time formats means that additional custom formats cannot be utilized. For example, this library does not include seconds or fractional seconds in formatted time strings. If a script's use case requires displaying the 'seconds' from a time of day, then 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎() must be used directly.
Fixed time zone offset format.
The `formatTime()` function of this library can optionally add the time zone offset at the end of the time string, but the format of the offset cannot be specified. Note: if the default format for time zone offset is not sufficient, the Timezone library can be imported directly to get the time zone offset string in a preferred format.
ADVANTAGES
There are benefits to utilizing this library instead of directly using 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎():
Easy to use from the user's perspective.
The date & time format enums provide a similar look and feel to the "Date format" and "Time hours format" options that already exist in the TradingView chart settings.
Easy to use from the author's perspective.
The exported functions from this library are modeled to behave similarly to the 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎(𝚝𝚒𝚖𝚎, 𝚏𝚘𝚛𝚖𝚊𝚝, 𝚝𝚒𝚖𝚎𝚣𝚘𝚗𝚎) built-in function from Pine Script.
Format quarter of the year.
The date formatting function from this library can display a fiscal quarter if it's included in the user-selected format. This is currently not possible with the built-in 𝚜𝚝𝚛.𝚏𝚘𝚛𝚖𝚊𝚝_𝚝𝚒𝚖𝚎().
EXPORTED ENUM TYPES
This section will list the available date/time formats that can be used as a script input. Each enum type has a detailed //@𝚏𝚞𝚗𝚌𝚝𝚒𝚘𝚗 description in the source code to help determine the best choice for your scripts.
Date Format Enums:
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔𝙰𝚋𝚋𝚛
𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔𝙵𝚞𝚕𝚕
𝙲𝚞𝚜𝚝𝚘𝚖𝙳𝚊𝚝𝚎𝙵𝚘𝚛𝚖𝚊𝚝
Supporting Date Enums:
𝙳𝚊𝚝𝚎𝙿𝚛𝚎𝚏𝚒𝚡
Time Format Enums:
𝚃𝚒𝚖𝚎𝙵𝚘𝚛𝚖𝚊𝚝
Supporting Time Enums:
𝚃𝚒𝚖𝚎𝙰𝚋𝚋𝚛𝚎𝚟𝚒𝚊𝚝𝚒𝚘𝚗
𝚃𝚒𝚖𝚎𝚂𝚎𝚙𝚊𝚛𝚊𝚝𝚘𝚛
𝚃𝚒𝚖𝚎𝙿𝚘𝚜𝚝𝚏𝚒𝚡
Note: all exported enums have custom titles for each field. This means that the supporting enums could also be exposed to the end-user as script inputs if necessary. The supporting enums are used as optional parameters in this library's formatting functions to allow further customizability.
EXPORTED FUNCTIONS
formatDate(timestamp, format, timezone, prefix, trim)
Converts a UNIX time into a date string formatted according to the selected `format`.
Parameters:
timestamp (series int) : A UNIX time.
format (series DateFormat) : A date format.
timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
prefix (series DatePrefix) : Optional day of week prefix.
trim (series bool) : Optional truncation of numeric month / day.
Returns: Calendar date string using the selected format.
⸻⸻⸻⸻⸻⸻⸻⸻
Required parameters: `timestamp`, `format`.
Note: there is a version of this function for each Date Format enum type. The only difference is the type of the `format` parameter.
Tip: hover over the `formatDate()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
formatTime(timestamp, format, timezone, trim, separator, postfix, space, offset)
Converts a UNIX time into a formatted time string using the 24-hour clock or 12-hour clock.
Parameters:
timestamp (series int) : A UNIX time.
format (series TimeFormat) : A time format.
timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
trim (series TimeAbbreviation) : Optional truncation of the hour and minute portion.
separator (series TimeSeparator) : Optional time separator.
postfix (series TimePostfix) : Optional format for the AM/PM postfix.
space (series bool) : Optional space between the time and the postfix.
offset (series bool) : Optional UTC offset as a suffix.
Returns: Time of day string using the selected format.
⸻⸻⸻⸻⸻⸻⸻⸻
Required parameters: `timestamp`, `format`.
Note: the `trim`, `postfix`, and `space` optional parameters are not applicable and will be ignored when using the 24-hour clock (`format` = TimeFormat.TWENTY_FOUR_HOURS).
Tip: hover over the `formatTime()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
Example outputs for combinations of TimeFormat.* enum values & optional parameters
NOTES
This library can be used in conjunction with the Timezone library to increase the usability of scripts that can benefit from allowing the user to input their preferred time zone.
Credits to HoanGhetti for publishing an informative Markdown resource which I referenced to create the formatted function descriptions that pop up when hovering over `formatDate()` and `formatTime()` function calls in the Pine Editor.
csv_series_libraryThe CSV Series Library is an innovative tool designed for Pine Script developers to efficiently parse and handle CSV data for series generation. This library seamlessly integrates with TradingView, enabling the storage and manipulation of large CSV datasets across multiple Pine Script libraries. It's optimized for performance and scalability, ensuring smooth operation even with extensive data.
Features:
Multi-library Support: Allows for distribution of large CSV datasets across several libraries, ensuring efficient data management and retrieval.
Dynamic CSV Parsing: Provides robust Python scripts for reading, formatting, and partitioning CSV data, tailored specifically for Pine Script requirements.
Extensive Data Handling: Supports parsing CSV strings into Pine Script-readable series, facilitating complex financial data analysis.
Automated Function Generation: Automatically wraps CSV blocks into distinct Pine Script functions, streamlining the process of integrating CSV data into Pine Script logic.
Usage:
Ideal for traders and developers who require extensive data analysis capabilities within Pine Script, especially when dealing with large datasets that need to be partitioned into manageable blocks. The library includes a set of predefined functions for parsing CSV data into usable series, making it indispensable for advanced trading strategy development.
Example Implementation:
CSV data is transformed into Pine Script series using generated functions.
Multiple CSV blocks can be managed and parsed, allowing for flexible data series creation.
The library includes comprehensive examples demonstrating the conversion of standard CSV files into functional Pine Script code.
To effectively utilize the CSV Series Library in Pine Script, it is imperative to initially generate the correct data format using the accompanying Python program. Here is a detailed explanation of the necessary steps:
1. Preparing the CSV Data:
The Python script provided with the CSV Series Library is designed to handle CSV files that strictly contain no-space, comma-separated single values. It is crucial that your CSV file adheres to this format to ensure compatibility and correctness of the data processing.
2. Using the Python Program to Generate Data:
Once your CSV file is prepared, you need to use the Python program to convert this file into a format that Pine Script can interpret. The Python script performs several key functions:
Reads the CSV file, ensuring that it matches the required format of no-space, comma-separated values.
Formats the data into blocks, where each block is a string of data that does not exceed a specified character limit (default is 4,000 characters). This helps manage large datasets by breaking them down into manageable chunks.
Wraps these blocks into Pine Script functions, each block being encapsulated in its own function to maintain organization and ease of access.
3. Generating and Managing Multiple Libraries:
If the data from your CSV file exceeds the Pine Script or platform limits (e.g., too many characters for a single script), the Python script can split this data into multiple blocks across several files.
4. Creating a Pine Script Library:
After generating the formatted data blocks, you must create a Pine Script library where these blocks are integrated. Each block of data is contained within its function, like my_csv_0(), my_csv_1(), etc. The full_csv() function in Pine Script then dynamically loads and concatenates these blocks to reconstruct the full data series.
5. Exporting the full_csv() Function:
Once your Pine Script library is set up with all the CSV data blocks and the full_csv() function, you export this function from the library. This exported function can then be used in your actual trading projects. It allows Pine Script to access and utilize the entire dataset as if it were a single, continuous series, despite potentially being segmented across multiple library files.
6. Reconstructing the Full Series Using vec :
When your dataset is particularly large, necessitating division into multiple parts, the vec type is instrumental in managing this complexity. Here’s how you can effectively reconstruct and utilize your segmented data:
Definition of vec Type: The vec type in Pine Script is specifically designed to hold a dataset as an array of floats, allowing you to manage chunks of CSV data efficiently.
Creating an Array of vec Instances: Once you have your data split into multiple blocks and each block is wrapped into its own function within Pine Script libraries, you will need to construct an array of vec instances. Each instance corresponds to a segment of your complete dataset.
Using array.from(): To create this array, you utilize the array.from() function in Pine Script. This function takes multiple arguments, each being a vec instance that encapsulates a data block. Here’s a generic example:
vec series_vector = array.from(vec.new(data_block_1), vec.new(data_block_2), ..., vec.new(data_block_n))
In this example, data_block_1, data_block_2, ..., data_block_n represent the different segments of your dataset, each returned from their respective functions like my_csv_0(), my_csv_1(), etc.
Accessing and Utilizing the Data: Once you have your vec array set up, you can access and manipulate the full series through Pine Script functions designed to handle such structures. You can traverse through each vec instance, processing or analyzing the data as required by your trading strategy.
This approach allows Pine Script users to handle very large datasets that exceed single-script limits by segmenting them and then methodically reconstructing the dataset for comprehensive analysis. The vec structure ensures that even with segmentation, the data can be accessed and utilized as if it were contiguous, thus enabling powerful and flexible data manipulation within Pine Script.
Library "csv_series_library"
A library for parsing and handling CSV data to generate series in Pine Script. Generally you will store the csv strings generated from the python code in libraries. It is set up so you can have multiple libraries to store large chunks of data. Just export the full_csv() function for use with this library.
method csv_parse(data)
Namespace types: array
Parameters:
data (array)
method make_series(series_container, start_index)
Namespace types: array
Parameters:
series_container (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
method make_series(series_vector, start_index)
Namespace types: array
Parameters:
series_vector (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
vec
A type that holds a dataset as an array of float arrays.
Fields:
data_set (array) : A chunk of csv data. (A float array)
[e2] Drawing Library :: Horizontal Ray█ OVERVIEW
Library "e2hray"
A drawing library that contains the hray() function, which draws a horizontal ray/s with an initial point determined by a specified condition. It plots a ray until it reached the price. The function let you control the visibility of historical levels and setup the alerts.
█ HORIZONTAL RAY FUNCTION
hray(condition, level, color, extend, hist_lines, alert_message, alert_delay, style, hist_style, width, hist_width)
Parameters:
condition : Boolean condition that defines the initial point of a ray
level : Ray price level.
color : Ray color.
extend : (optional) Default value true, current ray levels extend to the right, if false - up to the current bar.
hist_lines : (optional) Default value true, shows historical ray levels that were revisited, default is dashed lines. To avoid alert problems set to 'false' before creating alerts.
alert_message : (optional) Default value string(na), if declared, enables alerts that fire when price revisits a line, using the text specified
alert_delay : (optional) Default value int(0), number of bars to validate the level. Alerts won't trigger if the ray is broken during the 'delay'.
style : (optional) Default value 'line.style_solid'. Ray line style.
hist_style : (optional) Default value 'line.style_dashed'. Historical ray line style.
width : (optional) Default value int(1), ray width in pixels.
hist_width : (optional) Default value int(1), historical ray width in pixels.
Returns: void
█ EXAMPLES
• Example 1. Single horizontal ray from the dynamic input.
//@version=5
indicator("hray() example :: Dynamic input ray", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
inputTime = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date", confirm = true)
inputPrice = input.price(54, 'Price Level', confirm = true)
e2draw.hray(time == inputTime, inputPrice, color.blue, alert_message = 'Ray level re-test!')
var label mark = label.new(inputTime, inputPrice, 'Selected point to start the ray', xloc.bar_time)
• Example 2. Multiple horizontal rays on the moving averages cross.
//@version=5
indicator("hray() example :: MA Cross", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
float sma1 = ta.sma(close, 20)
float sma2 = ta.sma(close, 50)
bullishCross = ta.crossover( sma1, sma2)
bearishCross = ta.crossunder(sma1, sma2)
plot(sma1, 'sma1', color.purple)
plot(sma2, 'sma2', color.blue)
// 1a. We can use 2 function calls to distinguish long and short sides.
e2draw.hray(bullishCross, sma1, color.green, alert_message = 'Bullish Cross Level Broken!', alert_delay = 10)
e2draw.hray(bearishCross, sma2, color.red, alert_message = 'Bearish Cross Level Broken!', alert_delay = 10)
// 1b. Or a single call for both.
// e2draw.hray(bullishCross or bearishCross, sma1, bullishCross ? color.green : color.red)
• Example 3. Horizontal ray at the all time highs with an alert.
//@version=5
indicator("hray() example :: ATH", overlay = true)
import e2e4mfck/e2hray/1 as e2draw
var float ath = 0, ath := math.max(high, ath)
bool newAth = ta.change(ath)
e2draw.hray(nz(newAth ), high , color.orange, alert_message = 'All Time Highs Tested!', alert_delay = 10)