CSVParser█ OVERVIEW
The library contains functions for parsing and importing complex CSV configurations (with a special simple syntax) into a special hierarchical object (of type objProps ) as follows:
Functions:
parseConfig() - reads CSV text into an objProps object.
toT() - displays the contents of an objProps object in a table form, which allows to check the CSV text for syntax errors.
getPropAr() - returns objProps.arS array for child object with `prop` key in mpObj map (or na if not found)
This library is handy in allowing users to store presets for the scripts and switch between them (see, e.g., my HTF moving averages script where users can switch between several preset configuations of 24 MA's across 5 timeframes).
█ HOW THE SCRIPT WORKS.
The script works as follows:
all values read from config text are stored as strings
Nested brackets in config text create a named nested objects of objProps0, ... , objProps9 types.
objProps objects of each level have the following fields:
- array arS for storing values without names (e.g. "12, 23" will be imported into a string array arS as )
- map mpS for storing items with names (e.g. "tf = 60, length = 21" will be imported as <"tf", "60"> and <"length", "21"> pairs into mpS )
- map mpObj for storing nested objects (e.g. "TF1(tf=60, length(21,50,100))" creates a <"TF1, objProps0 object> pair in mpObj map property of the top level object (objProps) , "tf=60" is stored as <"tf", "60"> key-value pair in mpS map property of a next level object (objProps0) and "length (...)" creates a <"length", objProps1> pair in objProps0.mpObj map while length values are stored in objProps1.arS array as strings. Every opening bracket creates a next level objProps object.
If objects or properties with duplicate names are encountered only the latest is imported
(e.g. for "TF1(length(12,22)), TF1(tf=240)" only "TF1(tf=240)" will be imported
Line breaks are not regarded as part of syntax (i.e. values are imported with line breaks, you can supply
symbols "(" , ")" , "," and "=" are special characters and cannot be used within property values (with the exception of a quoted text as a value of a property as explained below)
named properties can have quoted text as their value. In that case special characters within quotation marks are regarded as normal characters. Text between "=" and opening quotation mark as well as text following the closing quotation mark and until next property value is ignored. E.g. "quote = ignored "The quote" also ignored" will be imported as <"quote", "The quote">. Quotation marks within quotes must be excaped with "\" .
if a key names happens to be a multi-line then only first line containing non-space characters (trimmed from spaces) is taken as a key.
")," or ") ," and similar do not create an empty ("") array item while ",," does. (",)" creates an "" array item)
█ CSV CONFIGURATION SYNTAX
Unnamed values: just list them comma separated and they will be imported into arS of the object of the current level.
Named values: use "=" sign as follows: "property1=value1, property2 = value2"
Value of several objects: Use brackets after the name of the object ant list all object properties within the brackets (including its child objects if necessary). E.g. "TF1(tf =60, length(21,200), TF2(tf=240, length(50,200)"
Named and unnamed values as well as objects can go in any order. E.g. "12, tf=60, 21" will be imported as follows: "12", "21" will go to arS array and <"tf", "60"> will go to mpS maP of objProps (the top level object).
You can play around and test your config text using demo in this library, just edit your text in script settings and see how it is parsed into objProps objects.
█ USAGE RECOMMENDATIONS AND SAMPLE USE
I suggest the following approach:
- create functions for your UDT which can set properties by name.
- create enumerator functions which iterates through all the property names (supplied as a const string array) and imports their values into the object
█ SAMPLE USE
A sample use of this library can be seen in my Multi-timeframe 24 moving averages + BB+SAR+Supertrend+VWAP script where settings for the MAs across many timeframes are imported from CSV configurations (presets).
█ FULL LIST OF FUNCTIONS AND PROPERTIES
nzs(_s, nz)
Like nz() but for strings. Returns `nz` arg (default = "") if _s is na.
Parameters:
_s (string)
nz (string)
method init(this)
Initializes objProps obj (creates child maps and arrays)
Namespace types: objProps
Parameters:
this (objProps)
method toT(this, nz)
Outputs objProps to string matrices for further display using autotable().
Namespace types: objProps, objProps1, ..., objProps9
Parameters:
this (objProps/objProps1/..../objProps9)
nz (string)
Returns: A tuple - value, merge and color matrix (autotable() parameters)
method parseConfig(this, s)
Reads config text into objProps (unnamed values into arS, named into mpS, sub-levels into mpObj)
Namespace types: objProps
Parameters:
this (objProps)
s (string)
method getPropArS(this, prop)
Returns a string array of values for a given property name `prop`. Looks for a key `prop` in objProps.mpObj
if finds pair returns obj.arS, otherwise returns na. Returns a reference to the original, not a copy.
Namespace types: objProps, objProps1, ..., objProps8
Parameters:
this (objProps/objProps1/..../objProps8)
prop (string)
method getPropVal(this, prop, id)
Checks if there is an array of values for property `prop` and returns its `id`'s element or na if not found
Namespace types: objProps, objProps1, ..., objProps8
Parameters:
this (objProps/objProps1/..../objProps8) : objProps object containing array of property values in a child objProp object corresponding to propertty name.
prop (string) : (string) Name of the property
id (int) : (int) Id of the element to be returned from the array pf property values
objProps9 type
Object for storing values read from CSV relating to a particular object or property name.
Fields:
mpS (map) : (map() Stores property values as pairs
arS (array) : (string ) Array of values
objProps, objProps0, ... objProps8 types
Object for storing values read from CSV relating to a particular object or property name.
Fields:
mpS (map) : (map() Stores property values as pairs
arS (array) : (string ) Array of values
mpObj (map) : (map() Stores objProps objects containing properties's data as pairs
Wskaźniki i strategie
Autotable█ OVERVIEW
The library allows to automatically draw a table based on a string or float matrix (or both) controlling all of the parameters of the table (including merging cells) with parameter matrices (like, e.g. matrix of cell colors).
All things you would normally do with table.new() and table.cell() are now possible using respective parameters of library's main function, autotable() (as explained further below).
Headers can be supplied as arrays.
Merging of the cells is controlled with a special matrix of "L" and "U" values which instruct a cell to merged with the cell to the left or upwards (please see examples in the script and in this description).
█ USAGE EXAMPLES
The simplest and most straightforward:
mxF = matrix.new(3,3, 3.14)
mxF.autotable(bgcolor = color.rgb(249, 209, 29)) // displays float matrix as a table in the top right corner with defalult settings
mxS = matrix.new(3,3,"PI")
// displays string matrix as a table in the top right corner with defalult settings
mxS.autotable(Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// displays matrix displaying a string value over a float value in each cell
mxS.autotable(mxF, Ypos = "middle", Xpos = "center", bgcolor = color.gray, text_color = #86f62a)
Draws this:
Tables with headers:
if barstate.islast
mxF = matrix.new(3,3, 3.14)
mxS = matrix.new(3,3,"PI")
arColHeaders = array.from("Col1", "Col2", "Col3")
arRowHeaders = array.from("Row1", "Row2", "Row3")
// float matrix with col headers
mxF.autotable(
bgcolor = #fdfd6b
, arColHeaders = arColHeaders
)
// string matrix with row headers
mxS.autotable(arRowHeaders = arRowHeaders, Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// string/float matrix with both row and column headers
mxS.autotable(mxF
, Ypos = "middle", Xpos = "center"
, arRowHeaders = arRowHeaders
, arColHeaders = arColHeaders
, cornerBgClr = #707070, cornerTitle = "Corner cell", cornerTxtClr = #ffdc13
, bgcolor = color.gray, text_color = #86f62a
)
Draws this:
█ FUNCTIONS
One main function is autotable() which has only one required argument mxValS, a string matrix.
Please see below the description of all of the function parameters:
The table:
tbl (table) (Optional) If supplied, this table will be deleted.
The data:
mxValS (matrix ) (Required) Cell text values
mxValF (matrix) (Optional) Numerical part of cell text values. Is concatenated to the mxValS values via `string_float_separator` string (default " ")
Table properties, have same effect as in table.new() :
defaultBgColor (color) (Optional) bgcolor to be used if mxBgColor is not supplied
Ypos (string) (Optional) "top", "bottom" or "center"
Xpos (string) (Optional) "left", "right", or "center"
frame_color (color) (Optional) frame_color like in table.new()
frame_width (int) (Optional) frame_width like in table.new()
border_color (color) (Optional) border_color like in table.new()
border_width (int) (Optional) border_width like in table.new()
force_overlay (simple bool) (Optional) If true draws table on main pane.
Cell parameters, have same effect as in table.cell() ):
mxBgColor (matrix) (Optional) like bgcolor argument in table.cell()
mxTextColor (matrix) (Optional) like text_color argument in table.cell()
mxTt (matrix) (Optional) like tooltip argument in table.cell()
mxWidth (matrix) (Optional) like width argument in table.cell()
mxHeight (matrix) (Optional) like height argument in table.cell()
mxHalign (matrix) (Optional) like text_halign argument in table.cell()
mxValign (matrix) (Optional) like text_valign argument in table.cell()
mxTextSize (matrix) (Optional) like text_size argument in table.cell()
mxFontFamily (matrix) (Optional) like text_font_family argument in table.cell()
Other table properties:
tableWidth (float) (Optional) Overrides table width if cell widths are non zero. E.g. if there are four columns and cell widths are 20 (either as set via cellW or via mxWidth) then if tableWidth is set to e.g. 50 then cell widths will be 50 * (20 / 80), where 80 is 20*4 = total width of all cells. Works simialar for widths set via mxWidth - determines max sum of widths across all cloumns of mxWidth and adjusts cell widths proportionally to it. If cell widths are 0 (i.e. auto-adjust) tableWidth has no effect.
tableHeight (float) (Optional) Overrides table height if cell heights are non zero. E.g. if there are four rows and cell heights are 20 (either as set via cellH or via mxHeight) then if tableHeigh is set to e.g. 50 then cell heights will be 50 * (20 / 80), where 80 is 20*4 = total height of all cells. Works simialar for heights set via mxHeight - determines max sum of heights across all cloumns of mxHeight and adjusts cell heights proportionally to it. If cell heights are 0 (i.e. auto-adjust) tableHeight has no effect.
defaultTxtColor (color) (Optional) text_color to be used if mxTextColor is not supplied
text_size (string) (Optional) text_size to be used if mxTextSize is not supplied
font_family (string) (Optional) cell text_font_family value to be used if a value in mxFontFamily is no supplied
cellW (float) (Optional) cell width to be used if a value in mxWidth is no supplied
cellH (float) (Optional) cell height to be used if a value in mxHeight is no supplied
halign (string) (Optional) cell text_halign value to be used if a value in mxHalign is no supplied
valign (string) (Optional) cell text_valign value to be used if a value in mxValign is no supplied
Headers parameters:
arColTitles (array) (Optional) Array of column titles. If not na a header row is added.
arRowTitles (array) (Optional) Array of row titles. If not na a header column is added.
cornerTitle (string) (Optional) If both row and column titles are supplied allows to set the value of the corner cell.
colTitlesBgColor (color) (Optional) bgcolor for header row
colTitlesTxtColor (color) (Optional) text_color for header row
rowTitlesBgColor (color) (Optional) bgcolor for header column
rowTitlesTxtColor (color) (Optional) text_color for header column
cornerBgClr (color) (Optional) bgcolor for the corner cell
cornerTxtClr (color) (Optional) text_color for the corner cell
Cell merge parameters:
mxMerge (matrix) (Optional) A matrix determining how cells will be merged. "L" - cell merges to the left, "U" - upwards.
mergeAllColTitles (bool) (Optional) Allows to print a table title instead of column headers, merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
mergeAllRowTitles (bool) (Optional) Allows to print one text value merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
Format:
string_float_separator (string) (Optional) A string used to separate string and float parts of cell values (mxValS and mxValF). Default is " "
format (string) (Optional) format string like in str.format() used to format numerical values
nz (string) (Optional) Determines how na numerical values are displayed.
The only other available function is autotable(string,... ) with a string parameter instead of string and float matrices which draws a one cell table.
█ SAMPLE USE
E.g., CSVParser library demo uses Autotable's for generating complex tables with merged cells.
█ CREDITS
The library was inspired by @kaigouthro's matrixautotable . A true master. Many thanks to him for his creative, beautiful and very helpful libraries.
StrTrimPadCase█ OVERVIEW
Contains various functions for manipulation with strings:
- padright() / padleft() - Pad a string to the right or left with a given char.
- trim2() - Trims not only spaces but also line breaks.
- nz(string) - like nz(), replaces na with a supplied string
█ FUNCTIONS
nz(s, replacement)
Similar to nz() but for strings. However, since `string(na)` is the same as `""`
there is no such thing as `na` for strings. So, the function just replaces `""` with `replacement`.
Parameters:
s (string)
replacement (string) : (string) (Optional) A string returned when `s` is `""` / `na`. Default: `""`
method toUppercase(s)
Converts a string to uppercase
Namespace types: series string, simple string, input string, const string
Parameters:
s (string)
method toLowercase(s)
Converts a string to uppercase
Namespace types: series string, simple string, input string, const string
Parameters:
s (string)
method padright(this, length, char)
pads a string up to `length` by adding `char`'s (spaces by default) to the end. (the first char of `char`
string is used). Respects max string length of 4096.
Namespace types: series string, simple string, input string, const string
Parameters:
this (string)
length (int)
char (simple string) : (string) A char to pad with. (if string longer than one char is supplied uses the first char)
method padleft(this, length, char)
pads a string up to `length` by adding `char`'s (spaces by default) to the beginning(the first char of
`char` string is used). Respects max string length of 4096.
Namespace types: series string, simple string, input string, const string
Parameters:
this (string)
length (int)
char (simple string) : (string) A char to pad with. (if string longer than one char is supplied uses the first char)
StrConcatWrap█ OVERVIEW
Contains functions for concatenation and wrapping of the strings:
- concatTrunc() / concatTrunc2() - Concatenate via a separator up to a given length truncating from left or right. concatTrunc2 returns also the number of overflowing chars (in a tuple)
- print() - A powerful concatenate function truncating chars from left or right and/or lines from top or bottom. By default just adds new lines respecting max length.
- wrap() - Wraps each line of the text adding prefix/postfix. If resulting string exceeds max length truncates from the end adding " "
- scroll() Returns a range of lines from the source string.
█ FUNCTIONS
method concatTrunc2(this, txt, separator, max_length, truncate_left, ignore_empty_strings)
Concatenates two strings leaving _max_length chars truncating from left/right. (Truncates from the end of the string by default).
this String to which txt is added
txt String to be added
max_length (int) (Optional) max length of string, default: 4096
separator (string) (Optional) If both this and txt are non empty separator is added in between. Usually " " is used.
truncate_left (bool) (Optional) if true truncates left string (this), if false - txt. Default - false (truncates txt)
ignore_empty_strings (bool) (Optional) if true and one of `this` or `txt` is empty just returns the other, if false - adds separator.
Returns: (tuple ) A tuple . E.g. if `this` is 4095 chars and separator is 2 chars then 4095+2=4097 exceeds default max_length = 4096 by 1, so will be returned, even if , e.g. `txt` is empty and `ignore_empty_strings` is true.
method concatTrunc(this, txt, separator, max_length, truncate_left, ignore_empty_strings)
Concatenates two strings leaving _max_length chars truncating from left/right. (Truncates from the end of the string by default).
this : string to which txt is added
txt : string to be added to this
max_length : max length of string, default: 4096
separator : If both this and txt are non empty separator is added in between. Usually " " is used.
truncate_left : if true truncates left string (this), if false - txt. Default - false (truncates txt)
ignore_empty_strings : (bool) (Optional) if true and one of `this` or `txt` is empty just returns the other, if false - adds separator.
Returns: (string) Resulting string
method printLines( this, txt, max_length, max_lines, line_break_regex, line_break, truncate_left, ignore_empty_strings, add_line_numbers, line_number_format, start_line_number, print_to_last_line)
Adds up to `max_lines` lines from `txt` to `this` observing `max_length`, truncating from left or right (truncating source strings `this` and/or `txt` themselves if necessary).
this : (string) Print outputs `txt` to the end of `this`
txt : (string) Print outputs `txt` to the end of `this`
max_length : (int) (Optional) Chars in excess of `max_length` will be truncated (ending chars by default, see `truncate_left` arg). Default: 4096
max_lines : (int) (Optional) Lines in excess of `max_lines` will be truncated (from end by default, see `truncate_left` arg). Default: 4096
line_break_regex : (string) (Optional) A regex expression used to search for linebrakes. Default is "( |\\r|\\r )"
line_break : (string) (Optional) A string added as a line break. Default is " ".
truncate_left : (bool) (Optional) If true chars in excess of `max_length` will be truncated from the beginning , if false - from the end. Default: false.
ignore_empty_strings : (bool) (Optional) If false a line break will be added (as an empty string), if false `this` will not change.
add_line_numbers : (bool) (Optional) If true adds number before each line. Default format: "LN0001". Custom fomat can be set with `line_number_format'.
line_numbers_format : (string) (Optional) Line number format (like in `str.format()`). Default: `"LN{0000: }"`
print_to_last_line : (string) (Optional) If true will add text to the last line (notwithout adding line break before the first added line). Default: false.
Returns: ` ` where `outS` = `this` + added lines, `intLenthOverflow` = number of truncated chars (including separator), e.g. if `this` is 4095 chars and separator is 2 chars then 4095+2=4097 exceeds default max_length = 4096 by 1, so will be returned, even if , e.g. `txt` is empty and `ignore_empty_strings` is true, and n - number of added lines
method print( this, txt, max_length, max_lines, truncate_left, truncate_top, truncate_lines_src, add_line_numbers, line_number_format, print_to_last_line)
Powerful concatenate function. In simplest form (`this.print(txt)`) just adds `txt` to the end of `this` starting from new line. If `print_to_last_line` is true then concatenates. Can truncate for _max_length (from right by default) and max_lines (truncating from top or bottom). (First removes excessive lines (over `max_lines`) then concatenates truncating for `max_length`.) `print()` looks for all kinds of line breaks (`\r`, ` ` or `\r `) and replaces them with ` `.
this : (string) Print outputs `txt` to the end of `this`
txt : (string) Print outputs `txt` to the end of `this`
max_length : (int) (Optional) Chars in excess of `max_length` will be truncated (ending chars by default, see `truncate_left` arg). Default: 4096
max_lines : (int) (Optional) Lines in excess of `max_lines` will be truncated (from end by default, see `truncate_left` arg). Default: 4096
truncate_left : (bool) (Optional) If true chars in excess of `max_length` will be truncated from the beginning , if false - from the end. Default: false.
truncate_top : (bool) (Optional) If true lines in excess of `max_lines` will be truncated from the top, if false - from the bottom. Default: false.
truncate_lines_src : (bool) (Optional) If true and either `this` or `txt` exceed `max_lines` they will be truncated (excessive lines removed). (Characters in excess of max_length will be truncated regardless). If truncate_top and txt has more than max_lines lines excessive lines will be truncated from the top. (if truncate_top escessive lines from `this` will be truncated regardless of truncate_src). If not truncate_top and this has more than max_lines lines excessive lines will be truncated from the bottom. (if not truncate_top escessive lines from `txt` will be truncated regardless of truncate_src)
add_line_numbers : (bool) (Optional) If true adds number before each line. Default format: "LN0001". Custom fomat can be set with `line_number_format'.
line_numbers_format : (string) (Optional) Line number format (like in `str.format()`). Default: `"LN{0000: }"`
print_to_last_line : (string) (Optional) If true will add text to the last line (notwithout adding line break before the first added line). Default: false.
Returns: ` ` where `outS` = `this` + added lines.
method wrap(this, wrap_width, breaker_prefix, breaker_postfix, line_postfix, max_length)
Wraps each line of `this` to wrap_width adding breaker_prefix to the end of each line (before " ") and breaker_postfix to the beginning of each line (after " ")" (i.e. breaker_prefix'es are effectively added to the end of each line (but the last) and breaker_postfix'es to the beginning of new line starting from second). If with breakers the line exceeds 4096 it is truncated from the right and " " is added at the end.
wrap_width : (series int) Width of each line (chars).
breaker_prefix : (series string) (Optional) Text to add at the end of each line. (Default = "")
breaker_postfix : (series string) (Optional) Text to add after the each added line break at the beginning of next line. (Default = "")
Returns: the wrapped text
export method scroll(this, start_line, lines_in_window, show_line_numbers, show_header)
Scrolls the text (this) by returning a given number of lines (`lines_in_window`) starting from `start_line`. Can add line numbers and/or a header line in the form "Starting from line ... out of total ... lines, ... chars"
start_line : (int) (Optional) Start line
lines_in_window : (int) (Optional) Number of lines to read and return
show_line_numbers : (bool) (Optional) If true preceeds each line with a line number in the form "LN0001}: "
show_header : (bool) (Optional) If true shows the header string in the form "Starting from line {0} out of total {1} lines, {2} chars" followed by a separator line "----------".
Returns: (string) Range of strings.
RegexLib█ OVERVIEW
This library contains regular expression (regex) search functions which are helpful, in particular, in reading configuration inputs.
feedRgx(): Searches for the first occurrence of `regex` pattern in the `src` and returns `src` split into parts as a tuple: ` `. If no match returns ` `
countRgx(): Counts `regex` occurrences in the `src`.
matchRgx(): Finds given `occurence` of `regex` pattern in `src` string.
NB! countRgx() and matchRgx() do not support `^` (beginning of the string placeholder), lookbehind some other complex patterns, because they works by cutting off the part of the string up to the first found occurence (inclusive) and then continuing the search on the remainder of the string. E.g. in a four line source `(?<= ).+ ` should match the second and the third lines but matchRgx only matches the second line since after matching it continues to search in the remainder AFTER the match only.
█ FULL LIST OF FUNCTIONS AND PARAMETERS
method feedRgx(src, regex)
Searches for the first occurrence of ` regex ` pattern in the ` src ` and returns ` src ` split into parts as a tuple: ` `. If no match returns ` `
Namespace types: series string, simple string, input string, const string
Parameters:
src (string) : (string) String to search for the regex pattern
regex (string) : (string) RegEx pattern
Returns: A tuple ` ` where `begS` is the part of the `src` string from the beginning up to the
first occurence of the `regex` pattern (or up to the end if not found), `matchS` - the first occurrence of the
regex pattern and `endS` the part of the strinf following the first occurrence of the `regex` pattern.
method countRgx(src, regex)
Counts `regex` occurrences in the `src`. ___NB!___ _Does not support `^` (beginning of the string
placeholder), lookbehind some other complex patterns, because it works by cutting off the part of the string up to
the first found occurence (inclusive) and then continuing the search on the remainder of the string. E.g. in a four line source `(?<= ).+ ` should match the second and the third lines but matchRgx only
matches the second line since after matching it continues to search in the remainder AFTER the match only. _
Namespace types: series string, simple string, input string, const string
Parameters:
src (string) : (string) String in which the regex pattern occurences are to be counted
regex (string) : (string) RegEx pattern
Returns: The number of occurrences of the `regex` pattern in the `src` string.
method matchRgx(src, regex, occurrence)
Finds given `occurence` of `regex` pattern in `src` string. ___NB!___ _Does not support `^` (beginning of the string placeholder), lookbehind and some other complex patterns, because it works by cutting off the part of the string up to the first found occurence (inclusive) and then continuing the search on the remainder of the string. E.g. in a four line source `(?<= ).+ ` should match the second and the third lines but matchRgx only matches the second line since after matching it continues to search in the remainder AFTER the match only. _
Namespace types: series string, simple string, input string, const string
Parameters:
src (string) : (string) String to search for the regex pattern
regex (string) : (string) RegEx pattern
occurrence (int) : (int) (Default is 1) The number of the occurrence to search for. If this params exceeds the actual
number of occurrences of the pattern in the `src` string the following tuple is returned
Returns: A tuple, matchS - matched substring, matchPos - position of the match, matchL - match length
█ HOW TO USE
See DEMO section in the script.
You can test regex patterns by playing around with script input settings.
Another usage example can be found in my CSVParser and HTFMAs libraries.
Adaptive SuperTrend Oscillator [AlgoAlpha]Adaptive SuperTrend Oscillator 🤖📈
Introducing the Adaptive SuperTrend Oscillator , an innovative blend of volatility clustering and SuperTrend logic designed to identify market trends with precision! 🚀 This indicator uses K-Means clustering to dynamically adjust volatility levels, helping traders spot bullish and bearish trends. The oscillator smoothly tracks price movements, adapting to market conditions for reliable signals. Whether you're scalping or riding long-term trends, this tool has got you covered! 💹✨
🔑 Key Features:
📊 Volatility Clustering with K-Means: Segments volatility into three levels (high, medium, low) using a K-Means algorithm for precise trend detection.
📈 Normalized Oscillator : Allows for customizable smoothing and normalization, ensuring the oscillator remains within a fixed range for easy interpretation.
🔄 Heiken Ashi Candles : Optionally visualize smoothed trends with Heiken Ashi-style candlesticks to better capture market momentum.
🔔 Alert System : Get notified when key conditions like trend shifts or volatility changes occur.
🎨 Customizable Appearance : Fully customizable colors for bullish/bearish signals, along with adjustable smoothing methods and lengths.
📚 How to Use:
⭐ Add the indicator to favorites by pressing the star icon. Customize settings to your preference:
👀 Watch the chart for trend signals and reversals. The oscillator will change color when trends shift, offering visual confirmation.
🔔 Enable alerts to be notified of critical trend changes or volatility conditions
⚙️ How It Works:
This script integrates SuperTrend with volatility clustering by analyzing ATR (Average True Range) to dynamically identify high, medium, and low volatility clusters using a K-Means algorithm . The SuperTrend logic adjusts based on the assigned volatility level, creating adaptive trend signals. These signals are then smoothed and optionally normalized for clearer visual interpretation. The Heiken Ashi transformation adds an additional layer of smoothing, helping traders better identify the market's true momentum. Alerts are set to notify users of key trend shifts and volatility changes, allowing traders to react promptly.
Support and Resistance HeatmapThe "Support and Resistance Heatmap" indicator is designed to identify key support and resistance levels in the price action by using pivots and ATR (Average True Range) to define the sensitivity of zone detection. The zones are plotted as horizontal lines on the chart, representing areas where the price has shown significant interaction. The indicator features a customizable heatmap to visualize the intensity of these zones, making it a powerful tool for technical analysis.
Features:
Dynamic Support and Resistance Zones:
Identifies potential support and resistance areas based on price pivots.
Zones are defined by ATR-based thresholds, making them adaptive to market volatility.
Customization Options:
Heatmap Visualization: Toggle the heatmap on/off to view the strength of each zone.
Sensitivity Control: Modify the zone sensitivity with the ATR Multiplier to increase or decrease zone detection precision.
Confirmations: Set how many touches a level needs before it is confirmed as a zone.
Extended Zone Visualization:
Option to extend the zones for better long-term visibility.
Ability to limit the number of zones displayed to avoid clutter on the chart.
Color-Coded Zones:
Color-coded zones help differentiate between bullish (support) and bearish (resistance) levels, providing visual clarity for traders.
Heatmap Integration:
Gradient-based color changes on levels show the intensity of touches, helping traders understand which zones are more reliable.
Inputs and Settings:
1. Settings Group:
Length:
Determines the number of bars used for the pivot lookback. This directly affects how frequently new zones are formed.
Sensitivity:
Controls the sensitivity of the zone calculation using ATR (Average True Range). A higher value will result in fewer, larger zones, while a lower value increases the number of detected zones.
Confirmations:
Sets the number of price touches needed before a level is confirmed as a support/resistance zone. Lower values will result in more zones.
2. Visual Group:
Extend Zones:
Option to extend the support and resistance lines across the chart for better visibility over time.
Max Zones to Display (maxZonesToShow):
Limits the maximum number of zones shown on the chart to avoid clutter.
3. Heatmap Group:
Show Heatmap:
Toggle the heatmap display on/off. When enabled, the script visualizes the strength of the zones using color intensity.
Core Logic:
Pivot Calculation:
The script identifies support and resistance zones by using the pivotHigh and pivotLow functions. These pivots are calculated using a lookback period, which defines the number of candles to the left and right of the pivot point.
ATR-Based Threshold:
ATR (Average True Range) is used to create dynamic zones based on volatility. The ATR acts as a buffer around the identified pivot points, creating zones that are more flexible and adaptable to market conditions.
Merging Zones:
If two zones are close to each other (within a certain threshold), they are merged into a single zone. This reduces overlapping zones and gives a cleaner visual representation of significant price levels.
Confirmation Mechanism:
Each time the price touches a zone, the confirmation counter for that zone increases. The more confirmations a zone has, the more reliable it is. Zones are only displayed if they meet the required number of confirmations as specified by the user.
Color Gradient:
Zones are color-coded based on the number of confirmations. A gradient is used to visually represent the strength of each zone, with stronger zones being more vividly colored.
Heatmap Visualization:
When the heatmap is enabled, the color intensity of the zones is adjusted based on the proximity of the price to the zone and the number of touches the zone has received. This helps traders quickly identify which zones are more critical.
How to Use:
Identifying Support and Resistance Zones:
After adding the indicator to your chart, you will see horizontal lines representing key support (bullish) and resistance (bearish) levels. These zones are dynamically updated based on price action and pivots.
Adjusting Zone Sensitivity:
Use the "ATR Multiplier" to fine-tune how sensitive the indicator is to price fluctuations. A higher multiplier will reduce the number of zones, focusing on more significant levels.
Using Confirmations:
The more times a price interacts with a zone, the stronger that zone becomes. Use the "Confirmations" input to filter out weaker zones. This ensures that only zones with enough interaction (touches) are plotted.
Activating the Heatmap:
Enabling the heatmap will provide a color-coded visual representation of the strength of the zones. Zones with more price interactions will appear more vividly, helping you focus on the most significant areas.
Best Practices:
Combine with Other Indicators:
This support and resistance indicator works well when combined with other technical analysis tools, such as oscillators (e.g., RSI, MACD) or moving averages, for better trade confirmations.
Adjust Sensitivity Based on Market Conditions:
In volatile markets, you may want to increase the ATR multiplier to focus on more significant support and resistance zones. In calmer markets, decreasing the multiplier can help you spot smaller, but relevant, levels.
Use in Different Time Frames:
This indicator can be used effectively across different time frames, from intraday charts (e.g., 1-minute or 5-minute charts) to longer-term analysis on daily or weekly charts.
Look for Confluences:
Zones that overlap with other indicators, such as Fibonacci retracements or key moving averages, tend to be more reliable. Use the zones in conjunction with other forms of analysis to increase your confidence in trade setups.
Limitations and Considerations:
False Breakouts:
In highly volatile markets, there may be false breakouts where the price briefly moves through a zone without a sustained trend. Consider combining this indicator with momentum-based tools to avoid false signals.
Sensitivity to ATR Settings:
The ATR multiplier is a key component of this indicator. Adjusting it too high or too low may result in too few or too many zones, respectively. It is important to fine-tune this setting based on your specific trading style and market conditions.
Crypto Heatmap [Pinescriptlabs]🌟 Crypto Heatmap is a visual tool that enables quick and efficient visualization of price behavior and percentage changes of various cryptocurrencies.
📊 It generates a heatmap to show variations in daily closing prices, helping traders quickly identify assets with the most movement.
📈 Percentage Change Calculation: It calculates the difference between the current price and the previous day's price, updating with each ticker.
✨ It uses a dynamic approach that adjusts colors based on market movements, making it easier to detect trading opportunities.
👀 You will notice for a moment that some cells disappear; this is because the table updates with each ticker to show real-time changes.
Español:
🌟 Crypto Heatmap es una herramienta visual que permite una rápida y eficiente visualización del comportamiento de precios y cambios porcentuales de varias criptomonedas.
📊 Genera un mapa de calor para mostrar las variaciones en los precios de cierre diario, ayudando a los traders a identificar rápidamente los activos con mayor movimiento.
📈 Cálculo del cambio porcentual: Calcula la diferencia entre el precio actual y el del día anterior, actualizándose en cada ticker.
✨ Utiliza un enfoque dinámico que ajusta los colores según los movimientos del mercado, facilitando la detección de oportunidades de trading.
Aquí tienes la traducción al español:
👀 **Observarás por un momento que algunas celdas desaparecen; esto es porque la tabla se actualiza en cada ticker para mostrar el cambio en tiempo real.**
Volume Performance Table (Weekdays Only)This is a volume performance table that compares the volume from the previous trading day to the average daily volume from the previous week, month, 3-month, 6-month, and 12-month period in order to show where the rate of change of volume is contributing to the price trend.
For example, if the price trend is bullish and volume is accelerating, that is a bullish confirmation.
If the price is bearish and volume is accelerating, that is a bearish confirmation.
If the price is bullish and volume is decelerating, that is a bearish divergence.
If the price is bearish and volume is decelerating, that is a bullish divergence.
This does not include weekend trading when applied to digital assets such as cryptocurrencies.
2024 - Seasonality - Open to CloseScript Description:
This Pine Script is designed to visualise **seasonality** in the financial markets by calculating the **open-to-close percentage change** for each month of a selected asset. It creates a **heatmap** table to display the monthly performance over multiple years. The script provides detailed statistical summaries, including:
- **Average monthly percentage changes**
- **Standard deviation** of the changes
- **Percentage of months with positive returns**
The script also allows users to adjust colour intensities for positive and negative values, specify which year to start from, and skip specific months. Key metrics such as averages, standard deviations, and percentages of positive months can be toggled on or off based on user preferences. The result is a clear, visual representation of how an asset typically performs month by month, aiding in seasonality analysis.
FVG Channel [LuxAlgo]The FVG Channel indicator displays a channel constructed from the averages of unmitigated historical fair value gaps (FVG), allowing to identify trends and potential reversals in the market.
Users can control the amount of FVGs to consider for the calculation of the channels, as well as their degree of smoothness through user settings.
🔶 USAGE
The FVG Channel is constructed by averaging together recent unmitigated Bullish FVGs (contributing to the creation of the upper bands), and Bearish unmitigated FVGs (contributing to the creation of the lower bands) within a lookback determined by the user. A higher lookback will return longer-term indications from the indicator.
The channel includes 5 bands, with one upper and one lower outer extremities, as well as an inner series of values determined using the Fibonacci ratios (respectively 0.786, 0.5, 0.236) from the channel's outer extremities.
An uptrend can be identified by price holding above the inner upper band (obtained from the 0.786 ratio), this band can also provide occasional support when the price retraces to it while in an uptrend.
Breaking below the inner upper band with an unwillingness to reach above again is a clear sign of hesitation in the market and can be indicative of an upcoming consolidation or reversal.
This can directly be applied to downtrends as well, below are examples displaying both scenarios.
Uptrend Example:
Downtrend Example:
🔹 Breakout Levels
When the price mitigates all FVGs in a single direction except for 1, the indicator will display a "Breakout Level". This is the level that price will need to cross in order for all FVGs in that direction to be mitigated, because of this they can also be aptly called "Last Stand Levels".
These levels can be considered as potential support and resistance levels, however, should always be monitored for breakouts since a substantial push above or below these points would indicate strong momentum.
🔹 Signals
The indicator includes Bullish and Bearish Signals, these signals fire when all FVGs for a single direction have been mitigated and an engulfing candle occurs in the opposite direction. These are reversal signals and should be used alongside other indicators to appropriately manage risk.
Note: When all FVGs in a single direction have been mitigated, the candles will change colors accordingly.
🔶 DETAILS
The script uses a typical identification method for FVGs. Once identified, the script collects and stores the mitigation levels of the respective bullish and bearish FVGs:
For Bullish FVGs this is the bottom of the FVG.
For Bearish FVGs this is the top of the FVG.
The data is managed to only consider a specific amount of FVG mitigation levels, determined by the set "Unmitigated FVG Lookback". If an FVG is mitigated, it frees up a spot in the memory for a new FVG, however, if the memory is full, the oldest will be deleted.
The averages displayed (Channel Upper and Lower) are created from 2 calculation steps, the first step involves taking the raw average of the FVG mitigation levels, and the second step applies a simple moving average (SMA) smoothing of the precedent obtained averages.
Note: To view the mitigation levels average obtained in the first step, the "Smoothing Length" can be set to 1.
🔶 SETTINGS
Unmitigated FVG Lookback: Sets the maximum number of Unmitigated FVG mitigation levels that the script will use to calculate the channel.
Smoothing Length: Sets the smoothing length for the channel to reduce noise from the raw data.
E9 Shark-32 Pattern Strategy The E9 Shark-32 Pattern is a powerful trading tool designed to capitalize on the Shark-32 pattern—a specific Candlestick pattern.
The Shark-32 Pattern: What Is It?
The Shark-32 pattern is a technical formation that occurs when the following conditions are met:
Higher Highs and Lower Lows: The low of two bars ago is lower than the previous bar, and the previous bar's low is lower than the current bar. At the same time, the high of two bars ago is higher than the previous bar, and the previous bar’s high is higher than the current bar.
This unique setup forms the "Shark-32" pattern, which signals potential volume squeezes and trend changes in the market.
How Does the Strategy Work?
The E9 Shark-32 Pattern Strategy builds upon this pattern by defining clear entry and exit rules based on the pattern's confirmation. Here's a breakdown of how the strategy operates:
1. Identifying the Shark-32 Pattern
When the Shark-32 pattern is confirmed, the strategy "locks" the high and low prices from the initial bar of the pattern. These locked prices serve as key levels for future trade entries and exits.
2. Entry Conditions
The strategy waits for the price to cross the pattern's locked high or low, signaling potential market direction.
Long Entry: A long trade is triggered when the closing price crosses above the locked pattern high (green line).
Short Entry: A short trade is triggered when the closing price crosses below the locked pattern low (red line).
The strategy ensures that only one trade is taken for each Shark-32 pattern, preventing overtrading and allowing traders to focus on high-probability setups.
3. Stop Loss and Take Profit Levels
The strategy has built-in risk management through stop-loss and take-profit levels, which are visually represented by the lines on the chart:
Stop Loss:
Stop loss can be adjusted in settings.
Take Profit:
For long trades: The take-profit target is set at the upper white dotted line, which is projected above the pattern high.
For short trades: The take-profit target is set at the lower white dotted line, which is projected below the pattern low.
These clearly defined levels help traders to manage risk effectively while maximizing potential returns.
4. Visual Cues
To make trading decisions even easier, the strategy provides helpful visual cues:
Green Line (Pattern High): This line represents the high of the Shark-32 pattern and serves as a resistance level and short entry signal.
Red Line (Pattern Low): This line represents the low of the Shark-32 pattern and serves as a support level and long entry signal.
White Dotted Lines: These lines represent potential profit targets, projected both above and below the pattern. They help traders define where the market might go next.
Additionally, the strategy highlights the pattern formation with color-coded bars and background shading to draw attention to the Shark-32 pattern when it is confirmed. This adds a layer of visual confirmation, making it easier to spot opportunities in real-time.
5. No Repeated Trades
An important aspect of the strategy is that once a trade is taken (either long or short), no additional trades are executed until a new Shark-32 pattern is identified. This ensures that only valid and confirmed setups are acted upon.
ATR with Donchian Channels and SMAsThis script combines the Average True Range (ATR), Donchian Channels, and Simple Moving Averages (SMAs) to provide a comprehensive tool for volatility and trend analysis.
Key Components:
ATR Calculation: The ATR is used to measure market volatility. It is calculated as a moving average of the true range over a specified length, which you can customize using different smoothing methods: RMA, SMA, EMA, or WMA. ATR helps identify periods of high and low volatility, giving insights into potential breakout or consolidation phases in the market.
Donchian Channels on ATR: The Donchian Channels are calculated based on the highest and lowest values of the ATR over a user-defined period. The upper and lower bands provide a volatility range, and the middle line represents the average of the two. This can help visualize the range of market volatility and detect possible trend reversals or continuations.
SMAs on ATR: Two Simple Moving Averages (SMA) are applied to the ATR values. These SMAs act as a smoothed version of the ATR, providing additional insight into volatility trends. By adjusting the length of these SMAs, you can track short-term and long-term volatility movements, helping in decision-making for potential entries and exits.
Inputs:
ATR Length: Set the length for calculating the ATR.
Smoothing Method: Choose from RMA, SMA, EMA, or WMA for smoothing the ATR calculation.
Donchian Channel Length: Set the length for calculating the highest and lowest ATR values for Donchian Channels.
SMA Lengths: Two adjustable lengths for applying SMAs to the ATR.
Visualization:
ATR Plot: The ATR is plotted in red, allowing you to see the market's volatility at a glance.
Donchian Channels: Blue lines represent the upper and lower bands, while the green line represents the middle line of the Donchian Channels, helping you visualize the volatility range.
SMAs: Two SMAs (green and orange) are plotted to smooth out the ATR and identify trends in volatility.
Use Cases:
Breakout Detection: High ATR values breaking out of the Donchian Channels may signal increased volatility and a potential breakout.
Trend Analysis: SMAs on ATR help smooth volatility trends, aiding in determining if the market is entering a more volatile or stable period.
Stop-Loss Placement: ATR and Donchian Channels can be used to set dynamic stop-loss levels based on market volatility.
This script is versatile and can be used across different asset classes, such as stocks, forex, crypto, and commodities. It is especially useful for traders who want to incorporate volatility into their trading strategies for better risk management and trend detection.
Common Volume Spike Indicator with Price Color on SpikeIndicator Name: Common Volume Spike Indicator with Price Color on Spike
Description:
The “Common Volume Spike Indicator with Price Color on Spike” is designed to detect significant volume spikes and highlight them on the chart. It not only identifies moments when the trading volume exceeds a certain threshold but also colors the price bars based on price movement during these spikes.
Key Features:
• Volume Spike Detection: Detects volume spikes when the current volume exceeds a specified multiple of the average volume over a user-defined lookback period.
• Dynamic Volume Break: Highlights bars where the volume exceeds a threshold, dynamically calculated as a multiple of the average volume (default is 10x the average volume).
• Price Color on Volume Spike: When a volume spike occurs, bars are colored green if the price closes higher than the previous bar, and red if the price closes lower. This feature helps traders easily identify significant price movements during high-volume periods.
• Customizable Parameters:
• Threshold Multiplier: Adjust the sensitivity of volume spike detection.
• Lookback Period: Define the period over which the average volume is calculated.
• Volume Break Multiplier: Set a multiplier for the average volume to identify extreme volume breaks.
This indicator is suitable for traders who want to quickly spot critical market events driven by significant increases in volume. It helps to visualize both the volume activity and the corresponding price movement, providing an additional layer of market insight.
How to Use:
1. Green Bars: When the volume spike condition is met and the price closes higher than the previous bar, the bar is colored green.
2. Red Bars: When the volume spike condition is met and the price closes lower than the previous bar, the bar is colored red.
3. Blue Bars: Indicates a significant volume break, where the current volume exceeds a specified multiple of the average volume (default: 10x).
Ideal for intraday and swing traders who rely on volume and price action for market entries and exits. This indicator works well across different asset classes, including stocks, forex, and cryptocurrencies.
You can adjust the input parameters to fit your specific trading strategy and timeframe.
Disclaimer: This indicator is a tool to help with market analysis and should not be considered financial advice. Always perform your own due diligence before making any trading decisions.
This description outlines the key functionality and how the indicator can benefit traders on TradingView.
ToStringMx█ OVERVIEW
Contains methods for conversion of matrices to string.
Supports matrices of int/float/bool/string/color/line/label/box/.
- toStringMx(matrix) - converts matrix to a string matrix converting each of its elements to string
- toS(matrix) - converts matrix to a string matrix (using toStringMx()) and outputs as string using str.tostring(matrix)
Conversion of each item to string is made using toS() function from moebius1977/ToS/1 library.
█ GENERAL DESCRIPTION OF FUNCTIONS
All toStringMx(matrix) and toS(matrix) methods have same parameters. The only difference will be in format parameter as explained below.
Parameters:
this (matrix) Matrix to be converted to a string matrix.
format (string) Format string.
nz (string) Placeholder for na items.
format parameter depends on the type:
For matrix format parameter works in the same way as `str.format()` (i.e. you can use same format strings as with `str.format()` with `{0}` as a placeholder for the value) with some shorthand "format" options available:
--- number ---
- "" => "{0}"
- "number" => "{0}"
- "0" => "{0, number, 0 }"
- "0.0" => "{0, number, 0.0 }"
- "0.00" => "{0, number, 0.00 }"
- "0.000" => "{0, number, 0.000 }"
- "0.0000" => "{0, number, 0.0000 }"
- "0.00000" => "{0, number, 0.00000 }"
- "0.000000" => "{0, number, 0.000000 }"
- "0.0000000" => "{0, number, 0.0000000}"
--- date ---
- "date" => "{0, date, dd.MM.YY}"
- "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}"
- "dd.MM" => "{0, date, dd:MM}"
- "dd" => "{0, date, dd}"
- "... ... " in any place is substituted with "{0, date, dd.MM.YY}"
--- time ---
- "time" => "{0, time, HH:mm:ss}"
- "HH:mm" => "{0, time, HH:mm}"
- "mm:ss" => "{0, time, mm:ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "date, time" => "{0, date, dd.MM.YY\}, {0, time, HH.mm.ss}"
- "date,time" => "{0, date, dd.MM.YY\},{0, time, HH.mm.ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "... ... " in any place is substituted with "{0, time, HH.mm.ss}"
For matrix :
format (string) : (string) (Optional) Use `x1` as placeholder for `x1` and so on. E.g. default format is `"(x1, y1) - (x2, y2)"`.
For matrix :
format (string) : (string) (Optional) Use `x1` as placeholder for `x`, `y1 - for `y` and `txt` for label's text. E.g. default format is `(x1, y1): "txt"` if ptint_text is true and `(x1, y1)` if false.
For matrix :
format (string) : (string) (Optional) Use `x1` as placeholder for `x`, `y1 - for `y` etc. E.g. default format is "(x1, y1) - (x2, y2)".
For matrix :
format (string) : (string) (Optional) Options are "HEX" (e.g. "#FFFFFF33") or "RGB" (e.g. "rgb(122,122,122,23)"). Default is "HEX".
█ FULL LIST OF FUNCTIONS AND PARAMETERS
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) Like in str.format()
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) Like in str.format() with some shorthand options:
```
--- number ---
- "" => "{0}"
- "number" => "{0}"
- "0" => "{0, number, 0 }"
- "0.0" => "{0, number, 0.0 }"
- "0.00" => "{0, number, 0.00 }"
- "0.000" => "{0, number, 0.000 }"
- "0.0000" => "{0, number, 0.0000 }"
- "0.00000" => "{0, number, 0.00000 }"
- "0.000000" => "{0, number, 0.000000 }"
- "0.0000000" => "{0, number, 0.0000000}"
--- date ---
- "date" => "{0, date, dd.MM.YY}"
- "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}"
- "dd.MM" => "{0, date, dd:MM}"
- "dd" => "{0, date, dd}"
- "... ... " in any place is substituted with "{0, date, dd.MM.YY}"
--- time ---
- "time" => "{0, time, HH:mm:ss}"
- "HH:mm" => "{0, time, HH:mm}"
- "mm:ss" => "{0, time, mm:ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "date, time" => "{0, date, dd.MM.YY\}, {0, time, HH.mm.ss}"
- "date,time" => "{0, date, dd.MM.YY\},{0, time, HH.mm.ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "... ... " in any place is substituted with "{0, time, HH.mm.ss}"
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) Like in str.format() with some shorthand options:
```
--- number ---
- "" => "{0}"
- "number" => "{0}"
- "0" => "{0, number, 0 }"
- "0.0" => "{0, number, 0.0 }"
- "0.00" => "{0, number, 0.00 }"
- "0.000" => "{0, number, 0.000 }"
- "0.0000" => "{0, number, 0.0000 }"
- "0.00000" => "{0, number, 0.00000 }"
- "0.000000" => "{0, number, 0.000000 }"
- "0.0000000" => "{0, number, 0.0000000}"
--- date ---
- "date" => "{0, date, dd.MM.YY}"
- "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}"
- "dd.MM" => "{0, date, dd:MM}"
- "dd" => "{0, date, dd}"
- "... ... " in any place is substituted with "{0, date, dd.MM.YY}"
--- time ---
- "time" => "{0, time, HH:mm:ss}"
- "HH:mm" => "{0, time, HH:mm}"
- "mm:ss" => "{0, time, mm:ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "date, time" => "{0, date, dd.MM.YY\}, {0, time, HH.mm.ss}"
- "date,time" => "{0, date, dd.MM.YY\},{0, time, HH.mm.ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "... ... " in any place is substituted with "{0, time, HH.mm.ss}"
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) Like in str.format()
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) "HEX" (default) or "RGB"
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toStringMx(mx, format, nz)
Returns a string matrix made of original matrix items converted to string with toS().
Namespace types: matrix
Parameters:
mx (matrix)
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) Format string as in str.format()
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) Like in str.format() with some shorthand options:
```
--- number ---
- "" => "{0}"
- "number" => "{0}"
- "0" => "{0, number, 0 }"
- "0.0" => "{0, number, 0.0 }"
- "0.00" => "{0, number, 0.00 }"
- "0.000" => "{0, number, 0.000 }"
- "0.0000" => "{0, number, 0.0000 }"
- "0.00000" => "{0, number, 0.00000 }"
- "0.000000" => "{0, number, 0.000000 }"
- "0.0000000" => "{0, number, 0.0000000}"
--- date ---
- "date" => "{0, date, dd.MM.YY}"
- "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}"
- "dd.MM" => "{0, date, dd:MM}"
- "dd" => "{0, date, dd}"
- "... ... " in any place is substituted with "{0, date, dd.MM.YY}"
--- time ---
- "time" => "{0, time, HH:mm:ss}"
- "HH:mm" => "{0, time, HH:mm}"
- "mm:ss" => "{0, time, mm:ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "date, time" => "{0, date, dd.MM.YY\}, {0, time, HH.mm.ss}"
- "date,time" => "{0, date, dd.MM.YY\},{0, time, HH.mm.ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "... ... " in any place is substituted with "{0, time, HH.mm.ss}"
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) Format string as in str.format()
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) "HEX" (default) or "RGB"
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
method toS(this, format, nz)
Converts each element of the matrix to string outputs using str.tostring(matrix)
Namespace types: matrix
Parameters:
this (matrix) : (matrix) Matrix to be converted to string
format (string) : (string) (Optional) Format string. By default "{0}: {1}" if showIDs = true or "{1}" otherwise. (use "{0}" as a placeholder for id and "{1}" for item value)
nz (string) : (string) If val is na and nz is not na the value of nz param is returned instead.export method toS(matrix this, string format = "", string nz = na) => str.tostring(this.toStringMx(format, nz))
ToStringAr█ OVERVIEW
Contains to string conversion methods arrays of int/float/bool/string/line/label/box types
- toS() - method works like array.join() with more flexibility and
- toStringAr() - converts array to string on a per item basis and returns the resulting string array
Conversion of each item to string is made using toS() function from moebius1977/ToS/1 library.
█ GENERAL DESCRIPTION OF LIBRARY FUNCTIONS
All toS(array) methods have same parameters. The only difference will be in format parameter as explained below.
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Like array.join() but with string length limit. Joins elements into readable string (length capped at 4000, truncating the end or beg)
Parameters:
this (array) : array to be converted to string
index_from (int) : index_from (int) (Optional) Start from this id (starting from 0, in insertion order). If omitted - start from the first item.
index_to (int) : index_to (int) (Optional) End with this pair (inclusive, in insertion order). If omitted - to last item.
separator (string) : separator (string) (Optional) String to be inserted between pairs. Default: `", "`
showIDs (bool) : showIDs (bool) (Optional) If true item's id is added in the form `id: value`.
format (string) : format (string) (Optional) Format string fo toS(). If omitted default format is used depending in the type.
truncate_left (bool) : truncate_left (bool) (Optional) Truncate from left or right. Default: false.
size_limit (int) : size_limit (int) (Optional) Max output string length. Default: 4000.
nz (string) : nz (string) (Optional) A string used to represent na (na values are substituted with this string).
format parameter depends on the type:
For toS(bool/int/float ...) format parameter works in the same way as `str.format()` (i.e. you can use same format strings as with `str.format()` with `{0}` as a placeholder for the value) with some shorthand "format" options available:
--- number ---
- "" => "{0}"
- "number" => "{0}"
- "0" => "{0, number, 0 }"
- "0.0" => "{0, number, 0.0 }"
- "0.00" => "{0, number, 0.00 }"
- "0.000" => "{0, number, 0.000 }"
- "0.0000" => "{0, number, 0.0000 }"
- "0.00000" => "{0, number, 0.00000 }"
- "0.000000" => "{0, number, 0.000000 }"
- "0.0000000" => "{0, number, 0.0000000}"
--- date ---
- "... ... " in any place is substituted with "{0, date, dd.MM.YY}" (e.g. " " results in "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}")
- "date" => "{0, date, dd.MM.YY}"
- "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}"
- "dd.MM" => "{0, date, dd:MM}"
- "dd" => "{0, date, dd}"
--- time ---
- "... ... " in any place is substituted with "{0, time, HH.mm.ss}" (e.g. " " results in "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}")
- "time" => "{0, time, HH:mm:ss}"
- "HH:mm" => "{0, time, HH:mm}"
- "mm:ss" => "{0, time, mm:ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
- "date, time" => "{0, date, dd.MM.YY\}, {0, time, HH.mm.ss}"
- "date,time" => "{0, date, dd.MM.YY\},{0, time, HH.mm.ss}"
- "date time" => "{0, date, dd.MM.YY\} {0, time, HH.mm.ss}"
For toS(line ...):
format (string) : (string) (Optional) Use `x1` as placeholder for `x1` and so on. E.g. default format is `"(x1, y1) - (x2, y2)"`.
For toS(label ...) :
format (string) : (string) (Optional) Use `x1` as placeholder for `x`, `y1 - for `y` and `txt` for label's text. E.g. default format is `(x1, y1): "txt"` if ptint_text is true and `(x1, y1)` if false.
For toS(box ... ) :
format (string) : (string) (Optional) Use `x1` as placeholder for `x`, `y1 - for `y` etc. E.g. default format is "(x1, y1) - (x2, y2)".
For toS(color] ... ) :
format (string) : (string) (Optional) Options are "HEX" (e.g. "#FFFFFF33") or "RGB" (e.g. "rgb(122,122,122,23)"). Default is "HEX".
All toStringAr() methods just convert each item to string using toS with same format options as described above.
Parameters:
arr (array) : Array to be converted to a string array.
format (string) : Format string.
nz (string) : Placeholder for na items.
█ FULL OF FUNCTIONS AND PARAMETERS
Library "ToStringAr"
Contains toString/toS conversion methods for int/float/bool/string/line/label/box and arrays and matrices thereof. Also contains a string wraping function.
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toS(this, index_from, index_to, separator, showIDs, format, truncate_left, size_limit, nz)
Namespace types: array
Parameters:
this (array)
index_from (int)
index_to (int)
separator (string)
showIDs (bool)
format (string)
truncate_left (bool)
size_limit (int)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
method toStringAr(arr, format, nz)
Namespace types: array
Parameters:
arr (array)
format (string)
nz (string)
Fed Net LiquidityNet Liquidity = Federal Reserve Total Assets - Treasury General Account (TGA) - Reverse Repurchase Agreements (RRP) Balance
1. Federal Reserve Total Assets: This is the sum of everything the Fed owns, like government bonds and mortgage-backed securities. You can snag this data from the Fed’s weekly balance sheet report.
2. Treasury General Account (TGA): Think of this as the U.S. government’s checking account at the Fed. When the TGA balance goes up, it means the government is pulling liquidity out of the market, and vice versa.
3. Reverse Repurchase Agreements (RRP) Balance: This represents the liquidity the Fed absorbs from the market through reverse repo operations. When financial institutions park money in the Fed’s RRP account, there’s less cash available in the market.
Why Use Net Liquidity?
Net liquidity is seen as a key indicator of the actual amount of money available in the market. It helps gauge the overall liquidity conditions that can influence financial markets.
Where to Find the Data:
1. Federal Reserve Total Assets: You can find this in the Fed’s weekly balance sheet (the H.4.1 report). Here’s the link: Federal Reserve Statistical Release - H.4.1.
Steps to Calculate Net Liquidity Yourself:
1. Get the Fed’s Total Assets: Look up the latest H.4.1 report and jot down the total assets figure.
2. Find the TGA Balance: Head over to the U.S. Treasury’s Daily Treasury Statement to locate the “Treasury General Account” balance.
3. Get the RRP Balance: You can find this number in the H.4.1 report or on the New York Fed’s website under “Reverse Repurchase Agreements.”
4. Do the Math: Simply subtract the TGA and RRP balances from the Fed’s total assets—that gives you the net liquidity.
Risk RewardThe Risk Reward indicator, developed by OmegaTools, is a versatile technical tool designed to help traders visualize and evaluate potential reward and risk levels in their trades. By comparing recent price action against moving averages and volatility deviations, it calculates a range-weighted assessment of upside reward and downside risk. It provides a clear, color-coded visual representation of these potential ranges, along with critical support and resistance levels to aid in trade decision-making. This indicator is ideal for traders seeking to optimize their risk-reward ratio and make informed trade management decisions.
Features
Reward and Risk Visualization: Provides a histogram showing the relative potential of upside reward versus downside risk based on current price action.
Dynamic Support and Resistance Levels: Calculates and plots key price levels based on extreme of historical volatility, helping traders to identify important price zones.
Trade Size Customization: Users can adjust the trade size, and the indicator will calculate and display the estimated risk and reward in monetary terms based on the contract value.
Adaptive Volatility Extensions: Automatically adjusts extension lines based on volume, helping traders anticipate future price ranges and potential breakouts or breakdowns.
Customizable Visuals: Allows users to personalize the color scheme for bullish and bearish scenarios, making the chart more intuitive and user-friendly.
User Guide
Trade Size (size): Adjust the trade size in units (default is 1). This parameter impacts the risk and reward calculation shown in the summary table.
Length (lnt): Set the length for the exponential moving average (EMA) and the highest/lowest price calculations. This length determines the sensitivity of the indicator.
Different Visual (down): A boolean input to adjust the method for calculating downside risk. When set to true, it uses a different visual scheme.
Bullish Color (upc): Customize the color of the bullish (upside) histogram and support levels.
Bearish Color (dnc): Customize the color of the bearish (downside) histogram and resistance levels.
Plots
First Probability: Displays a histogram representing the higher value between reward and risk. It is colored according to whether the upside or downside is greater, providing a clear signal for potential trade direction.
Second Probability: A secondary histogram plot that visualizes the lower value between reward and risk, offering an additional perspective on the trade’s risk-reward balance.
Low Level/High Level: Displays dynamic support and resistance levels based on historical price data and volatility deviations.
Extension Lines: Visualize potential future price levels using volatility-adjusted projections. These lines help traders anticipate where price could move based on current conditions.
On-Chart Labels and Risk-Reward Table:
Risk and Reward Calculations: The indicator calculates the monetary value of downside risk and upside reward based on the provided trade size, volatility measures, and price movements.
Risk/Reward Table: Displayed directly on the chart, showing the downside risk and upside reward in easy-to-understand numerical values. This helps traders quickly assess the feasibility of a trade.
How It Works:
Moving Average Comparison: The indicator first calculates the 21-period (default) exponential moving average (EMA). It then compares the current price against this moving average to determine whether the market is in a bullish or bearish phase.
Deviation Calculation: It calculates the average deviation between the price and the EMA for both bullish and bearish movements, which is used to establish dynamic support and resistance levels.
Risk-Reward Calculation: Based on the highest and lowest price levels over the set period and the calculated deviations, it determines the potential upside reward and downside risk. The reward is calculated as the distance between the current price and the upper resistance levels, while the risk is determined as the distance to the lower support levels.
Visual Representation
The indicator plots histograms representing the relative magnitude of potential reward and risk.
Support and resistance levels are dynamically plotted on the chart using circles and lines, helping traders easily spot key areas of interest.
Extension lines are drawn to visualize potential future price levels based on current volatility.
Risk/Reward Table: This feature displays the calculated monetary risk and reward based on the trade size. It updates dynamically with price changes, offering a constant reference point for traders to evaluate their trade setup.
Practical Application
Identify Entry Points: Use the dynamic support and resistance levels to identify ideal trade entry points. The histogram helps determine whether the potential reward justifies the risk.
Risk Management: The calculated downside risk provides traders with an objective view of where to place stop-loss levels, while the upside reward aids in setting profit targets.
Trade Execution: By visually assessing whether reward outweighs risk, traders can make more informed decisions on trade execution, with the risk-reward ratio clearly displayed on the chart.
Best Practices:
Use Alongside Other Indicators: While this indicator offers a powerful standalone tool for assessing risk and reward, it works best when combined with other trend or momentum indicators for confirmation.
Adjust Inputs Based on Market Conditions: Adjust the length and trade size inputs depending on the asset being traded and the time horizon, as different assets may require different sensitivity settings.
display_valueOVERVIEW
This script is a tinny library for creating and displaying formatted values in TradingView scripts. It provides a structured way to present key information like titles, percentages, currency values, decimals, and integers with clear formatting. This allows you to coordinate your strings in advance and hold one item to use for calling your string to a label, box, table.. Made for day to day use of most typical use cases, more advanced techniques should be used for complicated scenarios.
Building Blocks
User Defined Types (UDTs)
The script defines a UDT called `DisplayValue` to encapsulate the components of a display value:
* title : The title or label of the value.
* format_string : The string used to format the value (e.g., "{0} - 1,number,percent}").
* value : The actual value to be displayed.
* format : An enum value specifying the desired format (percent, currency, etc.).
Enums
The `DisplayFormat` enum provides predefined constants for various formatting options, making the code more readable and less prone to errors.
Functions
* create() : This function creates a new `DisplayValue` instance. It takes the title, value, and desired format as arguments and generates the appropriate format string.
* to_string() : This function converts a `DisplayValue` instance into a formatted string ready for display on the chart.
How to Use
1. Import the library:
import kaigouthro/display_value/1as dv
2. Create a DisplayValue instance:
myValue = dv.create("My Percentage", 0.5, dv.DisplayFormat.percent)
3. Convert it to a string:
formattedString = dv.to_string(myValue)
4. Display the formatted string:
label.new(bar_index, high, formattedString)
Example
//@version=5
import kaigouthro/display_value/1 as dv
myValue = dv.create("Profit", 0.15, dv.DisplayFormat.percent)
formattedString = dv.to_string(myValue)
label.new(bar_index, high, formattedString)
This will display a label on the chart with the text "Profit - 15%".
### Notes
* The library handles the formatting details, making it easier to display values consistently in your scripts.
* The use of enums and UDTs improves code organization and readability.
--------
Library "display_value"
create(display_name, display_value, display_format)
Gets the appropriate format string based on the display format.
Parameters:
display_name (string) : (string) The name of the display value. Default is na.
display_value (float)
display_format (series DisplayFormat)
Returns: (DisplayValue) A new DisplayValue instance with the formatted value.
to_string(item)
Converts the display value to a string with the specified format.
Parameters:
item (DisplayValue) : (DisplayValue) The display value to convert to a string.
Returns: (string) The string representation of the display value.
DisplayValue
Structure representing a display value.
Fields:
title (series string) : (string) The title of the display value.
format_string (series string) : (string) The format string to use for display.
value (series float) : (float) The value to display.
format (series DisplayFormat) : (DisplayFormat) The format to use.
RSI 30-50-70 moving averageDescription:
The RSI 30-50-70 Moving Average indicator plots three distinct moving averages based on different RSI ranges (30%, 50%, and 70%). Each moving average corresponds to different market conditions and provides potential entry and exit signals. Here's how it works:
• RSI_30 Range (25%-35%): The moving average of closing prices when the RSI is between 25% and 35%, representing potential oversold conditions.
• RSI_50 Range (45%-55%): The moving average of closing prices when the RSI is between 45% and 55%, providing a balanced perspective for trend-following strategies.
• RSI_70 Range (65%-75%): The moving average of closing prices when the RSI is between 65% and 75%, representing potential overbought conditions.
This indicator offers flexibility, as users can adjust key parameters such as RSI ranges, periods, and time frames to fine-tune the signals for their trading strategies.
How it Works:
Like traditional moving averages, the RSI 30-50-70 Moving Averages can highlight dynamic levels of support and resistance. They offer additional insight by focusing on specific RSI ranges, providing early signals for trend reversals or continuation. The default settings can be used across various assets but should be optimized via backtesting.
Default Settings:
• RSI_30: 25% to 35% (Oversold Zone, yellow line)
• RSI_50: 45% to 55% (Neutral/Trend Zone, green line)
• RSI_70: 65% to 75% (Overbought Zone, red line)
• RSI Period: 14
Buy Conditions:
• Use the 5- or 15-minute time frame.
• Wait for the price to move below the RSI_30 line, indicating potential oversold conditions.
• Enter a buy order when the price closes above the RSI_30 line, signaling a recovery from the oversold zone.
• For a more conservative approach, use the RSI_50 line as the buy signal to confirm a trend reversal.
• Important: Before entering, ensure that the RSI_30 moving average has flattened or started to level off, signaling that the oversold momentum has slowed.
Sell Conditions:
• Use the 5- or 15-minute time frame.
• Wait for the price to close above the RSI_70 line, indicating potential overbought conditions.
• Enter a sell order when the price closes below the RSI_70 line, signaling a decline from the overbought zone.
• Important: Similar to buying, wait for the RSI_70 moving average to flatten or level off before selling, indicating the overbought conditions are stalling.
Key Features:
1. Dynamic Range Customization: The indicator allows users to modify the RSI ranges and periods, tailoring the moving averages to fit different market conditions or asset classes.
2. Trend-Following and Reversal Signals: The RSI 30-50-70 moving averages provide both reversal and trend-following signals, making it a versatile tool for short-term traders.
3. Visual Representation of Market Strength: By plotting moving averages based on RSI levels, traders can visually interpret the market’s strength and potential turning points.
4. Risk Management: The built-in flexibility allows traders to choose lower-risk entries by adjusting which RSI level (e.g., RSI_30 vs. RSI_50) they rely on for signals.
Practical Use:
Different assets respond uniquely to RSI-based moving averages, so it's recommended to backtest and adjust ranges for specific instruments. For example, volatile assets may require wider RSI ranges, while more stable assets could benefit from tighter ranges.
Checking for Buy conditions:
1st: Wait for current price to go below the RSI_30 (yellow line)
2nd: Wait and observe for bullish divergence
3rd: RSI_30 has flattened indicating potential gain of momentum after a bullish divergence.
4th: Enter a buy order when the price closed above the RSI_30, preferably when a green candle appeared.
Breakout and Breakdown Indicator with RetestsThis indicator is designed to help traders identify high-probability breakout and breakdown points based on the first 5 minutes of market activity (9:30 am to 9:35 am). It works effectively on both the 1-minute and 5-minute timeframes, making it ideal for day traders and scalpers.
This indicator is a better indicator of my previous 5-Minute Opening Range Breakout indicator.
Key Features:
Dynamic Support and Resistance Lines: Automatically plots the highest and lowest price levels from 9:30 am to 9:35 am, providing essential support and resistance zones.
Breakout/Breakdown Detection: Identifies and marks successful breakout and breakdown points only after a confirmed retest, ensuring more accurate signals.
Visual Markers: Uses customizable green diamonds for successful breakouts and red diamonds for successful breakdowns, allowing easy identification on the chart.
Customization Options:
Change Colors: You can personalize the color of the breakout and breakdown markers, the label text, and the lines drawn from the 9:30 am to 9:35 am window.
Adapt to Your Chart: Adjust the indicator to match your preferred charting theme, ensuring it blends seamlessly with your trading setup.
How It Works:
Plots Key Levels: Identifies the highest and lowest prices during the first 5 minutes of trading (9:30 am to 9:35 am) and plots them on the chart.
Monitors Retests: Waits for a retest of these levels before confirming a breakout or breakdown.
Labels Breakouts/Breakdowns: After a retest, successful breakouts are marked with green diamonds and "Breakout" text, while breakdowns are marked with red diamonds and "Breakdown" text.
Why Use This Indicator?
Avoid False Signals: The retest requirement helps filter out false breakouts and breakdowns, offering more reliable trading signals.
Works Across Timeframes: Suitable for both 1-minute and 5-minute charts, allowing flexibility for different trading styles.
Some what Customizable: Adjust colors to fit your charting preferences and enhance visual clarity.
Recommended Use: Combine this indicator with other technical analysis tools, such as volume, candlestick patterns, or moving averages, for more informed trading decisions.
Relative PPP for USDBRLThis indicator calculates the USDBRL exchange rate using the Relative Purchasing Power Parity method, which considers that the variation in the exchange rate is equal to the variation in inflation in Brazil minus the variation in inflation in the US. It is derived from the Law of One Price, which states that an identical good should have the same price in different markets when adjusted for exchange rates, assuming the absence of arbitrage barriers such as transaction costs or trade restrictions.
The indicator is calculated starting from June 1994, at the launch of the Real Plan, which equalized the value of the Brazilian Real and the US Dollar at that time. This indicator is useful for providing an idea of the long-term trend of the Dollar exchange rate (months or years), acting similarly to a moving average, around which the exchange rate gravitates.
It's useful for analysts who have to forecast the USDBRL in the long term.
US Recessions based on James Hamilton's JHDUSRGDPBRThis simple script uses James Hamilton's JHDUSRGDPBR indicator to colour areas representing recession periods in the US. Best used in conjunction with other macroeconomics indicators, like –as in the example– unemployment rates