MLPivotsBreakoutsLibrary "MLPivotsBreakouts"
Utilizes k-NN machine learning to predict breakout zones from pivot points, aiding traders in identifying potential bullish and bearish market movements. Ideal for trend-following and breakout strategies.
breakouts(source, pivotBars, numNeighbors, maxData, predictionSmoothing)
Parameters:
source (float) : series float: Price data for analysis.
pivotBars (int) : int: Number of bars for pivot point detection.
numNeighbors (int) : int: Neighbors count for k-NN prediction.
maxData (int) : int: Maximum pivot data points for analysis.
predictionSmoothing (int) : int: Smoothing period for predictions.
@return : Lower and higher prediction bands plus pivot signal, 1 for ph and -1 for pl.
Penunjuk dan strategi
DynamicMAsLibrary "DynamicMAs"
Custom MA's that allow a dynamic calculation beginning from the first bar, irrespective of lookback period.
SMA(src, length)
Dynamic SMA
Parameters:
src (float)
length (int)
EMA(src, length)
Dynamic EMA
Parameters:
src (float)
length (int)
DEMA(src, length)
Dynamic DEMA
Parameters:
src (float)
length (int)
TEMA(src, length)
Dynamic TEMA
Parameters:
src (float)
length (int)
WMA(src, length)
Dynamic WMA
Parameters:
src (float)
length (int)
HMA(src, length)
Dynamic HMA
Parameters:
src (float)
length (int)
VWMA(src, length)
Dynamic VWMA
Parameters:
src (float)
length (int)
SMMA(src, length)
Dynamic SMMA
Parameters:
src (float)
length (int)
LSMA(src, length)
Dynamic LSMA
Parameters:
src (float)
length (int)
ALMA(src, length, offset_sigma, sigma)
Dynamic ALMA
Parameters:
src (float)
length (int)
offset_sigma (float)
sigma (float)
HyperMA(src, length)
Dynamic HyperbolicMA
Parameters:
src (float)
length (int)
lib_risk_managementLibrary "lib_risk_management"
a lib to help with dynamic position sizing
position_size(risk, account_balance, entry_price, sl_price)
calculate the position size required to meet the account size based risk given when the stop loss is triggered
Parameters:
risk (float) : percentage of account balance to risk (1-100)
account_balance (float) : account balance in instrument currency
entry_price (float) : entry price
sl_price (float) : stop loss price
Returns: the position size in instrument currency that will loose the given risk percentage of the account balance when a stop loss is triggered
account_balance(to_currency, live)
converts the (current(default)/initial) account balance to the given currency at the daily rate
Parameters:
to_currency (simple string) The currency in which the account balance is to be converted. Possible values: a three-letter string with the currency code in the ISO 4217 format (e.g. "USD"), or one of the built-in variables that return currency codes, like syminfo.currency or currency.USD.
live (bool) converts the current account balance (strategy.equity) (default:true) or otherwise the initial capital (strategy.initial_capital)
Returns: the (current/initial) account balance converted to the given currency with at the current daily rate
TimeSeriesRecurrencePlotLibrary "TimeSeriesRecurrencePlot"
In descriptive statistics and chaos theory, a recurrence plot (RP) is a plot showing, for each moment i i in time, the times at which the state of a dynamical system returns to the previous state at `i`, i.e., when the phase space trajectory visits roughly the same area in the phase space as at time `j`.
```
A recurrence plot (RP) is a graphical representation used in the analysis of time series data and dynamical systems. It visualizes recurring states or events over time by transforming the original time series into a binary matrix, where each element represents whether two consecutive points are above or below a specified threshold. The resulting Recurrence Plot Matrix reveals patterns, structures, and correlations within the data while providing insights into underlying mechanisms of complex systems.
```
~starling7b
___
Reference:
en.wikipedia.org
github.com
github.com
github.com
github.com
juliadynamics.github.io
distance_matrix(series1, series2, max_freq, norm)
Generate distance matrix between two series.
Parameters:
series1 (float) : Source series 1.
series2 (float) : Source series 2.
max_freq (int) : Maximum frequency to inpect or the size of the generated matrix.
norm (string) : Norm of the distance metric, default=`euclidean`, options=`euclidean`, `manhattan`, `max`.
Returns: Matrix with distance values.
method normalize_distance(M)
Normalizes a matrix within its Min-Max range.
Namespace types: matrix
Parameters:
M (matrix) : Source matrix.
Returns: Normalized matrix.
method threshold(M, threshold)
Updates the matrix with the condition `M(i,j) > threshold ? 1 : 0`.
Namespace types: matrix
Parameters:
M (matrix) : Source matrix.
threshold (float)
Returns: Cross matrix.
rolling_window(a, b, sample_size)
An experimental alternative method to plot a recurrence_plot.
Parameters:
a (array) : Array with data.
b (array) : Array with data.
sample_size (int)
Returns: Recurrence_plot matrix.
TimeSeriesGrammianAngularFieldLibrary "TimeSeriesGrammianAngularField"
provides Grammian angular field and associated utility functions.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
www.researchgate.net
method normalize(data, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.
Namespace types: array
Parameters:
data (array) : Sample data to normalize.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized array within new range.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
normalize_series(source, length, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.\
*Note that this may provide a different result than the array version due to rolling range*.
Parameters:
source (float) : Series to normalize.
length (int) : Number of bars to sample the range.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized series within new range.
method polar(data)
Turns a normalized sample array into polar coordinates.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Converted array into polar coordinates.
polar_series(source)
Turns a normalized series into polar coordinates.
Parameters:
source (float) : Source series.
Returns: Converted series into polar coordinates.
method gasf(data)
Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
method gasf_id(data)
Trig. identity of Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
method gadf(data)
Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
method gadf_id(data)
Trig. identity of Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
ATE_Common_Functions_LibraryLibrary "ATE_Common_Functions_Library"
- ATE_Common_Functions_Library was created to assist in constructing CCOMET Scanners
RCI(_rciLength, _source, _interval)
You will see me using this a lot. DEFINITELY my favorite oscillator to utilize for SO many different things from
timing entries/exits to determining trends.Calculation of this indicator based on Spearmans Correlation.
Parameters:
_rciLength (int) : (int)
Amount of bars back to use in RCI calculations.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). RCI calculation groups bars by this amount and then will.
rank these groups of bars.
Returns: (float)
Returns a single RCI value that will oscillates between -100 and +100.
RCIAVG(_rciSMAlen, _source, _interval, firstLength, lastLength)
20 RCI's are averaged together to get this RCI Avg (Rank Correlation Index Average). Each RCI (of the 20 total RCI)
has a progressively LARGER Lookback Length. Rather than having ALL of the RCI Lengths be individually adjustable (because of too many inputs),
I have made the FIRST Length used (smallest Length value in the set) and the LAST Length used (largest length value in the set) be adjustable
and all other 18 Lengths are equally spread out between the 'firstLength' and the 'lastLength'.
Parameters:
_rciSMAlen (int) : (int)
Unlike the Single RCI Function, this function smooths out the end result using an SMA with a length value that is this parameter.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). Within the RCI calculation, bars next to each other are grouped together
and then these groups are Ranked against each other. This parameter is the number of adjacent bars that are grouped together.
firstLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 200).
This parameter is the Lookback Length for the 1st RCI used (so the SMALLEST Length used) in the RCI Avg.
lastLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 2500).
This parameter is the Lookback Length for the 20th(the LAST) RCI used (so the LARGEST Length used) in the RCI Avg.
***** BEWARE ***** The 'lastLength' must be less than (or possibly equal to) 5000 because Tradingview has capped it at 5000, causing an error.
***** BEWARE ***** If the script gives a compiler "time out" error then the 'lastLength' must be lowered until it no longer times out when compiling.
Returns: (float)
Returns a single RCI value that is the Avg of many RCI values that will oscillate between -100 and +100.
PercentChange(_startingValue, _endingValue)
This is a quick function to calculate how much % change has occurred between the '_startingValue' and the '_endingValue'
that you input into the function.
Parameters:
_startingValue (float) : (float)
The source value to START the % change calculation from.
_endingValue (float) : (float)
The source value to END the % change caluclation from.
Returns: Returns a single output being the % value between 0-100 (with trailing numbers behind a decimal). If you want only
a certain amount of numbers behind the decimal, this function needs to be put within a formatting function to do so.
Rescale(_source, _oldMin, _oldMax, _newMin, _newMax)
Rescales series with a known '_oldMin' & '_oldMax'. Use this when the scale of the '_source' to
rescale is known (bounded).
Parameters:
_source (float) : (float)
Source to be normalized.
_oldMin (int) : (float)
The known minimum of the '_source'.
_oldMax (int) : (float)
The known maximum of the '_source'.
_newMin (int) : (float)
What you want the NEW minimum of the '_source' to be.
_newMax (int) : (float)
What you want the NEW maximum of the '_source' to be.
Returns: Outputs your previously bounded '_source', but now the value will only move between the '_newMin' and '_newMax'
values you set in the variables.
Normalize_Historical(_source, _minimumLvl, _maximumLvl)
Normalizes '_source' that has a previously unknown min/max(unbounded) determining the max & min of the '_source'
FROM THE ENTIRE CHARTS HISTORY. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns your same '_source', but now the value will MOSTLY stay between the minimum and maximum values you set in the
'_minimumLvl' and '_maximumLvl' variables (ie. if the source you input is an RSI...the output is the same RSI value but
instead of moving between 0-100 it will move between the maxand min you set).
Normailize_Local(_source, _length, _minimumLvl, _maximumLvl)
Normalizes series with previously unknown min/max(unbounded). Much like the Normalize_Historical function above this one,
but rather than using the Highest/Lowest Values within the ENTIRE charts history, this on looks for the Highest/Lowest
values of '_source' within the last ___ bars (set by user as/in the '_length' parameter. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_length (int) : (float)
The amount of bars to look back to determine the highest/lowest '_source' value.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns a single output variable being the previously unbounded '_source' that is now normalized and bound between
the values used for '_minimumLvl'/'_maximumLvl' of the '_source' within the user defined lookback period.
CCOMET_Scanner_LibraryLibrary "CCOMET_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing CCOMET Scanners
Loc_tIDs_Col(_string, _firstLocation)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your CCOMET Scanner.
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my CCOMET Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the TickerIDs, 40 variables for the locations for alert labels, and 40 Colors for labels/plots
TickeridForLabelsAndSecurity(_ticker, _includeExchange)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
_includeExchange (simple bool) : (bool)
Optional (if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your CCOMET Scanner as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the CCOMET Scanner's input.
InvalID_LblSz(_barCnt, _close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your CCOMET Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_close (float) : (float)
Put your 'close' variable named '_close' from the security function here.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never registered then the logic counts the asset as INVALID.
This will be the 1st TickerID variable (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (array) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
_tablePosition (simple string) : (string)
Optional (if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional (if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here, otherwise they will all be in a row.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
convergingpatternsLibrary "convergingpatterns"
Library having implementation of converging chart patterns
getPatternNameByType(patternType)
Returns pattern name based on type
Parameters:
patternType (int) : integer value representing pattern type
Returns: string name of the pattern
method find(this, sProperties, dProperties, patterns, ohlcArray)
find converging patterns for given zigzag
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Current zigzag Object
sProperties (ScanProperties) : ScanProperties Object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/5) : DrawingProperties Object
patterns (array type from Trendoscope/abstractchartpatterns/5) : array of existing patterns to check for duplicates
ohlcArray (array type from Trendoscope/ohlc/1) : array of OHLC values for historical reference
Returns: string name of the pattern
ScanProperties
Object containing properties for pattern scanning
Fields:
baseProperties (ScanProperties type from Trendoscope/abstractchartpatterns/5) : Object of Base Scan Properties
convergingDistanceMultiplier (series float) : when multiplied with pattern size gets the max number of bars within which the pattern should converge
simpletradeLibrary "simpletrade"
Library with Simple Trade types and tracking mechanism
method evaluate(this)
Evaluate current trade and update status
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that need to be evaluated
Returns: current SimpleTrade object
method erase(this)
Erase SimpleTrade drawings
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that needs to be erased
Returns: void
method draw(this, offset, gap)
Draw SimpleTrade drawings
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that needs to be drawn
offset (int) : offset distance at which the drawing needs to be drawn.
gap (int) : gap between start and end of the Simple trade drawings
Returns: updated offset
TradeDrawing
Object containing Trade drawings
Fields:
entryToStop (series box) : box showing entry to stop range
entryToTarget (series box) : box showing entry to target range
maxGain (series box) : box highlighting max gain of the Trade
maxLoss (series box) : box highlighting max lowss of the Trade
invalidationLine (series line) : line displaying trade invalidation price
invalidationLabel (series label) : label displaying trade invalidation price
stopLabel (series label) : label displaying trade stop price
entryLabel (series label) : label displaying trade entry price
targetLabel (series label) : label displaying trade target price
patternLabel (series label) : label displaying trade pattern details
SimpleTrade
Object containing Simple trade details for tracking
Fields:
id (series int) : Unique trade id
pid (series int) : parent id for trade. Multiple trades can have single parent id
dir (series int) : trade direction
tradeName (series string) : Trade name or description
tradeColor (series color) : color in which the trade needs to be drawn
entry (series float) : trade entry price
stop (series float) : trade stop price
invalidation (series float) : trade invalidation price
target (series float) : trade target price
maxGainPrice (series float) : price at which the trade attained max gain
maxLossPrice (series float) : price at which the trade attained max loss
drawing (TradeDrawing) : TradeDrawing object contianing drawing items
status (series int) : current status of the trade
maxStatus (series int) : max status attained by the trade
HolidayLibrary "Holiday"
- Full Control over Holidays and Daylight Savings Time (DLS)
The Holiday Library is an essential tool for traders and analysts who engage in backtesting and live trading . This comprehensive library enables the incorporation of crucial calendar elements - specifically Daylight Savings Time (DLS) adjustments and public holidays - into trading strategies and backtesting environments.
Key Features:
- DLS Adjustments: The library takes into account the shifts in time due to Daylight Savings. This feature is particularly vital for backtesting strategies, as DLS can impact trading hours, which in turn affects the volatility and liquidity in the market. Accurate DLS adjustments ensure that backtesting scenarios are as close to real-life conditions as possible.
- Comprehensive Holiday Metadata: The library includes a rich set of holiday metadata, allowing for the detailed scheduling of trading activities around public holidays. This feature is crucial for avoiding skewed results in backtesting, where holiday trading sessions might differ significantly in terms of volume and price movement.
- Customizable Holiday Schedules: Users can add or remove specific holidays, tailoring the library to fit various regional market schedules or specific trading requirements.
- Visualization Aids: The library supports on-chart labels, making it visually intuitive to identify holidays and DLS shifts directly on trading charts.
Use Cases:
1. Strategy Development: When developing trading strategies, it’s important to account for non-trading days and altered trading hours due to holidays and DLS. This library enables a realistic and accurate representation of these factors.
2. Risk Management: Trading around holidays can be riskier due to thinner liquidity and greater volatility. By integrating holiday data, traders can better manage their risk exposure.
3. Backtesting Accuracy: For backtesting to be effective, it must simulate the actual market conditions as closely as possible. Incorporating holidays and DLS adjustments contributes to more reliable and realistic backtesting results.
4. Global Trading: For traders active in multiple global markets, this library provides an easy way to handle different holiday schedules and DLS shifts across regions.
The Holiday Library is a versatile tool that enhances the precision and realism of trading simulations and strategy development . Its integration into the trading workflow is straightforward and beneficial for both novice and experienced traders.
EasterAlgo(_year)
Calculates the date of Easter Sunday for a given year using the Anonymous Gregorian algorithm.
`Gauss Algorithm for Easter Sunday` was developed by the mathematician Carl Friedrich Gauss
This algorithm is based on the cycles of the moon and the fact that Easter always falls on the first Sunday after the first ecclesiastical full moon that occurs on or after March 21.
While it's not considered to be 100% accurate due to rare exceptions, it does give the correct date in most cases.
It's important to note that Gauss's formula has been found to be inaccurate for some 21st-century years in the Gregorian calendar. Specifically, the next suggested failure years are 2038, 2051.
This function can be used for Good Friday (Friday before Easter), Easter Sunday, and Easter Monday (following Monday).
en.wikipedia.org
Parameters:
_year (int) : `int` - The year for which to calculate the date of Easter Sunday. This should be a four-digit year (YYYY).
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday for the given year.
easterInit()
Inits the date of Easter Sunday and Good Friday for a given year.
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday and Good Friday for the given year.
isLeapYear(_year)
Determine if a year is a leap year.
Parameters:
_year (int) : `int` - 4 digit year to check => YYYY
Returns: `bool` - true if input year is a leap year
method timezoneHelper(utc)
Helper function to convert UTC time.
Namespace types: series int, simple int, input int, const int
Parameters:
utc (int) : `int` - UTC time shift in hours.
Returns: `string`- UTC time string with shift applied.
weekofmonth()
Function to find the week of the month of a given Unix Time.
Returns: number - The week of the month of the specified UTC time.
dayLightSavingsAdjustedUTC(utc, adjustForDLS)
dayLightSavingsAdjustedUTC
Parameters:
utc (int) : `int` - The normal UTC timestamp to be used for reference.
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS).
Returns: `int` - The adjusted UTC timestamp for the given normal UTC timestamp.
getDayOfYear(monthOfYear, dayOfMonth, weekOfMonth, dayOfWeek, lastOccurrenceInMonth, holiday)
Function gets the day of the year of a given holiday (1-366)
Parameters:
monthOfYear (int)
dayOfMonth (int)
weekOfMonth (int)
dayOfWeek (int)
lastOccurrenceInMonth (bool)
holiday (string)
Returns: `int` - The day of the year of the holiday 1-366.
method buildMap(holidayMap, holiday, monthOfYear, weekOfMonth, dayOfWeek, dayOfMonth, lastOccurrenceInMonth, closingTime)
Function to build the `holidaysMap`.
Namespace types: map
Parameters:
holidayMap (map) : `map` - The map of holidays.
holiday (string) : `string` - The name of the holiday.
monthOfYear (int) : `int` - The month of the year of the holiday.
weekOfMonth (int) : `int` - The week of the month of the holiday.
dayOfWeek (int) : `int` - The day of the week of the holiday.
dayOfMonth (int) : `int` - The day of the month of the holiday.
lastOccurrenceInMonth (bool) : `bool` - Flag indicating whether the holiday is the last occurrence of the day in the month.
closingTime (int) : `int` - The closing time of the holiday.
Returns: `map` - The updated map of holidays
holidayInit(addHolidaysArray, removeHolidaysArray, defaultHolidays)
Initializes a HolidayStorage object with predefined US holidays.
Parameters:
addHolidaysArray (array) : `array` - The array of additional holidays to be added.
removeHolidaysArray (array) : `array` - The array of holidays to be removed.
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays.
Returns: `map` - The map of holidays.
Holidays(utc, addHolidaysArray, removeHolidaysArray, adjustForDLS, displayLabel, defaultHolidays)
Main function to build the holidays object, this is the only function from this library that should be needed. \
all functionality should be available through this function. \
With the exception of initializing a `HolidayMetaData` object to add a holiday or early close. \
\
**Default Holidays:** \
`DLS begin`, `DLS end`, `New Year's Day`, `MLK Jr. Day`, \
`Washington Day`, `Memorial Day`, `Independence Day`, `Labor Day`, \
`Columbus Day`, `Veterans Day`, `Thanksgiving Day`, `Christmas Day` \
\
**Example**
```
HolidayMetaData valentinesDay = HolidayMetaData.new(holiday="Valentine's Day", monthOfYear=2, dayOfMonth=14)
HolidayMetaData stPatricksDay = HolidayMetaData.new(holiday="St. Patrick's Day", monthOfYear=3, dayOfMonth=17)
HolidayMetaData addHolidaysArray = array.from(valentinesDay, stPatricksDay)
string removeHolidaysArray = array.from("DLS begin", "DLS end")
܂Holidays = Holidays(
܂ utc=-6,
܂ addHolidaysArray=addHolidaysArray,
܂ removeHolidaysArray=removeHolidaysArray,
܂ adjustForDLS=true,
܂ displayLabel=true,
܂ defaultHolidays=true,
܂ )
plot(Holidays.newHoliday ? open : na, title="newHoliday", color=color.red, linewidth=4, style=plot.style_circles)
```
Parameters:
utc (int) : `int` - The UTC time shift in hours
addHolidaysArray (array) : `array` - The array of additional holidays to be added
removeHolidaysArray (array) : `array` - The array of holidays to be removed
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS)
displayLabel (bool) : `bool` - Flag indicating whether to display a label on the chart
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays
Returns: `HolidayObject` - The holidays object | Holidays = (holidaysMap: map, newHoliday: bool, holiday: string, dayString: string)
HolidayMetaData
HolidayMetaData
Fields:
holiday (series string) : `string` - The name of the holiday.
dayOfYear (series int) : `int` - The day of the year of the holiday.
monthOfYear (series int) : `int` - The month of the year of the holiday.
dayOfMonth (series int) : `int` - The day of the month of the holiday.
weekOfMonth (series int) : `int` - The week of the month of the holiday.
dayOfWeek (series int) : `int` - The day of the week of the holiday.
lastOccurrenceInMonth (series bool)
closingTime (series int) : `int` - The closing time of the holiday.
utc (series int) : `int` - The UTC time shift in hours.
HolidayObject
HolidayObject
Fields:
holidaysMap (map) : `map` - The map of holidays.
newHoliday (series bool) : `bool` - Flag indicating whether today is a new holiday.
activeHoliday (series bool) : `bool` - Flag indicating whether today is an active holiday.
holiday (series string) : `string` - The name of the holiday.
dayString (series string) : `string` - The day of the week of the holiday.
LIB_TradeAssistLibrary "LIB_TradeAssist"
This library is a collection of assistence tools saving me the need to copy same code again and again in my various indicators and strategies.
Slop_Magnitude(val_now, val_older, mult_factor)
Calculate the slop magnetude betwen current price and an older price. Since the change is usually minimal, we multiply it by def value of 3000 to make it usable.You can optionally pass other multiply factor
Parameters:
val_now (float)
val_older (float)
mult_factor (float)
Returns: : Slop angle magnetude
basechartpatternsLibrary "basechartpatterns"
Library having complete chart pattern implementation
getPatternNameById(id)
Returns pattern name by id
Parameters:
id (int) : pattern id
Returns: Pattern name
method find(points, properties, dProperties, ohlcArray)
Find patterns based on array of points
Namespace types: chart.point
Parameters:
points (chart.point ) : array of chart.point objects
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
method find(this, properties, dProperties, patterns, ohlcArray)
Find patterns based on the currect zigzag object but will not store them in the pattern array.
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Zigzag object containing pivots
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
patterns (Pattern type from Trendoscope/abstractchartpatterns/1) : Array of Pattern objects
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
abstractchartpatternsLibrary "abstractchartpatterns"
Library having abstract types and methods for chart pattern implementations
checkBarRatio(p1, p2, p3, properties)
checks if three zigzag pivot points are having uniform bar ratios
Parameters:
p1 (chart.point) : First pivot point
p2 (chart.point) : Second pivot point
p3 (chart.point) : Third pivot point
properties (ScanProperties)
Returns: true if points are having uniform bar ratio
getRatioDiff(p1, p2, p3)
gets ratio difference between 3 pivot combinations
Parameters:
p1 (chart.point)
p2 (chart.point)
p3 (chart.point)
Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio
method inspect(points, stratingBar, endingBar, direction, ohlcArray)
Creates a trend line between 2 or 3 points and validates and selects best combination
Namespace types: chart.point
Parameters:
points (chart.point ) : Array of chart.point objects used for drawing trend line
stratingBar (int) : starting bar of the trend line
endingBar (int) : ending bar of the trend line
direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots
ohlcArray (OHLC type from Trendoscope/ohlc/1) : Array of OHLC values
Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method push(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: Pattern
Parameters:
this (Pattern ) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method deepcopy(this)
Perform deep copy of a chart point array
Namespace types: chart.point
Parameters:
this (chart.point ) : array of chart.point objects
Returns: deep copy array
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
points (chart.point )
originalPoints (chart.point )
trendLine1 (Line type from Trendoscope/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (label ) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
allowedPatterns (bool ) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (int ) : array of int representing allowed last pivot direction for each pattern types
themeColors (color ) : color array of themes to be used.
series_collectionLibrary "series_collection"
A personal collection of commonly used series types like moving averages that are supported directly by
the pinescript library ('ALMA', 'DEMA', 'EMA', 'HMA', 'RMA', 'SMA', 'SWMA', 'VWMA', 'WMA'), highest and lowest source,
median and pivots. One single function (with overloads) that can be configured easily by the user input and can be
used as a core piece of functionality for many user cases. This library was created to abstract away and re-use this
commonly used functionality in my "Two MA Signal Indicator" script and the "Template Trailing Strategy" script. Both
of them use the "two_ma_logic" for defining entry and exit signals. While this piece of work does not contain any
novel mathematical expressions and just adds a convinient (and configurable) way to do things, I hope that might add
value to other scripts as well and future projects.
cust_series(length, seriesType, source)
cust_series - Calculate the custom series of the given source for the given length and type
Parameters:
length (simple int) : - The length of the custom series
seriesType (simple string) : - The type of the custom series
source (float) : - The source of the values
Returns: - The resulting value of the calculations of the custom series
cust_series(length, seriesType, source)
cust_series - Calculate the custom series of the given source for the given length and type
Parameters:
length (simple float) : - The length of the custom series (ceiled)
seriesType (simple string) : - The type of the custom series
source (float) : - The source of the values
Returns: - The resulting value of the calculations of the custom series
TimeSeriesClassificationActivationFunctionsLibrary "TimeSeriesClassificationActivationFunctions"
Provides some activation functions useful in time series classification.
___
reference:
github.com
method scale(dist, weights)
Activate values by a normalized scale.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: Normalized distribution map.
method softmax(dist, weights)
Activate values with a softmax algorithm.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: Normalized distribution map.
method argmax(dist, weights)
Activate values with a argmax algorithm.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: first key of argmax value of the transformed distribution.
MatrixScaleDownLibrary "MatrixScaleDown"
Provides a function to scale down a matrix into a smaller square format were its values are averaged to mantain matrix topology.
method scale_down(mat, size)
scale a matrix to a new smaller square size.
Namespace types: matrix
Parameters:
mat (matrix) : Source matrix.
size (int) : New matrix size.
Returns: New matrix with scaled down size. Source values will be averaged together.
FunctionsLibrary "Functions"
half_candle()
Half Candles
Returns: half candles (difference between open and close)
super_smoother(source, len)
Ehlers Super Smoother
Parameters:
source (float) : Source
len (int)
Returns: super smoothed moving average
quotient(length, K)
Ehlers early onset trend
Parameters:
length (int) : Length (default = 1)
K (float) : Factor (default = 0.8)
Returns: Ehlers early onset trend
butterworth_2Pole(src, length)
Ehlers 2 Pole Butterworth Filter
Parameters:
src (float) : Source
length (int) : Length
Returns: Ehlers 2 Pole Butterworth Filter
hann_ma(src, length)
Ehler's Hann Moving Average
Parameters:
src (float) : Source
length (int) : Length
Returns: Ehler's Hann Moving Average
oef(src)
Ehlers Optimum Elliptic Filter
Parameters:
src (float) : Source
Returns: Ehlers Optimum Elliptic Filter
moef(src)
Ehlers Modified Optimum Elliptic Filter
Parameters:
src (float) : Source
Returns: Ehlers Modified Optimum Elliptic Filter
arsi(src, length)
Advanced RSI
Parameters:
src (float) : Source
length (simple int) : Length (default = 14)
Returns: ARSI
smoothrng(src, length, multi)
Smooth Range
Parameters:
src (float) : Source
length (simple int) : Length
multi (float) : Multiplikator (default 3.0)
Returns: Smooth Range
ottlibLibrary "ottlib"
█ OVERVIEW
This library contains functions for the calculation of the OTT (Optimized Trend Tracker) and its variants, originally created by Anıl Özekşi (Anil_Ozeksi). Special thanks to him for the concept and to Kıvanç Özbilgiç (KivancOzbilgic) and dg_factor (dg_factor) for adapting them to Pine Script.
█ WHAT IS "OTT"
The OTT (Optimized Trend Tracker) is a highly customizable and very effective trend-following indicator that relies on moving averages and a trailing stop at its core. Moving averages help reduce noise by smoothing out sudden price movements in the markets, while trailing stops assist in detecting trend reversals with precision. Initially developed as a noise-free trailing stop, the current variants of OTT range from rapid trend reversal detection to long-term trend confirmation, thanks to its extensive customizability.
It's well-known variants are:
OTT (Optimized Trend Tracker).
TOTT (Twin OTT).
OTT Channels.
RISOTTO (RSI OTT).
SOTT (Stochastic OTT).
HOTT & LOTT (Highest & Lowest OTT)
ROTT (Relative OTT)
FT (Original name is Fırsatçı Trend in Turkish which translates to Opportunist Trend)
█ LIBRARY FEATURES
This library has been prepared in accordance with the style, coding, and annotation standards of Pine Script version 5. As a result, explanations and examples will appear when users hover over functions or enter function parameters in the editor.
█ USAGE
Usage of this library is very simple. Just import it to your script with the code below and use its functions.
import ismailcarlik/ottlib/1 as ottlib
█ FUNCTIONS
• f_vidya(source, length, cmoLength)
Short Definition: Chande's Variable Index Dynamic Average (VIDYA).
Details: This function computes Chande's Variable Index Dynamic Average (VIDYA), which serves as the original moving average for OTT. The 'length' parameter determines the number of bars used to calculate the average of the given source. Lower values result in less smoothing of prices, while higher values lead to greater smoothing. While primarily used internally in this library, it has been made available for users who wish to utilize it as a moving average or use in custom OTT implementations.
Parameters:
source (float) : (series float) Series of values to process.
length (simple int) : (simple int) Number of bars to lookback.
cmoLength (simple int) : (simple int) Number of bars to lookback for calculating CMO. Default value is `9`.
Returns: (float) Calculated average of `source` for `length` bars back.
Example:
vidyaValue = ottlib.f_vidya(source = close, length = 20)
plot(vidyaValue, color = color.blue)
• f_mostTrail(source, multiplier)
Short Definition: Calculates trailing stop value.
Details: This function calculates the trailing stop value for a given source and the percentage. The 'multiplier' parameter defines the percentage of the trailing stop. Lower values are beneficial for catching short-term reversals, while higher values aid in identifying long-term trends. Although only used once internally in this library, it has been made available for users who wish to utilize it as a traditional trailing stop or use in custom OTT implementations.
Parameters:
source (float) : (series int/float) Series of values to process.
multiplier (simple float) : (simple float) Percent of trailing stop.
Returns: (float) Calculated value of trailing stop.
Example:
emaValue = ta.ema(source = close, length = 14)
mostValue = ottlib.f_mostTrail(source = emaValue, multiplier = 2.0)
plot(mostValue, color = emaValue >= mostValue ? color.green : color.red)
• f_ottTrail(source, multiplier)
Short Definition: Calculates OTT-specific trailing stop value.
Details: This function calculates the trailing stop value for a given source in the manner used in OTT. Unlike a traditional trailing stop, this function modifies the traditional trailing stop value from two bars prior by adjusting it further with half the specified percentage. The 'multiplier' parameter defines the percentage of the trailing stop. Lower values are beneficial for catching short-term reversals, while higher values aid in identifying long-term trends. Although primarily used internally in this library, it has been made available for users who wish to utilize it as a trailing stop or use in custom OTT implementations.
Parameters:
source (float) : (series int/float) Series of values to process.
multiplier (simple float) : (simple float) Percent of trailing stop.
Returns: (float) Calculated value of OTT-specific trailing stop.
Example:
vidyaValue = ottlib.f_vidya(source = close, length = 20)
ottValue = ottlib.f_ottTrail(source = vidyaValue, multiplier = 1.5)
plot(ottValue, color = vidyaValue >= ottValue ? color.green : color.red)
• ott(source, length, multiplier)
Short Definition: Calculates OTT (Optimized Trend Tracker).
Details: The OTT consists of two lines. The first, known as the "Support Line", is the VIDYA of the given source. The second, called the "OTT Line", is the trailing stop based on the Support Line. The market is considered to be in an uptrend when the Support Line is above the OTT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `2`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `1.4`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `ottLine`.
Example:
= ottlib.ott(source = close, length = 2, multiplier = 1.4)
longCondition = ta.crossover(supportLine, ottLine)
shortCondition = ta.crossunder(supportLine, ottLine)
• tott(source, length, multiplier, bandsMultiplier)
Short Definition: Calculates TOTT (Twin OTT).
Details: TOTT consists of three lines: the "Support Line," which is the VIDYA of the given source; the "Upper Line," a trailing stop of the Support Line adjusted with an added multiplier; and the "Lower Line," another trailing stop of the Support Line, adjusted with a reduced multiplier. The market is considered in an uptrend if the Support Line is above the Upper Line and in a downtrend if it is below the Lower Line.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `40`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.6`.
bandsMultiplier (simple float) : Multiplier for bands. Default value is `0.0006`.
Returns: ( [ float, float, float ]) Tuple of `supportLine`, `upperLine` and `lowerLine`.
Example:
= ottlib.tott(source = close, length = 40, multiplier = 0.6, bandsMultiplier = 0.0006)
longCondition = ta.crossover(supportLine, upperLine)
shortCondition = ta.crossunder(supportLine, lowerLine)
• ott_channel(source, length, multiplier, ulMultiplier, llMultiplier)
Short Definition: Calculates OTT Channels.
Details: OTT Channels comprise nine lines. The central line, known as the "Mid Line," is the OTT of the given source's VIDYA. The remaining lines are positioned above and below the Mid Line, shifted by specified multipliers.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`
length (simple int) : (simple int) Number of bars to lookback. Default value is `2`
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `1.4`
ulMultiplier (simple float) : (simple float) Multiplier for upper line. Default value is `0.01`
llMultiplier (simple float) : (simple float) Multiplier for lower line. Default value is `0.01`
Returns: ( [ float, float, float, float, float, float, float, float, float ]) Tuple of `ul4`, `ul3`, `ul2`, `ul1`, `midLine`, `ll1`, `ll2`, `ll3`, `ll4`.
Example:
= ottlib.ott_channel(source = close, length = 2, multiplier = 1.4, ulMultiplier = 0.01, llMultiplier = 0.01)
• risotto(source, length, rsiLength, multiplier)
Short Definition: Calculates RISOTTO (RSI OTT).
Details: RISOTTO comprised of two lines: the "Support Line," which is the VIDYA of the given source's RSI value, calculated based on the length parameter, and the "RISOTTO Line," a trailing stop of the Support Line. The market is considered in an uptrend when the Support Line is above the RISOTTO Line, and in a downtrend if it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `50`.
rsiLength (simple int) : (simple int) Number of bars used for RSI calculation. Default value is `100`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.2`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `risottoLine`.
Example:
= ottlib.risotto(source = close, length = 50, rsiLength = 100, multiplier = 0.2)
longCondition = ta.crossover(supportLine, risottoLine)
shortCondition = ta.crossunder(supportLine, risottoLine)
• sott(source, kLength, dLength, multiplier)
Short Definition: Calculates SOTT (Stochastic OTT).
Details: SOTT is comprised of two lines: the "Support Line," which is the VIDYA of the given source's Stochastic value, based on the %K and %D lengths, and the "SOTT Line," serving as the trailing stop of the Support Line. The market is considered in an uptrend when the Support Line is above the SOTT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
kLength (simple int) : (simple int) Stochastic %K length. Default value is `500`.
dLength (simple int) : (simple int) Stochastic %D length. Default value is `200`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.5`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `sottLine`.
Example:
= ottlib.sott(source = close, kLength = 500, dLength = 200, multiplier = 0.5)
longCondition = ta.crossover(supportLine, sottLine)
shortCondition = ta.crossunder(supportLine, sottLine)
• hottlott(length, multiplier)
Short Definition: Calculates HOTT & LOTT (Highest & Lowest OTT).
Details: HOTT & LOTT are composed of two lines: the "HOTT Line", which is the OTT of the highest price's VIDYA, and the "LOTT Line", the OTT of the lowest price's VIDYA. A high price surpassing the HOTT Line can be considered a long signal, while a low price dropping below the LOTT Line may indicate a short signal.
Parameters:
length (simple int) : (simple int) Number of bars to lookback. Default value is `20`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.6`.
Returns: ( [ float, float ]) Tuple of `hottLine` and `lottLine`.
Example:
= ottlib.hottlott(length = 20, multiplier = 0.6)
longCondition = ta.crossover(high, hottLine)
shortCondition = ta.crossunder(low, lottLine)
• rott(source, length, multiplier)
Short Definition: Calculates ROTT (Relative OTT).
Details: ROTT comprises two lines: the "Support Line", which is the VIDYA of the given source, and the "ROTT Line", the OTT of the Support Line's VIDYA. The market is considered in an uptrend if the Support Line is above the ROTT Line, and in a downtrend if it is below. ROTT is similar to OTT, but the key difference is that the ROTT Line is derived from the VIDYA of two bars of Support Line, not directly from it.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `200`.
multiplier (simple float) : (simple float) Percent of trailing stop. Default value is `0.1`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `rottLine`.
Example:
= ottlib.rott(source = close, length = 200, multiplier = 0.1)
isUpTrend = supportLine > rottLine
isDownTrend = supportLine < rottLine
• ft(source, length, majorMultiplier, minorMultiplier)
Short Definition: Calculates Fırsatçı Trend (Opportunist Trend).
Details: FT is comprised of two lines: the "Support Line", which is the VIDYA of the given source, and the "FT Line", a trailing stop of the Support Line calculated using both minor and major trend values. The market is considered in an uptrend when the Support Line is above the FT Line, and in a downtrend when it is below.
Parameters:
source (float) : (series float) Series of values to process. Default value is `close`.
length (simple int) : (simple int) Number of bars to lookback. Default value is `30`.
majorMultiplier (simple float) : (simple float) Percent of major trend. Default value is `3.6`.
minorMultiplier (simple float) : (simple float) Percent of minor trend. Default value is `1.8`.
Returns: ( [ float, float ]) Tuple of `supportLine` and `ftLine`.
Example:
= ottlib.ft(source = close, length = 30, majorMultiplier = 3.6, minorMultiplier = 1.8)
longCondition = ta.crossover(supportLine, ftLine)
shortCondition = ta.crossunder(supportLine, ftLine)
█ CUSTOM OTT CREATION
Users can create custom OTT implementations using f_ottTrail function in this library. The example code which uses EMA of 7 period as moving average and calculates OTT based of it is below.
Source Code:
//@version=5
indicator("Custom OTT", shorttitle = "COTT", overlay = true)
import ismailcarlik/ottlib/1 as ottlib
src = input.source(close, title = "Source")
length = input.int(7, title = "Length", minval = 1)
multiplier = input.float(2.0, title = "Multiplier", minval = 0.1)
support = ta.ema(source = src, length = length)
ott = ottlib.f_ottTrail(source = support, multiplier = multiplier)
pSupport = plot(support, title = "Moving Average Line (Support)", color = color.blue)
pOtt = plot(ott, title = "Custom OTT Line", color = color.orange)
fillColor = support >= ott ? color.new(color.green, 60) : color.new(color.red, 60)
fill(pSupport, pOtt, color = fillColor, title = "Direction")
Result:
█ DISCLAIMER
Trading is risky and most of the day traders lose money eventually. This library and its functions are only for educational purposes and should not be construed as financial advice. Past performances does not guarantee future results.
ohlcLibrary "ohlc"
Library having OHLC and Indicator type and method implementations.
getOhlcArray(o, h, l, c, barindex, bartime, indicators)
get array of OHLC values when called on every bar
Parameters:
o (float) : Open price
h (float) : High Price
l (float) : Low Price
c (float) : Close Price
barindex (int) : bar_index of OHLC data
bartime (int) : time of OHLC cata
indicators (Indicator ) : array containing indicator
Returns: Array of OHLC objects
push(this, item, maxItems)
Push items to OHLC array with maxItems limit
Parameters:
this (OHLC )
item (OHLC) : OHLC Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
push(this, item, maxItems)
Push items to Indicator array with maxItems limit
Parameters:
this (Indicator )
item (Indicator) : Indicator Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshift(this, item, maxItems)
Unshift items to OHLC array with maxItems limit
Parameters:
this (OHLC )
item (OHLC) : OHLC Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshift(this, item, maxItems)
Unshift items to Indicator array with maxItems limit
Parameters:
this (Indicator )
item (Indicator) : Indicator Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
method getPoints(indicators)
get array of points based on array of indicator values
Namespace types: Indicator
Parameters:
indicators (Indicator ) : Array containing indicator objects
Returns: array of indicator points
method plot(indicator, xloc, line_color, line_style, line_width)
plots an array of Indicator using polyline
Namespace types: Indicator
Parameters:
indicator (Indicator ) : Array containing indicator objects
xloc (string) : can have values xloc.bar_index or xloc.bar_time. Used for drawing the line based on either bars or time.
line_color (color) : color in which the plots need to be printed on chart.
line_style (string) : line style line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both
line_width (int) : width of the plot line
Returns: array of plot polyline
Indicator
Object containing Indicator name and value
Fields:
name (series string) : Indicator Name
value (chart.point) : Indicator Value as a chart point
OHLC
Object containing OHLC and indicator values
Fields:
o (series float) : Open price
h (series float) : High Price
l (series float) : Low Price
c (series float) : Close Price
barindex (series int) : bar_index of OHLC data
bartime (series int) : time of OHLC cata
indicators (Indicator ) : array containing indicator
forex_factory_decodingLibrary "forex_factory_decoding"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for formatting and saving Forex Factory News events.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
MMM(M)
Converts a month from a numerical integer format to a MMM format (i.e. 'Jan').
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Month in MMM format (i.e. 'Jan').
array2string(S, FWD)
Converts a string array to a simple string, concatenating its elements.
Parameters:
S (string ) : String array, or string array slice, to turn into a simple string.
FWD (bool) : Boolean defaulted to True. If True the array will be concatenated from head to tail, reversed order if False.
Returns: Returns the simple string equivalent of the provided string array.
month2number(M)
Converts a month string in 'MMM' format to its integer equivalent.
Parameters:
M (string) : Month string, in 'MMM' format.
Returns: Returns the integer equivalent of the provided Month string in 'MMM' format.
shiftFWD_Days(D)
Shifts forward the current Date by N days.
Parameters:
D (int) : Number of days to forward-shift, default is 7.
Returns: Returns the forward-shifted date in 'MMM %D' format (i.e. Jan 8, Sep 12).
ff_dow(D)
Converts a numbered day of the week string in format to 'DDD' format (i.e. "1" = Sun).
Parameters:
D (string) : Numbered day of the week from 1 to 7, starting on Sunday.
Returns: Returns the day of the week in 'DDD' format (i.e. "Fri").
ff_currency(C)
Converts a numbered currency string in format to 'CCC' format (i.e. "1" = AUD).
Parameters:
C (string) : Numbered currency, where "1" = "AUD", "2" = "CAD", "3" = "CHF", "4" = "CNY", "5" = "EUR", "6" = "GBP", "7" = "JPY", "8" = "NZD", "9" = "USD".
Returns: Returns the currency in 'CCC' format (i.e. "USD").
ff_t(T)
Converts a time of the day in 'hhmm' format into an intger.
Parameters:
T (string) : Time of the day string in 'hhmm' format.
Returns: Returns the time of the day integer in 'hhmm' format, or -1 if all day.
ff_tod(T)
Converts a time of the day from an integer 'hhmm' format into 'hh:mm' format.
Parameters:
T (int)
Returns: Returns the N Forex Factory News array with time of the day string in 'hh:mm' format, or 'All Day'.
ff_impact(I)
Converts a number from 1 to 4 to a relative color based on Forex Factory Impact types.
Parameters:
I (string) : Impact number string from 1 to 4, where "1" = Holiday, "2" = Low Impact, "3" = Medium Impact, "4" = High Impact.
Returns: Returns the color associated to the impact number based on Forex Factory Impact types.
ff_tmst(D, T)
Parameters:
D (string)
T (string)
decode(ID)
Decodes TOODEGREES_FOREX_FACTORY_SLOT_n Symbols' Pine Seeds data into Forex Factory News Events.
Parameters:
ID (int) : Identifier of the Forex Factory News Event, in "DCHHMMI%T" format (D = day of the week from 1 to 7, C = currency from 1 to 9, HHMM = hour:minute in 24h, I = impact from 1 to 4, %T = event title ID) .
Returns: Returns the Forex Factory News Event.
method pullNews(N, n)
Decodes the Forex Factory News Event and adds it to the Forex Factory News array.
Namespace types: ffUtil.News
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
n (float) : imported data from custom feed.
Returns: void
method readNews(N, S)
Pulls the individual Forex Factory News Event from the custom data feed format (joint News string), decodes them and adds them to the Forex Factory News array.
Namespace types: ffUtil.News
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
S (string) : joint string of the imported data from custom feed.
Returns: void
marketClosed(N, S, S1, S2, S3, S4, S5, S6, S7, S8, S9)
If the current ticker's market is closed, Pine Seeds data will be pushed twice upon new day. This function saves the data pushed from the missing day.
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
S (string ) : String array containing the Pine Seeds daya from the missing day.
S1 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_1.
S2 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_2.
S3 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_3.
S4 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_4.
S5 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_5.
S6 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_6.
S7 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_7.
S8 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_8.
S9 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_9.
Returns: Updated string array containing the Pine Seeds daya from the missing day.
forex_factory_events_id_BLibrary "forex_factory_events_id_B"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; database with the second 500 Forex Factory News Event types.
ff_titleB(ID)
Converts a number to Forex Factory News title (second 500).
Parameters:
ID (string) : Identifier of the Forex Factory News Event. Please see the library for more information.
Returns: Returns the title of the Forex Factory News Event.
forex_factory_events_id_ALibrary "forex_factory_events_id_A"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; database with the first 500 Forex Factory News Event types.
ff_titleA(ID)
Converts a number to Forex Factory News title (first 500).
Parameters:
ID (string) : Identifier of the Forex Factory News Event. Please see the library for more information.
Returns: Returns the title of the Forex Factory News Event.
forex_factory_utilityLibrary "forex_factory_utility"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for data handling, and plotting news event data.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
size(S, N)
Converts a size string into the corresponding Pine Script v5 format, or N times smaller/bigger.
Parameters:
S (string) : Size string: "Tiny", "Small", "Normal", "Large", or "Huge".
N (int) : Size variation, can be positive (larger than S), or negative (smaller than S).
Returns: Size string in Pine Script v5 format.
lineStyle(S)
Converts a line style string into the corresponding Pine Script v5 format.
Parameters:
S (string) : Line style string: "Dashed", "Dotted" or "Solid".
Returns: Line style string in Pine Script v5 format.
lineTrnsp(S)
Converts a transparency style string into the corresponding integer value.
Parameters:
S (string) : Line style string: "Light", "Medium" or "Heavy".
Returns: Transparency integer.
boxLoc(X, Y)
Converts position strings of X and Y into a table position in Pine Script v5 format.
Parameters:
X (string) : X-axis string: "Left", "Center", or "Right".
Y (string) : Y-axis string: "Top", "Middle", or "Bottom".
Returns: Table location string in Pine Script v5 format.
method bubbleSort_NewsTOD(N)
Performs bubble sort on a Forex Factory News array of all news from the same date, ordering them in ascending order based on the time of the day.
Namespace types: News
Parameters:
N (News ) : Forex Factory News array.
Returns: void
bubbleSort_News(N)
Performs bubble sort on a Forex Factory News array, ordering them in ascending order based on the time of the day, and date.
Parameters:
N (News ) : Forex Factory News array.
Returns: Sorted Forex Factory News array.
weekNews(N, C, I)
Creates a Forex Factory News array containing the current week's Forex Factory News.
Parameters:
N (News ) : Forex Factory News array containing this week's unfiltered Forex Factory News.
C (string ) : Currency filter array (string array).
I (color ) : Impact filter array (color array).
Returns: Forex Factory News array containing the current week's Forex Factory News.
todayNews(W, D, M)
Creates a Forex Factory News array containing the current day's Forex Factory News.
Parameters:
W (News ) : Forex Factory News array containing this week's Forex Factory News.
D (News ) : Forex Factory News array for the current day's Forex Factory News.
M (bool) : Boolean that marks whether the current chart has a Day candle-switch at Midnight New York Time.
Returns: Forex Factory News array containing the current day's Forex Factory News.
impFilter(X, L, M, H)
Creates a filter array from the User's desired Forex Facory News to be shown based on Impact.
Parameters:
X (bool) : Boolean - if True Holidays listed on Forex Factory will be shown.
L (bool) : Boolean - if True Low Impact listed on Forex Factory News will be shown.
M (bool) : Boolean - if True Medium Impact listed on Forex Factory News will be shown.
H (bool) : Boolean - if True High Impact listed on Forex Factory News will be shown.
Returns: Color array with the colors corresponding to the Forex Factory News to be shown.
curFilter(A, C1, C2, C3, C4, C5, C6, C7, C8, C9)
Creates a filter array from the User's desired Forex Facory News to be shown based on Currency.
Parameters:
A (bool) : Boolean - if True News related to the current Chart's symbol listed on Forex Factory will be shown.
C1 (bool) : Boolean - if True News related to the Australian Dollar listed on Forex Factory will be shown.
C2 (bool) : Boolean - if True News related to the Canadian Dollar listed on Forex Factory will be shown.
C3 (bool) : Boolean - if True News related to the Swiss Franc listed on Forex Factory will be shown.
C4 (bool) : Boolean - if True News related to the Chinese Yuan listed on Forex Factory will be shown.
C5 (bool) : Boolean - if True News related to the Euro listed on Forex Factory will be shown.
C6 (bool) : Boolean - if True News related to the British Pound listed on Forex Factory will be shown.
C7 (bool) : Boolean - if True News related to the Japanese Yen listed on Forex Factory will be shown.
C8 (bool) : Boolean - if True News related to the New Zealand Dollar listed on Forex Factory will be shown.
C9 (bool) : Boolean - if True News related to the US Dollar listed on Forex Factory will be shown.
Returns: String array with the currencies corresponding to the Forex Factory News to be shown.
FF_OnChartLine(N, T, S)
Plots vertical lines where a Forex Factory News event will occur, or has already occurred.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
T (int) : Transparency integer value (0-100) for the lines.
S (string) : Line style in Pine Script v5 format.
Returns: void
method updateStringMatrix(M, P, V)
Namespace types: matrix
Parameters:
M (matrix)
P (int)
V (string)
FF_OnChartLabel(N, Y, S)
Plots labels where a Forex Factory News has already occurred based on its/their impact.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
Y (string) : String that gives direction on where to plot the label (options= "Above", "Below", "Auto").
S (string) : Label size in Pine Script v5 format.
Returns: void
historical(T, D, W, X)
Deletes Forex Factory News drawings which are ourside a specific Time window.
Parameters:
T (int) : Number of days input used for Forex Factory News drawings' history.
D (bool) : Boolean that when true will only display Forex Factory News drawings of the current day.
W (bool) : Boolean that when true will only display Forex Factory News drawings of the current week.
X (string) : String that gives direction on what lines to plot based on Time (options= "Past", "Future", "Both").
Returns: void
newTable(P)
Creates a new Table object with parameters tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
Returns: Empty Forex Factory News Table.
resetTable(P, S, headTextC, headBgC)
Resets a Table object with parameters and headers tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
Returns: Empty Forex Factory News Table.
logNews(N, TBL, R, S, rowTextC, rowBgC)
Adds an event to the Forex Factory News Table.
Parameters:
N (News) : News-type object.
TBL (table) : Forex Factory News Table object to add the News to.
R (int) : Row to add the event to in the Forex Factory News Table.
S (string) : Size string for the event's text, in Pine Script v5 format.
rowTextC (color)
rowBgC (color)
Returns: void
FF_Table(N, P, S, headTextC, headBgC, rowTextC, rowBgC)
Creates the Forex Factory News Table.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
rowTextC (color)
rowBgC (color)
Returns: Forex Factory News Table.
timeline(N, T, F, D)
Shades Forex Factory News events in the Forex Factory News Table after they occur.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
T (table) : Forex Facory News table object.
F (color) : Color used as shading once the Forex Factory News has occurred.
D (bool) : Daily Forex Factory News flag.
Returns: Forex Factory News Table.
News
Custom News type which contains informatino about a Forex Factory News Event.
Fields:
dow (series string) : Day of the week, in DDD format (i.e. 'Mon').
dat (series string) : Date, in MMM D format (i.e. 'Jan 1').
_t (series int)
tod (series string) : Time of the day, in hh:mm 24-Hour format (i.e 17:10).
cur (series string) : Currency, in CCC format (i.e. "USD").
imp (series color) : Impact, the respective impact color for Forex Factory News Events.
ttl (series string) : Title, encoded in a custom number mapping (see the toodegrees/toodegrees_forex_factory library to learn more).
tmst (series int)
ln (series line)