fork_libsmc
Library "fork_libsmc"
this is fork of robbatt's lib_smc
description:
This is an adaptation of LuxAlgo's Smart Money Concepts indicator with numerous changes.
Main changes include integration of object based plotting, plenty of performance improvements, live tracking of Order Blocks, integration of volume profiles to refine Order Blocks, and many more.This is a library for developers,
////////////////////////////////////////////////////////////
fork_libsmc
v1 - support show price level: swing point, market structure, broken OrderBlock ( using profile.show_price_levels )
Indikatoren und Strategien
suntimelibLibrary "suntimelib"
calculate_sunrise_time_trig(latitude, longitude, day, mon, yr, is_sunset)
Parameters:
latitude (float)
longitude (float)
day (int)
mon (int)
yr (int)
is_sunset (bool)
calculate_sunrise_time(cityId, _year, _month, _dayofmonth, lat, lon)
Parameters:
cityId (string)
_year (int)
_month (int)
_dayofmonth (int)
lat (float)
lon (float)
sunArray
Fields:
cityId (series string)
year (series int)
month (series int)
dates (array)
cityArray
Fields:
cityId (series string)
sunArrays (array)
PineVersatilitiesBundleLibrary "PineVersatilitiesBundle"
Versatilities (aka, Versatile Utilities) Pack includes:
- Eighteen Price Variants bundled in a Map,
- Nine Smoothing Variants bundled in a Map,
- Visualisations that indicate on both - pane and chart.
price_variants(lb)
Computes Several different averages using current and previous OHLC values
Parameters:
lb (int) : - lookback distance for combining OHLC values from the past with the present
Returns: Map of Eighteen Uncommon Combinations of single and two-bar OHLC averages (rounded-to-mintick)
dynamic_MA(masrc, malen, lsmaoff, almasgm, almaoff, almaflr)
Dynamically computes Eight different MAs and returns a Map containing Nine MAs
Parameters:
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: Map of MAs - 'ALMA', 'EMA', 'HMA', 'LSMA', 'RMA', 'SMA', 'SWMA', 'WMA', 'ALL' (rounded-to-mintick)
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
Volatility_ZigZag_LibraryLibrary "Volatility_ZigZag_Library"
getValues_andStyling_VolatilityZigZag_byBrettkind(hl_src, SOURCE, length, min_dev_input, pvt_length, stdev_fctr, ZigZag, zz_color, zz_width, zz_devline, zz_points, zz_alert_sign, ZZ_Label, ZZ_Label_clr, rev_text, zz_bars_text, pcabs_text, avg_pcabs_text, pcrel_text, avg_pcrel_text, vol_text, avg_vol_text, text_size, input_currency)
Parameters:
hl_src (bool)
SOURCE (float)
length (int)
min_dev_input (float)
pvt_length (int)
stdev_fctr (float)
ZigZag (bool)
zz_color (color)
zz_width (int)
zz_devline (bool)
zz_points (bool)
zz_alert_sign (bool)
ZZ_Label (bool)
ZZ_Label_clr (color)
rev_text (bool)
zz_bars_text (bool)
pcabs_text (bool)
avg_pcabs_text (bool)
pcrel_text (bool)
avg_pcrel_text (bool)
vol_text (bool)
avg_vol_text (bool)
text_size (string)
input_currency (string)
getStatisticTable_VolatilityZigZag_byBrettkind(x1, Y1_array, number_of_bars_array, draw_tbl)
Parameters:
x1 (int)
Y1_array (array)
number_of_bars_array (array)
draw_tbl (bool)
MyReusableFunctionsLibrary "MyReusableFunctions"
Library of trend direction functions using pivot points
CurrentSymbolTrendDirection(pivotPeriod)
Parameters:
pivotPeriod (int) : The period to use for pivot point detection
Returns: String direction ("up"/"down"), integer direction (1/-1), and previous pivot high/low values
OtherSymbolSmallTrendDirection(symbol, timeframe)
Parameters:
symbol (string) : The symbol to analyze
timeframe (string) : The timeframe to use
Returns: String direction ("up"/"down"), integer direction (1/-1), and previous pivot high/low values
OtherSymbolLargeTrendDirection(symbol, timeframe)
Parameters:
symbol (string)
timeframe (string)
isInCustomTimeRange(startHour, startMinute, endHour, endMinute)
Parameters:
startHour (int) : Starting hour (0-23)
startMinute (int) : Starting minute (0-59)
endHour (int) : Ending hour (0-23)
endMinute (int) : Ending minute (0-59)
Returns: boolean True if current time is within the specified range
getTimeConditions()
TimeConditions
Fields:
isMarketHours (series bool)
isPreMarket (series bool)
isMarketOpen (series bool)
isMarketClose (series bool)
isLondonOpen (series bool)
isOvernightHours (series bool)
financial_history_utilsLibrary "financial_history_utils"
get_fq_value_n_quarters_ago(symbol, financial_id, n)
Parameters:
symbol (string)
financial_id (string)
n (int)
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)
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)
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
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
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.