timeUtilsLibrary "timeUtils"
Utils for time series
tradingDaysTillEndOfMonth() Calculates how many full trading days left until the end of the current month. (It doesn't take into account market holidays)
Returns: int series of the remaining trading days until the end of the month.
insideRange()
Timesessions
bytimeLibrary "bytime"
TODO: to do something at the specified time.
////Return =>> ht = hour , mt = minute , st = second ,Dt = Day, Mt = month, Yt = year , dateTime = full time format./////////////
Note : Remember to always add import when you call our library and change Gtime() to Timeset.Gtime() is used to access internal data.
import hapharmonic/bytime/1 as Timeset
=Timeset.Gtime()
/////////////Set a time to trigger an alert./////////////
ck = false
///hour : minute : second
if ht == TH and mt == TM and st == TS
//some action
//...
//.
ck := true
Gtime()
FunctionWeekofmonthLibrary "FunctionWeekofmonth"
Week of Month function.
weekofmonth(utime) Week of month for provided unix time.
Parameters:
utime : int, unix timestamp.
Returns: int
TimeLockedMALibrary "TimeLockedMA"
Library & function(s) which generates a moving average that stays locked to users desired time preference.
TODO - Add functionality for more moving average types. IE: smooth, weighted etc...
Example:
time_locked_ma(close, length=1, timeframe='days', type='ema')
Will generate a 1 day exponential moving average that will stay consistent across all chart intervals.
Error Handling
On small time frames with large moving averages (IE: 1min chart with a 50 week moving average), you'll get a study error that says "(function "sma") references too many candles in history" .
To fix this, make sure you have timeframe="" as an indicator() header. Next, in the indicator settings, increase the timeframe from to a higher interval until the error goes away.
By default, it's set to "Chart". Bringing the interval up to 1hr will usually solve the issue.
Furthermore, adding timeframe_gaps=false to your indicator() header will give you an approximation of real-time values.
Misc Info
For time_lock_ma() setting type='na' will return the relative length value that adjusts dynamically to user's chart time interval.
This is good for plugging into other functions where a lookback or length is required. (IE: Bollinger Bands)
time_locked_ma(source, length, timeframe, type) Creates a moving average that is locked to a desired timeframe
Parameters:
source : float, Moving average source
length : int, Moving average length
timeframe : string, Desired timeframe. Use: "minutes", "hours", "days", "weeks", "months", "chart"
type : string, string Moving average type. Use "SMA" (default) or "EMA". Value of "NA" will return relative lookback length.
Returns: moving average that is locked to desired timeframe.
timeframe_convert(t, a, b) Converts timeframe to desired timeframe. From a --> b
Parameters:
t : int, Time interval
a : string, Time period
b : string, Time period to convert to
Returns: Converted timeframe value
chart_time(timeframe_period, timeframe_multiplier) Separates timeframe.period function and returns chart interval and period
Parameters:
timeframe_period : string, timeframe.period
timeframe_multiplier : int, timeframe.multiplier
Enjoy :)
SetSessionTimesLibrary "SetSessionTimes"
Function to automatically set session times for symbols and eventually timezone.
Useful mainly for futures contracts, to differentiate between pit and overnight sessions, and for 24 hours symbols if you want to "create" sessions for them
This library only returns correct session times to the calling script and does nothing by itself on the chart. the calling script must then use the returned session times to do anything.
For example, in the attached chart this library is used by my initial balance indicator, which calls it to retrieve the correct session times for the selected symbol in the chart, given that different futures contracts have different pit session times (RTH times) and Tradingview hasn't implemented that yet.
SetSessionTimes()
options_expiration_and_strike_price_calculatorLibrary "options_expiration_and_strike_price_calculator"
TODO: add library description here
fun()
this is a library to help calculate options strike price and expiration that you can add to a script i use it mainly for symbol calulation to place orders to buy options on TD ameritrade so it will be set up to order options on TD ameritrade using json order placer and webhook it fills in the area in the json under symbol i suggest manually adding the year it should look like this is an example of an order to buy 10 call options using json through td ameritrade api
"complexOrderStrategyType": "NONE",
"orderType": "LIMIT",
"session": "NORMAL",
"price": "6.45",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection":
}
Last Available Bar InfoLibrary "Last_Available_Bar_Info"
getLastBarTimeStamp()
getAvailableBars()
This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change.
For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart).
Methods
getLastBarTimeStamp()
: Returns Timestamp of the last available bar (Constant)
getAvailableBars()
:Returns Number of Available Bars on the chart (Constant)
Example
import paragjyoti2012/Last_Available_Bar_Info/v1 as LastBarInfo
last_bar_timestamp=LastBarInfo.getLastBarTimeStamp()
no_of_bars=LastBarInfo.getAvailableBars()
If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe.
In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted,
previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results.
To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available.
tf=timeframe.period
real_available_bars = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() , lookahead = barmerge.lookahead_off)
last_available_bar_timestamp = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() , lookahead = barmerge.lookahead_off)
FunctionZigZagMultipleMethodsLibrary "FunctionZigZagMultipleMethods"
ZigZag Multiple Methods.
method(idx) Helper methods enumeration.
Parameters:
idx : int, index of method, range 0 to 4.
Returns: string
function(method, value_x, value_y) Multiple method ZigZag.
Parameters:
method : string, default='(MANUAL) Percent price move over X * Y', method for zigzag.
value_x : float, x value in method.
value_y : float, y value in method.
Returns: tuple with:
zigzag float
direction
reverse_line float
realtimeofpivot int
arsenalLibrary "arsenal"
This library is a collection of weapons that will help us win the war against the market.
isNewbar(res, timezone) Checks if the res is in new bar at the current timeframe
Parameters:
res : - resolution of the bar to check if new
timezone : - timezone of the resolution
Returns: ch: - 1=true, 0=false
SessionInfoLibrary "SessionInfo"
Utility functions for session specific information like the bar index of the session.
inSession(spec) Returns true if the current bar is in the session specification.
Parameters:
spec : session.regular (default), session.extended or other time spec.
Returns: True if the current is in session; otherwise false.
minutesToLen(minutes, multiple) Converts the number of minutes to a length to be used with indicators.
Parameters:
minutes : The number of minutes.
multiple : The length multiplier.
Returns: math.ceil(minutes * multiple / timeframe.multiplier)
bar(spec, res) Returns the intraday bar index. May not always map directly to time as a bars can be skipped.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: The integer index of the bar of the session.
isFirstBar(spec, res) Returns true if the current bar is the first one of the session.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: True if the current bar is the first one of the session.
wasLastBar(spec, res) Returns Returns true if the previous bar was the last of the session.
Parameters:
spec : session.regular (default), session.extended or other time spec.
res : The resolution (default = "1440").
Returns: True if was the last bar of the session.
ZenLibraryLibrary "ZenLibrary"
A collection of custom tools & utility functions commonly used with my scripts.
getDecimals() Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
truncate(float, float) Truncates (cuts) excess decimal places
Parameters:
float : _number The number to truncate
float : _decimalPlaces (default=2) The number of decimal places to truncate to
Returns: The given _number truncated to the given _decimalPlaces
toWhole(float) Converts pips into whole numbers
Parameters:
float : _number The pip number to convert into a whole number
Returns: The converted number
toPips(float) Converts whole numbers back into pips
Parameters:
float : _number The whole number to convert into pips
Returns: The converted number
av_getPositionSize(float, float, float, float) Calculates OANDA forex position size for AutoView based on the given parameters
Parameters:
float : _balance The account balance to use
float : _risk The risk percentage amount (as a whole number - eg. 1 = 1% risk)
float : _stopPoints The stop loss distance in POINTS (not pips)
float : _conversionRate The conversion rate of our account balance currency
Returns: The calculated position size (in units - only compatible with OANDA)
getMA(int, string) Gets a Moving Average based on type
Parameters:
int : _length The MA period
string : _maType The type of MA
Returns: A moving average with the given parameters
getEAP(float) Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20)
Parameters:
float : _atr The given ATR to base the EAP SL calculation on
Returns: The EAP SL converted ATR size
barsAboveMA(int, float) Counts how many candles are above the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to check
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(int, float) Counts how many candles are below the MA
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(int, float) Counts how many times the EMA was crossed recently
Parameters:
int : _lookback The lookback period to look back over
float : _ma The moving average to reference
Returns: The bar count of how many times price recently crossed the EMA
getPullbackBarCount(int, int) Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
int : _lookback The lookback period to look back over
int : _direction The color of the bar to count (1 = Green, -1 = Red)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize() Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize() Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize() Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent() Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(float, bool) Checks if the current bar is a hammer candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be green? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(float, bool) Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
float : _fib (default=0.382) The fib to base candle body on
bool : _colorMatch (default=false) Does the candle need to be red? (true/false)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(float, bool) Checks if the current bar is a doji candle based on the given parameters
Parameters:
float : _wickSize (default=2) The maximum top wick size compared to the bottom (and vice versa)
bool : _bodySize (default=0.05) The maximum body size as a percentage compared to the entire candle size
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(float, float, bool) Checks if the current bar is a bullish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(float, float, bool) Checks if the current bar is a bearish engulfing candle
Parameters:
float : _allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps)
float : _rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage
bool : _engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well?
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
timeFilter(string, bool) Determines if the current price bar falls inside the specified session
Parameters:
string : _sess The session to check
bool : _useFilter (default=false) Whether or not to actually use this filter
Returns: A boolean - true if the current bar falls within the given time session
dateFilter(int, int) Determines if this bar's time falls within date filter range
Parameters:
int : _startTime The UNIX date timestamp to begin searching from
int : _endTime the UNIX date timestamp to stop searching from
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(bool, bool, bool, bool, bool, bool, bool) Checks if the current bar's day is in the list of given days to analyze
Parameters:
bool : _monday Should the script analyze this day? (true/false)
bool : _tuesday Should the script analyze this day? (true/false)
bool : _wednesday Should the script analyze this day? (true/false)
bool : _thursday Should the script analyze this day? (true/false)
bool : _friday Should the script analyze this day? (true/false)
bool : _saturday Should the script analyze this day? (true/false)
bool : _sunday Should the script analyze this day? (true/false)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter(float, float) Checks the current bar's size against the given ATR and max size
Parameters:
float : _atr (default=ATR 14 period) The given ATR to check
float : _maxSize The maximum ATR multiplier of the current candle
Returns: A boolean - true if the current bar's size is less than or equal to _atr x _maxSize
fillCell(table, int, int, string, string, color, color) This updates the given table's cell with the given values
Parameters:
table : _table The table ID to update
int : _column The column to update
int : _row The row to update
string : _title The title of this cell
string : _value The value of this cell
color : _bgcolor The background color of this cell
color : _txtcolor The text color of this cell
Returns: A boolean - true if the current bar falls within the given dates
LibraryCheckNthBarLibrary "LibraryCheckNthBar"
TODO: add library description here
canwestart(UTC, prd) this function can be used if current bar is in last Nth bar
Parameters:
UTC : is UTC of the chart
prd : is the length of last Nth bar
Returns: true if the current bar is in N bar
FunctionDaysInMonthLibrary "FunctionDaysInMonth"
Method to find the number of days in a given month of year.
days_in_month(year, month) Method to find the number of days in a given month of year.
Parameters:
year : int, year of month, so we know if year is a leap year or not.
month : int, month number.
Returns: int
FunctionDatestringLibrary "FunctionDatestring"
Methods to stringify date/time, altho there is already builtin support for it.
datetime(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
date_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
time_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string