TimeFilterLibrary "TimeFilter"
provides utilities for dates and times
inSession(session, timezone, period)
Parameters:
session (simple string)
timezone (simple string)
period (simple string)
Returns: bool inSession Whether the current time is within the defined time session
inDateRange(startDate, endDate)
Parameters:
startDate (int)
endDate (int)
Returns: bool inRange Whether the current time is within the defined date range
isWeekDay(weekDay, timezone)
Parameters:
weekDay (int)
timezone (simple string)
Returns: bool isWeekDay Whether the provided day is the current day of the week
inWeek(useMon, useTue, useWed, useThu, useFri, useSat, useSun, timezone)
Parameters:
useMon (bool)
useTue (bool)
useWed (bool)
useThu (bool)
useFri (bool)
useSat (bool)
useSun (bool)
timezone (simple string)
Returns: bool inWeek Whether the current time is one of the defined days
filter(useRange, useSession, useWeek, inRange, inSession, inWeek)
Parameters:
useRange (bool)
useSession (bool)
useWeek (bool)
inRange (bool)
inSession (bool)
inWeek (bool)
Returns: bool filter Whether the filter matches or not
Dates
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.
chrono_utilsLibrary "chrono_utils"
📝 Description
Collection of objects and common functions that are related to datetime windows session days and time ranges. The main purpose of this library is to handle time-related functionality and make it easy to reason about a future bar checking if it will be part of a predefined session and/or inside a datetime window. All existing session functionality I found in the documentation e.g. "not na(time(timeframe, session, timezone))" are not suitable for strategy scripts, since the execution of the orders is delayed by one bar, due to the script execution happening at the bar close. Moreover, a history operator with a negative value that looks forward is not allowed in any pinescript expression. So, a prediction for the next bar using the bars_back argument of "time()"" and "time_close()" was necessary. Thus, I created this library to overcome this small but very important limitation. In the meantime, I added useful functionality to handle session-based behavior. An interesting utility that emerged from this development is data anomaly detection where a comparison between the prediction and the actual value is happening. If those two values are different then a data inconsistency happens between the prediction bar and the actual bar (probably due to a holiday, half session day, a timezone change etc..)
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/chrono_utils/2 as chr
To check if a future bar will be inside a window first of all you have to initialize a DateTimeWindow object.
A code example is the following:
var dateTimeWindow = chr.DateTimeWindow.new().init(fromDateTime = timestamp('01 Jan 2023 00:00'), toDateTime = timestamp('01 Jan 2024 00:00'))
Then you have to "ask" the dateTimeWindow if the future bar defined by an offset (default is 1 that corresponds th the next bar), will be inside that window:
// Filter bars outside of the datetime window
bool dateFilterApproval = dateTimeWindow.is_bar_included()
You can visualize the result by drawing the background of the bars that are outside the given window:
bgcolor(color = dateFilterApproval ? na : color.new(color.fuchsia, 90), offset = 1, title = 'Datetime Window Filter')
In the same way, you can "ask" the Session if the future bar defined by an offset it will be inside that session.
First of all, you should initialize a Session object.
A code example is the following:
var sess = chr.Session.new().from_sess_string(sess = '0800-1700:23456', refTimezone = 'UTC')
Then check if the given bar defined by the offset (default is 1 that corresponds th the next bar), will be inside the session like that:
// Filter bars outside the sessions
bool sessionFilterApproval = view.sess.is_bar_included()
You can visualize the result by drawing the background of the bars that are outside the given session:
bgcolor(color = sessionFilterApproval ? na : color.new(color.red, 90), offset = 1, title = 'Session Filter')
In case you want to visualize multiple session ranges you can create a SessionView object like that:
var view = SessionView.new().init(SessionDays.new().from_sess_string('2345'), array.from(SessionTimeRange.new().from_sess_string('0800-1600'), SessionTimeRange.new().from_sess_string('1300-2200')), array.from('London', 'New York'), array.from(color.blue, color.orange))
and then call the draw method of the SessionView object like that:
view.draw()
🏋️♂️ Please refer to the "EXAMPLE DATETIME WINDOW FILTER" and "EXAMPLE SESSION FILTER" regions of the script for more advanced code examples of how to utilize the full potential of this library, including user input settings and advanced visualization!
⚠️ Caveats
As I mentioned in the description there are some cases that the prediction of the next bar is not accurate. A wrong prediction will affect the outcome of the filtering. The main reasons this could happen are the following:
Public holidays when the market is closed
Half trading days usually before public holidays
Change in the daylight saving time (DST)
A data anomaly of the chart, where there are missing and/or inconsistent data.
A bug in this library (Please report by PM sending the symbol, timeframe, and settings)
Special thanks to @robbatt and @skinra for the constructive feedback 🏆. Without them, the exposed API of this library would be very lengthy and complicated to use. Thanks to them, now the user of this library will be able to get the most, with only a few lines of code!
SessionAndTimeFct_publicLibrary "SessionAndTimeFct_public"
is_in_session(sessionTime, sessionTimeZone)
: Check if actual bar is in specific session with specific time zone
Parameters:
sessionTime
sessionTimeZone
is_session_start(sessionTime, sessionTimeZone)
: Check if actual bar the first bar of a specific session
Parameters:
sessionTime
sessionTimeZone
is_new_day(timeZone)
: Check if a new day started
Parameters:
timeZone
is_new_week(timeZone)
: Check if a new week started
Parameters:
timeZone
is_new_month(timeZone)
: Check if a new month started
Parameters:
timeZone
is_element_to_show_with_tf_up(base, value)
: Check if an element is to show compared to a specific timeframe >
Parameters:
base
value
is_element_to_show_with_tf_down(base, value)
: Check if an element is to show compared to a specific timeframe <
Parameters:
base
value
ATR+ Advanced Sessions ATR for DaterangeATR+ Advanced Sessions ATR for Daterange
The ATR+ adds the following additional filters to the stock ATR indicator by Tradingview:
- Calculates the overall average ATR for a user defined daterange, optionally filtered by trading session and selected weekdays, presented as a secondary line over the standard ATR line.
- Basic ATR line, with colour highlight to indicate the selected sessions, days and timeframe being calculated by the average ATR+ line.
- Average ATR+ line indicating the average of all ATRs within the defined timeframe, optionally filtered by instances of a selected trading session and selected weekdays.
- Customisable appearance.
- The ATR+ also includes the basic ATR configuration options typically found in the standard ATR by Tradingview, including period length and smoothing type. Defaults are set to the factory standards: 14 length, RMA smoothing type.
What Is the Average True Range (ATR)?
The ATR is a technical analysis tool that measures market volatility by decomposing the entire range asset price for that period. Investopedia describes the ATR as follows:
"The average true range (ATR) is a technical analysis indicator, introduced by market technician J. Welles Wilder Jr. in his book New Concepts in Technical Trading Systems, that measures market volatility by decomposing the entire range of an asset price for that period.
The true range indicator is taken as the greatest of the following: current high less the current low; the absolute value of the current high less the previous close; and the absolute value of the current low less the previous close. The ATR is then a moving average, generally using 14 days, of the true ranges."
For more information on the ATR and its calculations and use cases, see here:
Investopedia link here.
Tradingview link here.
Note
The indicator may time out if the number of bars being calculated is too long. If this happens, you will need to reduce the datetime range, or increase the chart timeframe in order to reduce the number of bars being calculated and the indicator will attempt to recalculate.
Historical Crypto Conference DatesJust a basic list date script to display various conference dates from the crypto sector. Updates to add more conferences.
Red - BTC Miami
Blue - Consensus
Gann Seasonal Dates by JayCThis script marks important seasonal dates with a vertical line that Gann used to watch for Trend changes.
March 21st
June 22nd
September 23rd
December 22nd
And 50% Levels - Minor seasonal dates.
February 4th
May 6th
August 8th
November 7th
In the settings you can change line colors and toggle the Offset. Offset is the way the script draws lines to show future dates, I offset by 365 so it will show incorrectly at some points in back testing.
200DMA last DOM - ajhImplements and backtests a simple 200 day moving average trend following rules based on last day of month to limits trades to 12 per year.
From the book : 5 BEST Moving Average Strategies (That beat buy and hold) by Steve Burns and Holly Burns
Click on the cog to set the input date range eg; 2000-01-01 to 2016-12-31
The book back tested SP500 returns from 2000-2016 317% using this method vs 125% buy and hold only with less drawdown.
Simple 200 day moving average test and trading on last day of month.
(you may find it trades on next available day close to end of month as not all dates can be traded weekends etc..)
Rules are ;
1. if last day of month and stock over 200 day moving average, then go long 100%
2. if last day of month and stock under 200 day moving average, then close long 100% and goto cash.
Aims to miss market declines and keep you long for upside.
Note: Have found doesn't work well in choppy markets moving sideways like the FTSE100 for same period 2000-2016 and causes losses. Also for many stocks.
Quantitative Easing DatesThis indicator shows the beginning and the end of quantitative easing policy.
Specific Date Series (llnylk's)Show specific dates/bars (useful for Ichimoku cloud)
Show where are -9th bar, -20th bar, -26th bar, -52th bars in the past
Major Event Price Indicators (Coronavirus Lows)This very simple script adds a corridor for two low price ranges, where Corona started to hit. Useful to visualize where a stock currently trades at, relative to the Corona / Covid-19 crisis.
Can easily be adjusted for different dates regarding any major events, crashes. Useful when you run out of Alarms and just want to see "is that still below or above where it was before ?".
Add as many dates as you want, just alter the names of each indicator.
Built upon the script of vitvlkv.
How To Set Trade Dates
Example how to backtest specific date(s) which can be useful for testing seasonality strategy ideas such as "Sell in May", etc.
If using Daily period with wild card dates it will not trade on 1st day of month. If market is closed will trade on next open day.
Works only with Daily or lower timeframes. When using on Daily timeframe set dates 1 day earlier to execute on desired dates.
Entering 0 in any of the date fields acts a wild card. Example -> Entry Year: 0 is "Every Year", Exit Month: 0 is "Every Month", etc.
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
How To Auto Set Date RangeExample how to automatically set the date range window to be backtested from X days or weeks ago to present. Additional options are also included to manually set the date range or to show entire range available.
Normally when you change chart period it changes the number of days being backtested, which means as you increase the chart period (for example from 5min to 15min), you also increase the number of days traded. So you can not compare apples to apples for which period would yield best performance for your strategy.
By incorporating this code with your own strategy's logic (replacing buy and sell), it will allow you to compare results of different period backtests over the same duration of time.
Date Range: ALL uses entire history.
Date Range: DAYS uses number you set in # Days or Weeks
Date Range: WEEKS uses number you set in # Days or Weeks
Date Range: MANUAL uses manual dates you set in From and To fields
Much gratitude to @pinechrix for suggesting this improvement to me, and to @Gesundheit for pointing me in the right direction on the original example I published previously. Thank you both!
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!