next_libsmcLibrary "next_libsmc"
TODO: add library description here
method init(this)
Namespace types: OrderBlockConfig
Parameters:
this (OrderBlockConfig)
method delete(this)
Namespace types: OrderBlock
Parameters:
this (OrderBlock)
method delete(blocks)
Namespace types: array
Parameters:
blocks (array)
method delete(this)
delete the plot of an object, including deleting it from the chart
Namespace types: FVG
Parameters:
this (FVG)
method delete(fvgs)
delete the plot of an array of objects, including deleting it from the chart
Namespace types: array
Parameters:
fvgs (array)
create_ob(id, mode, start_t, start_i, top, end_t, end_i, bottom, break_price, break_mode)
INTERNAL: set internal order block coordinates
Parameters:
id (int)
mode (int) : 1: bullish, -1 bearish block
start_t (int)
start_i (int)
top (float)
end_t (int)
end_i (int)
bottom (float)
break_price (float)
break_mode (simple LevelBreakMode)
Returns: signals are true if an according order block was broken/mitigated
method align_to_profile(block, align_edge, align_break_price)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
align_edge (bool)
align_break_price (bool)
method create_profile(block, opens, tops, bottoms, closes, values, resolution, vah_pc, val_pc, init_calculated, use_open_close_data_for_blocks_shorter_than_bars)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
opens (array)
tops (array)
bottoms (array)
closes (array)
values (array)
resolution (int)
vah_pc (float)
val_pc (float)
init_calculated (bool)
use_open_close_data_for_blocks_shorter_than_bars (simple int)
method create_profile(block, resolution, vah_pc, val_pc, init_calculated, use_open_close_data_for_blocks_shorter_than_bars)
Namespace types: OrderBlock
Parameters:
block (OrderBlock)
resolution (int)
vah_pc (float)
val_pc (float)
init_calculated (bool)
use_open_close_data_for_blocks_shorter_than_bars (simple int)
track_obs(swing_len, swing_high_confirmed, swing_low_confirmed, bull_bos_alert, bull_choch_alert, bear_bos_alert, bear_choch_alert, min_block_size, max_block_size, enabled, include_consecutive_bars, capture_profile, align_edge_to_value_area, align_break_price_to_poc, use_soft_confirm, soft_confirm_offset, use_soft_confirm_big_candle, use_retracements_with_FVG_out, broken_by, keep_broken_max, gc_cycle)
Parameters:
swing_len (int)
swing_high_confirmed (float)
swing_low_confirmed (float)
bull_bos_alert (bool)
bull_choch_alert (bool)
bear_bos_alert (bool)
bear_choch_alert (bool)
min_block_size (float)
max_block_size (float)
enabled (bool)
include_consecutive_bars (simple bool)
capture_profile (simple bool)
align_edge_to_value_area (simple bool)
align_break_price_to_poc (simple bool)
use_soft_confirm (simple bool)
soft_confirm_offset (float)
use_soft_confirm_big_candle (simple bool)
use_retracements_with_FVG_out (simple bool)
broken_by (simple LevelBreakMode)
keep_broken_max (simple int)
gc_cycle (simple int)
method draw(this, config, extend_only, force_overlay, left_override, right_override)
plot order block
Namespace types: OrderBlock
Parameters:
this (OrderBlock) : OrderBlock to draw
config (OrderBlockConfig) : OrderBlockConfig to apply to block
extend_only (bool) : if true, only the right x coordinate will be updated after initial draw. This enables usage of xloc.bar_index older than 254 bars (given the block has been drawn once within the 254 bars after the left coordinate bar). If you want to draw with changing left x coordinate set this to false (default: true)
force_overlay (simple bool)
left_override (int)
right_override (int)
method draw(blocks, config, extend_only, force_overlay, left_override, right_override)
plot order blocks
Namespace types: array
Parameters:
blocks (array) : array of OrderBlocks to draw
config (OrderBlockConfig) : OrderBlockConfig to apply to all blocks
extend_only (bool) : if true, only the right x coordinate will be updated after initial draw. This enables usage of xloc.bar_index older than 254 bars (given the block has been drawn once within the 254 bars after the left coordinate bar). If you want to draw with changing left x coordinate set this to false (default: true)
force_overlay (simple bool)
left_override (int) : ob left coordinate (defaults to xloc.bar_index, configure config.args.xloc to use bar_time)
right_override (int) : ob right coordinate (defaults to xloc.bar_index, configure config.args.xloc to use bar_time)
method draw(blocks, config, extend_only, force_overlay, left_override, right_override)
plot order blocks
Namespace types: map
Parameters:
blocks (map) : array of OrderBlocks to draw
config (OrderBlockConfig) : OrderBlockConfig to apply to all blocks
extend_only (bool) : if true, only the right x coordinate will be updated after initial draw. This enables usage of xloc.bar_index older than 254 bars (given the block has been drawn once within the 254 bars after the left coordinate bar). If you want to draw with changing left x coordinate set this to false (default: true)
force_overlay (simple bool)
left_override (int) : ob left x coordinate (defaults to xloc.bar_index, configure config.args.xloc to use bar_time)
right_override (int) : ob right x coordinate (defaults to xloc.bar_index, configure config.args.xloc to use bar_time)
method draw(this, config, extend_only, force_overlay, left_override, right_override)
plot FVG (Fair Value Gap)
Namespace types: FVG
Parameters:
this (FVG) : FVG to draw
config (FVGConfig) : FVGConfig to apply to fvg
extend_only (bool) : if true, only the right x coordinate will be updated after initial draw. This enables usage of xloc.bar_index older than 254 bars (given the block has been drawn once within the 254 bars after the left coordinate bar). If you want to draw with changing left x coordinate set this to false (default: true)
force_overlay (simple bool)
left_override (int)
right_override (int)
method draw(fvgs, config, extend_only, force_overlay, left_override, right_override)
plot fvgs
Namespace types: array
Parameters:
fvgs (array) : array of FVGs to draw
config (FVGConfig) : FVGConfig to apply to all fvgs
extend_only (bool) : if true, only the right x coordinate will be updated after initial draw. This enables usage of xloc.bar_index older than 254 bars (given the block has been drawn once within the 254 bars after the left coordinate bar). If you want to draw with changing left x coordinate set this to false (default: true)
force_overlay (simple bool)
left_override (int)
right_override (int)
method hide(this)
hide the plot of an object, without deleting it from the chart, so it can re-appear later without triggering a max_bars_back error when redrawing an object that has a x coordinate > 244 bars in the past (the limit for the default buffer)
Namespace types: OrderBlock
Parameters:
this (OrderBlock)
method hide(this)
hide the plot of an object, without deleting it from the chart, so it can re-appear later without triggering a max_bars_back error when redrawing an object that has a x coordinate > 244 bars in the past (the limit for the default buffer)
Namespace types: FVG
Parameters:
this (FVG)
detect_swings(length)
INTERNAL: detect swing points (HH and LL) in given range
Parameters:
length (simple int)
Returns: values are the price level where and if a new HH or LL was detected, else na
detect_pivot(mode, trend, hhll_x, hhll, super_hhll, filter_insignificant_internal_breaks)
INTERNAL: detect whether a structural level has been broken and if it was in trend direction (BoS) or against trend direction (ChoCh), also track the latest high and low swing points
Parameters:
mode (simple int) : detect 1: bullish, -1 bearish pivot points
trend (int) : current trend direction
hhll_x (int) : x-coordinate of newly detected hh/ll (bar_index)
hhll (float) : y-coordinate of newly detected hh/ll (price)
super_hhll (float) : level/y-coordinate of superior hhll (if this is an internal structure pivot level)
filter_insignificant_internal_breaks (bool) : if true pivot points / internal structure will be ignored where the wick in trend direction is longer than the opposite (likely to push further in direction of main trend)
Returns: coordinates of internal structure that has been broken (x,y): start of structure, (trail_x, trail_y): tracking hh/ll after structure break, (bos_alert, choch_alert): signal whether a structural level has been broken
detect_structure(swing_len, super_hh, super_ll, filter_insignificant_internal_breaks)
detect (and plot) structural breaks and the resulting new trend
Parameters:
swing_len (simple int)
super_hh (float) : level/y-coordinate of superior hh (for internal structure detection)
super_ll (float) : level/y-coordinate of superior ll (for internal structure detection)
filter_insignificant_internal_breaks (bool) : if true pivot points / internal structure will be ignored where the wick in trend direction is longer than the opposite (likely to push further in direction of main trend)
Returns: trend: direction 1:bullish -1:bearish, (bull_bos_alert, bull_choch_alert, top_x, top_y, trail_up_x, trail_up): whether and which level broke in a bullish direction, trailing high, (bbear_bos_alert, bear_choch_alert, tm_x, btm_y, trail_dn_x, trail_dn): same in bearish direction
plot_pivot_points(mode, x, y, enabled, args, keep_history)
INTERNAL: plot swing points
Parameters:
mode (int) : 1: bullish, -1 bearish block
x (int) : x-coordingate of swing point to plot (bar_index)
y (float) : y-coordingate of swing point to plot (price)
enabled (bool) : switch to enable/disable plotting of swing point labels
args (LabelArgs type from robbatt/lib_plot_objects/56) : object for swing point label styling
keep_history (bool) : weather to remove older swing point labels or only keep the most recent
plot_swing_levels(mode, trail_x, trail_y, trend, enabled, label_args, line_args, override_right_index)
INTERNAL: plot latest swing levels
Parameters:
mode (int) : 1: bullish, -1 bearish block
trail_x (int) : x-coordinate for latest swing point (bar_index)
trail_y (float) : y-coordinate for latest swing point (price)
trend (int) : the current trend 1: bullish, -1: bearish, to determine Strong/Weak Low/Highs
enabled (bool) : switch to enable/disable plotting of swing point labels
label_args (LabelArgs type from robbatt/lib_plot_objects/56) : object for swing point label styling
line_args (LineArgs type from robbatt/lib_plot_objects/56) : object for swing point line styling
override_right_index (int)
plot_structure(x, y, is_bos, is_choch, label_args, line_args, keep_history)
INTERNAL: plot structural breaks (BoS/ChoCh)
Parameters:
x (int) : x-coordinate of newly broken structure (bar_index)
y (float) : y-coordinate of newly broken structure (price)
is_bos (bool) : whether this structural break was in trend direction
is_choch (bool) : whether this structural break was against trend direction
label_args (LabelArgs type from robbatt/lib_plot_objects/56) : object for plot structure styling
line_args (LineArgs type from robbatt/lib_plot_objects/56) : object for plot structure styling
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
detect_equal_level(mode, len, eq_threshold, enabled)
INTERNAL: detect equal levels (double top/bottom)
Parameters:
mode (int) : detect 1: bullish/high, -1 bearish/low pivot points
len (int) : lookback period for equal level (swing point) detection
eq_threshold (float) : maximum price offset for a level to be considered equal
enabled (bool)
Returns: eq_alert whether an equal level was detected and coordinates of the first and the second level/swing point
detect_equal_levels(len, threshold, enabled)
detect (and plot) equal levels (double top/bottom), returns coordinates
Parameters:
len (int) : lookback period for equal level (swing point) detection
threshold (float) : maximum price offset for a level to be considered equal
enabled (bool) : whether detection is enabled
Returns: (eqh_alert, eqh_x1, eqh_y1, eqh_x2, eqh_y2) whether an equal high was detected and coordinates of the first and the second level/swing point, (eql_alert, eql_x1, eql_y1, eql_x2, eql_y2) same for equal lows
plot_equal_level(show_eq, x1, y1, x2, y2, label_txt, label_args, line_args, keep_history, force_overlay)
INTERNAL: plot equal levels (double top/bottom)
Parameters:
show_eq (bool) : whether to plot the level or not
x1 (int) : x-coordinate of the first level / swing point
y1 (float) : y-coordinate of the first level / swing point
x2 (int) : x-coordinate of the second level / swing point
y2 (float) : y-coordinate of the second level / swing point
label_txt (string) : text for the label above/below the line connecting the equal levels
label_args (LabelArgs type from robbatt/lib_plot_objects/56)
line_args (LineArgs type from robbatt/lib_plot_objects/56)
keep_history (bool) : weater to remove older swing point labels and only keep the most recent
force_overlay (bool)
_detect_fvg(mode, enabled, size_threshold)
INTERNAL: detect FVG (fair value gap)
Parameters:
mode (int) : detect 1: bullish, -1 bearish gaps
enabled (bool) : whether detection is enabled
size_threshold (float) : filter small/insignificant gaps that are smaller than this value
Returns: whether a new FVG was detected and its top/bottom levels
_detect_fvg_object(mode, enabled, size_threshold, fill_mode, fill_target_ratio)
INTERNAL: detect FVG points (fair value gap)
Parameters:
mode (int) : detect 1: bullish, -1 bearish gaps
enabled (bool) : whether detection is enabled
size_threshold (float) : filter small/insignificant gaps that are smaller than this value
fill_mode (series LevelBreakMode)
fill_target_ratio (float) : at which point the FVG is considered as filled
Returns: whether a new FVG was detected and its left_top/right_bottom chart.points
_clear_broken_fvg(mode, upper_boxes, lower_boxes, fill_ratio)
INTERNAL: clear mitigated FVGs (fair value gaps)
Parameters:
mode (int) : detect 1: bullish, -1 bearish gaps
upper_boxes (array) : array that stores the upper parts of the FVG boxes
lower_boxes (array) : array that stores the lower parts of the FVG boxes
fill_ratio (float)
plot_fvg(mode, show, top, btm, border_color, extend_box, fill_ratio)
INTERNAL: plot (and clear broken) FVG (fair value gap)
Parameters:
mode (int) : plot 1: bullish, -1 bearish gap
show (bool) : whether plotting is enabled
top (float) : top level of fvg
btm (float) : bottom level of fvg
border_color (color) : color for the FVG box
extend_box (int) : how many bars into the future the FVG box should be extended after detection
fill_ratio (float) : target fill ratio of FVG (optional, defaults to 50%)
fvgs_values(size_threshold, enabled)
detect FVGs (fair value gaps), and return alerts and level values
Parameters:
size_threshold (float) : filter small/insignificant gaps that are smaller than this value
enabled (bool) : whether detection is enabled
Returns: (bullish_fvg_alert, bull_top, bull_btm): whether a new bullish FVG was detected and its top/bottom levels, (bearish_fvg_alert, bear_top, bear_btm): same for bearish FVGs
method clear_filled(fvgs, filled_buffer, filled_new_buffer, keep_history, discard_buffer)
Namespace types: array
Parameters:
fvgs (array)
filled_buffer (array)
filled_new_buffer (array)
keep_history (int)
discard_buffer (array)
method update(this)
Namespace types: FVG
Parameters:
this (FVG)
method update(fvgs)
Namespace types: array
Parameters:
fvgs (array)
method remove_insignificant(fvgs, size_threshold, removed_buffer)
removes FVGs smaller than size_threshold from fvgs. If a removed_buffer is passed, it adds it to that buffer (plots are not deleted because it would be a 'side effect' in security calls, make sure to call delete() on each removed FVG to remove it from the chart as well.)
Namespace types: array
Parameters:
fvgs (array)
size_threshold (float)
removed_buffer (array)
fvgs_objects(fill_mode, fill_target_ratio, size_threshold, enabled, filled_max_keep, gc_cycle)
detect FVGs (fair value gaps), and return FVG objects
Parameters:
fill_mode (simple LevelBreakMode)
fill_target_ratio (float)
size_threshold (float) : filter small/insignificant gaps that are smaller than this value
enabled (simple bool) : whether detection is enabled
filled_max_keep (simple int)
gc_cycle (simple int)
Returns: (bullish_fvg_alert, bearish_fvg_alert) boolean flag to indicate a new FVG | (buffer_bull, buffer_bear) persistent buffers of unfilled FVGs with latest at the end | (new_bull, new_bear) newly detected FVG objects additionally to being added to the buffer | (filled_bull, filled_bear) non persistent arrays of FVGs filled in this candle
fvgs_plot(bullish_fvg_alert, bull_top, bull_btm, bearish_fvg_alert, bear_top, bear_btm, color_bull, color_bear, extend_box, fill_ratio, show)
detect (and plot / clear broken) FVGs (fair value gaps), and return alerts and level values
Parameters:
bullish_fvg_alert (bool)
bull_top (float)
bull_btm (float)
bearish_fvg_alert (bool)
bear_top (float)
bear_btm (float)
color_bull (color) : color for bullish FVG boxes
color_bear (color) : color for bearish FVG boxes
extend_box (int) : how many bars into the future the FVG box should be extended after detection
fill_ratio (float) : (optional) target fill ratio at which the box is removed (defaults to 0.5)
show (bool) : whether plotting is enabled
Returns: (bullish_fvg_alert, bull_top, bull_mid, bull_btm): whether a new bullish FVG was detected and its top/mid/bottom levels, (bearish_fvg_alert, bear_top, bear_mid, bear_btm): same for bearish FVGs
fvgs(size_threshold, color_bull, color_bear, extend_box, fill_ratio, enabled, show)
detect (and plot / clear broken) FVGs (fair value gaps)
Parameters:
size_threshold (float) : filter small/insignificant gaps that are smaller than this value
color_bull (color) : color for bullish FVG boxes
color_bear (color) : color for bearish FVG boxes
extend_box (int) : how many bars into the future the FVG box should be extended after detection
fill_ratio (float) : (optional) target fill ratio at which the box is removed (defaults to 0.5)
enabled (bool) : whether detection is enabled
show (bool) : whether plotting is enabled
Returns: (bullish_fvg_alert): whether a new bullish FVG was detected, (bearish_fvg_alert): same for bearish FVGs
OrderBlock
Fields:
id (series int)
dir (series int)
left_top (chart.point)
right_bottom (chart.point)
break_price (series float)
break_mode (series LevelBreakMode)
ltf_open (array)
ltf_high (array)
ltf_low (array)
ltf_close (array)
ltf_volume (array)
plot (Box type from robbatt/lib_plot_objects/56)
profile (Profile type from robbatt/lib_profile/44)
probability (series float)
trailing (series bool)
extending (series bool)
awaiting_confirmation (series bool)
touched_break_price_before_confirmation (series bool)
soft_confirmed (series bool)
has_fvg_out (series bool)
has_big_candle (series bool)
hidden (series bool)
broken (series bool)
broken_time (series int)
broken_index (series int)
OrderBlockConfig
Fields:
show (series bool)
show_last (series int)
show_id (series bool)
show_profile (series bool)
show_text (series bool)
show_fvg_out (series bool)
show_probability (series bool)
extend_until_broken (series bool)
args (BoxArgs type from robbatt/lib_plot_objects/56)
txt (series string)
txt_args (BoxTextArgs type from robbatt/lib_plot_objects/56)
use_profile (series bool)
profile_config (ProfileConfig type from robbatt/lib_profile/44)
FVGConfig
Fields:
show_box (series bool)
show_target (series bool)
show_target_label (series bool)
show_last (series int)
show_text (series bool)
show_probability (series bool)
show_profile (series bool)
box_args (BoxArgs type from robbatt/lib_plot_objects/56)
box_text_args (BoxTextArgs type from robbatt/lib_plot_objects/56)
line_args (LineArgs type from robbatt/lib_plot_objects/56)
label_args (LabelArgs type from robbatt/lib_plot_objects/56)
txt (series string)
extend_bars (series int)
extend_until_filled (series bool)
FVG
Fields:
dir (series int)
fill_mode (series LevelBreakMode)
left_top (chart.point)
right_bottom (chart.point)
fvg_fill_target_ratio (series float)
fill_target_level (series float)
fill_current_ratio (series float)
fill_current_level (series float)
total_volume (series float)
probability (series float)
filled (series bool)
fill_time (series int)
fill_index (series int)
plot_box (Box type from robbatt/lib_plot_objects/56)
plot_fill_target_level (Line type from robbatt/lib_plot_objects/56)
plot_fill_target_label (Label type from robbatt/lib_plot_objects/56)
hidden (series bool)
Penunjuk dan strategi
EMACrossLibLibrary "EMACrossLib"
Common functions for EMA strategies
calcEMAs(src, fastLength, slowLength)
Parameters:
src (float)
fastLength (simple int)
slowLength (simple int)
detectCrossovers(fastEMA, slowEMA)
Parameters:
fastEMA (float)
slowEMA (float)
prepareWebhookMessage(epic, direction, size)
Parameters:
epic (string)
direction (string)
size (float)
NYCSessionLibrary "NYCSession"
Library for New York trading session time functions
@author abneralvarado
@version 1.0
isInNYSession(sessionStart, sessionEnd)
Determines if the current bar is within New York trading session
Parameters:
sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM) like 0930 for 9:30 AM ET
sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM) like 1600 for 4:00 PM ET
Returns: True if current bar is within the NY session time, false otherwise
getNYSessionStartTime(lookback, sessionStart)
Gets the start time of NY session for a given bar
Parameters:
lookback (simple int) : Bar index to check (0 is current bar)
sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
Returns: Unix timestamp for the start of NY session on the given bar's date
getNYSessionEndTime(lookback, sessionEnd)
Gets the end time of NY session for a given bar
Parameters:
lookback (simple int) : Bar index to check (0 is current bar)
sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
Returns: Unix timestamp for the end of NY session on the given bar's date
isNYSessionOpen(sessionStart)
Checks if current bar opens the NY session
Parameters:
sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
Returns: True if current bar marks the session opening, false otherwise
isNYSessionClose(sessionEnd)
Checks if current bar closes the NY session
Parameters:
sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
Returns: True if current bar marks the session closing, false otherwise
isWeekday()
Determines if the current day is a weekday (Mon-Fri)
Returns: True if current bar is on a weekday, false otherwise
getSessionBackgroundColor(sessionStart, sessionEnd, bgColor)
Gets session background color with transparency
Parameters:
sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
bgColor (color) : Background color for session highlighting
Returns: Color value for background or na if not in session
DoppelLibLibrary "DoppelLib"
getDailyClose(offset)
Returns the daily close for a specific offset.
For each offset value (from 1 to 21), the function uses a static request.security() call
to retrieve the daily close from the previous day at the specified offset.
Parameters:
offset (int) : (int) The offset value (from 1 to 21) representing the desired close value.
Returns: (float) The daily close for the specified offset or na if offset is out of range.
isVolumeAboveThreshold(vol, mediaPeriod, thresholdPercent)
Checks if the current volume is above the threshold based on its moving average.
The threshold is calculated as the average volume plus a percentage increment.
Parameters:
vol (float) : (series float) The volume series (e.g. the chart volume).
mediaPeriod (int) : (int) The period for calculating the moving average.
thresholdPercent (float) : (float) The percentage to add to the average for the threshold.
Returns: (bool) True if the volume exceeds the threshold, false otherwise.
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
Calculates the PVSRA candle color, determines if a vector candle has appeared,
and returns additional support parameters (average volume, volume spread, highest volume spread).
- "High" (Climax): volume >= 200% of the average OR (volume * candle spread) >= highest spread over the previous 10 bars.
-> Bull candle: green; Bear candle: red.
- "Medium": volume >= 150% of the average.
-> Bull candle: blue; Bear candle: violet.
- Otherwise, default (non-vector) candle colors are used.
Parameters:
pvsraVolume (float) : (series float) Volume series.
pvsraHigh (float) : (series float) High price series.
pvsraLow (float) : (series float) Low price series.
pvsraClose (float) : (series float) Close price series.
pvsraOpen (float) : (series float) Open price series.
redVectorColor (simple color) : (simple color) Color for bearish candle in high scenario.
greenVectorColor (simple color) : (simple color) Color for bullish candle in high scenario.
violetVectorColor (simple color) : (simple color) Color for bearish candle in medium scenario.
blueVectorColor (simple color) : (simple color) Color for bullish candle in medium scenario.
darkGreyCandleColor (simple color) : (simple color) Color for bearish candle in non-vector situation.
lightGrayCandleColor (simple color) : (simple color) Color for bullish candle in non-vector situation.
Returns: (tuple) A tuple containing: .
NR_VersatilitiesLibrary "NR_Versatilities"
Versatilities (aka, Versatile Utilities) includes:
- Seventeen Price Variants returned as a tuple,
- Eight Smoothing functions rolled into one,
- Pick any Past Value from any series with offset,
- Or just the previous value from any series.
pastVal(src, len)
Fetches past value from src that came len distance ago
Parameters:
src (float) : source series
len (int) : lookback distance - (optional) default is 1
Returns: latest src if len <= 0, else src
previous(src)
Fetches past value from src that came len distance ago
Parameters:
src (float) : source series
Returns: previous value in the series if found, else current value
price_variants()
Computes Several different averages using current and previous OHLC values
Returns: Seventeen Uncommon Average Price Combinations
dynamic_MA(matyp, masrc, malen, lsmaoff, almasgm, almaoff, almaflr)
Dynamically computes Eight different MAs on-demand individually, or an average of all taken together
Parameters:
matyp (string) : pick one of these MAs - ALMA, EMA, HMA, LSMA, RMA, SMA, SWMA, WMA, ALL
masrc (float) : source series to compute MA
malen (simple int) : lookback distance for MA
lsmaoff (simple int) : optional LSMA offset - default is 0
almasgm (simple float) : optional ALMA sigma - default is 5
almaoff (simple float) : optional ALMA offset - default is 0.5
almaflr (simple bool) : optional ALMA floor flag - default is false
Returns: MA series for chosen type or, an average of all of them, if chosen so
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! :)
projectiontrackingLibrary "projectiontracking"
Library contains few data structures and methods for tracking harmonic patterns and projections via pinescript.
method erase(this)
erase Harmonic Projection Drawing
Namespace types: HarmonicProjectionDrawing
Parameters:
this (HarmonicProjectionDrawing) : HarmonicProjectionDrawing object
Returns: void
method erase(this)
erase HarmonicProjection
Namespace types: HarmonicProjection
Parameters:
this (HarmonicProjection) : HarmonicProjection object
Returns: void
method draw(this)
draw HarmonicProjection
Namespace types: HarmonicProjection
Parameters:
this (HarmonicProjection) : HarmonicProjection object
Returns: HarmonicProjection object
method getRanges(projectionPrzRanges, dir)
Convert PRZRange to Projection ranges
Namespace types: array
Parameters:
projectionPrzRanges (array type from Trendoscope/HarmonicMapLib/1) : array of PrzRange objects
dir (int) : Projection direction
Returns: array
ProjectionRange
Harmonic Projection Range
Fields:
patterns (array) : array of pattern names
start (series float) : Start Range
end (series float) : End Range
status (series int) : Projection Status
ProjectionProperties
Harmonic Projection Properties
Fields:
fillMajorTriangles (series bool) : Use linefill for major triangles
fillMinorTriangles (series bool) : Use linefill for minor triangles
majorFillTransparency (series int) : transparency of major triangles
minorFillTransparency (series int) : transparency of minor triangles
showXABC (series bool) : Show XABC labels
lblSizePivots (series string) : Pivot labels size
showRatios (series bool) : Show ratio labels
useLogScaleForScan (series bool) : Log scale is used for scanning projections
activateOnB (series bool) : Activate projections on reaching B
activationRatio (series float) : Use activation ratio for activation
confirmationRatio (series float) : Confirmation ratio of projection before removal
HarmonicProjectionDrawing
Harmonic Projection Projection drawing objects
Fields:
xa (series line) : line xa
ab (series line) : line ab
bc (series line) : line bc
xb (series line) : line xb
ac (series line) : line ac
x (series label) : Pivot label x
a (series label) : Pivot label a
b (series label) : Pivot label b
c (series label) : Pivot label c
xabRatio (series label) : Label XAB Ratio
abcRatio (series label) : Label ABC Ratio
HarmonicProjection
Harmonic Projection Projection object
Fields:
patternId (series int) : id of the pattern
dir (series int) : projection direction
x (chart.point) : Pivot X
a (chart.point) : Pivot A
b (chart.point) : Pivot B
c (chart.point) : Pivot C
patternColor (series color) : Color in which pattern is displayed
przRange (PrzRange type from Trendoscope/HarmonicMapLib/1) : PRZ Range
activationPrice (series float) : Projection activation price
reversalPrice (series float) : Projection reversal price
status (series int) : Projection status
properties (ProjectionProperties) : Projection properties
projectionRanges (array) : array of Projection Ranges
initialD (series float) : Initial D pivot
d (chart.point) : Pivot D
drawing (HarmonicProjectionDrawing) : HarmonicProjectionDrawing Object
HarmonicMapLibLibrary "HarmonicMapLib"
Harmonic Pattern Library implementation utilising maps
method tostring(this)
convert Range value to string
Namespace types: Range
Parameters:
this (Range) : Range value
Returns: converted string representation
method tostring(this)
convert array of Range value to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
method tostring(this)
convert map of string to Range value to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert RatioMap to string
Namespace types: RatioMap
Parameters:
this (RatioMap) : RatioMap object
Returns: converted string representation
method tostring(this)
convert array of RatioMap to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
method tostring(this)
convert map of string to RatioMap to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert map of string to bool to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert PrzRange to string
Namespace types: PrzRange
Parameters:
this (PrzRange) : PrzRange object
Returns: converted string representation
method tostring(this)
convert array of PrzRange to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
getHarmonicMap()
Creates the RatioMap for harmonic patterns
Returns: map haronic ratio rules for all patterns
method evaluate(patternsMap, pattern, ratioRange, properties, ratioValue)
evaluates harmonic ratio range
Namespace types: map
Parameters:
patternsMap (map) : parameter containing valid pattern names
pattern (string) : Pattern type to be evaluated
ratioRange (Range) : ratio range to be checked
properties (ScanProperties) : Scan Properties
ratioValue (float)
Returns: void
method evaluate(przRange, pattern, ratioRange, priceRange, properties)
Evaluate PRZ ranges
Namespace types: map
Parameters:
przRange (map)
pattern (string) : Pattern name
ratioRange (Range) : Range of ratio for the pattern
priceRange (Range) : Price range based on ratio
properties (ScanProperties) : ScanProperties object
Returns: void
method scanRatio(currentPatterns, rules, properties, ratioName, ratioValue)
Scan for particular named ratio of harmonic pattern to filter valid patterns
Namespace types: map
Parameters:
currentPatterns (map) : Current valid patterns map
rules (map) : map Harmonic ratio rules
properties (ScanProperties) : ScanProperties object
ratioName (string) : Specific ratio name
ratioValue (float) : ratio value to be checked
Returns: updated currentPatterns object
method scanPatterns(patterns, x, a, b, c, d, properties)
Scan for patterns based on X, A, B, C, D values
Namespace types: map
Parameters:
patterns (map) : List of allowed patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
d (float) : D coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: updated valid patterns map
method scanProjections(patterns, x, a, b, c, properties)
Scan for projections based on X, A, B, C values
Namespace types: map
Parameters:
patterns (map) : List of allowed patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: updated valid projections map
method merge(this, other)
merge two ranges into one
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: combined range
method union(this, other)
union of two ranges into one
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: union range
method overlaps(this, other)
checks if two ranges intersect
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: true if intersects, false otherwise
method consolidate(this)
Consolidate ranges into PRZ
Namespace types: map
Parameters:
this (map) : map of Ranges
Returns: consolidated PRZ
method consolidateMany(this)
Consolidate ranges into multiple PRZ ranges
Namespace types: map
Parameters:
this (map) : map of Ranges
Returns: consolidated array of PRZ ranges
method getRange(currentPatterns, x, a, b, c, properties)
Get D range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: map of D ranges
method getPrzRange(currentPatterns, x, a, b, c, properties)
Get PRZ range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: PRZRange for the pattern
method getProjectionRanges(currentPatterns, x, a, b, c, properties)
Get projection range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: array of projection ranges
Range
Collection of range values
Fields:
values (array) : array of float values
RatioMap
ratio map for pattern
Fields:
ratioMap (map) : map of string to Range (array of float)
ScanProperties
Pattern Scanning properties
Fields:
strictMode (series bool) : strict scanning mode will check for overflows
logScale (series bool) : scan ratios in log scale
errorMin (series float) : min error threshold
errorMax (series float)
mintick (series float) : minimum tick value of price
PrzRange
Potential reversal zone range
Fields:
patterns (array) : array of pattern names for the given XABCD combination
prz (Range) : PRZ range
datastructuresLibrary "datastructures"
Collection of complex data structures not generally present as part of pinescript and can be used for collection and transformation of the data
method init(this)
initialise StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet to be initialised
Returns: current object of StringSet
method add(this, value)
add value to StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
@value the key of stringset to be set
value (string)
Returns: current object of StringSet
method clear(this)
clear StringSet contents
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
Returns: current object of StringSet
method remove(this, value)
remove value from StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
@value the key of stringset to be removed
value (string)
Returns: current object of StringSet
method size(this)
get size of the StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
Returns: size of StringSet map
method isEmpty(this)
check if stringset is empty
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
Returns: true if empty else returns false
method iterator(this)
get values of the StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
Returns: values of StringSet
method contains(this, value)
check if value is present in StringSet
Namespace types: StringSet
Parameters:
this (StringSet) : StringSet object
value (string)
Returns: true if Value is present. False otherwise
method initialiseCountMap(types, numberOfStates)
Initialise a new map of string to Count
Namespace types: array
Parameters:
types (array) : array of string containing map keys
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method initialiseCountMap(types, numberOfStates)
Initialise a new map of string to Count
Namespace types: map
Parameters:
types (map) : map containing types and configurable boolean flag
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method get(this, key, n)
get count based on primary string key and secondary int key
Namespace types: map
Parameters:
this (map) : map of string to to Count
key (string) : primary key
n (int) : secondary key
Returns: derived count from map of map
method get(this, key, n)
get array of int associated with key and n
Namespace types: map
Parameters:
this (map) : map of string to to MapToInts
key (string) : primary string key
n (int) : secondary int key
Returns: derived array of int for the given key combination
method get(this, key, n)
get array of float associated with key and n
Namespace types: map
Parameters:
this (map) : map of string to to MapToFloats
key (string) : primary string key
n (int) : secondary int key
Returns: derived array of float
method get(this, key)
get values of Ints based on key
Namespace types: map
Parameters:
this (map) : map of string to Ints
key (string) : string key
Returns: values inside Ints object associated in the map
method set(this, key, n, value)
set count for specific primary and secondary key
Namespace types: map
Parameters:
this (map) : map of string to to Count
key (string) : primary string key
n (int) : secondary int key
value (int) : the new count value to be set
Returns: updated value for key and n
method increment(this, key, n)
increment count for specific primary and secondary key
Namespace types: map
Parameters:
this (map) : map of string to to Count
key (string) : primary string key
n (int) : secondary int key
Returns: incremented value
method increment(this, key, n)
intcrement the value of Ints based on key and n (secondary key)
Namespace types: map
Parameters:
this (map) : map of string to Ints
key (string) : string key
n (int) : secondary int key
Returns: incremented nth object of Ints associated with key
method initialiseIntsMap(types, numberOfStates)
Initialise a new map of string to Map to Ints
Namespace types: array
Parameters:
types (array) : array of string containing map keys
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method initialiseIntsMap(types, numberOfStates)
Initialise a new map of string to Map to Ints
Namespace types: map
Parameters:
types (map) : map with boolean flag
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method initialiseFloatsMap(types, numberOfStates)
Initialise a new map of string to Map to Floats
Namespace types: array
Parameters:
types (array) : array of string containing map keys
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method initialiseFloatsMap(types, numberOfStates)
Initialise a new map of string to Map to Floats
Namespace types: map
Parameters:
types (map) : map with boolean flag
numberOfStates (int) : number of items to be tracked for each type
Returns: new map() with empty initialisation
method initialiseMapOfInts(types, numberOfStates)
Initialise map of two dimentional Ints based on types and number of states
Namespace types: array
Parameters:
types (array) : types array for which a new Map to Ints to be created
numberOfStates (int) : number of states for which the Ints needs to be initialised
Returns: new map of string to two dimension array of int (Ints)
method initialiseMapOfInts(types, numberOfStates)
Initialise map of two dimentional Ints based on types and number of states
Namespace types: map
Parameters:
types (map) : types map for which a new Map to Ints to be created along with bool flag
numberOfStates (int) : number of states for which the Ints needs to be initialised
Returns: new map of string to two dimension array of int (Ints)
StringSet
Set implementation using map
Fields:
strSet (map) : map of string to bool
Count
type containing map of int to int
Fields:
count (map) : map of int to int used for counting
Ints
custom type to enable array of array of int
Fields:
values (array) : int array
Floats
custom type to enable array of array of float
Fields:
values (array) : float array
MapToInts
type containing map of int to int array
Fields:
vmap (map) : map of int to Ints used as counting collection
MapToFloats
type containing map of int to float array
Fields:
vmap (map) : map of int to Floats used as floating stat collection
drawingutilsLibrary "drawingutils"
methods used in my scripts for some basic and customized drawings and arrays.
method line(this, p1, p2, lineColor, style, width, xloc, extend)
Draws line and adds to the array
Namespace types: array
Parameters:
this (array) : array to which the created line needs to be added
p1 (chart.point) : point1 of the line
p2 (chart.point) : point2 of the line
lineColor (color) : line color
style (string) : line style
width (int) : line width
xloc (string) : xloc.bar_index or xloc.bar_time
extend (string) : default is extend.none
Returns: line created
method label(this, p, txt, tooltip, xloc, yloc, color, style, textcolor, size, textalign)
Draws label and adds to the array
Namespace types: array
Parameters:
this (array) : array to which the created label needs to be added
p (chart.point) : point at which the label needs to be drawn
txt (string) : label text
tooltip (string) : tooltip text
xloc (string) : xloc value - xloc.bar_index or xloc.bar_time
yloc (string) : y location of the label
color (color) : label color
style (string) : label style
textcolor (color) : label text color
size (string) : Size of the label
textalign (string) : text alignment
Returns: label created
method linefill(this, ln1, ln2, fillColor, transparency)
Draws linefill and adds to array
Namespace types: array
Parameters:
this (array) : array to which the created linefill needs to be added
ln1 (line) : line1 of the fill
ln2 (line) : line2 of the fill
fillColor (color) : fill Color
transparency (int) : fill transparency
Returns: linefill created
draw_labelled_line(target, lblText, linecolor, labelcolor, index, highlight, linesArray, labelsArray, highlightSize, tinySize, yloc, textalign)
Draws labelled line
Parameters:
target (float) : target price
lblText (string) : label text
linecolor (color) : line color
labelcolor (color) : label color
index (int) : index to calculate the distance offset
highlight (bool) : highlight true/false
linesArray (array) : array of lines where the created line is added
labelsArray (array) : array of labels where the created label is added
highlightSize (string) : Size of highlighted text
tinySize (string) : size of non highlighted text
yloc (string) : y location
textalign (string) : text alignment
Returns: void
draw_labelled_box(y1, y2, labelColor, labelText, index, boxArray, labelArray, borderColor, borderStyle, borderWidth, textAlign, highlight, highLightLabel)
Draws custom labelled box
Parameters:
y1 (float) : price 1 of the box
y2 (float) : price 2 of the box
labelColor (color) : label color
labelText (string) : label text
index (int) : index to calculate the offset distance
boxArray (array) : box array to which the box needs to be added
labelArray (array) : label array to which the label needs to be added
borderColor (color) : border color
borderStyle (string) : border style
borderWidth (int) : border width
textAlign (string) : text align of the label
highlight (bool) : highlight label text
highLightLabel (bool) : highlight label size
Returns: void
HM_RTH_UtilsLibrary "HM_RTH_Utils"
getPrevRTHData(session)
Parameters:
session (string)
RTHData
Fields:
open (series float)
high (series float)
low (series float)
close (series float)
highVolume (series float)
lowVolume (series float)
totalVolume (series float)
MTFDataLibrary "MTFData"
Functions to store multi timeframe candle data and swing points.
getCandleData(timeframe, openArray, highArray, lowArray, closeArray, timeArray, olcLookback, alltfs_olcLookback, tfIndex)
Stores current or higher timeframe candle data in arrays.
Parameters:
timeframe (string) : The timeframe, for example "240" for 4h
openArray (array) : An array to store the candle open price
highArray (array) : An array to store the candle high price
lowArray (array) : An array to store the candle low price
closeArray (array) : An array to store the candle close price
timeArray (array) : An array to store the candle time
olcLookback (int) : The history reference of the lookback limiting candle
alltfs_olcLookback (array) : An array holding the candle time of olcLookback candles ago, which can be used for limiting lookbacks
tfIndex (int) : The timeframe's index in the alltfs_olcLookback array
Returns: true if the timeframe changed
trackHiLo(tfchange, timeframe, openArray, highArray, lowArray, closeArray, timeArray, highWickArray, highBodyArray, highTimeArray, lowWickArray, lowBodyArray, lowTimeArray, alltfs_olcLookback, tfIndex)
Stores current or higher timeframe swingpoint data into arrays.
Parameters:
tfchange (bool) : Must be true when the timeframe has changed (a new candle has opened)
timeframe (string) : The timeframe, for example "240" for 4h
openArray (array) : An array that stores the timeframe's candle open price
highArray (array) : An array that stores the timeframe's candle high price
lowArray (array) : An array that stores the timeframe's candle low price
closeArray (array) : An array that stores the timeframe's candle close price
timeArray (array) : An array that stores the timeframe's candle time
highWickArray (array) : An array to store the swing high price
highBodyArray (array) : An array to store the swing high's highest body price
highTimeArray (array) : An array to store the swing high candle's time
lowWickArray (array) : An array to store the swing low price
lowBodyArray (array) : An array to store the swing low's lowest body price
lowTimeArray (array) : An array to store the swing high candle's time
alltfs_olcLookback (array) : An array holding the time of the max allowed swing point age
tfIndex (int) : The timeframe's index in the alltfs_olcLookback array
Returns: Nothing. The array handling happens inside the function.
tfReadable(tfInSec)
Converts a timeframe string ("240") into a more readable string ("4h").
Parameters:
tfInSec (int) : The timeframe that should be converted, as timeframe.in_seconds()
Returns: A more readable timeframe string
TrendLibrary "Trend"
calculateSlopeTrend(source, length, thresholdMultiplier)
Parameters:
source (float)
length (int)
thresholdMultiplier (float)
Purpose:
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
Parameters:
`source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
`length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
`thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
Calculation Steps:
Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`:
If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
Return Value:
The function returns an integer representing the determined trend direction:
`1`: Upward trend
`-1`: Downward trend
`0`: Flat trend
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
TimeframeUtilsCustomLibrary "TimeframeUtilsCustom"
Timeframe utilities library
f_timeframe_to_minutes(tf)
Converts timeframe string to minutes
Parameters:
tf (string) : String representation of timeframe
Returns: Number of minutes in the given timeframe
f_bars_for_hours(timeframe_minutes, hours)
Calculate number of bars for a specified time period
Parameters:
timeframe_minutes (int) : Current timeframe in minutes
hours (int) : Number of hours to calculate bars for
Returns: Number of bars representing the specified hours
f_bars_for_days(timeframe_minutes, days)
Calculate number of bars for a specified number of days
Parameters:
timeframe_minutes (int) : Current timeframe in minutes
days (int) : Number of days to calculate bars for
Returns: Number of bars representing the specified days
crypto_sectors_requestLibrary "crypto_sectors_request"
TODO: add library description here
getGaming()
lib_plot_objects_1Library "lib_plot_objects_1"
method extend_to(this, end_time, end_idx, end_price)
Namespace types: Line
Parameters:
this (Line)
end_time (int)
end_idx (int)
end_price (float)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: LineArgs
Parameters:
args (LineArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: PolyLineArgs
Parameters:
args (PolyLineArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: LabelArgs
Parameters:
args (LabelArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: BoxArgs
Parameters:
args (BoxArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: BoxTextArgs
Parameters:
args (BoxTextArgs)
method direction(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_green(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_red(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_bullish(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_bearish(this)
Namespace types: Candle
Parameters:
this (Candle)
method total_size(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_size(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_top(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_bottom(this)
Namespace types: Candle
Parameters:
this (Candle)
method wick_size_top(this)
Namespace types: Candle
Parameters:
this (Candle)
method wick_size_bottom(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_total_ratio(this)
Namespace types: Candle
Parameters:
this (Candle)
method duration(this)
Namespace types: Candle
Parameters:
this (Candle)
create_candle(t, tc, idx, o, h, l, c, v)
Creates Candle with ohlc and index data
Parameters:
t (int) : bar time of this candle
tc (int) : bar close time of this candle
idx (int) : bar index of this candle
o (float) : open price of this candle
h (float) : highest price of this candle
l (float) : lowest price of this candle
c (float) : close price of this candle
v (float)
Returns: new Candle
create_point(x, price, xloc)
Creates a new chart.point based on xloc switch
Parameters:
x (int)
price (float)
xloc (string)
method calculate_center(indexA, priceA, indexB, priceB)
Creates center chart.point between two chart.points
Namespace types: series int, simple int, input int, const int
Parameters:
indexA (int) : coordinates of point A (using just index, because time will not work properly in session based instruments)
priceA (float) : coordinates of point A
indexB (int) : coordinates of point B (using just index, because time will not work properly in session based instruments)
priceB (float) : coordinates of point B
Returns: center coordinates
method calculate_center(this, other)
Creates center chart.point between an array of given chart.points
Namespace types: chart.point
Parameters:
this (chart.point)
other (chart.point)
Returns: center coordinates
method calculate_center(points)
Creates center chart.point between an array of given chart.points
Namespace types: array
Parameters:
points (array) : array of chart.points for calculation of the center
Returns: center chart.point
method calculate_center(this)
Namespace types: Line
Parameters:
this (Line)
method calculate_center(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
method create_center(this, other)
Creates center chart.point between two chart.points
Namespace types: chart.point
Parameters:
this (chart.point) : chart.point
other (chart.point) : chart.point
Returns: center chart.point
method create_center(points)
Creates center chart.point between an array of given chart.points
Namespace types: array
Parameters:
points (array) : array of chart.points for calculation of the center
Returns: center chart.point
method create_center(this)
Namespace types: Line
Parameters:
this (Line)
method create_center(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
create_label(x, y, xloc, txt, tooltip)
Creates a new Label object.
Parameters:
x (int)
y (float)
xloc (string)
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: chart.point
Parameters:
this (chart.point)
txt (string)
tooltip (string)
method create_label(txt, tooltip)
Creates a new Label object.
Namespace types: series string, simple string, input string, const string
Parameters:
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Line
Parameters:
this (Line)
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Box
Parameters:
this (Box)
txt (string)
tooltip (string)
method create_center_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Line
Parameters:
this (Line)
txt (string)
tooltip (string)
method create_center_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: PolyLine
Parameters:
this (PolyLine)
txt (string)
tooltip (string)
method nz(this, default)
Namespace types: chart.point
Parameters:
this (chart.point)
default (chart.point)
method nz(this, default)
Namespace types: Candle
Parameters:
this (Candle)
default (Candle)
method nz(this, default)
Namespace types: LabelArgs
Parameters:
this (LabelArgs)
default (LabelArgs)
method nz(this, default)
Namespace types: Label
Parameters:
this (Label)
default (Label)
method nz(this, default)
Namespace types: LineArgs
Parameters:
this (LineArgs)
default (LineArgs)
method nz(this, default)
Namespace types: Line
Parameters:
this (Line)
default (Line)
method nz(this, default)
Namespace types: PolyLineArgs
Parameters:
this (PolyLineArgs)
default (PolyLineArgs)
method nz(this, default)
Namespace types: PolyLine
Parameters:
this (PolyLine)
default (PolyLine)
method nz(this, default)
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
default (CenterLabel)
method nz(this, default)
Namespace types: LineFill
Parameters:
this (LineFill)
default (LineFill)
method nz(this, default)
Namespace types: BoxArgs
Parameters:
this (BoxArgs)
default (BoxArgs)
method nz(this, default)
Namespace types: BoxTextArgs
Parameters:
this (BoxTextArgs)
default (BoxTextArgs)
method nz(this, default)
Namespace types: Box
Parameters:
this (Box)
default (Box)
create_line(start_time, start_idx, start_price, end_time, end_idx, end_price)
Parameters:
start_time (int)
start_idx (int)
start_price (float)
end_time (int)
end_idx (int)
end_price (float)
create_line(x1, y1, x2, y2, xloc)
Parameters:
x1 (int)
y1 (float)
x2 (int)
y2 (float)
xloc (string)
create_line()
create_box(left_time, left_idx, top, right_time, right_idx, bottom, txt)
Parameters:
left_time (int)
left_idx (int)
top (float)
right_time (int)
right_idx (int)
bottom (float)
txt (string)
create_box(left, top, right, bottom, xloc, txt)
Parameters:
left (int)
top (float)
right (int)
bottom (float)
xloc (string)
txt (string)
create_box(txt)
Parameters:
txt (string)
method create_fill(this, other, fill_color, flip)
Creates a new LineFill object.
@field this The first Line object
@field other The second Line object
@field fill_color The color used to fill the space between the lines.
@field flip Optional if true, a new support line is created, drawn over other but with flipped start and end point
Namespace types: Line
Parameters:
this (Line)
other (Line)
fill_color (color)
flip (bool)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Candle)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (chart.point)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Label)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (CenterLabel)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Line)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (LineFill)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (PolyLine)
max (int)
method update(this, bar_time, bar_time_close, bar_idx, o, h, l, c, v)
Updates a Candle object with new data.
Namespace types: Candle
Parameters:
this (Candle)
bar_time (int)
bar_time_close (int)
bar_idx (int)
o (float)
h (float)
l (float)
c (float)
v (float)
method update(this, bar_time, bar_idx, price)
Updates a chart.point object with new data.
Namespace types: chart.point
Parameters:
this (chart.point)
bar_time (int)
bar_idx (int)
price (float)
Returns: true if changed, false otherwise
method update(this, x, price, xloc)
Updates a chart.point object with new data.
Namespace types: chart.point
Parameters:
this (chart.point)
x (int)
price (float)
xloc (string)
Returns: true if changed, false otherwise
method update(this, update)
Updates a chart.point object with new data from another chart.point.
Namespace types: chart.point
Parameters:
this (chart.point)
update (chart.point)
Returns: true if changed, false otherwise
method update(this, bar_time, bar_idx, price, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: Label
Parameters:
this (Label)
bar_time (int)
bar_idx (int)
price (float)
txt (string)
tooltip (string)
method update(this, point, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: Label
Parameters:
this (Label)
point (chart.point)
txt (string)
tooltip (string)
method update(this, points, txt, tooltip, condition)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
points (array)
txt (string)
tooltip (string)
condition (bool)
method update(this, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
txt (string)
tooltip (string)
method update(this, start, end)
Updates this Line's chart.point objects with new data from other chart.points.
Namespace types: Line
Parameters:
this (Line)
start (chart.point)
end (chart.point)
method update(this, points)
Updates this PolyLine's chart.point objects with new data from other chart.points. As the plot polyline has no options to be updated, it will be deleted before being redrawn in draw()
Namespace types: PolyLine
Parameters:
this (PolyLine)
points (array)
method update(this, left_top, right_bottom)
Updates a Box's chart.point objects with new data from other chart.points.
Namespace types: Box
Parameters:
this (Box)
left_top (chart.point)
right_bottom (chart.point)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Line
Parameters:
this (Line)
method delete(this)
Removes an objects representation from the chart.
Namespace types: PolyLine
Parameters:
this (PolyLine)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Label
Parameters:
this (Label)
method delete(this)
Removes an objects representation from the chart.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Box
Parameters:
this (Box)
method delete(this)
Removes an objects representation from the chart.
Namespace types: LineFill
Parameters:
this (LineFill)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method draw(this, a, b, args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: series line
Parameters:
this (line)
a (chart.point)
b (chart.point)
args (LineArgs)
extend_only (bool) : this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates and text).
Namespace types: Label
Parameters:
this (Label)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates and text).
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: Line
Parameters:
this (Line)
args (LineArgs)
extend_only (bool) : this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart.
Namespace types: PolyLine
Parameters:
this (PolyLine)
args (PolyLineArgs)
force_overlay (simple bool)
method draw(this, args, text_args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: Box
Parameters:
this (Box)
args (BoxArgs)
text_args (BoxTextArgs)
extend_only (bool) : this will omit redrawing the left side of the box, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, flip_support_args, force_overlay)
Adds/Replaces the representations of the object on the chart.
Namespace types: LineFill
Parameters:
this (LineFill)
flip_support_args (LineArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (PolyLineArgs)
force_overlay (simple bool)
method draw(this, args, extend_only, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LineArgs)
extend_only (bool)
force_overlay (simple bool)
method draw(this, flip_support_args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
flip_support_args (LineArgs)
force_overlay (simple bool)
method draw(this, args, txt_args, extend_only, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (BoxArgs)
txt_args (BoxTextArgs)
extend_only (bool)
force_overlay (simple bool)
method hide(this)
Namespace types: series label
Parameters:
this (label)
method hide(this)
Namespace types: series line
Parameters:
this (line)
method hide(this)
Namespace types: series polyline, series polyline, series polyline, series polyline
Parameters:
this (polyline)
method hide(this)
Namespace types: series box
Parameters:
this (box)
method hide(this)
Namespace types: chart.point
Parameters:
this (chart.point)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Label
Parameters:
this (Label)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Line
Parameters:
this (Line)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: PolyLine
Parameters:
this (PolyLine)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Box
Parameters:
this (Box)
method apply_style(this, args)
Namespace types: series line
Parameters:
this (line)
args (LineArgs)
method apply_style(this, args)
Namespace types: series label
Parameters:
this (label)
args (LabelArgs)
method apply_style(this, args, text_args)
Namespace types: series box
Parameters:
this (box)
args (BoxArgs)
text_args (BoxTextArgs)
method apply_style(this, args)
updates styles on this objects plot
Namespace types: Label
Parameters:
this (Label)
args (LabelArgs)
method apply_style(this, args)
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
args (LabelArgs)
method apply_style(this, args)
Namespace types: Line
Parameters:
this (Line)
args (LineArgs)
method apply_style(this, args, text_args)
updates styles on this objects plot
Namespace types: Box
Parameters:
this (Box)
args (BoxArgs)
text_args (BoxTextArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LineArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LineArgs)
method apply_style(this, args, text_args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (BoxArgs)
text_args (BoxTextArgs)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Label
Parameters:
this (Label)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Line
Parameters:
this (Line)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Box
Parameters:
this (Box)
method deep_copy(this, copy_references)
clones the whole object including points and plots
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
copy_references (bool)
method deep_copy(this, copy_references)
clones the whole object including points and plots
Namespace types: LineFill
Parameters:
this (LineFill)
copy_references (bool)
Candle
Fields:
bar_time (series int)
bar_time_close (series int)
bar_idx (series int)
o (series float)
h (series float)
l (series float)
c (series float)
v (series float)
LabelArgs
Fields:
text_color (series color) : Text color.
bg_color (series color) : Color of the label border and arrow.
text_font_family (series string) : The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
xloc (series string) : See description of x argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
yloc (series string) : Possible values are yloc.price, yloc.abovebar, yloc.belowbar. If yloc=yloc.price, y argument specifies the price of the label position. If yloc=yloc.abovebar, label is located above bar. If yloc=yloc.belowbar, label is located below bar. Default is yloc.price.
style (series string) : Label style. Possible values: label.style_none, label.style_xcross, label.style_cross, label.style_triangleup, label.style_triangledown, label.style_flag, label.style_circle, label.style_arrowup, label.style_arrowdown, label.style_label_up, label.style_label_down, label.style_label_left, label.style_label_right, label.style_label_lower_left, label.style_label_lower_right, label.style_label_upper_left, label.style_label_upper_right, label.style_label_center, label.style_square, label.style_diamond, label.style_text_outline. Default is label.style_label_down.
size (series string) : Label size. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default value is size.normal.
text_align (series string) : Label text alignment. Possible values: text.align_left, text.align_center, text.align_right. Default value is text.align_center.
Label
Fields:
point (chart.point) : The Label coordinates
txt (series string) : Label text. Default is empty string.
tooltip (series string) : Hover to see tooltip label.
hidden (series bool)
plot (series label) : The label object to be added and plotted via draw()
LineArgs
Fields:
line_color (series color) : Line color.
style (series string) : Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
width (series int) : Line width in pixels.
xloc (series string) : Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
extend (series string) : f extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none.
Line
Fields:
start (chart.point) : starting point of the line
end (chart.point)
hidden (series bool)
plot (series line) : The line object to be added and plotted via draw()
LineFill
Fields:
a (Line) : The first Line object
b (Line) : The second Line object
fill_color (series color) : The color used to fill the space between the lines.
flip_support (Line) : An additional Line that holds a flipped b support line (linefills are always drawn between line starts and line ends)
plot (series linefill) : The linefill object to be added and plotted via draw()
PolyLineArgs
Fields:
line_color (series color) : The color of the line segments. Optional. The default is color.gray.
fill_color (series color) : The fill color of the polyline. Optional. The default is na.
style (series string) : The style of the polyline. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Optional. The default is line.style_solid.
width (series int) : The width of the line segments, expressed in pixels. Optional. The default is 1.
xloc (series string) : Determines the field of the chart.point objects in the points array that the polyline will use for its x-coordinates. If xloc.bar_index, the polyline will use the index field from each point. If xloc.bar_time, it will use the time field. Optional. The default is xloc.bar_index.
PolyLine
Fields:
points (array) : point array data of the polyline
curved (series bool) : Line color. If true, the drawing will connect all points from the points array using curved line segments. Optional. The default is false.
closed (series bool) : Line color. If true, the drawing will also connect the first point to the last point from the points array, resulting in a closed polyline. Optional. The default is false.
hidden (series bool)
plot (series polyline) : The polyline object to be added and plotted via draw()
CenterLabel
Fields:
center_label (Label) : The generated, centered Label
source_line (Line)
source_polyline (PolyLine)
BoxArgs
Fields:
border_color (series color) : Color of the four borders. Optional. The default is color.blue.
border_width (series int) : Width of the four borders, in pixels. Optional. The default is 1 pixel.
border_style (series string) : Style of the four borders. Possible values: line.style_solid, line.style_dotted, line.style_dashed. Optional. The default value is line.style_solid.
bg_color (series color) : Background color of the box. Optional. The default is color.blue.
xloc (series string) : Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc = xloc.bar_index, the arguments must be a bar index. If xloc = xloc.bar_time, the arguments must be a UNIX time. Possible values: xloc.bar_index and xloc.bar_time. Optional. The default is xloc.bar_index.
extend (series string) : When extend.none is used, the horizontal borders start at the left border and end at the right border. With extend.left or extend.right, the horizontal borders are extended indefinitely to the left or right of the box, respectively. With extend.both, the horizontal borders are extended on both sides. Optional. The default value is extend.none.
BoxTextArgs
Fields:
text_color (series color) : The color of the text. Optional. The default is color.black.
text_size (series string) : The size of the text. An optional parameter, the default value is size.auto. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge.
text_halign (series string) : The horizontal alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_left, text.align_center, text.align_right.
text_valign (series string) : The vertical alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_top, text.align_center, text.align_bottom.
text_wrap (series string) : Defines whether the text is presented in a single line, extending past the width of the box if necessary, or wrapped so every line is no wider than the box itself (and clipped by the bottom border of the box if the height of the resulting wrapped text is higher than the height of the box). Optional. The default value is text.wrap_none. Possible values: text.wrap_none, text.wrap_auto.
text_font_family (series string) : The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
Box
Fields:
left_top (chart.point) : top-left corner of the box
right_bottom (chart.point) : bottom-right corner of the box
txt (series string) : The text to be displayed inside the box. Optional. The default is empty string.
hidden (series bool)
plot (series box) : The box object to be added and plotted via draw()
PivotLabelsLibrary "PivotLabels"
drawPivots(qtyLabels, leftLegs, rightLegs)
Displays a label for each of the last `qtyLabels` pivots.
Colors high pivots in green, low pivots in red, and breached pivots in gray.
Parameters:
qtyLabels (int) : (simple int) Quantity of last labels to display.
leftLegs (int) : (simple int) Left pivot legs.
rightLegs (int) : (simple int) Right pivot legs.
Returns: Nothing.
FA_PA_LIBLibrary "FA_PA_LIB"
A collection of custom tools & utility functions commonly used for coding Dr Al Brooks, Price Action System with my scripts
getBodySize()
Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize()
Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getTopWickPercent()
Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: Percent of total candle width that is occupied by the upper wick
getBottomWickSize()
Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBottomWickPercent()
Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: Percent of total candle width that is occupied by the lower wick
getBarMidPoint()
Gets the current candle's midpoint wick to wick
Returns: The current candle's mid point
getBodyPercent()
Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage (00.00)
bullFib(priceLow, priceHigh, fibRatio)
Calculates a bullish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
bearFib(priceLow, priceHigh, fibRatio)
Calculates a bearish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
isBr()
Checks if the current bar is a Bear Bar
Returns: A boolean - true if the current bar is bear candle
isBl()
Checks if the current bar is a Bull Bar
Returns: A boolean - true if the current bar is Bull candle
isTrendBar()
Checks if the current bar is a Trend Bar. Candle that its body size is greater than 50% of entire candle size
Returns: A boolean - true if the current bar is Trend candle
isBlTrendBar()
Checks if the current bar is a Bull Trend Bar. Bullish candle that its body size is greater than 50% of entire candle size
Returns: A boolean - true if the current bar is Bull Trend candle
isBrTrendBar()
Checks if the current bar is a Bull Trend Bar. Bullish candle that its body size is greater than 50% of entire candle size
Returns: A boolean - true if the current bar is Bull Trend candle
isBlRevB()
Checks if the current bar is a Bull Reversal Bar. Bullish candle that closes on upper half of candle body
Returns: A boolean - true if the current bar is Bull Reversal candle
isBrRevB()
Checks if the current bar is a Bear Reversal Bar. BulBearish candle that closes on lower half of candle body
Returns: A boolean - true if the current bar is Bear Reversal candle
isDoji(wickSize, bodySize)
Checks if the current bar is a doji candle based on the given parameters
Parameters:
wickSize (float) : (default=2) The maximum top wick size compared to the bottom (and vice versa)
bodySize (float) : (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isHammer(fib, colorMatch)
Checks if the current bar is a hammer candle based on the given parameters
Parameters:
fib (float) : (default=0.382) The fib to base candle body on
colorMatch (bool) : (default=true) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(fib, colorMatch)
Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
fib (float) : (default=0.382) The fib to base candle body on
colorMatch (bool) : (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isBlOB()
Detects Bullish outside bars(OB)
Returns: Returns true if the current bar is a bull outside bar
isBrOB()
Detects Bearish outside bars(OB)
Returns: Returns true if the current bar is a bear outside bar
bollingerBandsV2Library "bollingerBandsV2"
Bollinger bands related functions
get_multiple_bollinger_bands(stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, length, source)
: Calculates 7 sets of bollinger bands, with 7 different standard deviations
Parameters:
stdv1 (float) : (simple int): standard deviation 1
stdv2 (float) : (simple int): standard deviation 2
stdv3 (float) : (simple int): standard deviation 3
stdv4 (float) : (simple int): standard deviation 4
stdv5 (float) : (simple int): standard deviation 5
stdv6 (float) : (simple int): standard deviation 6
stdv7 (float) : (simple int): standard deviation 7
length (simple int) : (simple int): Length for the bands
source (float) : (simple float): source for the calculation
Returns: : Returns 8 levels plus the range of all the levels.
get_bb_volatility(bb_highest, bb_lowest, ma_length, lookback)
: Provides a volatility indicator based on Bollinger Bands, and indicates wheather the volatility is increasing or decreasing.
Parameters:
bb_highest (float) : (simple float): Top Bollinger Band on which to calculate the range.
bb_lowest (float) : (simple float): Bottom Bollinger Band on which to calculate the range.
ma_length (simple int) : (simple int): Length to use in the smoothing of Bollinger Bands range.
lookback (int) : (simple int): Lookback period to identify a change in the Bollinger Bands range.
Returns: : Returns 8 levels plus the range of all the levels.
get_bbVolatility_data(source, length, stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, trend_direction)
: Generates Bollinger Bands Volatility
Parameters:
source (float) : (float): Source for Bollinger Bands
length (simple int) : (int): Length for Bollinger Bands
stdv1 (int) : (int): Standard Deviation 1
stdv2 (int) : (int): Standard Deviation 2
stdv3 (int) : (int): Standard Deviation 3
stdv4 (int) : (int): Standard Deviation 4
stdv5 (int) : (int): Standard Deviation 5
stdv6 (int) : (int): Standard Deviation 6
stdv7 (int) : (int): Standard Deviation 7
trend_direction (string) : (string): Current direction of the trend
Returns: : Returns a map with the levels, plus direction flag and the data table
ZigZag█ Overview
This Pine Script™ library provides a comprehensive implementation of the ZigZag indicator using advanced object-oriented programming techniques. It serves as a developer resource rather than a standalone indicator, enabling Pine Script™ programmers to incorporate sophisticated ZigZag calculations into their own scripts.
Pine Script™ libraries contain reusable code that can be imported into indicators, strategies, and other libraries. For more information, consult the Libraries section of the Pine Script™ User Manual.
█ About the Original
This library is based on TradingView's official ZigZag implementation .
The original code provides a solid foundation with user-defined types and methods for calculating ZigZag pivot points.
█ What is ZigZag?
The ZigZag indicator filters out minor price movements to highlight significant market trends.
It works by:
1. Identifying significant pivot points (local highs and lows)
2. Connecting these points with straight lines
3. Ignoring smaller price movements that fall below a specified threshold
Traders typically use ZigZag for:
- Trend confirmation
- Identifying support and resistance levels
- Pattern recognition (such as Elliott Waves)
- Filtering out market noise
The algorithm identifies pivot points by analyzing price action over a specified number of bars, then only changes direction when price movement exceeds a user-defined percentage threshold.
█ My Enhancements
This modified version extends the original library with several key improvements:
1. Support and Resistance Visualization
- Adds horizontal lines at pivot points
- Customizable line length (offset from pivot)
- Adjustable line width and color
- Option to extend lines to the right edge of the chart
2. Support and Resistance Zones
- Creates semi-transparent zone areas around pivot points
- Customizable width for better visibility of important price levels
- Separate colors for support (lows) and resistance (highs)
- Visual representation of price areas rather than just single lines
3. Zig Zag Lines
- Separate colors for upward and downward ZigZag movements
- Visually distinguishes between bullish and bearish price swings
- Customizable colors for text
- Width customization
4. Enhanced Settings Structure
- Added new fields to the Settings type to support the additional features
- Extended Pivot type with supportResistance and supportResistanceZone fields
- Comprehensive configuration options for visual elements
These enhancements make the ZigZag more useful for technical analysis by clearly highlighting support/resistance levels and zones, and providing clearer visual cues about market direction.
█ Technical Implementation
This library leverages Pine Script™'s user-defined types (UDTs) to create a robust object-oriented architecture:
- Settings : Stores configuration parameters for calculation and display
- Pivot : Represents pivot points with their visual elements and properties
- ZigZag : Manages the overall state and behavior of the indicator
The implementation follows best practices from the Pine Script™ User Manual's Style Guide and uses advanced language features like methods and object references. These UDTs represent Pine Script™'s most advanced feature set, enabling sophisticated data structures and improved code organization.
For newcomers to Pine Script™, it's recommended to understand the language fundamentals before working with the UDT implementation in this library.
█ Usage Example
//@version=6
indicator("ZigZag Example", overlay = true, shorttitle = 'ZZA', max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
import andre_007/ZigZag/1 as ZIG
var group_1 = "ZigZag Settings"
//@variable Draw Zig Zag on the chart.
bool showZigZag = input.bool(true, "Show Zig-Zag Lines", group = group_1, tooltip = "If checked, the Zig Zag will be drawn on the chart.", inline = "1")
// @variable The deviation percentage from the last local high or low required to form a new Zig Zag point.
float deviationInput = input.float(5.0, "Deviation (%)", minval = 0.00001, maxval = 100.0,
tooltip = "The minimum percentage deviation from a previous pivot point required to change the Zig Zag's direction.", group = group_1, inline = "2")
// @variable The number of bars required for pivot detection.
int depthInput = input.int(10, "Depth", minval = 1, tooltip = "The number of bars required for pivot point detection.", group = group_1, inline = "3")
// @variable registerPivot (series bool) Optional. If `true`, the function compares a detected pivot
// point's coordinates to the latest `Pivot` object's `end` chart point, then
// updates the latest `Pivot` instance or adds a new instance to the `ZigZag`
// object's `pivots` array. If `false`, it does not modify the `ZigZag` object's
// data. The default is `true`.
bool allowZigZagOnOneBarInput = input.bool(true, "Allow Zig Zag on One Bar", tooltip = "If checked, the Zig Zag calculation can register a pivot high and pivot low on the same bar.",
group = group_1, inline = "allowZigZagOnOneBar")
var group_2 = "Display Settings"
// @variable The color of the Zig Zag's lines (up).
color lineColorUpInput = input.color(color.green, "Line Colors for Up/Down", group = group_2, inline = "4")
// @variable The color of the Zig Zag's lines (down).
color lineColorDownInput = input.color(color.red, "", group = group_2, inline = "4",
tooltip = "The color of the Zig Zag's lines")
// @variable The width of the Zig Zag's lines.
int lineWidthInput = input.int(1, "Line Width", minval = 1, tooltip = "The width of the Zig Zag's lines.", group = group_2, inline = "w")
// @variable If `true`, the Zig Zag will also display a line connecting the last known pivot to the current `close`.
bool extendInput = input.bool(true, "Extend to Last Bar", tooltip = "If checked, the last pivot will be connected to the current close.",
group = group_1, inline = "5")
// @variable If `true`, the pivot labels will display their price values.
bool showPriceInput = input.bool(true, "Display Reversal Price",
tooltip = "If checked, the pivot labels will display their price values.", group = group_2, inline = "6")
// @variable If `true`, each pivot label will display the volume accumulated since the previous pivot.
bool showVolInput = input.bool(true, "Display Cumulative Volume",
tooltip = "If checked, the pivot labels will display the volume accumulated since the previous pivot.", group = group_2, inline = "7")
// @variable If `true`, each pivot label will display the change in price from the previous pivot.
bool showChgInput = input.bool(true, "Display Reversal Price Change",
tooltip = "If checked, the pivot labels will display the change in price from the previous pivot.", group = group_2, inline = "8")
// @variable Controls whether the labels show price changes as raw values or percentages when `showChgInput` is `true`.
string priceDiffInput = input.string("Absolute", "", options = ,
tooltip = "Controls whether the labels show price changes as raw values or percentages when 'Display Reversal Price Change' is checked.",
group = group_2, inline = "8")
// @variable If `true`, the Zig Zag will display support and resistance lines.
bool showSupportResistanceInput = input.bool(true, "Show Support/Resistance Lines",
tooltip = "If checked, the Zig Zag will display support and resistance lines.", group = group_2, inline = "9")
// @variable The number of bars to extend the support and resistance lines from the last pivot point.
int supportResistanceOffsetInput = input.int(50, "Support/Resistance Offset", minval = 0,
tooltip = "The number of bars to extend the support and resistance lines from the last pivot point.", group = group_2, inline = "10")
// @variable The width of the support and resistance lines.
int supportResistanceWidthInput = input.int(1, "Support/Resistance Width", minval = 1,
tooltip = "The width of the support and resistance lines.", group = group_2, inline = "11")
// @variable The color of the support lines.
color supportColorInput = input.color(color.red, "Support/Resistance Color", group = group_2, inline = "12")
// @variable The color of the resistance lines.
color resistanceColorInput = input.color(color.green, "", group = group_2, inline = "12",
tooltip = "The color of the support/resistance lines.")
// @variable If `true`, the support and resistance lines will be drawn as zones.
bool showSupportResistanceZoneInput = input.bool(true, "Show Support/Resistance Zones",
tooltip = "If checked, the support and resistance lines will be drawn as zones.", group = group_2, inline = "12-1")
// @variable The color of the support zones.
color supportZoneColorInput = input.color(color.new(color.red, 70), "Support Zone Color", group = group_2, inline = "12-2")
// @variable The color of the resistance zones.
color resistanceZoneColorInput = input.color(color.new(color.green, 70), "", group = group_2, inline = "12-2",
tooltip = "The color of the support/resistance zones.")
// @variable The width of the support and resistance zones.
int supportResistanceZoneWidthInput = input.int(10, "Support/Resistance Zone Width", minval = 1,
tooltip = "The width of the support and resistance zones.", group = group_2, inline = "12-3")
// @variable If `true`, the support and resistance lines will extend to the right of the chart.
bool supportResistanceExtendInput = input.bool(false, "Extend to Right",
tooltip = "If checked, the lines will extend to the right of the chart.", group = group_2, inline = "13")
// @variable References a `Settings` instance that defines the `ZigZag` object's calculation and display properties.
var ZIG.Settings settings =
ZIG.Settings.new(
devThreshold = deviationInput,
depth = depthInput,
lineColorUp = lineColorUpInput,
lineColorDown = lineColorDownInput,
textUpColor = lineColorUpInput,
textDownColor = lineColorDownInput,
lineWidth = lineWidthInput,
extendLast = extendInput,
displayReversalPrice = showPriceInput,
displayCumulativeVolume = showVolInput,
displayReversalPriceChange = showChgInput,
differencePriceMode = priceDiffInput,
draw = showZigZag,
allowZigZagOnOneBar = allowZigZagOnOneBarInput,
drawSupportResistance = showSupportResistanceInput,
supportResistanceOffset = supportResistanceOffsetInput,
supportResistanceWidth = supportResistanceWidthInput,
supportColor = supportColorInput,
resistanceColor = resistanceColorInput,
supportResistanceExtend = supportResistanceExtendInput,
supportResistanceZoneWidth = supportResistanceZoneWidthInput,
drawSupportResistanceZone = showSupportResistanceZoneInput,
supportZoneColor = supportZoneColorInput,
resistanceZoneColor = resistanceZoneColorInput
)
// @variable References a `ZigZag` object created using the `settings`.
var ZIG.ZigZag zigZag = ZIG.newInstance(settings)
// Update the `zigZag` on every bar.
zigZag.update()
//#endregion
The example code demonstrates how to create a ZigZag indicator with customizable settings. It:
1. Creates a Settings object with user-defined parameters
2. Instantiates a ZigZag object using these settings
3. Updates the ZigZag on each bar to detect new pivot points
4. Automatically draws lines and labels when pivots are detected
This approach provides maximum flexibility while maintaining readability and ease of use.
vidya_calculateLibrary "vidya_calculate"
:
Calculates the Variable Index Dynamic Average (VIDYA).
Computes the VIDYA, which adjusts the degree of smoothing based on the strength of price momentum (absolute value of CMO),
and then returns the 15-period(variable) Simple Moving Average (SMA) of that VIDYA.
VIDYA tends to follow prices more closely when price fluctuations are large, and is smoothed more when fluctuations are small.
CMO = Chande Momentum Oscillator.
vidya(src, vidyaLength, vidyaMomentum, vidyaTrendPeriod)
: Calculates the Variable Index Dynamic Average (VIDYA)
Parameters:
src (float) : : Source
vidyaLength (int) : : VIDYA Length
vidyaMomentum (int) : : VIDYA Momentum
vidyaTrendPeriod (int) : : VIDYA Trend Period (Display)
Returns: : the 15-period(variable) Simple Moving Average (SMA) of that VIDYA
ChartPatternSetupsLibrary "ChartPatternSetups"
detectSymmetricalTriangle(lookback)
Detects a Symmetrical Triangle (Bullish or Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isBullish, isBearish, entry, sl, tp).
detectAscendingTriangle(lookback)
Detects an Ascending Triangle (Bullish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectDescendingTriangle(lookback)
Detects a Descending Triangle (Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectFallingWedge(lookback)
Detects a Falling Wedge (Bullish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
detectRisingWedge(lookback)
Detects a Rising Wedge (Bearish) and provides trade levels.
Parameters:
lookback (int) : Number of bars to look back for pivots.
Returns: Tuple of (isDetected, entry, sl, tp).
SCoLibraryAmsterdamLibrary "SCoLibraryAmsterdam"
This library contains functions to check Amsterdam strategy price events
calcTrendMom(FilterTrendWithMa50, FilterTrendWithMa200)
This function define the current trend and momentum force according to 4wma, 12wma, 21ema and 200sma
Parameters:
FilterTrendWithMa50 (bool) : is set to true will filter trend result with 50sma
FilterTrendWithMa200 (bool) : is set to true will filter trend result with 200sma
Returns: Return a positive value if trend is up (2 : strong momentum, 1 : weak momentum) and a negative value if trend is negative (-2 : strong momentum, -1 : weak momentum)
calcPriceAmstNodeMa01(close, AtrPeriod, AtrMultiplier)
This function checks if close, 4wma and 12wma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceAmstNodeMa123(close, AtrPeriod, AtrMultiplier)
This function checks if close, 12wma, 21ema and 50sma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceInsidebar()
This function checks inside bar candle configuration
Returns: true or false
calcPrice12wmaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 12wma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice21emaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 21ema by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice50smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 50sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice200smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 200sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPriceClimax(close, AtrPeriod, MovingAvgAtrMulti, VolAtrMulti)
This function checks if price is in climax evolution by comparing the extension between 4wma and 12wma, and a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the average true range period
MovingAvgAtrMulti (float) : is the extension ratio
VolAtrMulti (float) : is the volume extension relative to the 21sma volume
Returns: Return true or false
LinearRegressionLibrary "LinearRegression"
Calculates a variety of linear regression and deviation types, with optional emphasis weighting. Additionally, multiple of slope and Pearson’s R calculations.
calcSlope(_src, _len, _condition)
Calculates the slope of a linear regression over the specified length.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period for the linear regression.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The slope of the linear regression.
calcReg(_src, _len, _condition)
Calculates a basic linear regression, returning y1, y2, slope, and average.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) An array of 4 values: .
calcRegStandard(_src, _len, _emphasis, _condition)
Calculates an Standard linear regression with optional emphasis.
Parameters:
_src (float) : (series float) The source data series.
_len (int) : (int) The length of the lookback period.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegRidge(_src, _len, lambda, _emphasis, _condition)
Calculates a ridge regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda (float) : (float) The ridge regularization parameter.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegLasso(_src, _len, lambda, _emphasis, _condition)
Calculates a Lasso regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda (float) : (float) The Lasso regularization parameter.
_emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcElasticNetLinReg(_src, _len, lambda1, lambda2, _emphasis, _condition)
Calculates an Elastic Net regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
lambda1 (float) : (float) L1 regularization parameter (Lasso).
lambda2 (float) : (float) L2 regularization parameter (Ridge).
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegHuber(_src, _len, delta, iterations, _emphasis, _condition)
Calculates a Huber regression using Iteratively Reweighted Least Squares (IRLS).
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
delta (float) : (float) Huber threshold parameter.
iterations (int) : (int) Number of IRLS iterations.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegLAD(_src, _len, iterations, _emphasis, _condition)
Calculates a Least Absolute Deviations (LAD) regression via IRLS.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
iterations (int) : (int) Number of IRLS iterations for LAD.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRegBayesian(_src, _len, priorMean, priorSpan, sigma, _emphasis, _condition)
Calculates a Bayesian linear regression with optional emphasis.
Parameters:
_src (float) : (float) The source data series.
_len (int) : (int) The length of the lookback period.
priorMean (float) : (float) The prior mean for the slope.
priorSpan (float) : (float) The prior variance (or span) for the slope.
sigma (float) : (float) The assumed standard deviation of residuals.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: (float ) .
calcRFromLinReg(_src, _len, _slope, _average, _y1, _condition)
Calculates the Pearson correlation coefficient (R) based on linear regression parameters.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_average (float) : (float) The average value of the source data series.
_y1 (float) : (float) The starting point (y-intercept of the oldest bar) for the linear regression.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The Pearson correlation coefficient (R) adjusted for the direction of the slope.
calcRFromSource(_src, _len, _condition)
Calculates the correlation coefficient (R) using a specified length and source data.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
Returns: (float) The correlation coefficient (R).
calcSlopeLengthZero(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is flattest (closest to zero).
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length to consider (minimum of 2).
_minLen (int) : (int) The minimum length to start from (cannot exceed the max length).
_step (int) : (int) The increment step for lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is flattest.
calcSlopeLengthHighest(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is highest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is highest.
calcSlopeLengthLowest(_src, _len, _minLen, _step, _condition)
Identifies the length at which the slope is lowest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the slope is lowest.
calcSlopeLengthAbsolute(_src, _len, _minLen, _step, _condition)
Identifies the length at which the absolute slope value is highest.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length at which the absolute slope value is highest.
calcRLengthZero(_src, _len, _minLen, _step, _condition)
Identifies the length with the lowest absolute R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the lowest absolute R value.
calcRLengthHighest(_src, _len, _minLen, _step, _condition)
Identifies the length with the highest R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the highest R value.
calcRLengthLowest(_src, _len, _minLen, _step, _condition)
Identifies the length with the lowest R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the lowest R value.
calcRLengthAbsolute(_src, _len, _minLen, _step, _condition)
Identifies the length with the highest absolute R value.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The maximum lookback length (minimum of 2).
_minLen (int) : (int) The minimum length to start from.
_step (int) : (int) The step for incrementing lengths.
_condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
Returns: (int) The length with the highest absolute R value.
calcDevReverse(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the regressive linear deviation in reverse order, with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevForward(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the progressive linear deviation in forward order (oldest to most recent bar), with optional emphasis.
Parameters:
_src (float) : (float) The source data array, where _src is oldest and _src is most recent.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept of the linear regression (value at the most recent bar, adjusted by slope).
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevBalanced(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the balanced linear deviation with optional emphasis on recent or older data.
Parameters:
_src (float) : (float) Source data array, where _src is the most recent and _src is the oldest.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept of the linear regression (value at the oldest bar).
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevMean(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the mean absolute deviation from a forward-applied linear trend (oldest to most recent), with optional emphasis.
Parameters:
_src (float) : (float) The source data array, where _src is the most recent and _src is the oldest.
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevMedian(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates the median absolute deviation with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data array (index 0 = oldest, index _len - 1 = most recent).
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns:
calcDevPercent(_y1, _inputDev, _condition)
Calculates the percent deviation from a given value and a specified percentage.
Parameters:
_y1 (float) : (float) The base value from which to calculate deviation.
_inputDev (float) : (float) The deviation percentage.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevFitted(_len, _slope, _y1, _emphasis, _condition)
Calculates the weighted fitted deviation based on high and low series data, showing max deviation, with optional emphasis.
Parameters:
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcDevATR(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
Calculates an ATR-style deviation with optional emphasis on recent data.
Parameters:
_src (float) : (float) The source data (typically close).
_len (int) : (int) The length of the lookback period.
_slope (float) : (float) The slope of the linear regression.
_y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
_inputDev (float) : (float) The input deviation multiplier.
_emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
_condition (bool) : (bool) Flag to enable calculation (true = calculate).
Returns: A 2-element tuple: .
calcPricePositionPercent(_top, _bot, _src)
Calculates the percent position of a price within a linear regression channel. Top=100%, Bottom=0%.
Parameters:
_top (float) : (float) The top (positive) deviation, corresponding to 100%.
_bot (float) : (float) The bottom (negative) deviation, corresponding to 0%.
_src (float) : (float) The source price.
Returns: (float) The percent position within the channel.
plotLinReg(_len, _y1, _y2, _slope, _devTop, _devBot, _scaleTypeLog, _lineWidth, _extendLines, _channelStyle, _colorFill, _colUpLine, _colDnLine, _colUpFill, _colDnFill)
Plots the linear regression line and its deviations, with configurable styles and fill.
Parameters:
_len (int) : (int) The lookback period for the linear regression.
_y1 (float) : (float) The starting y-value of the regression line.
_y2 (float) : (float) The ending y-value of the regression line.
_slope (float) : (float) The slope of the regression line (used to determine line color).
_devTop (float) : (float) The top deviation to add to the line.
_devBot (float) : (float) The bottom deviation to subtract from the line.
_scaleTypeLog (bool) : (bool) Use a log scale if true; otherwise, linear scale.
_lineWidth (int) : (int) The width of the plotted lines.
_extendLines (string) : (string) How lines should extend (none, left, right, both).
_channelStyle (string) : (string) The style of the channel lines (solid, dashed, dotted).
_colorFill (bool) : (bool) Whether to fill the space between the top and bottom deviation lines.
_colUpLine (color) : (color) Line color when slope is positive.
_colDnLine (color) : (color) Line color when slope is negative.
_colUpFill (color) : (color) Fill color when slope is positive.
_colDnFill (color) : (color) Fill color when slope is negative.