DistributionsLibrary "Distributions"
Library with price distribution zones calculation helpers.
Based on research from "Trading Systems and Methods, 5th Edition" by Perry J. Kaufman
getZones(h, l, c, window)
Returns price distribution zones based on HLC and for some period
Parameters:
h : high price
l : low price
c : close price
window : period to calculate distributions
Returns: tuple of 5 price zones in descent order, from highest to lowest
Indicadores y estrategias
ColorsLibrary "Colors"
Helpers for color manipulations
opacify(oldColor, opacity)
Applies opacity to color
Parameters:
oldColor : color
opacity : opacity
Returns: color with opacity
PerformanceTableLibrary "PerformanceTable"
TODO: add library description here
This library was created as a library because adding a performance table to an existing strategy script made the strategy script lengthy and inconvenient to manage.
The monthly table script referenced @QuantNomad's code.
The performance table script referenced @myncrypto's code.
To use, copy and paste the code below at the bottom of the strategy script you are using, and the table for strategy performance will be displayed on a chart.
//------------Copy & Paste --------------------------------------//
import Cube_Lee/PerformanceTable/1 as PT
PT = input.bool(true, "Show Performance Table", tooltip = "전략의 성과를 우측상단에 테이블로 표시합니다.", group = "Performance Table")
MT = input.bool(true, "Show Monthly Table", tooltip = "전략의 월별 수익률을 우측하단에 테이블로 표시합니다.", group = "Performance Table")
if PT
PT.PerformanceTable()
if MT
PT.MonthlyTable()
//------------Copy & Paste---------------------------------------//
PerformanceTable()
MonthlyTable()
SH_LibraryLibrary "SH_Library"
events()
Returns the list of dates supported by this library as a string array.
Returns: array : Names of events supported by this library
fomcMeetings()
Gets the FOMC Meeting Dates. The FOMC meets eight times a year to determine the course of monetary policy. The FOMC announces its decision on the federal funds rate at the conclusion of each meeting and also issues a statement that provides information on the economic outlook and the Committee's assessment of the risks to the outlook.
Returns: array : FOMC Meeting Dates as timestamps
fomcMinutes()
Gets the FOMC Meeting Minutes Dates. The FOMC Minutes are released three weeks after each FOMC meeting. The Minutes provide information on the Committee's deliberations and decisions at the meeting.
Returns: array : FOMC Meeting Minutes Dates as timestamps
ppiReleases()
Gets the Producer Price Index (PPI) Dates. The Producer Price Index (PPI) measures the average change over time in the selling prices received by domestic producers for their output. The PPI is a leading indicator of CPI, and CPI is a leading indicator of inflation.
Returns: array : PPI Dates as timestamps
cpiReleases()
Gets the Consumer Price Index (CPI) Rekease Dates. The Consumer Price Index (CPI) measures changes in the price level of a market basket of consumer goods and services purchased by households. The CPI is a leading indicator of inflation.
Returns: array : CPI Dates as timestamps
csiReleases()
Gets the CSI release dates. The Consumer Sentiment Index (CSI) is a survey of consumer attitudes about the economy and their personal finances. The CSI is a leading indicator of consumer spending.
Returns: array : CSI Dates as timestamps
cciReleases()
Gets the CCI release dates. The Conference Board's Consumer Confidence Index (CCI) is a survey of consumer attitudes about the economy and their personal finances. The CCI is a leading indicator of consumer spending.
Returns: array : CCI Dates as timestamps
nfpReleases()
Gets the NFP release dates. Nonfarm payrolls is an employment report released monthly by the Bureau of Labor Statistics (BLS) that measures the change in the number of employed people in the United States.
Returns: array : NFP Dates as timestamps
eciReleases()
Gets the ECI The Employment Cost Index (ECI) is a measure of the change in the cost of labor,
Debugging_consoleRefer to notes for instruction
===================================================================
AntaresLibrary "Antares"
this library contains some utility functions that I use in my open source scripts including moving average helpers, candlstick helpers, money management, formatters, convertors, webhook integration, analysis, filters and drawing helpers
ma(type, length, source)
Wraps all ma functions
Parameters:
type : Either SMA or EMA or RMA or WMA or VWMA
length : Number of bars (length).
source : Series of values to process.
Returns: Moving average of `source` for `length` bars back by the of MA.
bb(ma, length, mult, source)
Overwrites `ta.bb` duo to limitations of simple int.float mult. Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price, but can be adjusted to user preferences.
Parameters:
ma : Either SMA or EMA or RMA or WMA or VWMA
length : Number of bars (length).
mult : Standard deviation factor.
source : Series of values to process.
Returns: Bollinger Bands.
atr(length, h, l, c)
Overwrites `ta.atr` duo to limitations of simple int length. Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close ), abs(low - close )).
Parameters:
length : Number of bars (length).
h : High price high price.
l : low price.
c : Close price close price.
Returns: Average true range.
rsi(length, source)
Overwrites `ta.rsi` duo to limitations of simple int length. Relative strength index. It is calculated using the `ta.rma()` of upward and downward changes of `source` over the last `length` bars.
Parameters:
length : Number of bars (length).
source : Series of values to process.
Returns: Relative strength index.
lowest(length, source, start)
Lowest value for a given number of bars back.
Parameters:
length : Number of bars (length).
source : Series of values to process.
start : Series number of bars that should be skipped before process.
Returns: Lowest value in the series.
highest(length, source, start)
Highest value for a given number of bars back.
Parameters:
length : Number of bars (length).
source : Series of values to process.
start : Series number of bars that should be skipped before process.
Returns: Highest value in the series.
atr_multiplier(rsi, atr_max_multiplier)
Dynamic atr multiplier calculated by RSI.
Parameters:
rsi : Relative strength index.
atr_max_multiplier : The maximum multiplier of atr
Returns: Dynamic multiplier of ATR
offset(atr, atr_multiplier)
Safe dynamic offset you need to use in your stoploss, stop buy/sell, etc.
Parameters:
atr : Average true range.
atr_multiplier : ATR multiplier got from `atr_multiplier(rsi, atr_max_multiplier)`
Returns: Dynamic offset
rsi_emotional(rsi, bottom, top)
Tells you if RSI is in emotional zone.
Parameters:
rsi : Relative Strength Index
bottom : The zone that below it market reacts emotionally
top : The zone that above it market reacts emotionally
Returns: false if RSI was between `bottom` and `top` otherwise true
rsi_signal(rsi, bottom, top)
Tells you if RSI is in good point to check your other strategy conditions.
Parameters:
rsi : Relative Strength Index
bottom : The zone that below it market reacts emotionally
top : The zone that above it market reacts emotionally
Returns: 1 if RSI crossed out 30, 50 or 70. -1 if RSI crossed under 70, 50, 30. otherwise is 0
DiscordLibraryLibrary "DiscordLibrary"
BoldString(str)
Bold String in Discord Function
Parameters:
str
ItalicizeString(str)
Italicize String in Discord Function
Parameters:
str
StrikeThroughString(str)
Strikethrough a String in Discord Function
Parameters:
str
UnderlineString(str)
Underline a String in Discord Function
Parameters:
str
SpoilerString(str)
When you send the text, it will be shown as a black block, and only by clicking on it will you be able to see what is written below, in a way, unveiling the text or giving spoilers
Parameters:
str
HighlightString(str)
Highlight String Function
Parameters:
str
BoxedString(str)
Put String in a Box Function
Parameters:
str
NonEmbeddedURLString(str)
Format URL String so that it is not an embedded Image but just the Link
Parameters:
str
InvisibleString(str)
Send Inivisible Text
Parameters:
str
FormatTimePeriodForDiscord(_timeperiod)
Parameters:
_timeperiod
GetDiscordEmbedJSON(_message, _avatarURL, _botName, _role, _color, _embed_title, _embed_subtitle, _title, _url, _icon_url, _icon2_url, _footer, _description)
Generate discord embed JSON
Parameters:
_message
_avatarURL
_botName
_role
_color
_embed_title
_embed_subtitle
_title
_url
_icon_url
_icon2_url
_footer
_description
GetDiscordTextJSON(_description)
Formats Content Only JSON Message
Parameters:
_description
Truncate(_number, _decimalPlaces)
Custom function to truncate (cut) excess decimal places
Parameters:
_number
_decimalPlaces
FormatDiscordMessage(_textmessage, _ticker, _timeframe)
format Content message
Parameters:
_textmessage
_ticker
_timeframe
FormatCoin(_coinText)
Format Ticker Symbol
Parameters:
_coinText
SessionInBoxesProLibrary "SessionInBoxesPro"
get_time_by_bar(bar_count)
Parameters:
bar_count
get_positions_func(sessiontime_, duration_)
Parameters:
sessiontime_
duration_
get_period(_session, _start, _lookback)
Parameters:
_session
_start
_lookback
is_start(_session)
Parameters:
_session
is_end(_session)
Parameters:
_session
draw_progress(_show, _session, _is_started, _is_ended, _color, _bottom, _delete_history)
Parameters:
_show
_session
_is_started
_is_ended
_color
_bottom
_delete_history
draw_label(_show, _session, _is_started, _color, _top, _bottom, _text, _delete_history, i_label_chg, i_label_size, i_label_position, i_tz, i_label_format_day)
Parameters:
_show
_session
_is_started
_color
_top
_bottom
_text
_delete_history
i_label_chg
i_label_size
i_label_position
i_tz
i_label_format_day
draw_fib(_show, _session, _is_started, _color, _top, _bottom, _level, _width, _style, _is_extend, _delete_history)
Parameters:
_show
_session
_is_started
_color
_top
_bottom
_level
_width
_style
_is_extend
_delete_history
get_op_stricts(_session, _is_started, top, bottom, i_o_minutes)
Parameters:
_session
_is_started
top
bottom
i_o_minutes
draw_op(_show, _session, _is_started, _color, top, bottom, _is_extend, _delete_history, i_o_minutes, i_o_opacity)
Parameters:
_show
_session
_is_started
_color
top
bottom
_is_extend
_delete_history
i_o_minutes
i_o_opacity
get_pm_stricts(_show, _show_pm, tf, ctf, _is_started)
Parameters:
_show
_show_pm
tf
ctf
_is_started
draw_pm(_show, _show_pm, tf, ctf, _is_started, _is_ended, _delete_history, _color)
Parameters:
_show
_show_pm
tf
ctf
_is_started
_is_ended
_delete_history
_color
draw_market(_show, _session, _is_started, _color, btr, _top, _bottom, _extend, _is_extend, _delete_history, i_sess_border_style, i_sess_border_width, i_sess_bgopacity)
Parameters:
_show
_session
_is_started
_color
btr
_top
_bottom
_extend
_is_extend
_delete_history
i_sess_border_style
i_sess_border_width
i_sess_bgopacity
draw(_show, _show_pm, pm_tf, ctf, _session, _color, btr, _label, _extend, _show_fib, _show_op, i_label_chg, i_label_size, i_label_position, i_o_minutes, i_o_opacity, i_sess_border_style, i_sess_border_width, i_sess_bgopacity, i_show_history, i_show_closed, i_label_show, i_f_linewidth, i_f_linestyle, top, bottom, i_tz, i_label_format_day)
Parameters:
_show
_show_pm
pm_tf
ctf
_session
_color
btr
_label
_extend
_show_fib
_show_op
i_label_chg
i_label_size
i_label_position
i_o_minutes
i_o_opacity
i_sess_border_style
i_sess_border_width
i_sess_bgopacity
i_show_history
i_show_closed
i_label_show
i_f_linewidth
i_f_linestyle
top
bottom
i_tz
i_label_format_day
UtilitiesLibrary "Utilities"
My utility functions library.
toPips(_v)
Convert price to pips.
Parameters:
_v : Price
Returns: Pips
toPrice(_p)
Convert pips to price.
Parameters:
_p
Returns: Price
price_range(_a, _b)
The difference will be returned.
Parameters:
_a
_b : @return Price as positive number
get_day(_n, _lang)
Get the day of the week
Parameters:
_n : Number of day of week
_lang : en or ja
source(_name)
TODO: add function description here
Parameters:
_name
Returns: TODO: add what function returns
clear_lines(_arr, _min)
Deletes the lines included in the array.
Parameters:
_arr : Array of lines
_min : Deletes the lines included in the array.
clear_labels(_arr, _min)
Deletes the labels included in the array.
Parameters:
_arr : Array of labels
_min : Deletes the labels included in the array.
clear_boxes(_arr, _min)
Deletes the boxes included in the array.
Parameters:
_arr : Array of boxes
_min : Deletes the boxes included in the array.
MLExtensionsLibrary "MLExtensions"
normalizeDeriv(src, quadraticMeanLength)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the first-order derivative for price).
quadraticMeanLength : The length of the quadratic mean (RMS).
Returns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
Rescales a source value with an unbounded range to a target range.
Parameters:
src : The input series
min : The minimum value of the unbounded range
max : The maximum value of the unbounded range
Returns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
Rescales a source value with a bounded range to anther bounded range
Parameters:
src : The input series
oldMin : The minimum value of the range to rescale from
oldMax : The maximum value of the range to rescale from
newMin : The minimum value of the range to rescale to
newMax : The maximum value of the range to rescale to
Returns: The rescaled series
color_green(prediction)
Assigns varying shades of the color green based on the KNN classification
Parameters:
prediction : Value (int|float) of the prediction
Returns: color
color_red(prediction)
Assigns varying shades of the color red based on the KNN classification
Parameters:
prediction : Value of the prediction
Returns: color
tanh(src)
Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
Parameters:
src : The input series (i.e., the normalized derivative).
Returns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the hyperbolic tangent).
lookback : The lookback window for the smoothing.
Returns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
Returns the tanh transform of the input series.
Parameters:
src : The input series (i.e., the result of the tanh calculation).
smoothingFrequency
quadraticMeanLength
Returns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
Returns the normalized RSI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the RSI calculation).
n1 : The length of the RSI.
n2 : The smoothing length of the RSI.
Returns: signal The normalized RSI.
n_cci(src, n1, n2)
Returns the normalized CCI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the CCI calculation).
n1 : The length of the CCI.
n2 : The smoothing length of the CCI.
Returns: signal The normalized CCI.
n_wt(src, n1, n2)
Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the WaveTrend Classic calculation).
n1
n2
Returns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
Returns the normalized ADX ideal for use in ML algorithms.
Parameters:
highSrc : The input series for the high price.
lowSrc : The input series for the low price.
closeSrc : The input series for the close price.
n1 : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
Parameters:
src
threshold
useRegimeFilter
filter_adx(src, length, adxThreshold, useAdxFilter)
filter_adx
Parameters:
src : The source series.
length : The length of the ADX.
adxThreshold : The ADX threshold.
useAdxFilter : Whether to use the ADX filter.
Returns: The ADX.
filter_volatility(minLength, maxLength, useVolatilityFilter)
filter_volatility
Parameters:
minLength : The minimum length of the ATR.
maxLength : The maximum length of the ATR.
useVolatilityFilter : Whether to use the volatility filter.
Returns: Boolean indicating whether or not to let the signal pass through the filter.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex, thisBarIndex)
Performs a basic backtest using the specified parameters and conditions.
Parameters:
high : The input series for the high price.
low : The input series for the low price.
open : The input series for the open price.
startLongTrade : The series of conditions that indicate the start of a long trade.`
endLongTrade : The series of conditions that indicate the end of a long trade.
startShortTrade : The series of conditions that indicate the start of a short trade.
endShortTrade : The series of conditions that indicate the end of a short trade.
isStopLossHit : The stop loss hit indicator.
maxBarsBackIndex : The maximum number of bars to go back in the backtest.
thisBarIndex : The current bar index.
Returns: A tuple containing backtest values
init_table()
init_table()
Returns: tbl The backtest results.
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, stopLosses)
update_table(tbl, tradeStats)
Parameters:
tbl : The backtest results table.
tradeStatsHeader : The trade stats header.
totalTrades : The total number of trades.
totalWins : The total number of wins.
totalLosses : The total number of losses.
winLossRatio : The win loss ratio.
winrate : The winrate.
stopLosses : The total number of stop losses.
Returns: Updated backtest results table.
BasicVisibleChartBasic library for the visible range chart; with functions to allow plotting Fibs from body high/low as well as wick high/low
-Thanks to code from @PineCoders Visible Chart library (PineCoders/VisibleChart/4), which is a much more comprehensive library than this, but which does not include some functions that I find useful:
-Added the following exportable functions: highest/lowest body, highest/lowest close, highest/lowest open. These allow one to anchor fibs from bodies rather than wicks
-Added a Fib Box function in the example code
The above chart shows the example code plotting a Fib range drawn from bodies and a highlighted retracement zone (61.8 % - 78.6% )
~~All Exportable Functions~~
barIsVisible()
highestClose()
highestOpen()
highestBody()
lowestClose()
lowestOpen()
lowestBody()
high()
highBarTime()
low()
lowBarTime()
open()
close()
theme_presetsStyle Made Easy with 175 Reversable light/dark themes
Built on to of my theme engine, so any tools built with one
will work with the other.
getTheme(_input)
Get a theme by name. (see lib for copy/paste list)
Parameters:
_input : string Name of Theme to use.
apathy()
Theme preset -> "Apathy"
Returns: Theme object
apprentice()
Theme preset -> "Apprentice"
Returns: Theme object
ashes()
Theme preset -> "Ashes"
Returns: Theme object
atelier_cave()
Theme preset -> "Atelier Cave"
Returns: Theme object
atelier_dune()
Theme preset -> "Atelier Dune"
Returns: Theme object
atelier_estuary()
Theme preset -> "Atelier Estuary"
Returns: Theme object
atelier_forest()
Theme preset -> "Atelier Forest"
Returns: Theme object
atelier_heath()
Theme preset -> "Atelier Heath"
Returns: Theme object
atelier_lakeside()
Theme preset -> "Atelier Lakeside"
Returns: Theme object
atelier_plateau()
Theme preset -> "Atelier Plateau"
Returns: Theme object
atelier_savanna()
Theme preset -> "Atelier Savanna"
Returns: Theme object
atelier_seaside()
Theme preset -> "Atelier Seaside"
Returns: Theme object
atelier_sulphurpool()
Theme preset -> "Atelier Sulphurpool"
Returns: Theme object
atlas()
Theme preset -> "Atlas"
Returns: Theme object
ayu()
Theme preset -> "Ayu"
Returns: Theme object
ayu_mirage()
Theme preset -> "Ayu Mirage"
Returns: Theme object
bespin()
Theme preset -> "Bespin"
Returns: Theme object
black_metal()
Theme preset -> "Black Metal"
Returns: Theme object
black_metal_bathory()
Theme preset -> "Black Metal (bathory)"
Returns: Theme object
black_metal_burzum()
Theme preset -> "Black Metal (burzum)"
Returns: Theme object
black_metal_funeral()
Theme preset -> "Black Metal (dark Funeral)"
Returns: Theme object
black_metal_gorgoroth()
Theme preset -> "Black Metal (gorgoroth)"
Returns: Theme object
black_metal_immortal()
Theme preset -> "Black Metal (immortal)"
Returns: Theme object
black_metal_khold()
Theme preset -> "Black Metal (khold)"
Returns: Theme object
black_metal_marduk()
Theme preset -> "Black Metal (marduk)"
Returns: Theme object
black_metal_mayhem()
Theme preset -> "Black Metal (mayhem)"
Returns: Theme object
black_metal_nile()
Theme preset -> "Black Metal (nile)"
Returns: Theme object
black_metal_venom()
Theme preset -> "Black Metal (venom)"
Returns: Theme object
blue_forest()
Theme preset -> "Blue Forest"
Returns: Theme object
blueish()
Theme preset -> "Blueish"
Returns: Theme object
brewer()
Theme preset -> "Brewer"
Returns: Theme object
bright()
Theme preset -> "Bright"
Returns: Theme object
brogrammer()
Theme preset -> "Brogrammer"
Returns: Theme object
brush_trees()
Theme preset -> "Brush Trees"
Returns: Theme object
catppuccin()
Theme preset -> "Catppuccin"
Returns: Theme object
chalk()
Theme preset -> "Chalk"
Returns: Theme object
circus()
Theme preset -> "Circus"
Returns: Theme object
classic()
Theme preset -> "Classic"
Returns: Theme object
clrs()
Theme preset -> "Colors"
Returns: Theme object
codeschool()
Theme preset -> "Codeschool"
Returns: Theme object
cupcake()
Theme preset -> "Cupcake"
Returns: Theme object
cupertino()
Theme preset -> "Cupertino"
Returns: Theme object
da_one_black()
Theme preset -> "Da One Black"
Returns: Theme object
da_one_gray()
Theme preset -> "Da One Gray"
Returns: Theme object
da_one_ocean()
Theme preset -> "Da One Ocean"
Returns: Theme object
da_one_paper()
Theme preset -> "Da One Paper"
Returns: Theme object
da_one_sea()
Theme preset -> "Da One Sea"
Returns: Theme object
da_one_white()
Theme preset -> "Da One White"
Returns: Theme object
danqing()
Theme preset -> "Danqing"
Returns: Theme object
darcula()
Theme preset -> "Darcula"
Returns: Theme object
dark_violet()
Theme preset -> "Dark Violet"
Returns: Theme object
darkmoss()
Theme preset -> "Darkmoss"
Returns: Theme object
darktooth()
Theme preset -> "Darktooth"
Returns: Theme object
decaf()
Theme preset -> "Decaf"
Returns: Theme object
dirtysea()
Theme preset -> "Dirtysea"
Returns: Theme object
dracula()
Theme preset -> "Dracula"
Returns: Theme object
edge()
Theme preset -> "Edge"
Returns: Theme object
eighties()
Theme preset -> "Eighties"
Returns: Theme object
embers()
Theme preset -> "Embers"
Returns: Theme object
emil()
Theme preset -> "Emil"
Returns: Theme object
equilibrium()
Theme preset -> "Equilibrium"
Returns: Theme object
equilibrium_gray()
Theme preset -> "Equilibrium Gray"
Returns: Theme object
espresso()
Theme preset -> "Espresso"
Returns: Theme object
eva()
Theme preset -> "Eva"
Returns: Theme object
everforest()
Theme preset -> "Everforest"
Returns: Theme object
flat()
Theme preset -> "Flat"
Returns: Theme object
framer()
Theme preset -> "Framer"
Returns: Theme object
fruit_soda()
Theme preset -> "Fruit Soda"
Returns: Theme object
gigavolt()
Theme preset -> "Gigavolt"
Returns: Theme object
github()
Theme preset -> "Github"
Returns: Theme object
google()
Theme preset -> "Google"
Returns: Theme object
gotham()
Theme preset -> "Gotham"
Returns: Theme object
grayscale()
Theme preset -> "Grayscale"
Returns: Theme object
green_screen()
Theme preset -> "Green Screen"
Returns: Theme object
gruber()
Theme preset -> "Gruber"
Returns: Theme object
gruvbox_hard()
Theme preset -> "Gruvbox Dark, Hard"
Returns: Theme object
gruvbox_medium()
Theme preset -> "Gruvbox Dark, Medium"
Returns: Theme object
gruvbox_pale()
Theme preset -> "Gruvbox Dark, Pale"
Returns: Theme object
gruvbox_soft()
Theme preset -> "Gruvbox Dark, Soft"
Returns: Theme object
gruvbox_material_hard()
Theme preset -> "Gruvbox Material Dark, Hard"
Returns: Theme object
gruvbox_material_medium()
Theme preset -> "Gruvbox Material Dark, Medium"
Returns: Theme object
gruvbox_material_soft()
Theme preset -> "Gruvbox Material Dark, Soft"
Returns: Theme object
hardcore()
Theme preset -> "Hardcore"
Returns: Theme object
harmonic16()
Theme preset -> "Harmonic16"
Returns: Theme object
heetch()
Theme preset -> "Heetch"
Returns: Theme object
helios()
Theme preset -> "Helios"
Returns: Theme object
hopscotch()
Theme preset -> "Hopscotch"
Returns: Theme object
horizon()
Theme preset -> "Horizon"
Returns: Theme object
horizon_terminal()
Theme preset -> "Horizon Terminal"
Returns: Theme object
humanoid()
Theme preset -> "Humanoid"
Returns: Theme object
ia()
Theme preset -> "Ia"
Returns: Theme object
icy()
Theme preset -> "Icy"
Returns: Theme object
ir_black()
Theme preset -> "Ir Black"
Returns: Theme object
isotope()
Theme preset -> "Isotope"
Returns: Theme object
kanagawa()
Theme preset -> "Kanagawa"
Returns: Theme object
katy()
Theme preset -> "Katy"
Returns: Theme object
kimber()
Theme preset -> "Kimber"
Returns: Theme object
lime()
Theme preset -> "Lime"
Returns: Theme object
london_tube()
Theme preset -> "London Tube"
Returns: Theme object
macintosh()
Theme preset -> "Macintosh"
Returns: Theme object
marrakesh()
Theme preset -> "Marrakesh"
Returns: Theme object
materia()
Theme preset -> "Materia"
Returns: Theme object
material()
Theme preset -> "Material"
Returns: Theme object
materialdarker()
Theme preset -> "Material Darker"
Returns: Theme object
material_palenight()
Theme preset -> "Material Palenight"
Returns: Theme object
material_vivid()
Theme preset -> "Material Vivid"
Returns: Theme object
mellow_purple()
Theme preset -> "Mellow Purple"
Returns: Theme object
mocha()
Theme preset -> "Mocha"
Returns: Theme object
monokai()
Theme preset -> "Monokai"
Returns: Theme object
Nebula()
Theme preset -> "Nebula"
Returns: Theme object
nord()
Theme preset -> "Nord"
Returns: Theme object
nova()
Theme preset -> "Nova"
Returns: Theme object
ocean()
Theme preset -> "Ocean"
Returns: Theme object
oceanicnext()
Theme preset -> "Oceanicnext"
Returns: Theme object
onedark()
Theme preset -> "Onedark"
Returns: Theme object
outrun()
Theme preset -> "Outrun"
Returns: Theme object
pandora()
Theme preset -> "Pandora"
Returns: Theme object
papercolor()
Theme preset -> "Papercolor"
Returns: Theme object
paraiso()
Theme preset -> "Paraiso"
Returns: Theme object
pasque()
Theme preset -> "Pasque"
Returns: Theme object
phd()
Theme preset -> "Phd"
Returns: Theme object
pico()
Theme preset -> "Pico"
Returns: Theme object
pinky()
Theme preset -> "Pinky"
Returns: Theme object
pop()
Theme preset -> "Pop"
Returns: Theme object
porple()
Theme preset -> "Porple"
Returns: Theme object
primer()
Theme preset -> "Primer"
Returns: Theme object
purpledream()
Theme preset -> "Purpledream"
Returns: Theme object
qualia()
Theme preset -> "Qualia"
Returns: Theme object
railscasts()
Theme preset -> "Railscasts"
Returns: Theme object
rebecca()
Theme preset -> "Rebecca"
Returns: Theme object
rose_pine()
Theme preset -> "Rosé Pine"
Returns: Theme object
rose_pine_dawn()
Theme preset -> "Rosé Pine Dawn"
Returns: Theme object
rose_pine_moon()
Theme preset -> "Rosé Pine Moon"
Returns: Theme object
sagelight()
Theme preset -> "Sagelight"
Returns: Theme object
sakura()
Theme preset -> "Sakura"
Returns: Theme object
sandcastle()
Theme preset -> "Sandcastle"
Returns: Theme object
seti_ui()
Theme preset -> "Seti Ui"
Returns: Theme object
shades_of_purple()
Theme preset -> "Shades Of Purple"
Returns: Theme object
shadesmear()
Theme preset -> "Shadesmear"
Returns: Theme object
shapeshifter()
Theme preset -> "Shapeshifter"
Returns: Theme object
silk()
Theme preset -> "Silk"
Returns: Theme object
snazzy()
Theme preset -> "Snazzy"
Returns: Theme object
solar_flare()
Theme preset -> "Solar Flare"
Returns: Theme object
solarized()
Theme preset -> "Solarized"
Returns: Theme object
spaceduck()
Theme preset -> "Spaceduck"
Returns: Theme object
spacemacs()
Theme preset -> "Spacemacs"
Returns: Theme object
stella()
Theme preset -> "Stella"
Returns: Theme object
still_alive()
Theme preset -> "Still Alive"
Returns: Theme object
summercamp()
Theme preset -> "Summercamp"
Returns: Theme object
summerfruit()
Theme preset -> "Summerfruit"
Returns: Theme object
synth_midnight_terminal()
Theme preset -> "Synth Midnight Terminal"
Returns: Theme object
tango()
Theme preset -> "Tango"
Returns: Theme object
tender()
Theme preset -> "Tender"
Returns: Theme object
tokyo_city()
Theme preset -> "Tokyo City"
Returns: Theme object
tokyo_city_terminal()
Theme preset -> "Tokyo City Terminal"
Returns: Theme object
tokyo_night()
Theme preset -> "Tokyo Night"
Returns: Theme object
tokyo_night_storm()
Theme preset -> "Tokyo Night Storm"
Returns: Theme object
tokyo_night_terminal()
Theme preset -> "Tokyo Night Terminal"
Returns: Theme object
tokyo_night_terminal_storm()
Theme preset -> "Tokyo Night Terminal Storm"
Returns: Theme object
tokyodark()
Theme preset -> "Tokyodark"
Returns: Theme object
tokyodark_terminal()
Theme preset -> "Tokyodark Terminal"
Returns: Theme object
tomorrow()
Theme preset -> "Tomorrow"
Returns: Theme object
tomorrow_night()
Theme preset -> "Tomorrow Night"
Returns: Theme object
tomorrow_night_eighties()
Theme preset -> "Tomorrow Night Eighties"
Returns: Theme object
twilight()
Theme preset -> "Twilight"
Returns: Theme object
unikitty()
Theme preset -> "Unikitty"
Returns: Theme object
unikitty_reversible()
Theme preset -> "Unikitty Reversible"
Returns: Theme object
uwunicorn()
Theme preset -> "Uwunicorn"
Returns: Theme object
vice()
Theme preset -> "Vice"
Returns: Theme object
vulcan()
Theme preset -> "Vulcan"
Returns: Theme object
windows_10()
Theme preset -> "Windows 10"
Returns: Theme object
windows_95()
Theme preset -> "Windows 95"
Returns: Theme object
windows_high_contrast()
Theme preset -> "Windows High Contrast"
Returns: Theme object
windows_nt()
Theme preset -> "Windows Nt"
Returns: Theme object
woodland()
Theme preset -> "Woodland"
Returns: Theme object
xcode_dusk()
Theme preset -> "Xcode Dusk"
Returns: Theme object
theme_engineLibrary "theme_engine"
Theme Builder and Structure for live generative themes
init(_name)
New theme object.
Parameters:
_name : (string) opptional name
Returns: a VAR theme (holds it's vals when updated if not overwritten)
globals(theme, _h1, _h2, _h3, _h4, _s, _val, _contrast)
Create light/dark theme globals
Parameters:
theme : (theme) Theme to add theses to
_h1 : (float) Hue #1 for Template
_h2 : (float) Hue #2 for Template
_h3 : (float) Hue #3 for Template
_h4 : (float) Hue #4 for Template
_s : (float) Saturation of theme
_val : (float) Luminosity (light/dark)
_contrast : (float) Contrast to apply
Returns: Theme wwith adjusted colors
setConfig(theme, setting)
Apply a Settings object to a theme
Parameters:
theme : Theme object to apply settings to.
setting : settings to apply
Returns: theme
Types :
settings
Settings for a theme
Fields:
h1 : (float) Hue #1 for Template
h2 : (float) Hue #2 for Template
h3 : (float) Hue #3 for Template
h4 : (float) Hue #4 for Template
sat : (float) Saturation of theme
lum : (float) Luminosity (light/dark)
vib : (float) Vibrance (Contrast)
r : (float) Hue of Red
o : (float) Hue of Orange
y : (float) Hue of Yellow
g : (float) Hue of Green
a : (float) Hue of Aqua
b : (float) Hue of Blue
i : (float) Hue of Indigo
v : (float) Hue of Violet
satvals : (settings) Array for use if desired to customize Saturation per color
lumvals : (settings) Array for use if desired to customize Luminancce per color
mods
Modifiers Item for Use if desired
Fields:
val : (float)
size : (float)
depth : (float)
hue : (float)
sat : (float)
alpha : (float)
mix : (float)
emit : (float)
ch : (float)
step : (int)
dist : (int)
holds : (mods)
isin : (mods)
track : (color)
varient
Light/Dark/Custom Theme Varients
Fields:
bg : (color) Bacckground Color
fg : (color) Foreground Color
accent : (color) Accccent Color
secondary : (color) Secondary Color
txt : (color) Text Color
theme
Theme Object
Fields:
name : (string) Theme name
dark : (varient) Theme dark Varient
light : (varient) Theme light Varient
red : (color) Color for red
orange : (color) Color for orange
yellow : (color) Color for yellow
green : (color) Color for green
aqua : (color) Color for aqua
blue : (color) Color for blue
purple : (color) Color for purple
pink : (color) Color for pink
tweaks : (mods) Modifiers UDT to use for adjusters
themedict
Fields:
names : (string ) Names of themes
themes : (theme ) Theme Items
MyLibraryLibrary "MyLibrary"
TODO: add library description here
isHammer(fib, colorMatch)
TODO: add function description here
Parameters:
fib
colorMatch
Returns: TODO: add what function returns
eHarmonicpatternsLogScaleLibrary "eHarmonicpatternsLogScale"
Library provides functions to scan harmonic patterns both or normal and log scale
getSupportedPatterns()
get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides PRZ range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Start and end of consolidated PRZ range
get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides PRZ range based on XAD range only
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Start and end of consolidated PRZ range
get_projection_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale)
Provides Projection range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
logScale : - calculate on log scale. Default is false
Returns: Array containing start and end ranges
isHarmonicPattern(x, a, b, c, d, flags, defaultEnabled, errorPercent, logScale)
Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
defaultEnabled
errorPercent : Error threshold
logScale : - calculate on log scale. Default is false
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, b, c, flags, defaultEnabled, errorPercent, logScale)
Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
defaultEnabled
errorPercent : Error threshold
logScale : - calculate on log scale. Default is false
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
E5TradingLibrary
This library replaces the previous MetaWorldEngineFilterLibrary3.
Library "E5TradingLibrary"
GetCandleStickSize(_src_high, _src_low)
returns size of the candle
Parameters:
_src_high
_src_low
Returns: candlestick size
GetCandleStickBodySize(_src_open, _src_close)
returns size of the candle body
Parameters:
_src_open
_src_close
Returns: candlestick body size
FilterLongerLowerWickCandles(_src_open, _src_close, _src_low)
Alters Candlestick Value to Magnify Candles with Long Wicks
Parameters:
_src_open
_src_close
_src_low
Returns: Midpoint of the candle body less the lower wick. If value returned has a large delta from midpoint of the body, then it is short wick
IsBullish(_src_open, _src_close)
Determine if Candle is Bullish or Bearish
Parameters:
_src_open
_src_close
Returns: True is Bullish
IsDoji(_candleIndex, _precision)
Determine if Candle is a Doji
Parameters:
_candleIndex
_precision
Returns: True if a Doji
MACD(_src, _fastLength, _slowLength, _signalLength)
Computes MACD
Parameters:
_src
_fastLength
_slowLength
_signalLength
Returns: Returns MACD and Signal Line
isFastSlowCrossed(SeriesA, SeriesB)
Computes if SeriesA crosses SeriesB
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses SeriesB then true else false
isReversalUpTrend(SeriesA, SeriesB)
Computes if SeriesA crosses over SeriesB to determine reversal uptrend
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses over SeriesB then true else false
isReversalDownTrend(SeriesA, SeriesB)
Computes if SeriesA crosses over SeriesB to determine reversal uptrend
Parameters:
SeriesA
SeriesB
Returns: if SeriesA crosses over SeriesB then true else false
SSMA(_src, smalength)
Computes smoothed SMA
Parameters:
_src
smalength
Returns: a single concatenated string for evaluation
GetTimeFrame()
Get Current timeframe in minutes
Returns: an integer value in minutes
getMA(_src, length, maType)
Gets a Moving Average based on type
Parameters:
_src
length
maType
Returns: A moving average with the given parameters
ATRSwitch(_src, _ATRMult, _ATRLength)
Average True Range Trailing Stops by Sylvain Vervoort
Parameters:
_src
_ATRMult
_ATRLength
Returns: upper ATR Line, lower ATR Line and the switch point
FibRatiosLibrary "FibRatios"
Library with calculation logic for fib retracement, extension and ratios
retracement(a, b, ratio, logScale, precision)
Calculates the retracement for points a, b with given ratio and scale
Parameters:
a : Starting point a
b : Second point b
ratio : Ratio for which we need to calculate retracement c
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: retracement point c for points a,b with given ratio and scale
retracementRatio(a, b, c, logScale, precision)
Calculates the retracement ratio for points a, b, c with given scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: retracement ratio for points a,b,c on given scale
extension(a, b, c, ratio, logScale, precision)
Calculates the extensions for points a, b, c with given ratio and scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
ratio : Ratio for which we need to calculate extension d
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: extensoin point d for points a,b,c with given ratio and scale
extensionRatio(a, b, c, d, logScale, precision)
Calculates the extension ratio for points a, b, c, d with given scale
Parameters:
a : Starting point a
b : Second point b
c : Retracement point. c should be placed between a and b
d : Extension point. d should be placed beyond a, c. But, can be with b,c or beyond b
logScale : Flag to get calculations in log scale. Default is false
precision : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: extension ratio for points a,b,c,d on given scale
DataCorrelationLibrary "DataCorrelation"
Implementation of functions related to data correlation calculations. Formulas have been transformed in such a way that we avoid running loops and instead make use of time series to gradually build the data we need to perform calculation. This allows the calculations to run on unbound series, and/or higher number of samples
🎲 Simplifying Covariance
Original Formula
//For Sample
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1)
//For Population
Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n
Now, if we look at numerator, this can be simplified as follows
∑ ((xᵢ-x̄)(yᵢ-ȳ))
=> (x₁-x̄)(y₁-ȳ) + (x₂-x̄)(y₂-ȳ) + (x₃-x̄)(y₃-ȳ) ... + (xₙ-x̄)(yₙ-ȳ)
=> (x₁y₁ + x̄ȳ - x₁ȳ - y₁x̄) + (x₂y₂ + x̄ȳ - x₂ȳ - y₂x̄) + (x₃y₃ + x̄ȳ - x₃ȳ - y₃x̄) ... + (xₙyₙ + x̄ȳ - xₙȳ - yₙx̄)
=> (x₁y₁ + x₂y₂ + x₃y₃ ... + xₙyₙ) + (x̄ȳ + x̄ȳ + x̄ȳ ... + x̄ȳ) - (x₁ȳ + x₂ȳ + x₃ȳ ... xₙȳ) - (y₁x̄ + y₂x̄ + y₃x̄ + yₙx̄)
=> ∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ
So, overall formula can be simplified to be used in pine as
//For Sample
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / (n-1)
//For Population
Covₓᵧ = (∑xᵢyᵢ + n(x̄ȳ) - ȳ∑xᵢ - x̄∑yᵢ) / n
🎲 Simplifying Standard Deviation
Original Formula
//For Sample
σ = √(∑(xᵢ-x̄)² / (n-1))
//For Population
σ = √(∑(xᵢ-x̄)² / n)
Now, if we look at numerator within square root
∑(xᵢ-x̄)²
=> (x₁² + x̄² - 2x₁x̄) + (x₂² + x̄² - 2x₂x̄) + (x₃² + x̄² - 2x₃x̄) ... + (xₙ² + x̄² - 2xₙx̄)
=> (x₁² + x₂² + x₃² ... + xₙ²) + (x̄² + x̄² + x̄² ... + x̄²) - (2x₁x̄ + 2x₂x̄ + 2x₃x̄ ... + 2xₙx̄)
=> ∑xᵢ² + nx̄² - 2x̄∑xᵢ
=> ∑xᵢ² + x̄(nx̄ - 2∑xᵢ)
So, overall formula can be simplified to be used in pine as
//For Sample
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / (n-1))
//For Population
σ = √(∑xᵢ² + x̄(nx̄ - 2∑xᵢ) / n)
🎲 Using BinaryInsertionSort library
Chatterjee Correlation and Spearman Correlation functions make use of BinaryInsertionSort library to speed up sorting. The library in turn implements mechanism to insert values into sorted order so that load on sorting is reduced by higher extent allowing the functions to work on higher sample size.
🎲 Function Documentation
chatterjeeCorrelation(x, y, sampleSize, plotSize)
Calculates chatterjee correlation between two series. Formula is - ξnₓᵧ = 1 - (3 * ∑ |rᵢ₊₁ - rᵢ|)/ (n²-1)
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Chatterjee correlation value if falls within plotSize, else returns na
spearmanCorrelation(x, y, sampleSize, plotSize)
Calculates spearman correlation between two series. Formula is - ρ = 1 - (6∑dᵢ²/n(n²-1))
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
sampleSize : number of samples to be considered for calculattion of correlation. Default is 20000
plotSize : How many historical values need to be plotted on chart.
Returns: float correlation - Spearman correlation value if falls within plotSize, else returns na
covariance(x, y, include, biased)
Calculates covariance between two series of unbound length. Formula is Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / (n-1) for sample and Covₓᵧ = ∑ ((xᵢ-x̄)(yᵢ-ȳ)) / n for population
Parameters:
x : First series for which covariance need to be calculated
y : Second series for which covariance need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float covariance - covariance of selective samples of two series x, y
stddev(x, include, biased)
Calculates Standard Deviation of a series. Formula is σ = √( ∑(xᵢ-x̄)² / n ) for sample and σ = √( ∑(xᵢ-x̄)² / (n-1) ) for population
Parameters:
x : Series for which Standard Deviation need to be calculated
include : boolean flag used for selectively including sample
biased : boolean flag representing population covariance instead of sample covariance
Returns: float stddev - standard deviation of selective samples of series x
correlation(x, y, include)
Calculates pearson correlation between two series of unbound length. Formula is r = Covₓᵧ / σₓσᵧ
Parameters:
x : First series for which correlation need to be calculated
y : Second series for which correlation need to be calculated
include : boolean flag used for selectively including sample
Returns: float correlation - correlation between selective samples of two series x, y
HiveLibraryLibrary "HiveLibrary"
: Custom library
RoundDown(number, decimals)
RoundDown() rounds the specified number down to the given number
of decimal places.
Parameters:
number : is the argument for rounding down & decimals is the number of digits after dot
decimals
Returns: return is the rounded down value of the number
JeeSauceScriptsLibrary "JeeSauceScripts"
getupdnvol()
GetTotalUpVolume(upvolume)
Parameters:
upvolume
GetTotalDnVolume(downvolume)
Parameters:
downvolume
GetDelta(totalupvolume, totaldownvolume)
Parameters:
totalupvolume
totaldownvolume
GetMaxUpVolume(upvolume)
Parameters:
upvolume
GetMaxDnVolume(downvolume)
Parameters:
downvolume
Getcvd()
Getcvdopen(cvd)
Parameters:
cvd
Getcvdhigh(cvd, maxvolumeup)
Parameters:
cvd
maxvolumeup
Getcvdlow(cvd, maxvolumedown)
Parameters:
cvd
maxvolumedown
Getcvdclose(cvd, delta)
Parameters:
cvd
delta
CombineData(data1, data2, data3, data4, data5, data6)
Parameters:
data1
data2
data3
data4
data5
data6
FindData(data, find)
Parameters:
data
find
MyLibraryLibrary "MyLibrary"
TODO: add library description here
init(value)
Parameters:
value
set(source, value)
Parameters:
source
value
get(source)
Parameters:
source
Motion▮ FEATURES
Now as library version :)
String-based transition-effects
Performance optimization. Reduced memory consumption up to >90% by kicking the output to the "stdout".
Use marquee- or loader-effect on any possible string location.
Example: UI Price-Ticker
----------------------------------------------------------------------------
Library "Motion"
_getStringMono(_len, _str, _sep)
Parameters:
_len
_str
_sep
marquee(this, _extern, _ws, _subLen, _subStart)
Parameters:
this
_extern
_ws
_subLen
_subStart
transition(this, _subLen, _subStart)
Parameters:
this
_subLen
_subStart
hold(this)
Parameters:
this
keyframe
keyframe A keyframe object.
Fields:
seq
intv
step
length
update_no
frame_no
ltr
hold
Replica of TradingView's Backtesting Engine with ArraysHello everyone,
Here is a perfectly replicated TradingView backtesting engine condensed into a single library function calculated with arrays. It includes TradingView's calculations for Net profit, Total Trades, Percent of Trades Profitable, Profit Factor, Max Drawdown (absolute and percent), and Average Trade (absolute and percent). Here's how TradingView defines each aspect of its backtesting system:
Net Profit: The overall profit or loss achieved.
Total Trades: The total number of closed trades, winning and losing.
Percent Profitable: The percentage of winning trades, the number of winning trades divided by the total number of closed trades.
Profit Factor: The amount of money the strategy made for every unit of money it lost, gross profits divided by gross losses.
Max Drawdown: The greatest loss drawdown, i.e., the greatest possible loss the strategy had compared to its highest profits.
Average Trade: The sum of money gained or lost by the average trade, Net Profit divided by the overall number of closed trades.
Here's how each variable is defined in the library function:
_backtest(bool _enter, bool _exit, float _startQty, float _tradeQty)
bool _enter: When the strategy should enter a trade (entry condition)
bool _exit: When the strategy should exit a trade (exit condition)
float _startQty: The starting capital in the account (for BTCUSD, it is the amount of USD the account starts with)
float _tradeQty: The amount of capital traded (if set to 1000 on BTCUSD, it will trade 1000 USD on each trade)
Currently, this library only works with long strategies, and I've included a commented out section under DEMO STRATEGY where you can replicate my results with TradingView's backtesting engine. There's tons I could do with this beyond what is shown, but this was a project I worked on back in June of 2022 before getting burned out. Feel free to comment with any suggestions or bugs, and I'll try to add or fix them all soon. Here's my list of thing to add to the library currently (may not all be added):
Add commission calculations.
Add support for shorting
Add a graph that resembles TradingView's overview graph.
Clean and optimize code.
Clean up in a way that makes it easy to add other TradingView calculations (such as Sharpe and Sortino ratio).
Separate all variables, so they become accessible outside of calculations (such as gross profit, gross loss, number of winning trades, number of losing trades, etc.).
Thanks for reading,
OztheWoz