EC_2023_Q4_ENLibrary "EC_2023_Q4_EN"
output2023()
Returns the list of events during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;;; ...
Where: is expressed as date + characteristics: YYYY,MM,DD,hh,mm,ss,x,y,z
x impact in numbers
y event name in numbers
z currency in numbers
name2023()
Returns the list of event names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, name
index: related to event name y
name event: event name related to y text
impact2023()
Returns the list of impact names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, impact
index: related to impact name x
impact: impact name related to x text
currency2023()
Returns the list of currencies during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, currency
index: related to currency name z
currency: currency name related to z text
Индикаторы и стратегии
EC_2023_Q3_ENLibrary "EC_2023_Q3_EN"
output2023()
Returns the list of events during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;;; ...
Where: is expressed as date + characteristics: YYYY,MM,DD,hh,mm,ss,x,y,z
x impact in numbers
y event name in numbers
z currency in numbers
name2023()
Returns the list of event names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, name
index: related to event name y
name event: event name related to y text
impact2023()
Returns the list of impact names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, impact
index: related to impact name x
impact: impact name related to x text
currency2023()
Returns the list of currencies during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, currency
index: related to currency name z
currency: currency name related to z text
EC_2023_Q2_ENLibrary "EC_2023_Q2_EN"
output2023()
Returns the list of events during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;;; ...
Where: is expressed as date + characteristics: YYYY,MM,DD,hh,mm,ss,x,y,z
x impact in numbers
y event name in numbers
z currency in numbers
name2023()
Returns the list of event names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, name
index: related to event name y
name event: event name related to y text
impact2023()
Returns the list of impact names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, impact
index: related to impact name x
impact: impact name related to x text
currency2023()
Returns the list of currencies during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, currency
index: related to currency name z
currency: currency name related to z text
EC_2023_Q1_ENLibrary "EC_2023_Q1_EN"
output2023()
Returns the list of events during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;;; ...
Where: is expressed as date + characteristics: YYYY,MM,DD,hh,mm,ss,x,y,z
x impact in numbers
y event name in numbers
z currency in numbers
name2023()
Returns the list of event names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, name
index: related to event name y
name event: event name related to y text
impact2023()
Returns the list of impact names during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, impact
index: related to impact name x
impact: impact name related to x text
currency2023()
Returns the list of currencies during the period.
Returns: array: (week1,week2, ... week_n)
week_n= ;; ...
Where: is expressed as: index, currency
index: related to currency name z
currency: currency name related to z text
Sessions KillZones Library [TradingFinder]🔵 Introduction
"The Forex Trading Sessions" highlight the active periods across different markets where significant trading volume and influence on the forex market are evident. The primary trading sessions globally include the "Asian Session," "London Session," and "New York Session."
A "Kill Zone" refers to a segment within a session characterized by high trading volume and notably sharper price movements. Consequently, there's a higher probability of encountering price action setups within these zones. Traders capitalize on this phenomenon in pursuit of more successful trading outcomes.
If you aim to integrate sessions or kill zones into your indicators or strategies, utilizing this library can amplify the precision and efficiency of your Python script development.
🔵 How to Use
First, you can add the library to your code as shown in the example below:
import TFlab/SessionAndKillZoneLibrary_TradingFinder/1
🟣 Parameters
SessionDetector(Session_Name, Session_Time, KillZone_Time, Session_Show, KillZone_Show, AreaUpdate, MoreInfo, Session_Color, Info_Color) =>
Parameters:
•Session_Name (string)
•Session_Time (string)
•KillZone_Time (string)
•Session_Show (bool)
•KillZone_Show (bool)
•AreaUpdate (string)
•MoreInfo (bool)
•Session_Color (color)
•Info_Color (color)
Session_Name : You must enter the session name in this parameter.
Session_Time : Enter here the start and end time of the session, which should be based on the UTC time zone.
KillZone_Time : Enter the start and end times of the kill zone, which should be based on the UTC time zone, here.
Session_Show : You can control whether or not to show the session using this entry. You must set true to display and false to not display.
KillZone_Show : Using this input you can control whether the kill zone is displayed or not. You must set true to display and false to not display.
AreaUpdate : If you want the session to be determined based on the time and high and low of the session itself, you must enter "Session" and if you want the area to be determined based on the time and high and low of the kill zone, you must enter "Kill Zone".
MoreInfo : If you want more information, you should set this entry to true, otherwise set to false. This information includes the number of candles in the area, the length of time in the area and the volume of transactions in the area.
Session_Color : Enter your desired color to display the session at this section. It is recommended to use bright and sharp colors.
Info_Color : Enter your desired color to display more information in this section.
🔵 Function Outputs
The outputs of this function are direct and indirect.
🟣 Indirect outputs
These outputs include session display, kill zone display, and time and volume information of session or kill zone.
🟣 Direct outputs
There are 8 direct outputs, which are:
Session Time : If the Session is active, it outputs 1, and if the Session is inactive, it outputs 0.
Kill Zone Time : If the Kill Zone is active, it outputs 1, and if the Kill Zone is inactive, it outputs 0.
Open : Session opening price.
High : The highest price of the session.
Low : The lowest price of the session.
Close : The last price of the session.
Low Touch Alert : If "Area Update" is in "Kill Zone" mode, if the price reaches the lowest price of the kill zone in the same session after the end of the kill zone, this output will be true. You can use this output to create an alert.
High Touch Alert : If "Area Update" is in "Kill Zone" mode, if the price reaches the highest price of the kill zone in the same session after the end of the kill zone, this output will be true. You can use this output to create an alert.
Important : To use "Open", "High", "Low" and "Close", "Area Update" must be in "Session" mode.
Useful_lib_publicLibrary "Useful_lib_public"
Useful functions
CountBarsOfDay()
count bars for one for the diffrent time frames
Returns: number of bars for one day
LastBarsOfDay()
Index number for the las bar for one day
Returns: TRUE is that the last bar from day
isTuesday()
TRUE is tuesday
Returns: TRUE is tuesday else FALSE
Rsi(src, len)
RSI calulation
Parameters:
src (float) : RSI Source
len (simple int) : RSI Length
Returns: RSI Value
CalcIndex(netPos, weeks)
Index calulation
Parameters:
netPos (float) : Source
weeks (simple int) : Length
Returns: "COT Index"
RsiStock(src, len, smoothK)
TRUE is tuesday
Parameters:
src (float)
len (simple int)
smoothK (int)
Returns: RSI Stochastik
Offset()
Use Offset for Day time frame
Returns: Offset
PercentChange(Data, LastData)
Calc different in Percent
Parameters:
Data (float)
LastData (float)
Returns: Change in percent
MathOperatorLibrary "MathOperator"
Methods to handle operators.
method add(value_a, value_b)
Add value a to b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: float.
method subtract(value_a, value_b)
subtract value b from a.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: float.
method multiply(value_a, value_b)
multiply value a with b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: float.
method divide(value_a, value_b)
divide value a with b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: float.
method remainder(value_a, value_b)
remainder of a with b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: float.
method equal(value_a, value_b)
equality of value a with b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method not_equal(value_a, value_b)
inequality of value a with b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method over(value_a, value_b)
value a is over b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method under(value_a, value_b)
value a is under b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method over_equal(value_a, value_b)
value a is over equal b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method under_equal(value_a, value_b)
value a is under equal b.
Namespace types: series float, simple float, input float, const float
Parameters:
value_a (float) : float, value a.
value_b (float) : float, value b.
Returns: bool.
method and_(value_a, value_b)
logical and of a with b
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
method or_(value_a, value_b)
logical or of a with b.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
method not_(value_a)
logical not of a.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
Returns: bool.
method xor_(value_a, value_b)
logical xor of a with b.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
method xnor_(value_a, value_b)
logical xnor of a with b.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
method nand_(value_a, value_b)
logical nand of a with b.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
method nor_(value_a, value_b)
logical nor of a with b.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
value_a (bool) : bool, value a.
value_b (bool) : bool, value b.
Returns: bool.
strategy_helpersThis library is designed to aid traders and developers in calculating risk metrics efficiently across different asset types like equities, futures, and forex. It includes comprehensive functions that calculate the number of units or contracts to trade, the value at risk, and the total value of the position based on provided entry prices, stop levels, and risk percentages. Whether you're managing a portfolio or developing trading strategies, this library provides essential tools for risk management. Functions also automatically select the appropriate risk calculation method based on asset type, calculate leverage levels, and determine potential liquidation points for leveraged positions. Perfect for enhancing the precision and effectiveness of your trading strategies.
Library "strategy_helpers"
Provides tools for calculating risk metrics across different types of trading strategies including equities, futures, and forex. Functions allow for precise control over risk management by calculating the number of units or contracts to trade, the value at risk, and the total position value based on entry prices, stop levels, and desired risk percentage. Additional utilities include automatic risk calculation based on asset type, leverage level calculations, and determination of liquidation levels for leveraged trades.
calculate_risk(entry, stop_level, stop_range, capital, risk_percent, trade_direction, whole_number_buy)
Calculates risk metrics for equity trades based on entry, stop level, and risk percent
Parameters:
entry (float) : The price at which the position is entered. Use close if you arent adding to a position. Use the original entry price if you are adding to a position.
stop_level (float) : The price level where the stop loss is placed
stop_range (float) : The price range from entry to stop level
capital (float) : The total capital available for trading
risk_percent (float) : The percentage of capital risked on the trade. 100% is represented by 100.
trade_direction (bool) : True for long trades, false for short trades
whole_number_buy (bool) : True to adjust the quantity to whole numbers
Returns: A tuple containing the number of units to trade, the value at risk, and the total value of the position:
calculate_risk_futures(risk_capital, stop_range)
Calculates risk metrics for futures trades based on the risk capital and stop range
Parameters:
risk_capital (float) : The capital allocated for the trade
stop_range (float) : The price range from entry to stop level
Returns: A tuple containing the number of contracts to trade, the value at risk, and the total value of the position:
calculate_risk_forex(entry, stop_level, stop_range, capital, risk_percent, trade_direction)
Calculates risk metrics for forex trades based on entry, stop level, and risk percent
Parameters:
entry (float) : The price at which the position is entered. Use close if you arent adding to a position. Use the original entry price if you are adding to a position.
stop_level (float) : The price level where the stop loss is placed
stop_range (float) : The price range from entry to stop level
capital (float) : The total capital available for trading
risk_percent (float) : The percentage of capital risked on the trade. 100% is represented by 100.
trade_direction (bool) : True for long trades, false for short trades
Returns: A tuple containing the number of lots to trade, the value at risk, and the total value of the position:
calculate_risk_auto(entry, stop_level, stop_range, capital, risk_percent, trade_direction, whole_number_buy)
Automatically selects the risk calculation method based on the asset type and calculates risk metrics
Parameters:
entry (float) : The price at which the position is entered. Use close if you arent adding to a position. Use the original entry price if you are adding to a position.
stop_level (float) : The price level where the stop loss is placed
stop_range (float) : The price range from entry to stop level
capital (float) : The total capital available for trading
risk_percent (float) : The percentage of capital risked on the trade. 100% is represented by 100.
trade_direction (bool) : True for long trades, false for short trades
whole_number_buy (bool) : True to adjust the quantity to whole numbers, applicable only for non-futures and non-forex trades
Returns: A tuple containing the number of units or contracts to trade, the value at risk, and the total value of the position:
leverage_level(account_equity, position_value)
Calculates the leverage level used based on account equity and position value
Parameters:
account_equity (float) : Total equity in the trading account
position_value (float) : Total value of the position taken
Returns: The leverage level used in the trade
calculate_liquidation_level(entry, leverage, trade_direction, maintenance_margine)
Calculates the liquidation price level for a leveraged trade
Parameters:
entry (float) : The price at which the position is entered
leverage (float) : The leverage level used in the trade
trade_direction (bool) : True for long trades, false for short trades
maintenance_margine (float) : The maintenance margin requirement, expressed as a percentage
Returns: The price level at which the position would be liquidated, or na if leverage is zero
WebhookMessageDevLibrary "WebhookMessageDev"
The webhook message library provides several functions for building JSON payloads
method buildWebhookJson(msg)
Builds the final JSON payload from a webhookMessage type.
Namespace types: webhookMessage
Parameters:
msg (webhookMessage) : (webhookMessage) A prepared webhookMessage.
Returns: A JSON Payload.
method buildTakeProfitJson(msg)
Builds the takeProfit JSON message to be used in a webhook message.
Namespace types: takeProfitMessage
Parameters:
msg (takeProfitMessage) : (takeProfitMessage)
Returns: A JSON takeProfit payload.
method buildStopLossJson(msg)
Builds the stopLoss JSON message to be used in a webhook message.
Namespace types: stopLossMessage
Parameters:
msg (stopLossMessage) : (stopLossMessage)
Returns: A JSON stopLoss payload.
webhookMessage
Final webhook message.
Fields:
ticker (series string)
action (series string)
sentiment (series string)
price (series float)
quantity (series int)
takeProfit (series string)
stopLoss (series string)
takeProfitMessage
Take profit message.
Fields:
limitPrice (series float)
percent (series float)
amount (series float)
stopLossMessage
Stop loss message.
Fields:
type (series string)
percent (series float)
amount (series float)
stopPrice (series float)
limitPrice (series float)
trailPrice (series float)
trailPercent (series float)
chrono_utilsLibrary "chrono_utils"
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 the 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 happened between the prediction bar and the actual bar
(probably due to a holiday, half session day, a timezone change etc..)
exTimezone(timezone)
exTimezone - Convert extended timezone to timezone string
Parameters:
timezone (simple string) : - The timezone or a special string
Returns: string representing the timezone
nameOfDay(day)
nameOfDay - Convert the day id into a short nameOfDay
Parameters:
day (int) : - The day id to convert
Returns: - The short name of the day
today()
today - Get the day id of this day
Returns: - The day id
nthDayAfter(day, n)
nthDayAfter - Get the day id of n days after the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days after the reference day
nextDayAfter(day)
nextDayAfter - Get the day id of next day after the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the next day after the reference day
nthDayBefore(day, n)
nthDayBefore - Get the day id of n days before the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days before the reference day
prevDayBefore(day)
prevDayBefore - Get the day id of previous day before the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the previous day before the reference day
tomorrow()
tomorrow - Get the day id of the next day
Returns: - The next day day id
normalize(num, min, max)
normalizeHour - Check if number is inthe range of
Parameters:
num (int)
min (int)
max (int)
Returns: - The normalized number
normalizeHour(hourInDay)
normalizeHour - Check if hour is valid and return a noralized hour range from
Parameters:
hourInDay (int)
Returns: - The normalized hour
normalizeMinute(minuteInHour)
normalizeMinute - Check if minute is valid and return a noralized minute from
Parameters:
minuteInHour (int)
Returns: - The normalized minute
monthInMilliseconds(mon)
monthInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Parameters:
mon (int) : - The month of reference to get the miliseconds
Returns: - The number of milliseconds of the month
barInMilliseconds()
barInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Returns: - The number of milliseconds in one bar
method to_string(this)
to_string - Formats the time window into a human-readable string
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The string of the time window
method to_string(this)
to_string - Formats the session days into a human-readable string with short day names
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The string of the session day short names
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session into a human-readable string
Namespace types: Session
Parameters:
this (Session) : - The session object with the day and the time range selection
Returns: - The string of the session
method init(this, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, refTimezone, chTimezone, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
refTimezone (simple string) : - The timezone of reference of the 'from' and 'to' dates
chTimezone (simple string) : - The target timezone to convert the 'from' and 'to' dates
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, sun, mon, tue, wed, thu, fri, sat)
init - Initialize the session days object from boolean values of each session day
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sun (bool) : - Is Sunday a trading day?
mon (bool) : - Is Monday a trading day?
tue (bool) : - Is Tuesday a trading day?
wed (bool) : - Is Wednesday a trading day?
thu (bool) : - Is Thursday a trading day?
fri (bool) : - Is Friday a trading day?
sat (bool) : - Is Saturday a trading day?
Returns: - The session days object
method init(this, unixTime)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
unixTime (int) : - The unix time
Returns: - The session time object
method init(this, hourInDay, minuteInHour)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
Returns: - The session time object
method init(this, hourInDay, minuteInHour, refTimezone)
init - Initialize the object from the hour and minute of the session time
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
refTimezone (string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method init(this, startTime, endTime)
init - Initialize the object from the start and end session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTime (SessionTime) : - The time the session begins
endTime (SessionTime) : - The time the session ends
Returns: - The session time range object
method init(this, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, refTimezone)
init - Initialize the object from the start and end session time
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTimeHour (int) : - The time hour the session begins
startTimeMinute (int) : - The time minute the session begins
endTimeHour (int) : - The time hour the session ends
endTimeMinute (int) : - The time minute the session ends
refTimezone (string)
Returns: - The session time range object
method init(this, days, timeRanges)
init - Initialize the session object from session days and time range
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (array) : - The array of all the session time ranges during a session day
Returns: - The session object
method init(this, days, timeRanges, names, colors)
init - Initialize the session object from session days and time range
Namespace types: SessionView
Parameters:
this (SessionView) : - The session view object that will hold the session, the names and the color selections
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (array) : - The array of all the session time ranges during a session day
names (array) : - The array of the names of the sessions
colors (array) : - The array of the colors of the sessions
Returns: - The session object
method get_size_in_secs(this)
get_size_in_secs - Count the seconds from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of seconds inside the time widow for the given timeframe
method get_size_in_secs(this)
get_size_in_secs - Calculate the seconds inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of seconds inside the session
method get_size_in_bars(this)
get_size_in_bars - Count the bars from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of bars inside the time widow for the given timeframe
method get_size_in_bars(this)
get_size_in_bars - Calculate the bars inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of bars inside the session for the given timeframe
method is_bar_included(this, offset_forward)
is_bar_included - Check if the given bar is between the start and end dates of the window
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
offset_forward (simple int) : - The number of bars forward. Default is 1
Returns: - Whether the current bar is inside the datetime window
method is_bar_included(this, offset_forward)
is_bar_included - Check if the given bar is inside the session as defined by the input params (what "not na(time(timeframe.period, this.to_sess_string()) )" should return if you could write it
Namespace types: Session
Parameters:
this (Session) : - The session with the day and the time range selection
offset_forward (simple int) : - The bar forward to check if it is between the from and to datetimes. Default is 1
Returns: - Whether the current time is inside the session
method to_sess_string(this)
to_sess_string - Formats the session days into a session string with day ids
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object
Returns: - The string of the session day ids
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session into a session string
Namespace types: Session
Parameters:
this (Session) : - The session object with the day and the time range selection
Returns: - The string of the session
method from_sess_string(this, sess)
from_sess_string - Initialize the session days object from the session string
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sess (string) : - The session string part that represents the days
Returns: - The session days object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
Returns: - The session time object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time object from the session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
refTimezone (simple string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time range object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time range object from the session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method from_sess_string(this, sess)
from_sess_string - Initialize the session object from the session string in exchange timezone (syminfo.timezone)
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
sess (string) : - The session string that represents the session HHmm-HHmm,HHmm-HHmm:ddddddd
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session object from the session string
Namespace types: Session
Parameters:
this (Session) : - The session object that will hold the day and the time range selection
sess (string) : - The session string that represents the session HHmm-HHmm,HHmm-HHmm:ddddddd
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method nth_day_after(this, day, n)
nth_day_after - The nth day after the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week after the given day
method nth_day_before(this, day, n)
nth_day_before - The nth day before the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week before the given day
method next_day(this)
next_day - The next day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the next session day of the week
method previous_day(this)
previous_day - The previous day that is session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the previous session day of the week
method get_sec_in_day(this)
get_sec_in_day - Count the seconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of seconds passed from the start of the day until that session time
method get_ms_in_day(this)
get_ms_in_day - Count the milliseconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of milliseconds passed from the start of the day until that session time
method is_day_included(this, day)
is_day_included - Check if the given day is inside the session days
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day to check if it is a trading day
Returns: - Whether the current day is included in the session days
DateTimeWindow
DateTimeWindow - Object that represents a datetime window with a beginning and an end
Fields:
fromDateTime (series int) : - The beginning of the datetime window
toDateTime (series int) : - The end of the datetime window
SessionDays
SessionDays - Object that represent the trading days of the week
Fields:
days (map) : - The map that contains all days of the week and their session flag
SessionTime
SessionTime - Object that represents the time (hour and minutes)
Fields:
hourInDay (series int) : - The hour of the day that ranges from 0 to 24
minuteInHour (series int) : - The minute of the hour that ranges from 0 to 59
minuteInDay (series int) : - The minute of the day that ranges from 0 to 1440. They will be calculated based on hourInDay and minuteInHour when method is called
SessionTimeRange
SessionTimeRange - Object that represents a range that extends from the start to the end time
Fields:
startTime (SessionTime) : - The beginning of the time range
endTime (SessionTime) : - The end of the time range
isOvernight (series bool) : - Whether or not this is an overnight time range
Session
Session - Object that represents a session
Fields:
days (SessionDays) : - The map of the trading days
timeRanges (array) : - The array with all time ranges of the session during the trading days
SessionView
SessionView - Object that visualize a session
Fields:
sess (Session) : - The Session object to be visualized
names (array) : - The names of the session time ranges
colors (array) : - The colors of the session time ranges
Order Block Drawing [TradingFinder]🔵 Introduction
Perhaps one of the most challenging tasks for Pine script developers (especially beginners) is properly drawing order blocks. While utilizing the latest technical analysis methods for "Price Action," beginners heavily rely on accurately plotting "Supply" and "Demand" zones, following concepts like "Smart Money Concept" and "ICT".
However, drawing "Order Blocks" may pose a challenge for developers. Therefore, to minimize bugs, increase accuracy, and speed up the process of coding order blocks, we have released the "Order Block Drawing" library.
Below, you can read more details about how to use this library.
Important :
This library has direct and indirect outputs. The indirect output includes the ranges of order blocks plotted on the chart. However, the direct output is a "Boolean" value that becomes "true" only when the price touches an order block, colloquially termed as "Mitigate." You can use this output for setting up alerts.
🔵 How to Use
First, you can add the library to your code as shown in the example below.
import TFlab/OrderBlockDrawing_TradingFinder/1
🟣Parameters
OBDrawing(OBType, TriggerCondition, DistalPrice, ProximalPrice, Index, OBValidDis, Show, ColorZone) =>
Parameters:
• OBType (string)
• TriggerCondition (bool)
• DistalPrice (float)
• ProximalPrice (float)
• Index (int)
• OBValidDis (int)
• Show (bool)
• ColorZone (color)
OBType : All order blocks are summarized into two types: "Supply" and "Demand." You should input your order block type in this parameter. Enter "Demand" for drawing demand zones and "Supply" for drawing supply zones.
TriggerCondition : Input the condition under which you want the order block to be drawn in this parameter.
DistalPrice : Generally, if each zone is formed by two lines, the farthest line from the price is termed "Distal." This input receives the price of the "Distal" line.
ProximalPrice : Generally, if each zone is formed by two lines, the nearest line to the price is termed "Proximal" line.
Index : This input receives the value of the "bar_index" at the beginning of the order block. You should store the "bar_index" value at the occurrence of the condition for the order block to be drawn and input it here.
OBValidDis : Order blocks continue to be drawn until a new order block is drawn or the order block is "Mitigate." You can specify how many candles after their initiation order blocks should continue. If you want no limitation, enter the number 4998.
Show : You may need to manage whether to display or hide order blocks. When this input is "On", order blocks are displayed, and when it's "Off", order blocks are not displayed.
ColorZone : You can input your preferred color for drawing order blocks.
🔵 Function Outputs
This function has only one output. This output is of type "Boolean" and becomes "true" only when the price touches an order block. Each order block can be touched only once and then loses its validity. You can use this output for alerts.
= Drawing.OBDrawing('Demand', Condition, Distal, Proximal, Index, 4998, true, Color)
mathLibrary "math"
It's a library of discrete aproximations of a price or Series float it uses Fourier Discrete transform, Laplace Discrete Original and Modified transform and Euler's Theoreum for Homogenus White noice operations. Calling functions without source value it automatically take close as the default source value.
Here is a picture of Laplace and Fourier approximated close prices from this library:
Copy this indicator and try it yourself:
import AutomatedTradingAlgorithms/math/1 as math
//@version=5
indicator("Close Price with Aproximations", shorttitle="Close and Aproximations", overlay=false)
// Sample input data (replace this with your own data)
inputData = close
// Plot Close Price
plot(inputData, color=color.blue, title="Close Price")
ltf32_result = math.LTF32(a=0.01)
plot(ltf32_result, color=color.green, title="LTF32 Aproximation")
fft_result = math.FFT()
plot(fft_result, color=color.red, title="Fourier Aproximation")
wavelet_result = math.Wavelet()
plot(wavelet_result, color=color.orange, title="Wavelet Aproximation")
wavelet_std_result = math.Wavelet_std()
plot(wavelet_std_result, color=color.yellow, title="Wavelet_std Aproximation")
DFT3(xval, _dir)
Discrete Fourier Transform with last 3 points
Parameters:
xval (float) : Source series
_dir (int) : Direction parameter
Returns: Aproxiated source value
DFT2(xval, _dir)
Discrete Fourier Transform with last 2 points
Parameters:
xval (float) : Source series
_dir (int) : Direction parameter
Returns: Aproxiated source value
FFT(xval)
Fast Fourier Transform once. It aproximates usig last 3 points.
Parameters:
xval (float) : Source series
Returns: Aproxiated source value
DFT32(xval)
Combined Discrete Fourier Transforms of DFT3 and DTF2 it aproximates last point by first
aproximating last 3 ponts and than using last 2 points of the previus.
Parameters:
xval (float) : Source series
Returns: Aproxiated source value
DTF32(xval)
Combined Discrete Fourier Transforms of DFT3 and DTF2 it aproximates last point by first
aproximating last 3 ponts and than using last 2 points of the previus.
Parameters:
xval (float) : Source series
Returns: Aproxiated source value
LFT3(xval, _dir, a)
Discrete Laplace Transform with last 3 points
Parameters:
xval (float) : Source series
_dir (int) : Direction parameter
a (float) : laplace coeficient
Returns: Aproxiated source value
LFT2(xval, _dir, a)
Discrete Laplace Transform with last 2 points
Parameters:
xval (float) : Source series
_dir (int) : Direction parameter
a (float) : laplace coeficient
Returns: Aproxiated source value
LFT(xval, a)
Fast Laplace Transform once. It aproximates usig last 3 points.
Parameters:
xval (float) : Source series
a (float) : laplace coeficient
Returns: Aproxiated source value
LFT32(xval, a)
Combined Discrete Laplace Transforms of LFT3 and LTF2 it aproximates last point by first
aproximating last 3 ponts and than using last 2 points of the previus.
Parameters:
xval (float) : Source series
a (float) : laplace coeficient
Returns: Aproxiated source value
LTF32(xval, a)
Combined Discrete Laplace Transforms of LFT3 and LTF2 it aproximates last point by first
aproximating last 3 ponts and than using last 2 points of the previus.
Parameters:
xval (float) : Source series
a (float) : laplace coeficient
Returns: Aproxiated source value
whitenoise(indic_, _devided, minEmaLength, maxEmaLength, src)
Ehler's Universal Oscillator with White Noise, without extra aproximated src.
It uses dinamic EMA to aproximate indicator and thus reducing noise.
Parameters:
indic_ (float) : Input series for the indicator values to be smoothed
_devided (int) : Divisor for oscillator calculations
minEmaLength (int) : Minimum EMA length
maxEmaLength (int) : Maximum EMA length
src (float) : Source series
Returns: Smoothed indicator value
whitenoise(indic_, dft1, _devided, minEmaLength, maxEmaLength, src)
Ehler's Universal Oscillator with White Noise and DFT1.
It uses src and sproxiated src (dft1) to clearly define white noice.
It uses dinamic EMA to aproximate indicator and thus reducing noise.
Parameters:
indic_ (float) : Input series for the indicator values to be smoothed
dft1 (float) : Aproximated src value for white noice calculation
_devided (int) : Divisor for oscillator calculations
minEmaLength (int) : Minimum EMA length
maxEmaLength (int) : Maximum EMA length
src (float) : Source series
Returns: Smoothed indicator value
smooth(dft1, indic__, _devided, minEmaLength, maxEmaLength, src)
Smoothing source value with help of indicator series and aproximated source value
It uses src and sproxiated src (dft1) to clearly define white noice.
It uses dinamic EMA to aproximate src and thus reducing noise.
Parameters:
dft1 (float) : Value to be smoothed.
indic__ (float) : Optional input for indicator to help smooth dft1 (default is FFT)
_devided (int) : Divisor for smoothing calculations
minEmaLength (int) : Minimum EMA length
maxEmaLength (int) : Maximum EMA length
src (float) : Source series
Returns: Smoothed source (src) series
smooth(indic__, _devided, minEmaLength, maxEmaLength, src)
Smoothing source value with help of indicator series
It uses dinamic EMA to aproximate src and thus reducing noise.
Parameters:
indic__ (float) : Optional input for indicator to help smooth dft1 (default is FFT)
_devided (int) : Divisor for smoothing calculations
minEmaLength (int) : Minimum EMA length
maxEmaLength (int) : Maximum EMA length
src (float) : Source series
Returns: Smoothed src series
vzo_ema(src, len)
Volume Zone Oscillator with EMA smoothing
Parameters:
src (float) : Source series
len (simple int) : Length parameter for EMA
Returns: VZO value
vzo_sma(src, len)
Volume Zone Oscillator with SMA smoothing
Parameters:
src (float) : Source series
len (int) : Length parameter for SMA
Returns: VZO value
vzo_wma(src, len)
Volume Zone Oscillator with WMA smoothing
Parameters:
src (float) : Source series
len (int) : Length parameter for WMA
Returns: VZO value
alma2(series, windowsize, offset, sigma)
Arnaud Legoux Moving Average 2 accepts sigma as series float
Parameters:
series (float) : Input series
windowsize (int) : Size of the moving average window
offset (float) : Offset parameter
sigma (float) : Sigma parameter
Returns: ALMA value
Wavelet(src, len, offset, sigma)
Aproxiates srt using Discrete wavelet transform.
Parameters:
src (float) : Source series
len (int) : Length parameter for ALMA
offset (simple float)
sigma (simple float)
Returns: Wavelet-transformed series
Wavelet_std(src, len, offset, mag)
Aproxiates srt using Discrete wavelet transform with standard deviation as a magnitude.
Parameters:
src (float) : Source series
len (int) : Length parameter for ALMA
offset (float) : Offset parameter for ALMA
mag (int) : Magnitude parameter for standard deviation
Returns: Wavelet-transformed series
LaplaceTransform(xval, N, a)
Original Laplace Transform over N set of close prices
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
Returns: Aproxiated source value
NLaplaceTransform(xval, N, a, repeat)
Y repetirions on Original Laplace Transform over N set of close prices, each time N-k set of close prices
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
repeat (int) : number of repetitions
Returns: Aproxiated source value
LaplaceTransformsum(xval, N, a, b)
Sum of 2 exponent coeficient of Laplace Transform over N set of close prices
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
Returns: Aproxiated source value
NLaplaceTransformdiff(xval, N, a, b, repeat)
Difference of 2 exponent coeficient of Laplace Transform over N set of close prices
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
repeat (int) : number of repetitions
Returns: Aproxiated source value
N_divLaplaceTransformdiff(xval, N, a, b, repeat)
N repetitions of Difference of 2 exponent coeficient of Laplace Transform over N set of close prices, with dynamic rotation
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
repeat (int) : number of repetitions
Returns: Aproxiated source value
LaplaceTransformdiff(xval, N, a, b)
Difference of 2 exponent coeficient of Laplace Transform over N set of close prices
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
Returns: Aproxiated source value
NLaplaceTransformdiffFrom2(xval, N, a, b, repeat)
N repetitions of Difference of 2 exponent coeficient of Laplace Transform over N set of close prices, second element has for 1 higher exponent factor
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
repeat (int) : number of repetitions
Returns: Aproxiated source value
N_divLaplaceTransformdiffFrom2(xval, N, a, b, repeat)
N repetitions of Difference of 2 exponent coeficient of Laplace Transform over N set of close prices, second element has for 1 higher exponent factor, dynamic rotation
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
repeat (int) : number of repetitions
Returns: Aproxiated source value
LaplaceTransformdiffFrom2(xval, N, a, b)
Difference of 2 exponent coeficient of Laplace Transform over N set of close prices, second element has for 1 higher exponent factor
Parameters:
xval (float) : series to aproximate
N (int) : number of close prices in calculations
a (float) : laplace coeficient
b (float) : second laplace coeficient
Returns: Aproxiated source value
time_and_sessionA library that provides utilities for working with trading sessions and time-based conditions. Functions include session checks, date range checks, day-of-week matching, and session high/low calculations for daily, weekly, monthly, and yearly timeframes. This library streamlines time-related calculations and enhances time-based strategies and indicators.
Library "time_and_session"
Provides functions for checking time and session-based conditions and retrieving session-specific high and low values.
is_session(session, timeframe, timezone)
Checks if the current time is within the specified trading session
Parameters:
session (string) : The trading session, defined using input.session()
timeframe (string) : The timeframe to use, defaults to the current chart's timeframe
timezone (string) : The timezone to use, defaults to the symbol's timezone
Returns: A boolean indicating whether the current time is within the specified trading session
is_date_range(start_time, end_time)
Checks if the current time is within a specified date range
Parameters:
start_time (int) : The start time, defined using input.time()
end_time (int) : The end time, defined using input.time()
Returns: A boolean indicating whether the current time is within the specified date range
is_day_of_week(sunday, monday, tuesday, wednesday, thursday, friday, saturday)
Checks if the current day of the week matches any of the specified days
Parameters:
sunday (bool) : A boolean indicating whether to check for Sunday
monday (bool) : A boolean indicating whether to check for Monday
tuesday (bool) : A boolean indicating whether to check for Tuesday
wednesday (bool) : A boolean indicating whether to check for Wednesday
thursday (bool) : A boolean indicating whether to check for Thursday
friday (bool) : A boolean indicating whether to check for Friday
saturday (bool) : A boolean indicating whether to check for Saturday
Returns: A boolean indicating whether the current day of the week matches any of the specified days
daily_high(source)
Returns the highest value of the specified source during the current daily session
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current daily session, or na if the timeframe is not suitable
daily_low(source)
Returns the lowest value of the specified source during the current daily session
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current daily session, or na if the timeframe is not suitable
regular_session_high(source, persist)
Returns the highest value of the specified source during the current regular trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of regular market hours, defaults to true
Returns: The highest value during the current regular trading session, or na if the timeframe is not suitable
regular_session_low(source, persist)
Returns the lowest value of the specified source during the current regular trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of regular market hours, defaults to true
Returns: The lowest value during the current regular trading session, or na if the timeframe is not suitable
premarket_session_high(source, persist)
Returns the highest value of the specified source during the current premarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of premarket hours, defaults to true
Returns: The highest value during the current premarket trading session, or na if the timeframe is not suitable
premarket_session_low(source, persist)
Returns the lowest value of the specified source during the current premarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of premarket hours, defaults to true
Returns: The lowest value during the current premarket trading session, or na if the timeframe is not suitable
postmarket_session_high(source, persist)
Returns the highest value of the specified source during the current postmarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to high
persist (bool) : A boolean indicating whether to retain the last value outside of postmarket hours, defaults to true
Returns: The highest value during the current postmarket trading session, or na if the timeframe is not suitable
postmarket_session_low(source, persist)
Returns the lowest value of the specified source during the current postmarket trading session
Parameters:
source (float) : The data series to evaluate, defaults to low
persist (bool) : A boolean indicating whether to retain the last value outside of postmarket hours, defaults to true
Returns: The lowest value during the current postmarket trading session, or na if the timeframe is not suitable
weekly_high(source)
Returns the highest value of the specified source during the current weekly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current weekly session, or na if the timeframe is not suitable
weekly_low(source)
Returns the lowest value of the specified source during the current weekly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current weekly session, or na if the timeframe is not suitable
monthly_high(source)
Returns the highest value of the specified source during the current monthly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current monthly session, or na if the timeframe is not suitable
monthly_low(source)
Returns the lowest value of the specified source during the current monthly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current monthly session, or na if the timeframe is not suitable
yearly_high(source)
Returns the highest value of the specified source during the current yearly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to high
Returns: The highest value during the current yearly session, or na if the timeframe is not suitable
yearly_low(source)
Returns the lowest value of the specified source during the current yearly session. Can fail on lower timeframes.
Parameters:
source (float) : The data series to evaluate, defaults to low
Returns: The lowest value during the current yearly session, or na if the timeframe is not suitable
garbage_collection_and_utilitiesGarbage Collection and Utilities is a library that offers a set of functions designed for efficient management of various types of arrays. This library provides garbage collection utilities to remove and delete excess elements, and also includes utilities for checking the size of arrays. It's particularly useful for developers who want to manage labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings efficiently within their scripts.
Both dump and trim act on the array backwards . This means that for trim , the elements that will be left start from 0. If you want the most recent element to be left after trim, you must use unshift().
Garbage Collection:
Functions to remove and delete excess elements from various types of arrays.
Useful for freeing up memory and keeping the arrays within desired size limits.
Size Checking:
Functions to check if arrays are larger than a specified size.
Helps in ensuring that arrays have enough elements before performing operations.
Supported Types:
Compatible with a wide range of array types, including labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
Usage:
The dump methods are ideal for clearing out unwanted elements from arrays, while the trim methods allow for more refined control over the size of arrays.
The ready methods enable you to verify if arrays have the required number of elements before proceeding with further operations.
Library "garbage_collection_and_utilities"
Provides garbage collection utilities for managing and trimming various types of arrays, and utilities to check if an array is of a specific size. Included types are: labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
method ready(self, size)
Checks if an array of labels is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of lines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of polylines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of boxes is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of linefills is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of chart points is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of floats is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of integers is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of booleans is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of strings is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
AminioLibraryLibrary "AminioLibrary"
: this is my personal library that is being used in different indicators and strategies
calculateMA(source, len, maType)
This fuction returns a moving average value based on the type
Parameters:
source (float) : Is the time series source to calculate average from
len (simple int) : The length of the moving average, this should be integer
maType (string) : The type of moving average, acceptable types are : SMA, HMA, EMA, RMA, WMA, VWMA
Returns: value of moving average
atr(source, len)
This fuction returns atr value for a given source
Parameters:
source (float) : Is the time series source to calculate atr from
len (simple int) : The length of the atr, this should be integer
Returns: value of atr from source
superTrend(source, factor, len)
This fuction returns value of super trend indicator and the trend direction as a tupple
Parameters:
source (float) : Is the time series source to calculate super trend from
factor (simple float) : The multiplication factor for upper and lower band calcualtion, this can be a float
len (simple int) : The length of the super trend, this should be integer
Returns: value of atr from source
halfTrend(am, chdev)
This fuction returns a hTrend type carrying different values for half trend indicator
Parameters:
am (int) : This is the amplitude used for calcucating the half trend, use integers
chdev (float) : This is the Channel Deviation value used for calculating upper and lower atr channel boundaries, you can use floats
Returns: hTrend data type
hTrend
Fields:
halfTrend (series__float)
trend (series__integer)
atrHigh (series__float)
atrLow (series__float)
arrowUp (series__float)
arrowDown (series__float)
Order Block Refiner [TradingFinder]🔵 Introduction
The "Refinement" feature allows you to adjust the width of the order block according to your strategy. There are two modes, "Aggressive" and "Defensive," in the "Order Block Refine". The difference between "Aggressive" and "Defensive" lies in the width of the order block.
For risk-averse traders, the "Defensive" mode is suitable as it provides a lower loss limit and a greater reward-to-risk ratio. For risk-taking traders, the "Aggressive" mode is more appropriate. These traders prefer to enter trades at higher prices, and this mode, which has a wider order block width, is more suitable for this group of individuals.
Important :
One of the advantages of using this library is increased code accuracy. Not only does it have the capability to create order blocks, but you can also simply define the condition for order block creation (true/false) and "bar_index," and you'll find the primary range without applying any filters.
🟣 Order Block Refinement Algorithm
The order block ranges are filtered in two stages. In the first stage, the "Open," "High," "Low," and "Close" of the current order block candle, its two or three previous candles, and one subsequent candle (if available) are examined. In this stage, minimum and maximum distances are calculated, and logical range filters are applied.
In the second stage, two modes, "Aggressive" and "Defensive," are calculated.
For the "Defensive" mode, the width of these ranges is compared with the "ATR" (Average True Range) of period 55, and if they are smaller than "ATR" or 1 to more than 4 times "ATR," the width of the range is reduced from 0 to 80 percent.
For the "Aggressive" mode, you get the same output as the first filter, which usually has a wider width than the "Defensive" mode.
• Order Block Refiner : Off
• Order Block Refiner : On / "Aggressive Mode"
• Order Block Refiner : On / "Defensive Mode"
🔵 How to Use
OBRefiner(string OBType, string OBRefine, string RefineMethod, bool TriggerCondition, int Index) =>
Parameters:
• OBType (string)
• OBRefine (string)
• RefineMethod (string)
• TriggerCondition (bool)
• Index (int)
To add "Order Block Refiner Library", you must first add the following code to your script.
import TFlab/OrderBlockRefiner_TradingFinder/1
OBType : This parameter receives 2 inputs. If the order block you want to "Refine" is of type demand, you should enter "Demand," and if it's of type supply, you should enter "Supply."
OBRefine : Set to "On" if you want the "Refine" operation to be performed. Otherwise, set to "Off."
RefineMethod : This input receives 2 modes, "Aggressive" and "Defensive." You can switch between these modes according to your needs.
TriggerCondition : Enter the condition with which the order block is formed in this parameter.
Index : Enter the "bar_index" of the candle where the order block is formed in this parameter.
🟣 Function Outputs
This function has 6 outputs: "bar_index" at the beginning of the "Distal" line, "bar_index+1" at the end of the "Distal" line, "Price" at the "Distal" line, "bar_index" at the beginning of the "Proximal" line, "bar_index+1" at the end of the "Proximal" line, and "Price" at the "Proximal" line, which can be used to draw order blocks.
Sample :
= Refiner.OBRefiner('Demand', 'Off', 'Aggressive',BuMChMain_Trigger, BuMChMain_Index)
if BuMChMain_Trigger
BuMChHlineMain := line.new(BuMChMain_Xp1 , BuMChMain_Yp12 , bar_index , BuMChMain_Yp12, color = color.black , style = line.style_dotted)
BuMChLlineMain := line.new(BuMChMain_Xd1 , BuMChMain_Yd12 , bar_index , BuMChMain_Yd12, color = color.black , style = line.style_dotted)
BuMChFilineMain := linefill.new(BuMChHlineMain ,BuMChLlineMain , color = color.rgb(76, 175, 80 , 75 ) )
Monty3192_LibraryLibrary "Monty3192_Library"
Libreria Monty3192 - MontyTrader
calc_func(inversion1, inversion2, inversion3, inversion4, inversion5, inversion6, inversion7, inversion8, inversion9, inversion10, precio1, precio2, precio3, precio4, precio5, precio6, precio7, precio8, precio9, precio10, act_1, act_2, act_3, act_4, act_5, act_6, act_7, act_8, act_9, act_10)
Parameters:
inversion1 (float)
inversion2 (float)
inversion3 (float)
inversion4 (float)
inversion5 (float)
inversion6 (float)
inversion7 (float)
inversion8 (float)
inversion9 (float)
inversion10 (float)
precio1 (float)
precio2 (float)
precio3 (float)
precio4 (float)
precio5 (float)
precio6 (float)
precio7 (float)
precio8 (float)
precio9 (float)
precio10 (float)
act_1 (bool)
act_2 (bool)
act_3 (bool)
act_4 (bool)
act_5 (bool)
act_6 (bool)
act_7 (bool)
act_8 (bool)
act_9 (bool)
act_10 (bool)
rend_func(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, po)
Parameters:
p1 (float)
p2 (float)
p3 (float)
p4 (float)
p5 (float)
p6 (float)
p7 (float)
p8 (float)
p9 (float)
p10 (float)
po (float)
f_drawLine(cond, x1, y1, x2, y2, colorr, txt, act, offset, txtc, txts)
Parameters:
cond (bool)
x1 (int)
y1 (float)
x2 (int)
y2 (float)
colorr (color)
txt (string)
act (bool)
offset (int)
txtc (color)
txts (string)
f_Vline(cond, x1, y1, x2, y2, colorr, txt, sel, txts, txtc)
Parameters:
cond (bool)
x1 (int)
y1 (float)
x2 (int)
y2 (float)
colorr (color)
txt (string)
sel (bool)
txts (string)
txtc (color)
get_all_time_high()
TRADINGLibrary "TRADING"
This library is a client script for making a webhook signal formatted string to PoABOT server.
entry_message(password, percent, leverage, margin_mode, kis_number)
Create a entry message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for entry based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
order_message(password, percent, leverage, margin_mode, kis_number)
Create a order message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for entry based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
close_message(password, percent, margin_mode, kis_number)
Create a close message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for close based on your wallet balance.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
exit_message(password, percent, margin_mode, kis_number)
Create a exit message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for exit based on your wallet balance.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
manual_message(password, exchange, base, quote, side, qty, price, percent, leverage, margin_mode, kis_number, order_name)
Create a manual message for POABOT
Parameters:
password (string) : (string) The password of your bot.
exchange (string) : (string) The exchange
base (string) : (string) The base
quote (string) : (string) The quote of order message
side (string) : (string) The side of order messsage
qty (float) : (float) The qty of order message
price (float) : (float) The price of order message
percent (float) : (float) The percent for order based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account.
order_name (string) : (string) The name of order message
Returns: (string) A json formatted string for webhook message.
in_trade(start_time, end_time, hide_trade_line)
Create a trade start line
Parameters:
start_time (int) : (int) The start of time.
end_time (int) : (int) The end of time.
hide_trade_line (bool) : (bool) if true, hide trade line. Default false.
Returns: (bool) Get bool for trade based on time range.
real_qty(qty, precision, leverage, contract_size, default_qty_type, default_qty_value)
Get exchange specific real qty
Parameters:
qty (float) : (float) qty
precision (float) : (float) precision
leverage (int) : (int) leverage
contract_size (float) : (float) contract_size
default_qty_type (string)
default_qty_value (float)
Returns: (float) exchange specific qty.
method set(this, password, start_time, end_time, leverage, initial_capital, default_qty_type, default_qty_value, margin_mode, contract_size, kis_number, entry_percent, close_percent, exit_percent, fixed_qty, fixed_cash, real, auto_alert_message, hide_trade_line)
Set bot object.
Namespace types: bot
Parameters:
this (bot)
password (string) : (string) password for poabot.
start_time (int) : (int) start_time timestamp.
end_time (int) : (int) end_time timestamp.
leverage (int) : (int) leverage.
initial_capital (float)
default_qty_type (string)
default_qty_value (float)
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
contract_size (float)
kis_number (int) : (int) kis_number for poabot.
entry_percent (float) : (float) entry_percent for poabot.
close_percent (float) : (float) close_percent for poabot.
exit_percent (float) : (float) exit_percent for poabot.
fixed_qty (float) : (float) fixed qty.
fixed_cash (float) : (float) fixed cash.
real (bool) : (bool) convert qty for exchange specific.
auto_alert_message (bool) : (bool) convert alert_message for exchange specific.
hide_trade_line (bool) : (bool) if true, Hide trade line. Default false.
Returns: (void)
method print(this, message)
Print message using log table.
Namespace types: bot
Parameters:
this (bot)
message (string)
Returns: (void)
method start_trade(this)
start trade using start_time and end_time
Namespace types: bot
Parameters:
this (bot)
Returns: (void)
method entry(this, id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, when)
It is a command to enter market position. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate an entry order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.order, the function strategy.entry is affected by pyramiding and it can reverse market position correctly. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
direction (string) : (string) A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop (float) : (float) An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name (string) : (string) An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
oca_type (string) : (string) An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method order(this, id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, when)
It is a command to place order. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.entry, the function strategy.order is not affected by pyramiding. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
direction (string) : (string) A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop (float) : (float) An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name (string) : (string) An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
oca_type (string) : (string) An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method close_all(this, comment, alert_message, immediately, when)
Exits the current market position, making it flat.
Namespace types: bot
Parameters:
this (bot)
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
immediately (bool) : (bool) An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method cancel(this, id, when)
It is a command to cancel/deactivate pending orders by referencing their names, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel an order by referencing its identifier.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method cancel_all(this, when)
It is a command to cancel/deactivate all pending orders, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
Namespace types: bot
Parameters:
this (bot)
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method close(this, id, comment, qty, qty_percent, alert_message, immediately, when)
It is a command to exit from the entry with the specified ID. If there were multiple entry orders with the same ID, all of them are exited at once. If there are no open entries with the specified ID by the moment the command is triggered, the command will not come into effect. The command uses market order. Every entry is closed by a separate market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
comment (string) : (string) An optional parameter. Additional notes on the order.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
qty_percent (float) : (float) Defines the percentage (0-100) of the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
alert_message (string) : (string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
immediately (bool) : (bool) An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
ticks_to_price(ticks, from)
Converts ticks to a price offset from the supplied price or the average entry price.
Parameters:
ticks (float) : (float) Ticks to convert to a price.
from (float) : (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
method exit(this, id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, comment_profit, comment_loss, comment_trailing, alert_message, alert_profit, alert_loss, alert_trailing, when)
It is a command to exit either a specific entry, or whole market position. If an order with the same ID is already pending, it is possible to modify the order. If an entry order was not filled, but an exit order is generated, the exit order will wait till entry order is filled and then the exit order is placed. To deactivate an exit order, the command strategy.cancel or strategy.cancel_all should be used. If the function strategy.exit is called once, it exits a position only once. If you want to exit multiple times, the command strategy.exit should be called multiple times. If you use a stop loss and a trailing stop, their order type is 'stop', so only one of them is placed (the one that is supposed to be filled first). If all the following parameters 'profit', 'limit', 'loss', 'stop', 'trail_points', 'trail_offset' are 'NaN', the command will fail. To use market order to exit, the command strategy.close or strategy.close_all should be used.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
from_entry (string) : (string) An optional parameter. The identifier of a specific entry order to exit from it. To exit all entries an empty string should be used. The default values is empty string.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
qty_percent (float) : (float) Defines the percentage of (0-100) the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
profit (float) : (float) An optional parameter. Profit target (specified in ticks). If it is specified, a limit order is placed to exit market position when the specified amount of profit (in ticks) is reached. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Profit target (requires a specific price). If it is specified, a limit order is placed to exit market position at the specified price (or better). Priority of the parameter 'limit' is higher than priority of the parameter 'profit' ('limit' is used instead of 'profit', if its value is not 'NaN'). The default value is 'NaN'.
loss (float) : (float) An optional parameter. Stop loss (specified in ticks). If it is specified, a stop order is placed to exit market position when the specified amount of loss (in ticks) is reached. The default value is 'NaN'.
stop (float) : (float) An optional parameter. Stop loss (requires a specific price). If it is specified, a stop order is placed to exit market position at the specified price (or worse). Priority of the parameter 'stop' is higher than priority of the parameter 'loss' ('stop' is used instead of 'loss', if its value is not 'NaN'). The default value is 'NaN'.
trail_price (float) : (float) An optional parameter. Trailing stop activation level (requires a specific price). If it is specified, a trailing stop order will be placed when the specified price level is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
trail_points (float) : (float) An optional parameter. Trailing stop activation level (profit specified in ticks). If it is specified, a trailing stop order will be placed when the calculated price level (specified amount of profit) is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
trail_offset (float) : (float) An optional parameter. Trailing stop price (specified in ticks). The offset in ticks to determine initial price of the trailing stop order: X ticks lower than 'trail_price' or 'trail_points' to exit long position; X ticks higher than 'trail_price' or 'trail_points' to exit short position. The default value is 'NaN'.
oca_name (string) : (string) An optional parameter. Name of the OCA group (oca_type = strategy.oca.reduce) the profit target, the stop loss / the trailing stop orders belong to. If the name is not specified, it will be generated automatically.
comment (string) : (string) Additional notes on the order. If specified, displays near the order marker on the chart. Optional. The default is na.
comment_profit (string) : (string) Additional notes on the order if the exit was triggered by crossing `profit` or `limit` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
comment_loss (string) : (string) Additional notes on the order if the exit was triggered by crossing `stop` or `loss` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
comment_trailing (string) : (string) Additional notes on the order if the exit was triggered by crossing `trail_offset` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
alert_message (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Optional. The default is na.
alert_profit (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `profit` or `limit` specifically. Optional. The default is na.
alert_loss (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `stop` or `loss` specifically. Optional. The default is na.
alert_trailing (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `trail_offset` specifically. Optional. The default is na.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
percent_to_ticks(percent, from)
Converts a percentage of the supplied price or the average entry price to ticks.
Parameters:
percent (float) : (float) The percentage of supplied price to convert to ticks. 50 is 50% of the entry price.
from (float) : (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
Returns: (float) A value in ticks.
percent_to_price(percent, from)
Converts a percentage of the supplied price or the average entry price to a price.
Parameters:
percent (float) : (float) The percentage of the supplied price to convert to price. 50 is 50% of the supplied price.
from (float) : (float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).
bot
Fields:
password (series__string)
start_time (series__integer)
end_time (series__integer)
leverage (series__integer)
initial_capital (series__float)
default_qty_type (series__string)
default_qty_value (series__float)
margin_mode (series__string)
contract_size (series__float)
kis_number (series__integer)
entry_percent (series__float)
close_percent (series__float)
exit_percent (series__float)
log_table (series__table)
fixed_qty (series__float)
fixed_cash (series__float)
real (series__bool)
auto_alert_message (series__bool)
hide_trade_line (series__bool)
LoggerLibLibrary "LoggerLib"
Function Description:
This library aims to extend the logging functionality by overloading various logging methods.
The objective is to enable appending ".log" at the end of different types to make logging outputs easier.
Key features of this function include:
Multi Debug Levels: The readout will encompass error, warning, and info messages.
Controlled Output: Logging can be set for every bar or only the last X bars.
Automatic Logging: Essential variables such as bar_index, time, price, and # of times log has been called can be extracted.
Methods Included:
Logs variables.
Logs floats.
Logs integers.
Logs strings.
Logs booleans.
Logs arrays.
Logs matrices.
Logs maps.
This comprehensive logging function enhances logging capabilities,
providing versatility and ease of use in capturing and debugging data across different contexts.
method log(this, debugLevel, showLast, verbose, showLabels)
Logs any variable type, excluding custom UDTs, and displays to the logs or as a label on bars.
```
// Example
variable = close
variable.log()
variable.log(2, 0,true,true)
// Example Arrays
ArrayVariable = array.from()
ArrayVariable.log()
// Examples Maps
MapVariable = map.new()
MapVariable.log( )
// Example Funky stuff
close.log(debugLevel = 1, showLast = 1, verbose = true, showLabels = true)
```
Namespace types: series float, simple float, input float, const float
Parameters:
this (float) : Variable to be formatted into a logger message
debugLevel (int) : Log Level `1 = log.info | 2 = log.warning 3 = log.error`
showLast (int) : Shows last x Logs, 0 shows all.
verbose (bool) : Include additional Debug logger Data.
showLabels (bool) : Create Labels of the logs on that main chart.
Returns: void
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series int, simple int, input int, const int
Parameters:
this (int)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series string, simple string, input string, const string
Parameters:
this (string)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
this (bool)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series color, simple color, input color, const color
Parameters:
this (color)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
divergingchartpatternLibrary "divergingchartpattern"
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)
booksLibrary "books"
this library contains excerpts from great books to help with trading.
enhiridion()
Fills the map with admonitions from Epictetus' "Enchiridion".
Returns: map with admonitions
CandleInsightsLibrary "CandleInsights"
CandleInsights provides a set of utility functions to facilitate identifying certain types of individual candles and candle patterns.
isBullish()
Returns true if candle is bullish.
Returns: bool
isBearish()
Returns true if candle is bearish.
Returns: bool
isHammer()
Returns true if candle is a hammer. TODO: Allow params
Returns: bool
isShootingStar()
Returns true if candle is a shooting star. TODO: Allow params
Returns: bool
isBearishToppingTail()
Returns true if candle is bearish with a top wick over half the range of the candle. TODO: Allow params
Returns: bool
isHanging()
Returns true if candle is considering a hanging candle (aka hanging man). TODO: Allow params
Returns: bool
isLongBullish(pctChg)
Parameters:
pctChg (float)
isBullishEngulfing()
utilsLibrary "utils"
Provides a set of utility functions for use in strategies or indicators.
colorGreen(opacity)
Parameters:
opacity (int)
colorRed(opacity)
Parameters:
opacity (int)
colorTeal(opacity)
Parameters:
opacity (int)
colorBlue(opacity)
Parameters:
opacity (int)
colorOrange(opacity)
Parameters:
opacity (int)
colorPurple(opacity)
Parameters:
opacity (int)
colorPink(opacity)
Parameters:
opacity (int)
colorYellow(opacity)
Parameters:
opacity (int)
colorWhite(opacity)
Parameters:
opacity (int)
colorBlack(opacity)
Parameters:
opacity (int)
trendChangingUp(emaShort, emaLong)
Signals when the trend is starting to change in a positive direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
trendChangingDown(emaShort, emaLong)
Signals when the trend is starting to change in a negative direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
percentChange(start, end)
Returns the percent change between a start number and end number. A positive change returns a positive value and vice versa.
Parameters:
start (float)
end (float)
Returns: float
percentOf(percent, n)
Returns the number that's the percentage of the provided value.
Parameters:
percent (float) : Use 0.2 for 20 percent, 0.35 for 35 percent, etc.
n (float) : The number to calculate the percentage of.
Returns: float
targetPriceByPercent(percent, n)
Parameters:
percent (float)
n (float)
hasNegativeSlope(start, end)
Parameters:
start (float)
end (float)
timeinrange(resolution, session, timezone)
Returns true when the current time is within a given session window. Note, the time is calculated in the "America/New_York" timezone.
Parameters:
resolution (simple string) : The time interval to use to start/end the background color. Use "1" for the coloring the background up to the minute.
session (simple string) : The session string to use to identify the time window. Example: "0930-1600:23456" means normal market hours on weekdays.
timezone (simple string)
Returns: series bool
barsSinceLastEntry()
Returns the number of bars since the last entry order.
Returns: series int
barsSinceLastExit()
Returns the number of bars since the last exit order.
Returns: series int
calcSlope(ln, lookback)
Calculates the slope of the provided line based on its x,y coordinates in the previous bar to the current bar.
Parameters:
ln (float)
lookback (int)
Returns: series float
openPL()
Returns slope of the line given the start and end x,y coordinates.
Returns: series float
hasConsecutiveNegativeCandles(lookbackInput)
Returns true if the number of consecutive red candles matches the provided count.
Parameters:
lookbackInput (int) : The amount of bars to look back to check for consecutive negative bars. Default = 1.
Returns: series bool
stdevPercent(stdev, price)
Returns the standard deviation as a percentage of price.
Parameters:
stdev (float) : The standard deviation value
price (float) : The current price of the target ticker.
Returns: series float