M-OscillatorM-Oscillator developed By Mohamed Fawzy, MFTA, CFTe
as Written in IFTA Journal 2018 Edition
more info : ifta.org
Interpretation
• M-Oscillator is a bounded oscillator that moves between (-14) and (+14),
• Movement above 10 is considered overbought, and movement below -10 is oversold.
Overbought/Oversold rule:
• Buy when the M-Oscillator violates the (-10) level to the downside and crosses back to the upside.
• Sell when the M-Oscillator crosses above the (+10) level and crosses back to the downside.
Crossover on Extreme Levels
• Sell signals are triggered when the M-Oscillator crosses its signal line above (13), which indicates an extreme market condition
• Buy signals are triggered when the M-Oscillator crosses its signal line below (- 13)
在腳本中搜尋"美元未来10天走势预测"
2-Period RSI strategy (with filter)2-period RSI strategy backtest described in several books of the trader Larry Connors . This strategy uses a 2 periods RSI , one slow arithmetic moving average and one fast arithmetic moving average.
Entry signal:
- RSI 2 value below oversold level (Larry Connors usually sets oversold to be below 5, but other authors prefer to work below 10 due to the higher number of signals).
- Closing above the slow average (200 periods).
- Entry at closing of candle or opening of next candle.
Exit signal:
- Occurs when the candlestick closes above the fast average (the most common fast average is 5 periods, but some traders also suggest the 10 period average).
Entry Filter (modification made by me):
- Applied an RSI2 arithmetic moving average to smooth out oscillations.
- Entered only when RSI2 is below oversold level and RSI2 moving average is below 30.
* NOTE: In the stocks that I evaluate daily the averages of 4 and 6 periods work very well as a filter.
Comments:
This strategy works very well in Daily charts but can be applied in other chart times as well. As this is a strategy to catch market fluctuations, it presents different results with different stocks.
I have been applying this strategy to the stocks of the Brazilian market (BOVESPA) and have enjoyed the result. Every day I evaluate the stocks that are generating entry signals and choose which one to trade based on the stocks with the highest Profit Value.
The RSI 2 averaging filter probably will reduce profit of the backtests because reduces the number of signals, but the Profit Value will usually increase. For me this was a good thing because without the filter, this strategy usually shows more signals than I have capital to allocate.
Before entering a trade I look at which fast average the paper has the highest Profit Value and then I use this average as my output signal for that trade (this change has greatly improved the result of the outputs).
This strategy does not use Stop Loss because normally Stop Loss decreases effectiveness (profit). In any case, the option to apply a percentage Stop Loss if desired is added in the script. As the strategy does not use stop, extra caution with risk management is advisable. I advise not to allocate more than 20% of the trade capital in the same operation.
I'm still studying ways to improve this strategy, but so far this is the best setup I've found. Suggestions are always welcome and we can test to see if they improve the backtest result.
Good luck and good trades.
================================================
Backtest das estratégia do IFR de 2 períodos descrita em varios livros do trader Larry Connors . Esta estratégia usa um IFR de 2 períodos, uma média movel aritmética lenta e uma média movel aritmética rápida.
Sinal de entrada:
- Valor do IFR 2 abaixo do nível de sobrevenda (Larry Connors usualmente define sobrevenda sendo abaixo de 5, mas outros autores preferem trabalhar abaixo de 10 devido ao maior número de sinais).
- Fechamento acima da média lenta (200 períodos).
- Realizado a compra no fechamento do candle ou na abertura do candle seguinte.
Sinal de saída:
- Ocorre quando o candle fecha acima da média rápida (a média rápida mais comum é a de 5 períodos, mas alguns traders sugerem também a média de 10 períodos).
Filtro para entrada (modificação feita por mim):
- Aplicado uma média móvel aritmética do IFR2 para suavisar as oscilações.
- Realizado a entrada apenas quando o IFR2 está abaixo do nível de sobrevenda e a média móvel do IFR2 está abaixo de 30.
*OBS: nos ativos que avalio diariamente as médias de 4 e 6 períodos funcionam muito bem como filtro.
Comentários:
Esta estratégia funciona muito bem no tempo gráfico Diário mas pode ser aplicada tambem em outros tempos gráficos. Como trata-se de uma estratégia para pegar oscilações do mercado, ela apresenta diferentes resultados com diferentes ativos.
Eu venho aplicando esta estratégia nos ativos do mercado brasileiro (BOVESPA) e tenho gostado do resultado. Diariamente eu avalio os papeis que estão gerando entrada e escolho qual irei realizar o trade baseado nos papeis que apresentam maior Profit Value.
O filtro da média do IFR 2 reduz o lucro nos backtests pois reduz também a quantidade de sinais, mas em compensação o Profit Value irá normalmente aumentar. Para mim isto foi algo positivo pois, sem o filtro, normalmente esta estratégia apresenta mais sinais do que possuo capital para alocar.
Antes de entrar em um trade eu olho em qual média rápida o papel apresenta maior Profit Value e então eu utilizo está média como meu sinal de saída para aquele trade (esta mudança tem melhorado bastante o resultado das saídas).
Está estratégia não utiliza Stop Loss pois normalmente o Stop Loss diminui a eficácia (lucro). De qualquer maneira, foi acrescentado no script a opção de aplicar um Stop Loss percentual caso seja desejado. Como a estratégia não utiliza stop é aconselhável um cuidado redobrado com o gerenciamento de risco. Eu aconselho não alocar mais de 20% do capital de trade em uma mesma operação.
Ainda estou estudando formas de melhorar esta estratégia, mas até o momento está é a melhor configuração que encontrei. Sugestões são sempre bem vindas e podemos testar para verificar se melhoram o resultado do backtest.
Boa sorte e bons trades.
Pinescript v3 Compatibility Framework (v4 Migration Tool)Pinescript v3 Compatibility Framework (v4 Migration Tool)
This code makes most v3 scripts work in v4 with only a few minor changes below. Place the framework code before the first input statement.
You can totally delete all comments.
Pros:
- to port to v4 you only need to make a few simple changes, not affecting the core v3 code functionality
Cons:
- without #include - large redundant code block, but can be reduced as needed
- no proper syntax highlighting, intellisence for substitute constant names
Make the following changes in v3 script:
1. standard types can't be var names, color_transp can't be in a function, rename in v3 script:
color() => color.new()
bool => bool_
integer => integer_
float => float_
string => string_
2. init na requires explicit type declaration
float a = na
color col = na
3. persistent var init (optional):
s = na
s := nz(s , s) // or s := na(s ) ? 0 : s
// can be replaced with var s
var s = 0
s := s + 1
___________________________________________________________
Key features of Pinescript v4 (FYI):
1. optional explicit type declaration/conversion (you still can't cast series to int)
float s
2. persistent var modifier
var s
var float s
3. string series - persistent strings now can be used in cond and output to screen dynamically
4. label and line objects
- can be dynamically created, deleted, modified using get/set functions, moved before/after the current bar
- can be in if or a function unlike plot
- max limit: 50-55 label, and 50-55 line drawing objects in addition to already existing plots - both not affected by max plot outputs 64
- can only be used in the main chart
- can serve as the only output function - at least one is required: plot, barcolor, line, label etc.
- dynamic var values (including strings) can be output to screen as text using label.new and to_string
str = close >= open ? "up" : "down"
label.new(bar_index, high, text=str)
col = close >= open ? color.green : color.red
label.new(bar_index, na, "close = " + tostring(close), color=col, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
// create new objects, delete old ones
l = line.new(bar_index, high, bar_index , low , width=4)
line.delete(l )
// free object buffer by deleting old objects first, then create new ones
var l = na
line.delete(l)
l = line.new(bar_index, high, bar_index , low , width=4)
Turtle Trade Channels by KıvanÇ fr3762his trend following system was designed by Dennis Gartman and Bill Eckhart, and relies on breakouts of historical highs and lows to take and close trades: it is the complete opposite to the "buy low and sell high" approach. This trend following system was taught to a group of average and normal individuals, and almost everyone turned into a profitable trader.
The main rule is "Trade an N-day breakout and take profits when an M-day high or low is breached (N must me above M)". Examples:
Buy a 10-day breakout and close the trade when price action reaches a 5-day low.
Go short a 20-day breakout and close the trade when price action reaches a 10-day high.
In this indicator, the red line is the trading line, and the dotted blue line is the exit line. Original system is:
Go long when the trading line crosses below close price
Go short when the trading line rosses above close price
Exit long positions when the price touches the exit line
Exit short positions when the price touches the exit line
Recommended initial stop-loss is ATR * 2 from the opening price. Default system parameters were 20,10 and 55,20.
Original Turtle Rules:
To trade exactly like the turtles did, you need to set up two indicators representing the main and the failsafe system.
Set up the main indicator with TradePeriod = 20 and StopPeriod = 10 (A.k.a S1)
Set up the failsafe indicator with TradePeriod = 55 and StopPeriod = 20 using a different color. (A.k.a S2)
The entry strategy using S1 is as follows
Buy 20-day breakouts using S1 only if last signaled trade was a loss.
Sell 20-day breakouts using S1 only if last signaled trade was a loss.
If last signaled trade by S1 was a win, you shouldn't trade -Irregardless of the direction or if you traded last signal it or not-
The entry strategy using S2 is as follows:
Buy 55-day breakouts only if you ignored last S1 signal and the market is rallying without you
Sell 55-day breakouts only if you ignored last S1 signal and the market is pluging without you
The turtles had a progressive position sizing approach that boosted their winnings. Once a trading decision has been made you should...
Developers: Dennis Gartman and Bill Eckhart
İndikatörü geliştiren: Dennis Gartman and Bill Eckhart
Amazing Crossover System - 100+ pips per day!I got the main concept for this system on another site. While I have made one important change, I must stress that the heart of this system was created by someone else! We must give credit where credit is due!
Y'all know baby pips. @ForexPhantom published about this system and did both back and forward test around 10 years ago.
I found it on the sit and now I put it to code to see how it performs. I assume 10 points spread for every trade. I use Renesource or AxiTrader to get the low spreads.
There are 2 mods, the single trades and constant trading on the direction.
Main concept
Indicators
5 EMA -- YELLOW
10 EMA -- RED
RSI (10 - Apply to Median Price: HL/2) -- One level at 50.
TIME FRAME
1 Hour Only (very important!)
PAIRS
Virtually any pair seems to work as this is strictly technical analysis.
I recommend sticking to the main currencies and avoiding cross currencies (just his preference).
WHEN TO ENTER A TRADE
Enter LONG when the Yellow EMA crosses the Red EMA from underneath.
RSI must be approaching 50 from the BOTTOM and cross 50 to warrant entry.
Enter SHORT when the Yellow EMA crosses the Red EMA from the top.
RSI must be approaching 50 from the TOP and cross 50 to warrant entry.
I've attached a picture which demonstrates all these conditions.
That's it!
f.bpcdn.co
Trend Score by KIVANÇ fr3762Trend Score compares close prices between last close with previous closes by a certain period of time.
It's like momentum but gives a score +1 when close price is equal to or above (defaultly) 10 bars ago and gives a score of -1 when below.
calculation continues from default length to the 2 times of length.
Defaultly (for 10 bars length)
If Trend Score converges to 10; that means there's a strong uptrend
conversely if Trend Score converges to -10; that means a strong downtrend market is on.
JSE Wyckoff Wave Volume Code// The Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE).
// The JSE Wyckoff Wave is in a separate code. This is the code for the volume of the wave. Please see code for the JSE Wyckoff Wave which goes with this indicator.
//
// The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks).
// The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves.
// This is only my attempt to select 10 stocks and a different selection can be made.
// I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock volumne so that moves are of equal magnitude.
// The then provides a view of the overall condition of the market and volume flow in the market.
//
// I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
//
// Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"/0.79
"JSE:SHP"/2.87
"JSE:NPN"/0.18
"JSE:AGL"/1.96
"JSE:SOL"/1.0
"JSE:CFR"/4.42
"JSE:MND"/1.40
"JSE:MTN"/7.63
"JSE:SLM"/7.29
"JSE:FSR"/8.25
JSE Wyckoff WaveThe Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE). Once the wave has been established the volume can also be calculated. Please see code for the JSE Wyckoff Wave Volume which goes with this indicator.
The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks). The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves. This is only my attempt to select 10 stocks and a different selection can be made. I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock so that moves are of equal magnitude. The then provides a view of the overall condition of the market and volume flow in the market.
I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
Most Indecies when constructed assume that all high prices and all low prices happen at the same time and therefor inflate the wicks of the bars. To make the wave more representatives for the SMI Wyckoff Wave the price is determined on the 5 minute timeframe which removes this bias. However, TradingView does not calculate properly when selecting a lower timeframe than in current period. A work around is to call the sma of the highs and add these which provides more realistic tails. Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"*0.79
"JSE:SHP"*2.87
"JSE:NPN"*0.18
"JSE:AGL"*1.96
"JSE:SOL"*1.0
"JSE:CFR"*4.42
"JSE:MND"*1.40
"JSE:MTN"*7.63
"JSE:SLM"*7.29
"JSE:FSR"*8.25
OHLC Daily Resolution BandsShout out to nPE- for the idea.
Bands made with stdev from 10 day OHLC.
Keeps resolution to daily, so you can use bands as daily pivots for day trading.
Upper band 1=yesterday close + 0.5 std(ohlc,10)
Upper band 1=yesterday close + 1 std(ohlc,10)
Mid=yesterday close
Lower band 1=yesterday close - 0.5 std(ohlc,10)
Lower band 2=yesterday close - 1 std(ohlc,1
XPloRR MA-Buy ATR-Trailing-Stop Long Term Strategy Beating B&HXPloRR MA-Buy ATR-MA-Trailing-Stop Strategy
Long term MA Trailing Stop strategy to beat Buy&Hold strategy
None of the strategies that I tested can beat the long term Buy&Hold strategy. That's the reason why I wrote this strategy.
Purpose: beat Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
My buy strategy is triggered by the EMA(blue) crossing over the SMA curve(orange).
My sell strategy is triggered by another EMA(lime) of the close value crossing the trailing stop(green) value.
The trailing stop value(green) is set to a multiple of the ATR(15) value.
ATR(15) is the SMA(15) value of the difference between high and low values.
Every stock has it's own "DNA", so first thing to do is find the right parameters to get the best strategy values voor EMA, SMA and Trailing Stop.
Then keep using these parameter for future buy/sell signals only for that particular stock.
Do the same for other stocks.
Here are the parameters:
Exponential MA: buy trigger when crossing over the SMA value (use values between 11-50)
Simple MA: buy trigger when EMA crosses over the SMA value (use values between 20 and 200)
Stop EMA: sell trigger when Stop EMA of close value crosses under the trailing stop value (use values between 8 and 16)
Trailing Stop #ATR: defines the trailing stop value as a multiple of the ATR(15) value
Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now):
BAR(Barco): EMA=11, SMA=82, StopEMA=12, Stop#ATR=9
Buy&HoldProfit: 45.82%, NetProfit: 294.7%, #Trades:8, %Profit:62.5%, ProfitFactor: 12.539
AAPL(Apple): EMA=12, SMA=45, StopEMA=12, Stop#ATR=6
Buy&HoldProfit: 2925.86%, NetProfit: 4035.92%, #Trades:10, %Profit:60%, ProfitFactor: 6.36
BEKB(Bekaert): EMA=12, SMA=42, StopEMA=12, Stop#ATR=7
Buy&HoldProfit: 81.11%, NetProfit: 521.37%, #Trades:10, %Profit:60%, ProfitFactor: 2.617
SOLB(Solvay): EMA=12, SMA=63, StopEMA=11, Stop#ATR=8
Buy&HoldProfit: 43.61%, NetProfit: 151.4%, #Trades:8, %Profit:75%, ProfitFactor: 3.794
PHIA(Philips): EMA=11, SMA=80, StopEMA=8, Stop#ATR=10
Buy&HoldProfit: 56.79%, NetProfit: 198.46%, #Trades:6, %Profit:83.33%, ProfitFactor: 23.07
I am very curious to see the parameters for your stocks and please make suggestions to improve this strategy.
Mattzab ArrowsMattzab Arrows
THE BASICS
Buy and Sell Signal Arrows
Tack Marks to show how close the next opposite arrow might be- showing possible trend reversals
Standard Bollinger Bands
10-Day SMA Line
Configurable
Open Source
THE NITTY GRITTY
For starters, all values listed below can be changed in the settings. Length of time, as well as source, can be changed. For the Hidden EMA, this can be made visible by increasing its transparency.
ARROWS
The buy and sell signal arrows are based on price and MACD histogram.
The MACD settings are as follows: 10 day fast EMA , 20 day slow EMA , 5 day SMA signal smoothing. Instead of close price, we are using the average point of the day's high, low, and close.
For the arrows, current price and yesterday's price are using hl2 for high/low average.
A BUY arrow is created when:
Current Price IS GREATER THAN Previous Price _AND_ Current MACD Histogram IS GREATER THAN Previous MACD Histogram.
Important Note! Because the MACD Histogram repaints, the buy arrows may appear, then disappear later in the day, if the MACD changes. Check on the changelog to see if I've fixed it by the time you're reading this. (TradingView doesn't let you edit the description after it's been posted)
A SELL arrow is created when:
Current Price IS LESS THAN Previous Price _AND_ Current MACD Histogram IS LESS THAN Yesterday's MACD Histogram _AND_ Close Price is below _EITHER_ the Hidden EMA (default set to 4) _OR_ the Visible SMA (Default set to 10, which is the black line).
The hidden EMA can be made visible by increasing it's transparency in the Style tab.
Including the requirement to only sell if the standard conditions are met, PLUS being below one of those moving average lines, helps to prevent false sell arrows and repainting.
TACK MARKS
The Red Tack is the threshold, or barrier, for the next arrow. It will not move. It is based on previous High/Low/Close Price + MACD.
The Blue Tack is the current point in space for our average Price and MACD Delta Values. It will move throughout the day (or hour or minute depending on your resolution). The Blue Tack will give you an indication of how close or how far from the reversal threshold (Red Tack) the ticker is at that point.
While the Blue Tack is ABOVE Red, the most recent signal arrow will be a buy, and we are in a buy/hold period.
While the Blue Tack is BELOW Red, the most recent signal arrow will be a sell, and we are in a sell/wait period.
If the Blue Tack crosses above or below Red, you'll get the next arrow.
MOVING AVERAGE LINES
There are three moving average lines in this indicator.
The first is black, and is by default a 10-Day Simple Moving Average Line.
This black line is a good safeguard against selling too early. This is a good support line and that's how I use it.
The second is invisible, but can be made visible in the Styling, and is by default a 4-Day Exponential Moving Average Line
The third is the blue 20-Day Bollinger Band line.
BOLLINGER BANDS
The Bollinger Bands are unmodified and are just a background indicator for your use. If you prefer not to see the Bollinger Bands , change their transparency to 0% to hide them. I've cleaned up the Bollinger Bands to make the indicator as a whole- easier on the eyes.
Please leave feedback on how the script works for you, if you run into problems, if you have any changes you'd like to see, etc.
MACDouble + RSI (rec. 15min-2hr intrv) Uses two sets of MACD plus an RSI to either long or short. All three indicators trigger buy/sell as one (ie it's not 'IF MACD1 OR MACD2 OR RSI > 1 = buy", its more like "IF 1 AND 2 AND RSI=buy", all 3 match required for trigger)
The MACD inputs should be tweaked depending on timeframe and what you are trading. If you are doing 1, 3, 5 min or real frequent trading then 21/44/20 and 32/66/29 or other high value MACDs should be considered. If you are doing longer intervals like 2, 3, 4hr then consider 9/19/9 and 21/44/20 for MACDs (experiment! I picked these example #s randomly).
Ideal usage for the MACD sets is to have MACD2 inputs at around 1.5x, 2x, or 3x MACD1's inputs.
Other settings to consider: try having fastlength1=macdlength1 and then (fastlength2 = macdlength2 - 2). Like 10/26/10 and 23/48/20. This seems to increase net profit since it is more likely to trigger before major price moves, but may decrease profitable trade %. Conversely, consider FL1=MCDL1 and FL2 = MCDL2 + (FL2 * 0.5). Example: 10/26/10 and 22/48/30 this can increase profitable trade %, though may cost some net profit.
Feel free to message me with suggestions or questions.
Kay_BBandsV3This is the 3rd version of Kay_BBands.
When +DI (Directional Index ) is above -DI , then Upper band will be visible and vice-versa.
This is when the ADX is above the threshold. 28 is the default in this version. I found its more appealing in 5M time frame.
BLUE - ADX under 10
GREEN - Uptrend, ADX over 10
RED - Downtrend, ADX over 10
Use it with another band with setting 20, 0.6 deviation. Prices keeping above or below the 2nd bands upper or lower bounds shows trending conditions.
I didn't know how to update the old script so published it again.
Changes - :
1) Updated default settings for the indicator
2) ADX setting are now DI (28), ADX (10), adx level to check is 10.
3) IMPORTANT one - When DI is up/down, lower/upper band will also have color (more visible that way.)
Play around the settings.. It really eliminates extra indicator checking visually... Please like if you think idea is good.
CM Renko Overlay BarsCM_Renko Overlay Bars V1
Overlays Renko Bars on Regular Price Bars.
Default Renko plot is based on Average True Range. Look Back period adjustable in Inputs Tab.
If you Choose to use "Traditional" Renko bars and pick the Size of the Renko Bars the please read below.
Value in Input Tab is multiplied by .001 (To work on Forex)
1 = 10 pips on EURUSD - 1 X .001 = .001 or 10 Pips
10 = .01 or 100 Pips
1000 = 1 point to the left of decimal. 1 Point in Stocks etc.
10000 = 10 Points on Stocks etc.
***V2 will fix this issue.
Custom Indicator - No Trade Zone Warning Back Ground Highlights!Years ago I did an analysis of my trades. Every period of the day was profitable except for two. From 10:00-1030, and 1:00 to 1:30. (I was actively Day Trading Futures) Imagine a vertical graph broken down in to 30 minute time segments. I had nice Green bars in every time slot (Showing Net Profits), and HUGE Red Bars from 10 to 10:30 and 1 to 1:30. After analysis I found I made consistent profits at session open, but then I would enter in to bad setups around 10 to make more money. I also found after I took lunch when I came back at 1:00 I would force trades instead of patiently waiting for a great trade setup. I created an indicator that plotted a red background around those times telling me I was not allowed to enter a trade. Profits went up!!! Details on How to adjust times are in 1st Post. You can adjust times and colors to meet your own trading needs.
HSM KILLZONE//@version=5
indicator('HSM KILLZONE', 'HSM KILLZONE', overlay=true, max_bars_back=500, explicit_plot_zorder=true)
import boitoki/AwesomeColor/4 as ac
import boitoki/Utilities/3 as util
///////////////
// Groups
///////////////
g0 = 'GENERAL'
g1_01 = '♯1 SESSION'
g1_02 = '♯2 SESSION'
g1_03 = '♯3 SESSION'
g1_04 = '♯4 SESSION'
g4 = 'BOX'
g6 = 'LABELS'
g5 = 'OPENING RANGE'
g7 = 'FIBONACCI LEVELS'
g8 = 'OPTIONS'
g11 = 'CANDLE'
g10 = 'Alerts visualized'
///////////////
// Defined
///////////////
max_bars = 500
option_yes = 'Yes'
option_no = '× No'
option_extend1 = 'Yes'
option_hide = '× Hide'
option_border_style1 = '────'
option_border_style2 = '- - - - - -'
option_border_style3 = '•••••••••'
option_chart_x = '× No'
option_chart_1 = 'Bar color'
option_chart_2 = 'Candles'
fmt_price = '{0,number,#.#####}'
fmt_pips = '{0,number,#.#}'
icon_separator = ' • '
color_none = color.new(color.black, 100)
color_text = color.new(color.white, 0)
///////////////
// Functions
///////////////
f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000
f_border_style (_style) =>
switch _style
option_border_style1 => line.style_solid
option_border_style2 => line.style_dashed
option_border_style3 => line.style_dotted
=> _style
f_get_period (_session, _start, _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session ) and _session
result := i+1
break
result
f_get_label_position (_y, _side) =>
switch _y
'top' => _side == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
'bottom' => _side == 'outside' ? label.style_label_upper_left : label.style_label_lower_left
f_get_started (_session) => na(_session ) and _session
f_get_ended (_session) => na(_session) and _session
f_message_limit_bars (_v) => '⚠️ This box\'s right position exceeds 500 bars(' + str.tostring(_v) + '). This box is not displayed correctly.'
f_set_line_x1 (_line, _x) =>
if (line.get_x1(_line) != _x)
line.set_x1(_line, _x)
f_set_line_x2 (_line, _x) =>
if (line.get_x2(_line) != _x)
line.set_x2(_line, _x)
f_set_box_right (_box, _x) =>
if box.get_right(_box) != _x
box.set_right(_box, _x)
///////////////
// Inputs
///////////////
// Timezone
i_tz = input.string('GMT-4', title='Timezone', options= , tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group=g0)
i_history_period = input.int(10, 'History', minval=0, group=g0)
i_show = i_history_period > 0
i_lookback = 12 * 60
// Sessions
i_show_sess1 = input.bool(true, 'Session 1 ', group=g1_01, inline='session1_1') and i_show
i_sess1_label = input.string('New York AM', '', group=g1_01, inline='session1_1')
i_sess1_color = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1_barcolor1 = input.color(#0a0a0a, '•', group=g1_01, inline='session1_1')
i_sess1_barcolor2 = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1 = input.session('0700-1100', 'Time', group=g1_01)
i_sess1_extend = input.string(option_no, 'Extend', options= , group=g1_01)
i_sess1_fib = input.string(option_no, 'Fibonacci levels', group=g1_01, options= ) != option_no
i_sess1_op = input.string(option_no, 'Opening range', group=g1_01, options= ) != option_no and i_show
i_sess1_chart = input.string(option_chart_x, 'Bar', options= , group=g1_01)
i_sess1_barcolor = i_sess1_chart == option_chart_1
i_sess1_plotcandle = i_sess1_chart == option_chart_2
i_show_sess2 = input.bool(true, 'Session 2 ', group=g1_02, inline='session2_1') and i_show
i_sess2_label = input.string('New York PM', '', group=g1_02, inline='session2_1')
i_sess2_color = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2_barcolor1 = input.color(#0a0a0a, '•', group=g1_02, inline='session2_1')
i_sess2_barcolor2 = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2 = input.session('1300-1600', 'Time', group=g1_02)
i_sess2_extend = input.string(option_no, 'Extend', options= , group=g1_02)
i_sess2_fib = input.string(option_no, 'Fibonacci levels', group=g1_02, options= ) != option_no
i_sess2_op = input.string(option_no, 'Opening range', group=g1_02, options= ) != option_no and i_show
i_sess2_chart = input.string(option_chart_x, 'Bar', options= , group=g1_02)
i_sess2_barcolor = i_sess2_chart == option_chart_1
i_sess2_plotcandle = i_sess2_chart == option_chart_2
i_show_sess3 = input.bool(true, 'Session 3 ', group=g1_03, inline='session3_1') and i_show
i_sess3_label = input.string('Asian Sesh', '', group=g1_03, inline='session3_1')
i_sess3_color = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3_barcolor1 = input.color(#0a0a0a, '•', group=g1_03, inline='session3_1')
i_sess3_barcolor2 = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3 = input.session('2000-0000', 'Time', group=g1_03)
i_sess3_extend = input.string(option_no, 'Extend', options= , group=g1_03)
i_sess3_fib = input.string(option_no, 'Fibonacci levels', group=g1_03, options= ) != option_no
i_sess3_op = input.string(option_no, 'Opening range', group=g1_03, options= ) != option_no and i_show
i_sess3_chart = input.string(option_chart_x, 'Bar', options= , group=g1_03)
i_sess3_barcolor = i_sess3_chart == option_chart_1
i_sess3_plotcandle = i_sess3_chart == option_chart_2
i_show_sess4 = input.bool(true, 'Session 4 ', group=g1_04, inline='session4_1') and i_show
i_sess4_label = input.string('London', '', group=g1_04, inline='session4_1')
i_sess4_color = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4_barcolor1 = input.color(#0a0a0a, '•', group=g1_04, inline='session4_1')
i_sess4_barcolor2 = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4 = input.session('0200-0500', 'Time', group=g1_04)
i_sess4_extend = input.string(option_no, 'Extend', options= , group=g1_04)
i_sess4_fib = input.string(option_no, 'Fibonacci levels', group=g1_04, options= ) != option_no
i_sess4_op = input.string(option_no, 'Opening range', group=g1_04, options= ) != option_no and i_show
i_sess4_chart = input.string(option_chart_x, 'Bar', options= , group=g1_04)
i_sess4_barcolor = i_sess4_chart == option_chart_1
i_sess4_plotcandle = i_sess4_chart == option_chart_2
// Show & Styles
i_sess_box_style = input.string('Box', 'Style', options= , group=g4)
i_sess_border_style = f_border_style(input.string(option_border_style2, 'Line style', options= , group=g4))
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=g4)
i_sess_bgopacity = input.int(94, 'Transp', minval=0, maxval=100, step=1, group=g4, tooltip='Setting the 100 is no background color')
// Candle
option_candle_body = 'OC'
option_candle_wick = 'OHLC'
i_candle = input.string(option_hide, 'Display', options= , group=g11)
i_candle_border_width = input.int(2, 'Thickness', minval=0, group=g11)
i_show_candle = (i_candle != option_hide) and (i_candle_border_width > 0)
i_show_candle_wick = i_candle == option_candle_wick
option_candle_color1 = 'Session\'s'
option_candle_color2 = 'Red • Green'
i_candle_color = input.string(option_candle_color2, 'Color ', options= , group=g11, inline='candle_color')
i_candle_color_g = input.color(#A6E22E, '', group=g11, inline='candle_color')
i_candle_color_r = input.color(#F92672, '', group=g11, inline='candle_color')
// Labels
i_label_show = input.bool(true, 'Labels', inline='label_show', group=g6) and i_show
i_label_size = str.lower(input.string('Small', '', options= , inline='label_show', group=g6))
i_label_position_y = str.lower(input.string('Top', '', options= , inline='label_show', group=g6))
i_label_position_s = str.lower(input.string('Outside', '', options= , inline='label_show', group=g6))
i_label_position = f_get_label_position(i_label_position_y, i_label_position_s)
i_label_format_name = input.bool(true, 'Name', inline='label_format', group=g6)
i_label_format_day = input.bool(false, 'Day', inline='label_format', group=g6)
i_label_format_price = input.bool(false, 'Price', inline='label_format', group=g6)
i_label_format_pips = input.bool(false, 'Pips', inline='label_format', group=g6)
// Fibonacci levels
i_f_linestyle = f_border_style(input.string(option_border_style1, title="Style", options= , group=g7))
i_f_linewidth = input.int(1, title="Thickness", minval=1, group=g7)
// Opening range
i_o_minutes = input.int(15, title='Periods (minutes)', minval=1, step=1, group=g5)
i_o_minutes := math.max(i_o_minutes, timeframe.multiplier + 1)
i_o_transp = input.int(88, title='Transp', minval=0, maxval=100, step=1, group=g5)
// Alerts
i_alert1_show = input.bool(false, 'Alerts - Sessions stard/end', group=g10)
i_alert2_show = input.bool(false, 'Alerts - Opening range breakouts', group=g10)
i_alert3_show = input.bool(false, 'Alerts - Price crossed session\'s High/Low after session closed', group=g10)
// ------------------------
// Drawing labels
// ------------------------
f_render_label (_show, _session, _is_started, _color, _top, _bottom, _text, _labels) =>
var label my_label = na
var int start_time = na
v_position_y = (i_label_position_y == 'top') ? _top : _bottom
v_label = array.new_string()
v_chg = _top - _bottom
if _is_started
start_time := time
if i_label_format_name and not na(_text)
array.push(v_label, _text)
if i_label_format_day
array.push(v_label, util.get_day(dayofweek(start_time, i_tz)))
if i_label_format_price
array.push(v_label, str.format(fmt_price, v_chg))
if i_label_format_pips
array.push(v_label, str.format(fmt_pips, util.toPips(v_chg)) + ' pips')
if _show
if _is_started
my_label := label.new(bar_index, v_position_y, array.join(v_label, icon_separator), textcolor=_color, color=color_none, size=i_label_size, style=i_label_position)
array.push(_labels, my_label)
util.clear_labels(_labels, i_history_period)
else if _session
label.set_y(my_label, v_position_y)
label.set_text(my_label, array.join(v_label, icon_separator))
// ------------------------
// Drawing Fibonacci levels
// ------------------------
f_render_fibonacci (_show, _session, _is_started, _x1, _x2, _color, _top, _bottom, _level, _width, _style, _is_extend, _lines) =>
var line my_line = na
if _show
y = (_top - _bottom) * _level + _bottom
if _is_started
my_line := line.new(_x1, y, _x2, y, width=_width, color=color.new(_color, 30), style=_style)
array.push(_lines, my_line)
if _is_extend
line.set_extend(my_line, extend.right)
else if _session
line.set_y1(my_line, y)
line.set_y2(my_line, y)
f_set_line_x2(my_line, _x2)
// ------------------------
// Drawing Opening range
// ------------------------
f_render_oprange (_show, _session, _is_started, _x1, _x2, _color, _max, _is_extend, _boxes) =>
var int start_time = na
var box my_box = na
top = ta.highest(high, _max)
bottom = ta.lowest(low, _max)
is_crossover = ta.crossover(close, box.get_top(my_box))
is_crossunder = ta.crossunder(close, box.get_bottom(my_box))
if _show
if _is_started
util.clear_boxes(_boxes, math.max(0, i_history_period - 1))
start_time := time
my_box := na
else if _session
time_op = start_time + (i_o_minutes * 60 * 1000)
time_op_delay = time_op - f_get_time_by_bar(1)
if time <= time_op and time > time_op_delay
my_box := box.new(_x1, top, _x2, bottom, border_width=0, bgcolor=color.new(_color, i_o_transp))
array.push(_boxes, my_box)
if _is_extend
box.set_extend(my_box, extend.right)
my_box
else
f_set_box_right(my_box, _x2)
if is_crossover
alert('Price crossed over the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_top(my_box), "×", color=color.blue, textcolor=ac.tradingview('blue'), style=label.style_none, size=size.large)
if is_crossunder
alert('Price crossed under the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_bottom(my_box), "×", color=color.red, textcolor=ac.tradingview('red'), style=label.style_none, size=size.large)
my_box
// ------------------------
// Drawing candle
// ------------------------
f_render_candle (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _open, _x1, _x2, _boxes, _lines) =>
var box body = na
var line wick1 = na
var line wick2 = na
border_width = i_candle_border_width
cx = math.round(math.avg(_x2, _x1)) - math.round(border_width / 2)
body_color = i_candle_color == option_candle_color2 ? close > _open ? i_candle_color_g : i_candle_color_r : _color
if _show
if _is_started
body := box.new(_x1, _top, _x2, _bottom, body_color, border_width, line.style_solid, bgcolor=color.new(color.black, 100))
wick1 := i_show_candle_wick ? line.new(cx, _top, cx, _top, color=_color, width=border_width, style=line.style_solid) : na
wick2 := i_show_candle_wick ? line.new(cx, _bottom, cx, _bottom, color=_color, width=border_width, style=line.style_solid) : na
array.push(_boxes, body)
array.push(_lines, wick1)
array.push(_lines, wick2)
util.clear_boxes(_boxes, i_history_period)
util.clear_lines(_lines, i_history_period * 2)
else if _session
top = math.max(_open, close)
bottom = math.min(_open, close)
box.set_top(body, top)
box.set_bottom(body, bottom)
box.set_right(body, _x2)
box.set_border_color(body, body_color)
line.set_y1(wick1, _top)
line.set_y2(wick1, top)
f_set_line_x1(wick1, cx)
f_set_line_x2(wick1, cx)
line.set_color(wick1, body_color)
line.set_y1(wick2, _bottom)
line.set_y2(wick2, bottom)
f_set_line_x1(wick2, cx)
f_set_line_x2(wick2, cx)
line.set_color(wick2, body_color)
else if _is_ended
box.set_right(body, bar_index)
// ------------------------
// Rendering limit message
// ------------------------
f_render_limitmessage (_show, _session, _is_started, _is_ended, _x, _y, _rightbars) =>
var label my_note = na
if _show
if _is_started
if _rightbars > max_bars
my_note := label.new(_x, _y, f_message_limit_bars(_rightbars), style=label.style_label_upper_left, color=color.yellow, textalign=text.align_left, yloc=yloc.price)
else if _session
if _rightbars > max_bars
label.set_y(my_note, _y)
label.set_text(my_note, f_message_limit_bars(_rightbars))
else
label.delete(my_note)
else if _is_ended
label.delete(my_note)
true
// Rendering session
//
f_render_sessionrange (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _lines) =>
var line above_line = na
var line below_line = na
if _show
if _is_started
above_line := line.new(_x1, _top, _x2, _top, width=i_sess_border_width, style=i_sess_border_style, color=_color)
below_line := line.new(_x1, _bottom, _x2, _bottom, width=i_sess_border_width, style=i_sess_border_style, color=_color)
linefill.new(above_line, below_line, color.new(_color, i_sess_bgopacity))
array.push(_lines, above_line)
array.push(_lines, below_line)
util.clear_lines(_lines, i_history_period * 2)
if _is_extend
line.set_extend(above_line, extend.right)
line.set_extend(below_line, extend.right)
else if _session
line.set_y1(above_line, _top)
line.set_y2(above_line, _top)
line.set_x2(above_line, _x2)
line.set_y1(below_line, _bottom)
line.set_y2(below_line, _bottom)
line.set_x2(below_line, _x2)
true
else if _is_ended
true
true
// ------------------------
// Rendering session box
// ------------------------
f_render_session (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _boxes) =>
var box my_box = na
if _show
if _is_started
my_box := box.new(_x1, _top, _x2, _bottom, _color, i_sess_border_width, i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
array.push(_boxes, my_box)
util.clear_boxes(_boxes, i_history_period)
if _is_extend
box.set_extend(my_box, extend.right)
else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
f_set_box_right(my_box, _x2)
else if _is_ended
box.set_right(my_box, bar_index)
my_box
// ------------------------
// Drawing market
// ------------------------
f_render_main (_show, _session, _is_started, _is_ended, _color, _top, _bottom) =>
var box my_box = na
var label my_note = na
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0
x0_1 = ta.valuewhen(na(_session ) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session , bar_index, 0)
x0_d = math.abs(x0_2 - x0_1)
limit_bars = max_bars
rightbars = x0_d
if _show
if _is_started
x1 := bar_index
x2 := bar_index + (math.min(x0_d, limit_bars))
session_open := open
session_high := _top
session_low := _bottom
else if _session
true_x2 = x1 + x0_d
rightbars := true_x2 - bar_index
limit_bars := bar_index + max_bars
x2 := math.min(true_x2, limit_bars)
session_high := _top
session_low := _bottom
else if _is_ended
session_open := na
// ------------------------
// Drawing
// ------------------------
draw (_show, _session, _color, _label, _extend, _show_fib, _show_op, _lookback, _boxes_session, _lines_session, _boxes_candle_body, _lines_candle_wick, _boxes_op, _lines_fib, _labels) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
is_extend = _extend != option_no
= f_render_main(_show, _session, is_started, is_ended, _color, top, bottom)
if i_sess_box_style == 'Box'
f_render_session(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _boxes_session)
if i_sess_box_style == 'Sandwich'
f_render_sessionrange(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _lines_session)
if i_show_candle
f_render_candle(_show, _session, is_started, is_ended, _color, top, bottom, _open, x1, x2, _boxes_candle_body, _lines_candle_wick)
if i_label_show
f_render_label(_show, _session, is_started, _color, top, bottom, _label, _labels)
if _show_op
f_render_oprange(_show, _session, is_started, x1, x2, _color, max, is_extend, _boxes_op)
if _show_fib
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.500, 2, line.style_solid, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.628, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.382, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
util.clear_lines(_lines_fib, i_history_period * 3)
f_render_limitmessage(_show, _session, is_started, is_ended, x1, bottom, _rightbars)
///////////////////
// Calculating
///////////////////
string tz = (i_tz == option_no or i_tz == '') ? na : i_tz
int sess1 = time(timeframe.period, i_sess1, tz)
int sess2 = time(timeframe.period, i_sess2, tz)
int sess3 = time(timeframe.period, i_sess3, tz)
int sess4 = time(timeframe.period, i_sess4, tz)
///////////////////
// Plotting
///////////////////
var sess1_box = array.new()
var sess2_box = array.new()
var sess3_box = array.new()
var sess4_box = array.new()
var sess1_line = array.new()
var sess2_line = array.new()
var sess3_line = array.new()
var sess4_line = array.new()
var sess1_op = array.new()
var sess2_op = array.new()
var sess3_op = array.new()
var sess4_op = array.new()
var sess1_fib = array.new()
var sess2_fib = array.new()
var sess3_fib = array.new()
var sess4_fib = array.new()
var sess1_candle_body = array.new()
var sess2_candle_body = array.new()
var sess3_candle_body = array.new()
var sess4_candle_body = array.new()
var sess1_candle_wick = array.new()
var sess2_candle_wick = array.new()
var sess3_candle_wick = array.new()
var sess4_candle_wick = array.new()
var sess1_labels = array.new()
var sess2_labels = array.new()
var sess3_labels = array.new()
var sess4_labels = array.new()
= draw(i_show_sess1, sess1, i_sess1_color, i_sess1_label, i_sess1_extend, i_sess1_fib, i_sess1_op, i_lookback, sess1_box, sess1_line, sess1_candle_body, sess1_candle_wick, sess1_op, sess1_fib, sess1_labels)
= draw(i_show_sess2, sess2, i_sess2_color, i_sess2_label, i_sess2_extend, i_sess2_fib, i_sess2_op, i_lookback, sess2_box, sess2_line, sess2_candle_body, sess2_candle_wick, sess2_op, sess2_fib, sess2_labels)
= draw(i_show_sess3, sess3, i_sess3_color, i_sess3_label, i_sess3_extend, i_sess3_fib, i_sess3_op, i_lookback, sess3_box, sess3_line, sess3_candle_body, sess3_candle_wick, sess3_op, sess3_fib, sess3_labels)
= draw(i_show_sess4, sess4, i_sess4_color, i_sess4_label, i_sess4_extend, i_sess4_fib, i_sess4_op, i_lookback, sess4_box, sess4_line, sess4_candle_body, sess4_candle_wick, sess4_op, sess4_fib, sess4_labels)
is_positive_bar = close > open
color c_barcolor = na
color c_plotcandle = na
c_sess1_barcolor = (is_sess1) ? (is_positive_bar ? i_sess1_barcolor1 : i_sess1_barcolor2) : na
c_sess2_barcolor = (is_sess2) ? (is_positive_bar ? i_sess2_barcolor1 : i_sess2_barcolor2) : na
c_sess3_barcolor = (is_sess3) ? (is_positive_bar ? i_sess3_barcolor1 : i_sess3_barcolor2) : na
c_sess4_barcolor = (is_sess4) ? (is_positive_bar ? i_sess4_barcolor1 : i_sess4_barcolor2) : na
if (i_sess1_chart != option_chart_x) and is_sess1
c_barcolor := i_sess1_barcolor ? c_sess1_barcolor : na
c_plotcandle := i_sess1_plotcandle ? c_sess1_barcolor : na
if (i_sess2_chart != option_chart_x) and is_sess2
c_barcolor := i_sess2_barcolor ? c_sess2_barcolor : na
c_plotcandle := i_sess2_plotcandle ? c_sess2_barcolor : na
if (i_sess3_chart != option_chart_x) and is_sess3
c_barcolor := i_sess3_barcolor ? c_sess3_barcolor : na
c_plotcandle := i_sess3_plotcandle ? c_sess3_barcolor : na
if (i_sess4_chart != option_chart_x) and is_sess4
c_barcolor := i_sess4_barcolor ? c_sess4_barcolor : na
c_plotcandle := i_sess4_plotcandle ? c_sess4_barcolor : na
barcolor(c_barcolor)
plotcandle(open, high, low, close, color=is_positive_bar ? color_none : c_plotcandle, bordercolor=c_plotcandle, wickcolor=c_plotcandle)
////////////////////
// Alerts
////////////////////
// Session alerts
sess1_started = is_sess1 and not is_sess1 , sess1_ended = not is_sess1 and is_sess1
sess2_started = is_sess2 and not is_sess2 , sess2_ended = not is_sess2 and is_sess2
sess3_started = is_sess3 and not is_sess3 , sess3_ended = not is_sess3 and is_sess3
sess4_started = is_sess4 and not is_sess4 , sess4_ended = not is_sess4 and is_sess4
alertcondition(sess1_started, 'Session #1 started')
alertcondition(sess1_ended, 'Session #1 ended')
alertcondition(sess2_started, 'Session #2 started')
alertcondition(sess2_ended, 'Session #2 ended')
alertcondition(sess3_started, 'Session #3 started')
alertcondition(sess3_ended, 'Session #3 ended')
alertcondition(sess4_started, 'Session #4 started')
alertcondition(sess4_ended, 'Session #4 ended')
alertcondition((not is_sess1) and ta.crossover(close, sess1_high), 'Session #1 High crossed (after session closed)')
alertcondition((not is_sess1) and ta.crossunder(close, sess1_low), 'Session #1 Low crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossover(close, sess2_high), 'Session #2 High crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossunder(close, sess2_low), 'Session #2 Low crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossover(close, sess3_high), 'Session #3 High crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossunder(close, sess3_low), 'Session #3 Low crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossover(close, sess4_high), 'Session #4 High crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossunder(close, sess4_low), 'Session #4 Low crossed (after session closed)')
// Alerts visualized
if i_alert1_show
if i_show_sess1
if sess1_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess1_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess2
if sess2_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess2_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess3
if sess3_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess3_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess4
if sess4_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess4_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
plot(i_alert3_show ? sess1_high : na, 'sess1_high', style=plot.style_linebr, color=i_sess1_color)
plot(i_alert3_show ? sess1_low : na, 'sess1_low' , style=plot.style_linebr, color=i_sess1_color, linewidth=2)
plot(i_alert3_show ? sess2_high : na, 'sess2_high', style=plot.style_linebr, color=i_sess2_color)
plot(i_alert3_show ? sess2_low : na, 'sess2_low' , style=plot.style_linebr, color=i_sess2_color, linewidth=2)
plot(i_alert3_show ? sess3_high : na, 'sess3_high', style=plot.style_linebr, color=i_sess3_color)
plot(i_alert3_show ? sess3_low : na, 'sess3_low' , style=plot.style_linebr, color=i_sess3_color, linewidth=2)
plot(i_alert3_show ? sess4_high : na, 'sess4_high', style=plot.style_linebr, color=i_sess4_color)
plot(i_alert3_show ? sess4_low : na, 'sess4_low' , style=plot.style_linebr, color=i_sess4_color, linewidth=2)
plotshape(i_alert3_show and (not is_sess1) and ta.crossover(close, sess1_high) ? sess1_high : na, 'cross sess1_high', color=i_sess1_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess1) and ta.crossunder(close, sess1_low) ? sess1_low : na, 'cross sess1_low', color=i_sess1_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossover(close, sess2_high) ? sess2_high : na, 'cross sess2_high', color=i_sess2_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossunder(close, sess2_low) ? sess2_low : na, 'cross sess2_low', color=i_sess2_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossover(close, sess3_high) ? sess3_high : na, 'cross sess3_high', color=i_sess3_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossunder(close, sess3_low) ? sess3_low : na, 'cross sess3_low', color=i_sess3_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossover(close, sess4_high) ? sess4_high : na, 'cross sess4_high', color=i_sess4_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossunder(close, sess4_low) ? sess4_low : na, 'cross sess4_low', color=i_sess4_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
HSM MACROS//@version=5
indicator('HSM MACROS', 'HSM MACROS', overlay=true, max_bars_back=500, explicit_plot_zorder=true)
import boitoki/AwesomeColor/4 as ac
import boitoki/Utilities/3 as util
///////////////
// Groups
///////////////
g0 = 'GENERAL'
g1_01 = '♯1 SESSION'
g1_02 = '♯2 SESSION'
g1_03 = '♯3 SESSION'
g1_04 = '♯4 SESSION'
g4 = 'BOX'
g6 = 'LABELS'
g5 = 'OPENING RANGE'
g7 = 'FIBONACCI LEVELS'
g8 = 'OPTIONS'
g11 = 'CANDLE'
g10 = 'Alerts visualized'
///////////////
// Defined
///////////////
max_bars = 500
option_yes = 'Yes'
option_no = '× No'
option_extend1 = 'Yes'
option_hide = '× Hide'
option_border_style1 = '────'
option_border_style2 = '- - - - - -'
option_border_style3 = '•••••••••'
option_chart_x = '× No'
option_chart_1 = 'Bar color'
option_chart_2 = 'Candles'
fmt_price = '{0,number,#.#####}'
fmt_pips = '{0,number,#.#}'
icon_separator = ' • '
color_none = color.new(color.black, 100)
color_text = color.new(color.white, 0)
///////////////
// Functions
///////////////
f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000
f_border_style (_style) =>
switch _style
option_border_style1 => line.style_solid
option_border_style2 => line.style_dashed
option_border_style3 => line.style_dotted
=> _style
f_get_period (_session, _start, _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session ) and _session
result := i+1
break
result
f_get_label_position (_y, _side) =>
switch _y
'top' => _side == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
'bottom' => _side == 'outside' ? label.style_label_upper_left : label.style_label_lower_left
f_get_started (_session) => na(_session ) and _session
f_get_ended (_session) => na(_session) and _session
f_message_limit_bars (_v) => '⚠️ This box\'s right position exceeds 500 bars(' + str.tostring(_v) + '). This box is not displayed correctly.'
f_set_line_x1 (_line, _x) =>
if (line.get_x1(_line) != _x)
line.set_x1(_line, _x)
f_set_line_x2 (_line, _x) =>
if (line.get_x2(_line) != _x)
line.set_x2(_line, _x)
f_set_box_right (_box, _x) =>
if box.get_right(_box) != _x
box.set_right(_box, _x)
///////////////
// Inputs
///////////////
// Timezone
i_tz = input.string('GMT-4', title='Timezone', options= , tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group=g0)
i_history_period = input.int(10, 'History', minval=0, group=g0)
i_show = i_history_period > 0
i_lookback = 12 * 60
// Sessions
i_show_sess1 = input.bool(true, 'Session 1 ', group=g1_01, inline='session1_1') and i_show
i_sess1_label = input.string('MC1', '', group=g1_01, inline='session1_1')
i_sess1_color = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1_barcolor1 = input.color(#0a0a0a, '•', group=g1_01, inline='session1_1')
i_sess1_barcolor2 = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1 = input.session('0820-0830', 'Time', group=g1_01)
i_sess1_extend = input.string(option_no, 'Extend', options= , group=g1_01)
i_sess1_fib = input.string(option_no, 'Fibonacci levels', group=g1_01, options= ) != option_no
i_sess1_op = input.string(option_no, 'Opening range', group=g1_01, options= ) != option_no and i_show
i_sess1_chart = input.string(option_chart_x, 'Bar', options= , group=g1_01)
i_sess1_barcolor = i_sess1_chart == option_chart_1
i_sess1_plotcandle = i_sess1_chart == option_chart_2
i_show_sess2 = input.bool(true, 'Session 2 ', group=g1_02, inline='session2_1') and i_show
i_sess2_label = input.string('MC2', '', group=g1_02, inline='session2_1')
i_sess2_color = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2_barcolor1 = input.color(#0a0a0a, '•', group=g1_02, inline='session2_1')
i_sess2_barcolor2 = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2 = input.session('0920-0930', 'Time', group=g1_02)
i_sess2_extend = input.string(option_no, 'Extend', options= , group=g1_02)
i_sess2_fib = input.string(option_no, 'Fibonacci levels', group=g1_02, options= ) != option_no
i_sess2_op = input.string(option_no, 'Opening range', group=g1_02, options= ) != option_no and i_show
i_sess2_chart = input.string(option_chart_x, 'Bar', options= , group=g1_02)
i_sess2_barcolor = i_sess2_chart == option_chart_1
i_sess2_plotcandle = i_sess2_chart == option_chart_2
i_show_sess3 = input.bool(true, 'Session 3 ', group=g1_03, inline='session3_1') and i_show
i_sess3_label = input.string('MC3', '', group=g1_03, inline='session3_1')
i_sess3_color = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3_barcolor1 = input.color(#0a0a0a, '•', group=g1_03, inline='session3_1')
i_sess3_barcolor2 = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3 = input.session('0950-1010', 'Time', group=g1_03)
i_sess3_extend = input.string(option_no, 'Extend', options= , group=g1_03)
i_sess3_fib = input.string(option_no, 'Fibonacci levels', group=g1_03, options= ) != option_no
i_sess3_op = input.string(option_no, 'Opening range', group=g1_03, options= ) != option_no and i_show
i_sess3_chart = input.string(option_chart_x, 'Bar', options= , group=g1_03)
i_sess3_barcolor = i_sess3_chart == option_chart_1
i_sess3_plotcandle = i_sess3_chart == option_chart_2
i_show_sess4 = input.bool(true, 'Session 4 ', group=g1_04, inline='session4_1') and i_show
i_sess4_label = input.string('MC4', '', group=g1_04, inline='session4_1')
i_sess4_color = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4_barcolor1 = input.color(#0a0a0a, '•', group=g1_04, inline='session4_1')
i_sess4_barcolor2 = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4 = input.session('1050-1110', 'Time', group=g1_04)
i_sess4_extend = input.string(option_no, 'Extend', options= , group=g1_04)
i_sess4_fib = input.string(option_no, 'Fibonacci levels', group=g1_04, options= ) != option_no
i_sess4_op = input.string(option_no, 'Opening range', group=g1_04, options= ) != option_no and i_show
i_sess4_chart = input.string(option_chart_x, 'Bar', options= , group=g1_04)
i_sess4_barcolor = i_sess4_chart == option_chart_1
i_sess4_plotcandle = i_sess4_chart == option_chart_2
// Show & Styles
i_sess_box_style = input.string('Box', 'Style', options= , group=g4)
i_sess_border_style = f_border_style(input.string(option_border_style2, 'Line style', options= , group=g4))
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=g4)
i_sess_bgopacity = input.int(94, 'Transp', minval=0, maxval=100, step=1, group=g4, tooltip='Setting the 100 is no background color')
// Candle
option_candle_body = 'OC'
option_candle_wick = 'OHLC'
i_candle = input.string(option_hide, 'Display', options= , group=g11)
i_candle_border_width = input.int(2, 'Thickness', minval=0, group=g11)
i_show_candle = (i_candle != option_hide) and (i_candle_border_width > 0)
i_show_candle_wick = i_candle == option_candle_wick
option_candle_color1 = 'Session\'s'
option_candle_color2 = 'Red • Green'
i_candle_color = input.string(option_candle_color2, 'Color ', options= , group=g11, inline='candle_color')
i_candle_color_g = input.color(#A6E22E, '', group=g11, inline='candle_color')
i_candle_color_r = input.color(#F92672, '', group=g11, inline='candle_color')
// Labels
i_label_show = input.bool(true, 'Labels', inline='label_show', group=g6) and i_show
i_label_size = str.lower(input.string('Small', '', options= , inline='label_show', group=g6))
i_label_position_y = str.lower(input.string('Top', '', options= , inline='label_show', group=g6))
i_label_position_s = str.lower(input.string('Outside', '', options= , inline='label_show', group=g6))
i_label_position = f_get_label_position(i_label_position_y, i_label_position_s)
i_label_format_name = input.bool(true, 'Name', inline='label_format', group=g6)
i_label_format_day = input.bool(false, 'Day', inline='label_format', group=g6)
i_label_format_price = input.bool(false, 'Price', inline='label_format', group=g6)
i_label_format_pips = input.bool(false, 'Pips', inline='label_format', group=g6)
// Fibonacci levels
i_f_linestyle = f_border_style(input.string(option_border_style1, title="Style", options= , group=g7))
i_f_linewidth = input.int(1, title="Thickness", minval=1, group=g7)
// Opening range
i_o_minutes = input.int(15, title='Periods (minutes)', minval=1, step=1, group=g5)
i_o_minutes := math.max(i_o_minutes, timeframe.multiplier + 1)
i_o_transp = input.int(88, title='Transp', minval=0, maxval=100, step=1, group=g5)
// Alerts
i_alert1_show = input.bool(false, 'Alerts - Sessions stard/end', group=g10)
i_alert2_show = input.bool(false, 'Alerts - Opening range breakouts', group=g10)
i_alert3_show = input.bool(false, 'Alerts - Price crossed session\'s High/Low after session closed', group=g10)
// ------------------------
// Drawing labels
// ------------------------
f_render_label (_show, _session, _is_started, _color, _top, _bottom, _text, _labels) =>
var label my_label = na
var int start_time = na
v_position_y = (i_label_position_y == 'top') ? _top : _bottom
v_label = array.new_string()
v_chg = _top - _bottom
if _is_started
start_time := time
if i_label_format_name and not na(_text)
array.push(v_label, _text)
if i_label_format_day
array.push(v_label, util.get_day(dayofweek(start_time, i_tz)))
if i_label_format_price
array.push(v_label, str.format(fmt_price, v_chg))
if i_label_format_pips
array.push(v_label, str.format(fmt_pips, util.toPips(v_chg)) + ' pips')
if _show
if _is_started
my_label := label.new(bar_index, v_position_y, array.join(v_label, icon_separator), textcolor=_color, color=color_none, size=i_label_size, style=i_label_position)
array.push(_labels, my_label)
util.clear_labels(_labels, i_history_period)
else if _session
label.set_y(my_label, v_position_y)
label.set_text(my_label, array.join(v_label, icon_separator))
// ------------------------
// Drawing Fibonacci levels
// ------------------------
f_render_fibonacci (_show, _session, _is_started, _x1, _x2, _color, _top, _bottom, _level, _width, _style, _is_extend, _lines) =>
var line my_line = na
if _show
y = (_top - _bottom) * _level + _bottom
if _is_started
my_line := line.new(_x1, y, _x2, y, width=_width, color=color.new(_color, 30), style=_style)
array.push(_lines, my_line)
if _is_extend
line.set_extend(my_line, extend.right)
else if _session
line.set_y1(my_line, y)
line.set_y2(my_line, y)
f_set_line_x2(my_line, _x2)
// ------------------------
// Drawing Opening range
// ------------------------
f_render_oprange (_show, _session, _is_started, _x1, _x2, _color, _max, _is_extend, _boxes) =>
var int start_time = na
var box my_box = na
top = ta.highest(high, _max)
bottom = ta.lowest(low, _max)
is_crossover = ta.crossover(close, box.get_top(my_box))
is_crossunder = ta.crossunder(close, box.get_bottom(my_box))
if _show
if _is_started
util.clear_boxes(_boxes, math.max(0, i_history_period - 1))
start_time := time
my_box := na
else if _session
time_op = start_time + (i_o_minutes * 60 * 1000)
time_op_delay = time_op - f_get_time_by_bar(1)
if time <= time_op and time > time_op_delay
my_box := box.new(_x1, top, _x2, bottom, border_width=0, bgcolor=color.new(_color, i_o_transp))
array.push(_boxes, my_box)
if _is_extend
box.set_extend(my_box, extend.right)
my_box
else
f_set_box_right(my_box, _x2)
if is_crossover
alert('Price crossed over the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_top(my_box), "×", color=color.blue, textcolor=ac.tradingview('blue'), style=label.style_none, size=size.large)
if is_crossunder
alert('Price crossed under the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_bottom(my_box), "×", color=color.red, textcolor=ac.tradingview('red'), style=label.style_none, size=size.large)
my_box
// ------------------------
// Drawing candle
// ------------------------
f_render_candle (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _open, _x1, _x2, _boxes, _lines) =>
var box body = na
var line wick1 = na
var line wick2 = na
border_width = i_candle_border_width
cx = math.round(math.avg(_x2, _x1)) - math.round(border_width / 2)
body_color = i_candle_color == option_candle_color2 ? close > _open ? i_candle_color_g : i_candle_color_r : _color
if _show
if _is_started
body := box.new(_x1, _top, _x2, _bottom, body_color, border_width, line.style_solid, bgcolor=color.new(color.black, 100))
wick1 := i_show_candle_wick ? line.new(cx, _top, cx, _top, color=_color, width=border_width, style=line.style_solid) : na
wick2 := i_show_candle_wick ? line.new(cx, _bottom, cx, _bottom, color=_color, width=border_width, style=line.style_solid) : na
array.push(_boxes, body)
array.push(_lines, wick1)
array.push(_lines, wick2)
util.clear_boxes(_boxes, i_history_period)
util.clear_lines(_lines, i_history_period * 2)
else if _session
top = math.max(_open, close)
bottom = math.min(_open, close)
box.set_top(body, top)
box.set_bottom(body, bottom)
box.set_right(body, _x2)
box.set_border_color(body, body_color)
line.set_y1(wick1, _top)
line.set_y2(wick1, top)
f_set_line_x1(wick1, cx)
f_set_line_x2(wick1, cx)
line.set_color(wick1, body_color)
line.set_y1(wick2, _bottom)
line.set_y2(wick2, bottom)
f_set_line_x1(wick2, cx)
f_set_line_x2(wick2, cx)
line.set_color(wick2, body_color)
else if _is_ended
box.set_right(body, bar_index)
// ------------------------
// Rendering limit message
// ------------------------
f_render_limitmessage (_show, _session, _is_started, _is_ended, _x, _y, _rightbars) =>
var label my_note = na
if _show
if _is_started
if _rightbars > max_bars
my_note := label.new(_x, _y, f_message_limit_bars(_rightbars), style=label.style_label_upper_left, color=color.yellow, textalign=text.align_left, yloc=yloc.price)
else if _session
if _rightbars > max_bars
label.set_y(my_note, _y)
label.set_text(my_note, f_message_limit_bars(_rightbars))
else
label.delete(my_note)
else if _is_ended
label.delete(my_note)
true
// Rendering session
//
f_render_sessionrange (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _lines) =>
var line above_line = na
var line below_line = na
if _show
if _is_started
above_line := line.new(_x1, _top, _x2, _top, width=i_sess_border_width, style=i_sess_border_style, color=_color)
below_line := line.new(_x1, _bottom, _x2, _bottom, width=i_sess_border_width, style=i_sess_border_style, color=_color)
linefill.new(above_line, below_line, color.new(_color, i_sess_bgopacity))
array.push(_lines, above_line)
array.push(_lines, below_line)
util.clear_lines(_lines, i_history_period * 2)
if _is_extend
line.set_extend(above_line, extend.right)
line.set_extend(below_line, extend.right)
else if _session
line.set_y1(above_line, _top)
line.set_y2(above_line, _top)
line.set_x2(above_line, _x2)
line.set_y1(below_line, _bottom)
line.set_y2(below_line, _bottom)
line.set_x2(below_line, _x2)
true
else if _is_ended
true
true
// ------------------------
// Rendering session box
// ------------------------
f_render_session (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _boxes) =>
var box my_box = na
if _show
if _is_started
my_box := box.new(_x1, _top, _x2, _bottom, _color, i_sess_border_width, i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
array.push(_boxes, my_box)
util.clear_boxes(_boxes, i_history_period)
if _is_extend
box.set_extend(my_box, extend.right)
else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
f_set_box_right(my_box, _x2)
else if _is_ended
box.set_right(my_box, bar_index)
my_box
// ------------------------
// Drawing market
// ------------------------
f_render_main (_show, _session, _is_started, _is_ended, _color, _top, _bottom) =>
var box my_box = na
var label my_note = na
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0
x0_1 = ta.valuewhen(na(_session ) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session , bar_index, 0)
x0_d = math.abs(x0_2 - x0_1)
limit_bars = max_bars
rightbars = x0_d
if _show
if _is_started
x1 := bar_index
x2 := bar_index + (math.min(x0_d, limit_bars))
session_open := open
session_high := _top
session_low := _bottom
else if _session
true_x2 = x1 + x0_d
rightbars := true_x2 - bar_index
limit_bars := bar_index + max_bars
x2 := math.min(true_x2, limit_bars)
session_high := _top
session_low := _bottom
else if _is_ended
session_open := na
// ------------------------
// Drawing
// ------------------------
draw (_show, _session, _color, _label, _extend, _show_fib, _show_op, _lookback, _boxes_session, _lines_session, _boxes_candle_body, _lines_candle_wick, _boxes_op, _lines_fib, _labels) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
is_extend = _extend != option_no
= f_render_main(_show, _session, is_started, is_ended, _color, top, bottom)
if i_sess_box_style == 'Box'
f_render_session(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _boxes_session)
if i_sess_box_style == 'Sandwich'
f_render_sessionrange(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _lines_session)
if i_show_candle
f_render_candle(_show, _session, is_started, is_ended, _color, top, bottom, _open, x1, x2, _boxes_candle_body, _lines_candle_wick)
if i_label_show
f_render_label(_show, _session, is_started, _color, top, bottom, _label, _labels)
if _show_op
f_render_oprange(_show, _session, is_started, x1, x2, _color, max, is_extend, _boxes_op)
if _show_fib
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.500, 2, line.style_solid, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.628, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.382, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
util.clear_lines(_lines_fib, i_history_period * 3)
f_render_limitmessage(_show, _session, is_started, is_ended, x1, bottom, _rightbars)
///////////////////
// Calculating
///////////////////
string tz = (i_tz == option_no or i_tz == '') ? na : i_tz
int sess1 = time(timeframe.period, i_sess1, tz)
int sess2 = time(timeframe.period, i_sess2, tz)
int sess3 = time(timeframe.period, i_sess3, tz)
int sess4 = time(timeframe.period, i_sess4, tz)
///////////////////
// Plotting
///////////////////
var sess1_box = array.new()
var sess2_box = array.new()
var sess3_box = array.new()
var sess4_box = array.new()
var sess1_line = array.new()
var sess2_line = array.new()
var sess3_line = array.new()
var sess4_line = array.new()
var sess1_op = array.new()
var sess2_op = array.new()
var sess3_op = array.new()
var sess4_op = array.new()
var sess1_fib = array.new()
var sess2_fib = array.new()
var sess3_fib = array.new()
var sess4_fib = array.new()
var sess1_candle_body = array.new()
var sess2_candle_body = array.new()
var sess3_candle_body = array.new()
var sess4_candle_body = array.new()
var sess1_candle_wick = array.new()
var sess2_candle_wick = array.new()
var sess3_candle_wick = array.new()
var sess4_candle_wick = array.new()
var sess1_labels = array.new()
var sess2_labels = array.new()
var sess3_labels = array.new()
var sess4_labels = array.new()
= draw(i_show_sess1, sess1, i_sess1_color, i_sess1_label, i_sess1_extend, i_sess1_fib, i_sess1_op, i_lookback, sess1_box, sess1_line, sess1_candle_body, sess1_candle_wick, sess1_op, sess1_fib, sess1_labels)
= draw(i_show_sess2, sess2, i_sess2_color, i_sess2_label, i_sess2_extend, i_sess2_fib, i_sess2_op, i_lookback, sess2_box, sess2_line, sess2_candle_body, sess2_candle_wick, sess2_op, sess2_fib, sess2_labels)
= draw(i_show_sess3, sess3, i_sess3_color, i_sess3_label, i_sess3_extend, i_sess3_fib, i_sess3_op, i_lookback, sess3_box, sess3_line, sess3_candle_body, sess3_candle_wick, sess3_op, sess3_fib, sess3_labels)
= draw(i_show_sess4, sess4, i_sess4_color, i_sess4_label, i_sess4_extend, i_sess4_fib, i_sess4_op, i_lookback, sess4_box, sess4_line, sess4_candle_body, sess4_candle_wick, sess4_op, sess4_fib, sess4_labels)
is_positive_bar = close > open
color c_barcolor = na
color c_plotcandle = na
c_sess1_barcolor = (is_sess1) ? (is_positive_bar ? i_sess1_barcolor1 : i_sess1_barcolor2) : na
c_sess2_barcolor = (is_sess2) ? (is_positive_bar ? i_sess2_barcolor1 : i_sess2_barcolor2) : na
c_sess3_barcolor = (is_sess3) ? (is_positive_bar ? i_sess3_barcolor1 : i_sess3_barcolor2) : na
c_sess4_barcolor = (is_sess4) ? (is_positive_bar ? i_sess4_barcolor1 : i_sess4_barcolor2) : na
if (i_sess1_chart != option_chart_x) and is_sess1
c_barcolor := i_sess1_barcolor ? c_sess1_barcolor : na
c_plotcandle := i_sess1_plotcandle ? c_sess1_barcolor : na
if (i_sess2_chart != option_chart_x) and is_sess2
c_barcolor := i_sess2_barcolor ? c_sess2_barcolor : na
c_plotcandle := i_sess2_plotcandle ? c_sess2_barcolor : na
if (i_sess3_chart != option_chart_x) and is_sess3
c_barcolor := i_sess3_barcolor ? c_sess3_barcolor : na
c_plotcandle := i_sess3_plotcandle ? c_sess3_barcolor : na
if (i_sess4_chart != option_chart_x) and is_sess4
c_barcolor := i_sess4_barcolor ? c_sess4_barcolor : na
c_plotcandle := i_sess4_plotcandle ? c_sess4_barcolor : na
barcolor(c_barcolor)
plotcandle(open, high, low, close, color=is_positive_bar ? color_none : c_plotcandle, bordercolor=c_plotcandle, wickcolor=c_plotcandle)
////////////////////
// Alerts
////////////////////
// Session alerts
sess1_started = is_sess1 and not is_sess1 , sess1_ended = not is_sess1 and is_sess1
sess2_started = is_sess2 and not is_sess2 , sess2_ended = not is_sess2 and is_sess2
sess3_started = is_sess3 and not is_sess3 , sess3_ended = not is_sess3 and is_sess3
sess4_started = is_sess4 and not is_sess4 , sess4_ended = not is_sess4 and is_sess4
alertcondition(sess1_started, 'Session #1 started')
alertcondition(sess1_ended, 'Session #1 ended')
alertcondition(sess2_started, 'Session #2 started')
alertcondition(sess2_ended, 'Session #2 ended')
alertcondition(sess3_started, 'Session #3 started')
alertcondition(sess3_ended, 'Session #3 ended')
alertcondition(sess4_started, 'Session #4 started')
alertcondition(sess4_ended, 'Session #4 ended')
alertcondition((not is_sess1) and ta.crossover(close, sess1_high), 'Session #1 High crossed (after session closed)')
alertcondition((not is_sess1) and ta.crossunder(close, sess1_low), 'Session #1 Low crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossover(close, sess2_high), 'Session #2 High crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossunder(close, sess2_low), 'Session #2 Low crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossover(close, sess3_high), 'Session #3 High crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossunder(close, sess3_low), 'Session #3 Low crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossover(close, sess4_high), 'Session #4 High crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossunder(close, sess4_low), 'Session #4 Low crossed (after session closed)')
// Alerts visualized
if i_alert1_show
if i_show_sess1
if sess1_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess1_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess2
if sess2_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess2_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess3
if sess3_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess3_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess4
if sess4_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess4_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
plot(i_alert3_show ? sess1_high : na, 'sess1_high', style=plot.style_linebr, color=i_sess1_color)
plot(i_alert3_show ? sess1_low : na, 'sess1_low' , style=plot.style_linebr, color=i_sess1_color, linewidth=2)
plot(i_alert3_show ? sess2_high : na, 'sess2_high', style=plot.style_linebr, color=i_sess2_color)
plot(i_alert3_show ? sess2_low : na, 'sess2_low' , style=plot.style_linebr, color=i_sess2_color, linewidth=2)
plot(i_alert3_show ? sess3_high : na, 'sess3_high', style=plot.style_linebr, color=i_sess3_color)
plot(i_alert3_show ? sess3_low : na, 'sess3_low' , style=plot.style_linebr, color=i_sess3_color, linewidth=2)
plot(i_alert3_show ? sess4_high : na, 'sess4_high', style=plot.style_linebr, color=i_sess4_color)
plot(i_alert3_show ? sess4_low : na, 'sess4_low' , style=plot.style_linebr, color=i_sess4_color, linewidth=2)
plotshape(i_alert3_show and (not is_sess1) and ta.crossover(close, sess1_high) ? sess1_high : na, 'cross sess1_high', color=i_sess1_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess1) and ta.crossunder(close, sess1_low) ? sess1_low : na, 'cross sess1_low', color=i_sess1_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossover(close, sess2_high) ? sess2_high : na, 'cross sess2_high', color=i_sess2_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossunder(close, sess2_low) ? sess2_low : na, 'cross sess2_low', color=i_sess2_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossover(close, sess3_high) ? sess3_high : na, 'cross sess3_high', color=i_sess3_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossunder(close, sess3_low) ? sess3_low : na, 'cross sess3_low', color=i_sess3_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossover(close, sess4_high) ? sess4_high : na, 'cross sess4_high', color=i_sess4_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossunder(close, sess4_low) ? sess4_low : na, 'cross sess4_low', color=i_sess4_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
HSM BULLET//@version=5
indicator('HSM BULLET', 'HSM BULLET', overlay=true, max_bars_back=500, explicit_plot_zorder=true)
import boitoki/AwesomeColor/4 as ac
import boitoki/Utilities/3 as util
///////////////
// Groups
///////////////
g0 = 'GENERAL'
g1_01 = '♯1 SESSION'
g1_02 = '♯2 SESSION'
g1_03 = '♯3 SESSION'
g1_04 = '♯4 SESSION'
g4 = 'BOX'
g6 = 'LABELS'
g5 = 'OPENING RANGE'
g7 = 'FIBONACCI LEVELS'
g8 = 'OPTIONS'
g11 = 'CANDLE'
g10 = 'Alerts visualized'
///////////////
// Defined
///////////////
max_bars = 500
option_yes = 'Yes'
option_no = '× No'
option_extend1 = 'Yes'
option_hide = '× Hide'
option_border_style1 = '────'
option_border_style2 = '- - - - - -'
option_border_style3 = '•••••••••'
option_chart_x = '× No'
option_chart_1 = 'Bar color'
option_chart_2 = 'Candles'
fmt_price = '{0,number,#.#####}'
fmt_pips = '{0,number,#.#}'
icon_separator = ' • '
color_none = color.new(color.black, 100)
color_text = color.new(color.white, 0)
///////////////
// Functions
///////////////
f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000
f_border_style (_style) =>
switch _style
option_border_style1 => line.style_solid
option_border_style2 => line.style_dashed
option_border_style3 => line.style_dotted
=> _style
f_get_period (_session, _start, _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session ) and _session
result := i+1
break
result
f_get_label_position (_y, _side) =>
switch _y
'top' => _side == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
'bottom' => _side == 'outside' ? label.style_label_upper_left : label.style_label_lower_left
f_get_started (_session) => na(_session ) and _session
f_get_ended (_session) => na(_session) and _session
f_message_limit_bars (_v) => '⚠️ This box\'s right position exceeds 500 bars(' + str.tostring(_v) + '). This box is not displayed correctly.'
f_set_line_x1 (_line, _x) =>
if (line.get_x1(_line) != _x)
line.set_x1(_line, _x)
f_set_line_x2 (_line, _x) =>
if (line.get_x2(_line) != _x)
line.set_x2(_line, _x)
f_set_box_right (_box, _x) =>
if box.get_right(_box) != _x
box.set_right(_box, _x)
///////////////
// Inputs
///////////////
// Timezone
i_tz = input.string('GMT-4', title='Timezone', options= , tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group=g0)
i_history_period = input.int(10, 'History', minval=0, group=g0)
i_show = i_history_period > 0
i_lookback = 12 * 60
// Sessions
i_show_sess1 = input.bool(true, 'Session 1 ', group=g1_01, inline='session1_1') and i_show
i_sess1_label = input.string('London Silver', '', group=g1_01, inline='session1_1')
i_sess1_color = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1_barcolor1 = input.color(#0a0a0a, '•', group=g1_01, inline='session1_1')
i_sess1_barcolor2 = input.color(#0a0a0a, '', group=g1_01, inline='session1_1')
i_sess1 = input.session('0300-0400', 'Time', group=g1_01)
i_sess1_extend = input.string(option_no, 'Extend', options= , group=g1_01)
i_sess1_fib = input.string(option_no, 'Fibonacci levels', group=g1_01, options= ) != option_no
i_sess1_op = input.string(option_no, 'Opening range', group=g1_01, options= ) != option_no and i_show
i_sess1_chart = input.string(option_chart_x, 'Bar', options= , group=g1_01)
i_sess1_barcolor = i_sess1_chart == option_chart_1
i_sess1_plotcandle = i_sess1_chart == option_chart_2
i_show_sess2 = input.bool(true, 'Session 2 ', group=g1_02, inline='session2_1') and i_show
i_sess2_label = input.string('NY AM Bullet', '', group=g1_02, inline='session2_1')
i_sess2_color = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2_barcolor1 = input.color(#0a0a0a, '•', group=g1_02, inline='session2_1')
i_sess2_barcolor2 = input.color(#0a0a0a, '', group=g1_02, inline='session2_1')
i_sess2 = input.session('1000-1100', 'Time', group=g1_02)
i_sess2_extend = input.string(option_no, 'Extend', options= , group=g1_02)
i_sess2_fib = input.string(option_no, 'Fibonacci levels', group=g1_02, options= ) != option_no
i_sess2_op = input.string(option_no, 'Opening range', group=g1_02, options= ) != option_no and i_show
i_sess2_chart = input.string(option_chart_x, 'Bar', options= , group=g1_02)
i_sess2_barcolor = i_sess2_chart == option_chart_1
i_sess2_plotcandle = i_sess2_chart == option_chart_2
i_show_sess3 = input.bool(true, 'Session 3 ', group=g1_03, inline='session3_1') and i_show
i_sess3_label = input.string('NY PM Bullet', '', group=g1_03, inline='session3_1')
i_sess3_color = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3_barcolor1 = input.color(#0a0a0a, '•', group=g1_03, inline='session3_1')
i_sess3_barcolor2 = input.color(#0a0a0a, '', group=g1_03, inline='session3_1')
i_sess3 = input.session('1400-1500', 'Time', group=g1_03)
i_sess3_extend = input.string(option_no, 'Extend', options= , group=g1_03)
i_sess3_fib = input.string(option_no, 'Fibonacci levels', group=g1_03, options= ) != option_no
i_sess3_op = input.string(option_no, 'Opening range', group=g1_03, options= ) != option_no and i_show
i_sess3_chart = input.string(option_chart_x, 'Bar', options= , group=g1_03)
i_sess3_barcolor = i_sess3_chart == option_chart_1
i_sess3_plotcandle = i_sess3_chart == option_chart_2
i_show_sess4 = input.bool(true, 'Session 4 ', group=g1_04, inline='session4_1') and i_show
i_sess4_label = input.string(' ', '', group=g1_04, inline='session4_1')
i_sess4_color = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4_barcolor1 = input.color(#0a0a0a, '•', group=g1_04, inline='session4_1')
i_sess4_barcolor2 = input.color(#0a0a0a, '', group=g1_04, inline='session4_1')
i_sess4 = input.session('1000-1000', 'Time', group=g1_04)
i_sess4_extend = input.string(option_no, 'Extend', options= , group=g1_04)
i_sess4_fib = input.string(option_no, 'Fibonacci levels', group=g1_04, options= ) != option_no
i_sess4_op = input.string(option_no, 'Opening range', group=g1_04, options= ) != option_no and i_show
i_sess4_chart = input.string(option_chart_x, 'Bar', options= , group=g1_04)
i_sess4_barcolor = i_sess4_chart == option_chart_1
i_sess4_plotcandle = i_sess4_chart == option_chart_2
// Show & Styles
i_sess_box_style = input.string('Box', 'Style', options= , group=g4)
i_sess_border_style = f_border_style(input.string(option_border_style2, 'Line style', options= , group=g4))
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=g4)
i_sess_bgopacity = input.int(94, 'Transp', minval=0, maxval=100, step=1, group=g4, tooltip='Setting the 100 is no background color')
// Candle
option_candle_body = 'OC'
option_candle_wick = 'OHLC'
i_candle = input.string(option_hide, 'Display', options= , group=g11)
i_candle_border_width = input.int(2, 'Thickness', minval=0, group=g11)
i_show_candle = (i_candle != option_hide) and (i_candle_border_width > 0)
i_show_candle_wick = i_candle == option_candle_wick
option_candle_color1 = 'Session\'s'
option_candle_color2 = 'Red • Green'
i_candle_color = input.string(option_candle_color2, 'Color ', options= , group=g11, inline='candle_color')
i_candle_color_g = input.color(#A6E22E, '', group=g11, inline='candle_color')
i_candle_color_r = input.color(#F92672, '', group=g11, inline='candle_color')
// Labels
i_label_show = input.bool(true, 'Labels', inline='label_show', group=g6) and i_show
i_label_size = str.lower(input.string('Small', '', options= , inline='label_show', group=g6))
i_label_position_y = str.lower(input.string('Top', '', options= , inline='label_show', group=g6))
i_label_position_s = str.lower(input.string('Outside', '', options= , inline='label_show', group=g6))
i_label_position = f_get_label_position(i_label_position_y, i_label_position_s)
i_label_format_name = input.bool(true, 'Name', inline='label_format', group=g6)
i_label_format_day = input.bool(false, 'Day', inline='label_format', group=g6)
i_label_format_price = input.bool(false, 'Price', inline='label_format', group=g6)
i_label_format_pips = input.bool(false, 'Pips', inline='label_format', group=g6)
// Fibonacci levels
i_f_linestyle = f_border_style(input.string(option_border_style1, title="Style", options= , group=g7))
i_f_linewidth = input.int(1, title="Thickness", minval=1, group=g7)
// Opening range
i_o_minutes = input.int(15, title='Periods (minutes)', minval=1, step=1, group=g5)
i_o_minutes := math.max(i_o_minutes, timeframe.multiplier + 1)
i_o_transp = input.int(88, title='Transp', minval=0, maxval=100, step=1, group=g5)
// Alerts
i_alert1_show = input.bool(false, 'Alerts - Sessions stard/end', group=g10)
i_alert2_show = input.bool(false, 'Alerts - Opening range breakouts', group=g10)
i_alert3_show = input.bool(false, 'Alerts - Price crossed session\'s High/Low after session closed', group=g10)
// ------------------------
// Drawing labels
// ------------------------
f_render_label (_show, _session, _is_started, _color, _top, _bottom, _text, _labels) =>
var label my_label = na
var int start_time = na
v_position_y = (i_label_position_y == 'top') ? _top : _bottom
v_label = array.new_string()
v_chg = _top - _bottom
if _is_started
start_time := time
if i_label_format_name and not na(_text)
array.push(v_label, _text)
if i_label_format_day
array.push(v_label, util.get_day(dayofweek(start_time, i_tz)))
if i_label_format_price
array.push(v_label, str.format(fmt_price, v_chg))
if i_label_format_pips
array.push(v_label, str.format(fmt_pips, util.toPips(v_chg)) + ' pips')
if _show
if _is_started
my_label := label.new(bar_index, v_position_y, array.join(v_label, icon_separator), textcolor=_color, color=color_none, size=i_label_size, style=i_label_position)
array.push(_labels, my_label)
util.clear_labels(_labels, i_history_period)
else if _session
label.set_y(my_label, v_position_y)
label.set_text(my_label, array.join(v_label, icon_separator))
// ------------------------
// Drawing Fibonacci levels
// ------------------------
f_render_fibonacci (_show, _session, _is_started, _x1, _x2, _color, _top, _bottom, _level, _width, _style, _is_extend, _lines) =>
var line my_line = na
if _show
y = (_top - _bottom) * _level + _bottom
if _is_started
my_line := line.new(_x1, y, _x2, y, width=_width, color=color.new(_color, 30), style=_style)
array.push(_lines, my_line)
if _is_extend
line.set_extend(my_line, extend.right)
else if _session
line.set_y1(my_line, y)
line.set_y2(my_line, y)
f_set_line_x2(my_line, _x2)
// ------------------------
// Drawing Opening range
// ------------------------
f_render_oprange (_show, _session, _is_started, _x1, _x2, _color, _max, _is_extend, _boxes) =>
var int start_time = na
var box my_box = na
top = ta.highest(high, _max)
bottom = ta.lowest(low, _max)
is_crossover = ta.crossover(close, box.get_top(my_box))
is_crossunder = ta.crossunder(close, box.get_bottom(my_box))
if _show
if _is_started
util.clear_boxes(_boxes, math.max(0, i_history_period - 1))
start_time := time
my_box := na
else if _session
time_op = start_time + (i_o_minutes * 60 * 1000)
time_op_delay = time_op - f_get_time_by_bar(1)
if time <= time_op and time > time_op_delay
my_box := box.new(_x1, top, _x2, bottom, border_width=0, bgcolor=color.new(_color, i_o_transp))
array.push(_boxes, my_box)
if _is_extend
box.set_extend(my_box, extend.right)
my_box
else
f_set_box_right(my_box, _x2)
if is_crossover
alert('Price crossed over the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_top(my_box), "×", color=color.blue, textcolor=ac.tradingview('blue'), style=label.style_none, size=size.large)
if is_crossunder
alert('Price crossed under the opening range', alert.freq_once_per_bar)
if i_alert2_show
label.new(bar_index, box.get_bottom(my_box), "×", color=color.red, textcolor=ac.tradingview('red'), style=label.style_none, size=size.large)
my_box
// ------------------------
// Drawing candle
// ------------------------
f_render_candle (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _open, _x1, _x2, _boxes, _lines) =>
var box body = na
var line wick1 = na
var line wick2 = na
border_width = i_candle_border_width
cx = math.round(math.avg(_x2, _x1)) - math.round(border_width / 2)
body_color = i_candle_color == option_candle_color2 ? close > _open ? i_candle_color_g : i_candle_color_r : _color
if _show
if _is_started
body := box.new(_x1, _top, _x2, _bottom, body_color, border_width, line.style_solid, bgcolor=color.new(color.black, 100))
wick1 := i_show_candle_wick ? line.new(cx, _top, cx, _top, color=_color, width=border_width, style=line.style_solid) : na
wick2 := i_show_candle_wick ? line.new(cx, _bottom, cx, _bottom, color=_color, width=border_width, style=line.style_solid) : na
array.push(_boxes, body)
array.push(_lines, wick1)
array.push(_lines, wick2)
util.clear_boxes(_boxes, i_history_period)
util.clear_lines(_lines, i_history_period * 2)
else if _session
top = math.max(_open, close)
bottom = math.min(_open, close)
box.set_top(body, top)
box.set_bottom(body, bottom)
box.set_right(body, _x2)
box.set_border_color(body, body_color)
line.set_y1(wick1, _top)
line.set_y2(wick1, top)
f_set_line_x1(wick1, cx)
f_set_line_x2(wick1, cx)
line.set_color(wick1, body_color)
line.set_y1(wick2, _bottom)
line.set_y2(wick2, bottom)
f_set_line_x1(wick2, cx)
f_set_line_x2(wick2, cx)
line.set_color(wick2, body_color)
else if _is_ended
box.set_right(body, bar_index)
// ------------------------
// Rendering limit message
// ------------------------
f_render_limitmessage (_show, _session, _is_started, _is_ended, _x, _y, _rightbars) =>
var label my_note = na
if _show
if _is_started
if _rightbars > max_bars
my_note := label.new(_x, _y, f_message_limit_bars(_rightbars), style=label.style_label_upper_left, color=color.yellow, textalign=text.align_left, yloc=yloc.price)
else if _session
if _rightbars > max_bars
label.set_y(my_note, _y)
label.set_text(my_note, f_message_limit_bars(_rightbars))
else
label.delete(my_note)
else if _is_ended
label.delete(my_note)
true
// Rendering session
//
f_render_sessionrange (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _lines) =>
var line above_line = na
var line below_line = na
if _show
if _is_started
above_line := line.new(_x1, _top, _x2, _top, width=i_sess_border_width, style=i_sess_border_style, color=_color)
below_line := line.new(_x1, _bottom, _x2, _bottom, width=i_sess_border_width, style=i_sess_border_style, color=_color)
linefill.new(above_line, below_line, color.new(_color, i_sess_bgopacity))
array.push(_lines, above_line)
array.push(_lines, below_line)
util.clear_lines(_lines, i_history_period * 2)
if _is_extend
line.set_extend(above_line, extend.right)
line.set_extend(below_line, extend.right)
else if _session
line.set_y1(above_line, _top)
line.set_y2(above_line, _top)
line.set_x2(above_line, _x2)
line.set_y1(below_line, _bottom)
line.set_y2(below_line, _bottom)
line.set_x2(below_line, _x2)
true
else if _is_ended
true
true
// ------------------------
// Rendering session box
// ------------------------
f_render_session (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _x1, _x2, _is_extend, _boxes) =>
var box my_box = na
if _show
if _is_started
my_box := box.new(_x1, _top, _x2, _bottom, _color, i_sess_border_width, i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
array.push(_boxes, my_box)
util.clear_boxes(_boxes, i_history_period)
if _is_extend
box.set_extend(my_box, extend.right)
else if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
f_set_box_right(my_box, _x2)
else if _is_ended
box.set_right(my_box, bar_index)
my_box
// ------------------------
// Drawing market
// ------------------------
f_render_main (_show, _session, _is_started, _is_ended, _color, _top, _bottom) =>
var box my_box = na
var label my_note = na
var x1 = 0
var x2 = 0
var session_open = 0.0
var session_high = 0.0
var session_low = 0.0
x0_1 = ta.valuewhen(na(_session ) and _session, bar_index, 1)
x0_2 = ta.valuewhen(na(_session) and _session , bar_index, 0)
x0_d = math.abs(x0_2 - x0_1)
limit_bars = max_bars
rightbars = x0_d
if _show
if _is_started
x1 := bar_index
x2 := bar_index + (math.min(x0_d, limit_bars))
session_open := open
session_high := _top
session_low := _bottom
else if _session
true_x2 = x1 + x0_d
rightbars := true_x2 - bar_index
limit_bars := bar_index + max_bars
x2 := math.min(true_x2, limit_bars)
session_high := _top
session_low := _bottom
else if _is_ended
session_open := na
// ------------------------
// Drawing
// ------------------------
draw (_show, _session, _color, _label, _extend, _show_fib, _show_op, _lookback, _boxes_session, _lines_session, _boxes_candle_body, _lines_candle_wick, _boxes_op, _lines_fib, _labels) =>
max = f_get_period(_session, 1, _lookback)
top = ta.highest(high, max)
bottom = ta.lowest(low, max)
is_started = f_get_started(_session)
is_ended = f_get_ended(_session)
is_extend = _extend != option_no
= f_render_main(_show, _session, is_started, is_ended, _color, top, bottom)
if i_sess_box_style == 'Box'
f_render_session(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _boxes_session)
if i_sess_box_style == 'Sandwich'
f_render_sessionrange(_show, _session, is_started, is_ended, _color, top, bottom, x1, x2, is_extend, _lines_session)
if i_show_candle
f_render_candle(_show, _session, is_started, is_ended, _color, top, bottom, _open, x1, x2, _boxes_candle_body, _lines_candle_wick)
if i_label_show
f_render_label(_show, _session, is_started, _color, top, bottom, _label, _labels)
if _show_op
f_render_oprange(_show, _session, is_started, x1, x2, _color, max, is_extend, _boxes_op)
if _show_fib
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.500, 2, line.style_solid, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.628, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
f_render_fibonacci(_show, _session, is_started, x1, x2, _color, top, bottom, 0.382, i_f_linewidth, i_f_linestyle, is_extend, _lines_fib)
util.clear_lines(_lines_fib, i_history_period * 3)
f_render_limitmessage(_show, _session, is_started, is_ended, x1, bottom, _rightbars)
///////////////////
// Calculating
///////////////////
string tz = (i_tz == option_no or i_tz == '') ? na : i_tz
int sess1 = time(timeframe.period, i_sess1, tz)
int sess2 = time(timeframe.period, i_sess2, tz)
int sess3 = time(timeframe.period, i_sess3, tz)
int sess4 = time(timeframe.period, i_sess4, tz)
///////////////////
// Plotting
///////////////////
var sess1_box = array.new()
var sess2_box = array.new()
var sess3_box = array.new()
var sess4_box = array.new()
var sess1_line = array.new()
var sess2_line = array.new()
var sess3_line = array.new()
var sess4_line = array.new()
var sess1_op = array.new()
var sess2_op = array.new()
var sess3_op = array.new()
var sess4_op = array.new()
var sess1_fib = array.new()
var sess2_fib = array.new()
var sess3_fib = array.new()
var sess4_fib = array.new()
var sess1_candle_body = array.new()
var sess2_candle_body = array.new()
var sess3_candle_body = array.new()
var sess4_candle_body = array.new()
var sess1_candle_wick = array.new()
var sess2_candle_wick = array.new()
var sess3_candle_wick = array.new()
var sess4_candle_wick = array.new()
var sess1_labels = array.new()
var sess2_labels = array.new()
var sess3_labels = array.new()
var sess4_labels = array.new()
= draw(i_show_sess1, sess1, i_sess1_color, i_sess1_label, i_sess1_extend, i_sess1_fib, i_sess1_op, i_lookback, sess1_box, sess1_line, sess1_candle_body, sess1_candle_wick, sess1_op, sess1_fib, sess1_labels)
= draw(i_show_sess2, sess2, i_sess2_color, i_sess2_label, i_sess2_extend, i_sess2_fib, i_sess2_op, i_lookback, sess2_box, sess2_line, sess2_candle_body, sess2_candle_wick, sess2_op, sess2_fib, sess2_labels)
= draw(i_show_sess3, sess3, i_sess3_color, i_sess3_label, i_sess3_extend, i_sess3_fib, i_sess3_op, i_lookback, sess3_box, sess3_line, sess3_candle_body, sess3_candle_wick, sess3_op, sess3_fib, sess3_labels)
= draw(i_show_sess4, sess4, i_sess4_color, i_sess4_label, i_sess4_extend, i_sess4_fib, i_sess4_op, i_lookback, sess4_box, sess4_line, sess4_candle_body, sess4_candle_wick, sess4_op, sess4_fib, sess4_labels)
is_positive_bar = close > open
color c_barcolor = na
color c_plotcandle = na
c_sess1_barcolor = (is_sess1) ? (is_positive_bar ? i_sess1_barcolor1 : i_sess1_barcolor2) : na
c_sess2_barcolor = (is_sess2) ? (is_positive_bar ? i_sess2_barcolor1 : i_sess2_barcolor2) : na
c_sess3_barcolor = (is_sess3) ? (is_positive_bar ? i_sess3_barcolor1 : i_sess3_barcolor2) : na
c_sess4_barcolor = (is_sess4) ? (is_positive_bar ? i_sess4_barcolor1 : i_sess4_barcolor2) : na
if (i_sess1_chart != option_chart_x) and is_sess1
c_barcolor := i_sess1_barcolor ? c_sess1_barcolor : na
c_plotcandle := i_sess1_plotcandle ? c_sess1_barcolor : na
if (i_sess2_chart != option_chart_x) and is_sess2
c_barcolor := i_sess2_barcolor ? c_sess2_barcolor : na
c_plotcandle := i_sess2_plotcandle ? c_sess2_barcolor : na
if (i_sess3_chart != option_chart_x) and is_sess3
c_barcolor := i_sess3_barcolor ? c_sess3_barcolor : na
c_plotcandle := i_sess3_plotcandle ? c_sess3_barcolor : na
if (i_sess4_chart != option_chart_x) and is_sess4
c_barcolor := i_sess4_barcolor ? c_sess4_barcolor : na
c_plotcandle := i_sess4_plotcandle ? c_sess4_barcolor : na
barcolor(c_barcolor)
plotcandle(open, high, low, close, color=is_positive_bar ? color_none : c_plotcandle, bordercolor=c_plotcandle, wickcolor=c_plotcandle)
////////////////////
// Alerts
////////////////////
// Session alerts
sess1_started = is_sess1 and not is_sess1 , sess1_ended = not is_sess1 and is_sess1
sess2_started = is_sess2 and not is_sess2 , sess2_ended = not is_sess2 and is_sess2
sess3_started = is_sess3 and not is_sess3 , sess3_ended = not is_sess3 and is_sess3
sess4_started = is_sess4 and not is_sess4 , sess4_ended = not is_sess4 and is_sess4
alertcondition(sess1_started, 'Session #1 started')
alertcondition(sess1_ended, 'Session #1 ended')
alertcondition(sess2_started, 'Session #2 started')
alertcondition(sess2_ended, 'Session #2 ended')
alertcondition(sess3_started, 'Session #3 started')
alertcondition(sess3_ended, 'Session #3 ended')
alertcondition(sess4_started, 'Session #4 started')
alertcondition(sess4_ended, 'Session #4 ended')
alertcondition((not is_sess1) and ta.crossover(close, sess1_high), 'Session #1 High crossed (after session closed)')
alertcondition((not is_sess1) and ta.crossunder(close, sess1_low), 'Session #1 Low crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossover(close, sess2_high), 'Session #2 High crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossunder(close, sess2_low), 'Session #2 Low crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossover(close, sess3_high), 'Session #3 High crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossunder(close, sess3_low), 'Session #3 Low crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossover(close, sess4_high), 'Session #4 High crossed (after session closed)')
alertcondition((not is_sess4) and ta.crossunder(close, sess4_low), 'Session #4 Low crossed (after session closed)')
// Alerts visualized
if i_alert1_show
if i_show_sess1
if sess1_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess1_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess1_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess2
if sess2_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess2_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess2_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess3
if sess3_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess3_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess3_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if i_show_sess4
if sess4_started
label.new(bar_index, close, 'Start', yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
if sess4_ended
label.new(bar_index, close, 'End' , yloc=yloc.abovebar, color=i_sess4_color, textcolor=color_text, size=size.small, style=label.style_label_down)
plot(i_alert3_show ? sess1_high : na, 'sess1_high', style=plot.style_linebr, color=i_sess1_color)
plot(i_alert3_show ? sess1_low : na, 'sess1_low' , style=plot.style_linebr, color=i_sess1_color, linewidth=2)
plot(i_alert3_show ? sess2_high : na, 'sess2_high', style=plot.style_linebr, color=i_sess2_color)
plot(i_alert3_show ? sess2_low : na, 'sess2_low' , style=plot.style_linebr, color=i_sess2_color, linewidth=2)
plot(i_alert3_show ? sess3_high : na, 'sess3_high', style=plot.style_linebr, color=i_sess3_color)
plot(i_alert3_show ? sess3_low : na, 'sess3_low' , style=plot.style_linebr, color=i_sess3_color, linewidth=2)
plot(i_alert3_show ? sess4_high : na, 'sess4_high', style=plot.style_linebr, color=i_sess4_color)
plot(i_alert3_show ? sess4_low : na, 'sess4_low' , style=plot.style_linebr, color=i_sess4_color, linewidth=2)
plotshape(i_alert3_show and (not is_sess1) and ta.crossover(close, sess1_high) ? sess1_high : na, 'cross sess1_high', color=i_sess1_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess1) and ta.crossunder(close, sess1_low) ? sess1_low : na, 'cross sess1_low', color=i_sess1_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossover(close, sess2_high) ? sess2_high : na, 'cross sess2_high', color=i_sess2_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossunder(close, sess2_low) ? sess2_low : na, 'cross sess2_low', color=i_sess2_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossover(close, sess3_high) ? sess3_high : na, 'cross sess3_high', color=i_sess3_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossunder(close, sess3_low) ? sess3_low : na, 'cross sess3_low', color=i_sess3_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossover(close, sess4_high) ? sess4_high : na, 'cross sess4_high', color=i_sess4_color, style=shape.triangleup, location=location.absolute, size=size.tiny)
plotshape(i_alert3_show and (not is_sess4) and ta.crossunder(close, sess4_low) ? sess4_low : na, 'cross sess4_low', color=i_sess4_color, style=shape.triangledown, location=location.absolute, size=size.tiny)
RSI Divergence ProjectionRSI Divergence Projection
Go beyond traditional, lagging indicators with this advanced RSI Divergence tool. It not only identifies four types of confirmed RSI divergence but also introduces a unique, forward-looking engine. This engine spots potential divergences as they form on the current candle and then projects the exact price threshold required to validate them.
Our core innovation is the Divergence Projection Line, a clean, clutter-free visualization that extends this calculated price target into the future, providing a clear and actionable level for your trading decisions.
The Core Logic: Understanding RSI Divergence
For those new to the concept, RSI Divergence is a powerful tool used to spot potential market reversals or continuations. It occurs when the price of an asset is moving in the opposite direction of the Relative Strength Index (RSI). This indicator automatically detects and plots four key types:
Regular Bullish Divergence: Price prints a lower low, but the RSI prints a higher low. This often signals that bearish momentum is fading and a potential reversal to the upside is near.
Hidden Bullish Divergence: Price prints a higher low, but the RSI prints a lower low. This is often seen in an uptrend and can signal a continuation of the bullish move.
Regular Bearish Divergence: Price prints a higher high, but the RSI prints a lower high. This suggests that bullish momentum is weakening and a potential reversal to the downside is coming.
Hidden Bearish Divergence: Price prints a lower high, but the RSI prints a higher high. This is often seen in a downtrend and can signal a continuation of the bearish move.
Confirmed divergences are plotted with solid-colored lines on the price chart and marked with a "B" (Bearish/Bullish) or "HB" (Hidden Bearish/Hidden Bullish) label.
The Core Innovation: The Divergence Projection
This is where the indicator truly shines and sets itself apart. Instead of waiting for a pivot point to be confirmed, our engine analyzes the current, unclosed candle.
Potential Divergence Detection: When the indicator notices that the current price and RSI are setting up for a potential divergence against the last confirmed pivot, it will draw a dashed line on the chart. This gives you a critical head-start before the signal is confirmed.
The Projection Line (Our Innovation): This is the game-changer. Rather than cluttering your chart with messy labels, the indicator calculates the exact closing price the next candle needs to achieve to make the current RSI level equal to the RSI of the last pivot.
It then projects a clean, horizontal dashed line at this price level into the future.
Attached to the end of this line is a single, consolidated label that tells you the type of potential divergence and the exact threshold price.
This unique visualization transforms a vague concept into a precise, actionable price target, completely free of chart clutter.
How to Use This Indicator
1. Trading Confirmed Divergences:
Look for the solid lines and the "B" or "HB" labels that appear after a candle has closed and a pivot is confirmed.
A Regular Bullish divergence can be an entry signal for a long position, often placed after the confirmation candle closes.
A Regular Bearish divergence can be an entry signal for a short position.
Hidden Divergences can be used as confirmation to stay in a trade or to enter a trade in the direction of the prevailing trend.
2. Using the Divergence Projection for a Tactical Advantage:
When a dashed line appears on the current price action, you are seeing a potential divergence in real-time.
Look to the right of the current candle for the Projection Line. The price level of this line is your key level to watch.
Example (Potential Bullish Divergence): You see a dashed green line forming from a previous low to the current lower low. To the right, you see a horizontal line projected with a label: "Potential Bull Div | Thresh: 10,750.50".
Interpretation: This means that if the next candle closes below 10,750.50, the RSI will not be high enough to form a divergence. However, if the price pushes up and the next candle closes above 10,750.50, the bullish divergence remains intact and is more likely to be confirmed. This gives you a concrete price level to monitor for entry or exit decisions.
How the Projection Engine Works: A Deeper Dive
To fully trust this tool, it's helpful to understand the logic behind it. The projection engine is not based on guesswork or repainting; it's based on a precise mathematical reverse-engineering of the RSI formula.
The Concept: The engine calculates the "tipping point." The Threshold Price is the exact closing price at which the new RSI value would be identical to the RSI value of the previous pivot point. It answers the question: "For this potential divergence to remain valid, where does the next candle need to close?"
The Technicals: The script takes the target RSI from the last pivot, reverse-engineers the formula to find the required average gain/loss ratio, and then solves for the one unknown variable: the gain or loss needed on the next candle. This required price change is then added to or subtracted from the previous close to determine the exact threshold price.
This calculation provides the precise closing price needed to hit our target, which is then plotted as the clean and simple Projection Line on your chart.
Features and Customization
- RSI Settings: Adjust the RSI period and source.
- Divergence Detection: Fine-tune the pivot lookback periods and the min/max range for detecting divergences.
- Price Source: Choose whether to detect divergences using candle Wicks or Bodies.
- Display Toggles: Enable or disable any of the four divergence types, as well as the entire projection engine, to keep your chart as clean as you need it.
Summary of Advantages
- Proactive Signals: Get ahead of the market by seeing potential divergences before they are confirmed.
- Unprecedented Clarity: Our unique Projection Line eliminates chart clutter from overlapping labels.
- Actionable Data: The threshold price provides a specific, objective level to watch, removing guesswork.
- Fully Customizable: Tailor the indicator's settings to match any timeframe or trading strategy.
- All-in-One Tool: No need for a separate RSI indicator; everything you need is displayed directly and cleanly on the price action.
We hope this tool empowers you to make more informed and timely trading decisions. Happy trading
EMA–VWAP Strategy (Confirmed crosses, 1 trade/cross)Wait for 10 and 20 ema to cross
Buy between 10 and 20
wait for 20 and 50 to cross
buy at vwap
10/20/50 ema and vwap is plotted
Globex Trap w/ percentage [SLICKRICK]Globex Trap w/ Percentage
Overview
The Globex Trap w/ Percentage indicator is a powerful tool designed to help traders identify high-probability trading opportunities by analyzing price action during the Globex (overnight) session and regular trading hours. By combining Globex session ranges with Supply & Demand zones, this indicator highlights potential "trap" areas where significant price reactions may occur. Additionally, it calculates the Globex session range as a percentage of the daily Average True Range (ATR), providing valuable context for assessing market volatility.
This indicator is ideal for traders in futures markets or other instruments traded during Globex sessions, offering a visual and analytical edge for spotting key price levels and potential reversals or breakouts.
Key Features
Globex Session Tracking:
Visualizes the high and low of the Globex session (default: 3:00 PM to 6:30 AM PST) with customizable time settings.
Displays a semi-transparent box to mark the Globex range, with labels for "Globex High" and "Globex Low."
Calculates the Globex range as a percentage of the daily ATR, displayed as a label for quick reference.
Supply & Demand Zones:
Identifies Supply & Demand zones during regular trading hours (default: 6:00 AM to 8:00 AM PST) with customizable time settings.
Draws semi-transparent boxes to highlight these zones, aiding in the identification of key support and resistance areas.
Trap Area Identification:
Highlights potential trap zones where Globex ranges and Supply & Demand zones overlap, indicating areas where price may reverse or consolidate due to trapped traders.
Customizable Settings:
Adjust Globex and Supply & Demand session times to suit your trading preferences.
Toggle visibility of Globex and Supply & Demand zones independently.
Customize box colors for better chart readability.
Set the lookback period (default: 10 days) to control how many historical zones are displayed.
Configure the ATR length (default: 14) for the percentage calculation.
PST Timezone Default:
All times are based on Pacific Standard Time (PST) by default, ensuring accurate session tracking for users in this timezone or those aligning with U.S. West Coast market hours.
Recommended Usage
Timeframes: Best used on 1-hour charts or lower (e.g., 15-minute, 5-minute) for precise entry and exit points.
Markets: Optimized for futures (e.g., ES, NQ, CL) and other instruments traded during Globex sessions.
Historical Data: Ensure at least 10 days of historical data for optimal visualization of zones.
Strategy Integration: Use the indicator to identify potential reversals or breakouts at Globex highs/lows or Supply & Demand zones. The ATR percentage provides context for whether the Globex range is significant relative to typical daily volatility.
How It Works
Globex Session:
Tracks the high and low prices during the user-defined Globex session (default: 3:00 PM to 6:30 AM PST).
When the session ends, a box is drawn from the start to the end of the session, capturing the high and low prices.
Labels are placed at the midpoint of the session, showing "Globex High," "Globex Low," and the range as a percentage of the daily ATR (e.g., "75.23% of Daily ATR").
Supply & Demand Zones:
Tracks the high and low prices during the user-defined regular trading hours (default: 6:00 AM to 8:00 AM PST).
Draws a box to mark these zones, which often act as key support or resistance levels.
ATR Percentage:
Calculates the Globex range (high minus low) and divides it by the daily ATR to express it as a percentage.
This metric helps traders gauge whether the overnight price movement is significant compared to the instrument’s typical volatility.
Time Handling:
Uses PST (UTC-8) for all time calculations, ensuring accurate session timing for users aligning with this timezone.
Properly handles overnight sessions that cross midnight, ensuring seamless tracking.
Input Settings
Globex Session Settings:
Show Globex Session: Enable/disable Globex session visualization (default: true).
Globex Start/End Time: Set the start and end times for the Globex session (default: 3:00 PM to 6:30 AM PST).
Globex Box Color: Customize the color of the Globex session box (default: semi-transparent gray).
Supply & Demand Zone Settings:
Show Supply & Demand Zone: Enable/disable zone visualization (default: true).
Zone Start/End Time: Set the start and end times for Supply & Demand zones (default: 6:00 AM to 8:00 AM PST).
Zone Box Color: Customize the color of the zone box (default: semi-transparent aqua).
General Settings:
Days to Look Back: Number of historical days to display zones (default: 10).
ATR Length: Period for calculating the daily ATR (default: 14).
Notes
All times are in Pacific Standard Time (PST). Adjust the start and end times if your market operates in a different timezone or if you prefer different session windows.
The indicator is optimized for instruments with active Globex sessions, such as futures. Results may vary for non-24/5 markets.
A typo in the label "Globe Low" (should be "Globex Low") will be corrected in future updates.
Ensure your TradingView chart is set to display sufficient historical data to view the full lookback period.
Why Use This Indicator?
The Globex Trap w/ Percentage indicator provides a unique combination of session-based range analysis, Supply & Demand zone identification, and volatility context via the ATR percentage. Whether you’re a day trader, swing trader, or scalper, this tool helps you:
Pinpoint key price levels where institutional traders may act.
Assess the significance of overnight price movements relative to daily volatility.
Identify potential trap zones for high-probability setups.
Customize the indicator to fit your trading style and market preferences.
HorizonSigma Pro [CHE]HorizonSigma Pro
Disclaimer
Not every timeframe will yield good results . Very short charts are dominated by microstructure noise, spreads, and slippage; signals can flip and the tradable edge shrinks after costs. Very high timeframes adapt more slowly, provide fewer samples, and can lag regime shifts. When you change timeframe, you also change the ratios between horizon, lookbacks, and correlation windows—what works on M5 won’t automatically hold on H1 or D1. Liquidity, session effects (overnight gaps, news bursts), and volatility do not scale linearly with time. Always validate per symbol and timeframe, then retune horizon, z-length, correlation window, and either the neutral band or the z-threshold. On fast charts, “components” mode adapts quicker; on slower charts, “super” reduces noise. Keep prior-shift and calibration enabled, monitor Hit Rate with its confidence interval and the Brier score, and execute only on confirmed (closed-bar) values.
For example, what do “UP 61%” and “DOWN 21%” mean?
“UP 61%” is the model’s estimated probability that the close will be higher after your selected horizon—directional probability, not a price target or profit guarantee. “DOWN 21%” still reports the probability of up; here it’s 21%, which implies 79% for down (a short bias). The label switches to “DOWN” because the probability falls below your short threshold. With a neutral-band policy, for example ±7%, signals are: Long above 57%, Short below 43%, Neutral in between. In z-score mode, fixed z-cutoffs drive the call instead of percentages. The arrow length on the chart is an ATR-scaled projection to visualize reach; treat it as guidance, not a promise.
Part 1 — Scientific description
Objective.
The indicator estimates the probability that price will be higher after a user-defined horizon (a chosen number of bars) and emits long, short, or neutral decisions under explicit thresholds. It combines multi‑feature, z‑normalized inputs, adaptive correlation‑based weighting, a prior‑shifted sigmoid mapping, optional rolling probability calibration, and repaint‑safe confirmation. It also visualizes an ATR‑scaled forward projection and prints a compact statistics panel.
Data and labeling.
For each bar, the target label is whether price increased over the past chosen horizon. Learning is deliberately backward‑looking to avoid look‑ahead: features are associated with outcomes that are only known after that horizon has elapsed.
Feature engineering.
The feature set includes momentum, RSI, stochastic %K, MACD histogram slope, a normalized EMA(20/50) trend spread, ATR as a share of price, Bollinger Band width, and volume normalized by its moving average. All features are standardized over rolling windows. A compressed “super‑feature” is available that aggregates core trend and momentum components while penalizing excessive width (volatility). Users can switch between a “components” mode (weighted sum of individual features) and a “super” mode (single compressed driver).
Weighting and learning.
Weights are the rolling correlations between features (evaluated one horizon ago) and realized directional outcomes, smoothed by an EMA and optionally clamped to a bounded range to stabilize outliers. This produces an adaptive, regime‑aware weighting without explicit machine‑learning libraries.
Scoring and probability mapping.
The raw score is either the weighted component sum or the weighted super‑feature. The score is standardized again and passed through a sigmoid whose steepness is user‑controlled. A “prior shift” moves the sigmoid’s midpoint to the current base rate of up moves, estimated over the evaluation window, so that probabilities remain well‑calibrated when markets drift bullish or bearish. Probabilities and standardized scores are EMA‑smoothed for stability.
Decision policy.
Two modes are supported:
- Neutral band: go long if the probability is above one half plus a user‑set band; go short if it is below one half minus that band; otherwise stay neutral.
- Z‑score thresholds: use symmetric positive/negative cutoffs on the standardized score to trigger long/short.
Repaint protection.
All values used for decisions can be locked to confirmed (closed) bars. Intrabar updates are available as a preview, but confirmed values drive evaluation and stats.
Calibration.
An optional rolling linear calibration maps past confirmed probabilities to realized outcomes over the evaluation window. The mapping is clipped to the unit interval and can be injected back into the decision logic if desired. This improves reliability (probabilities that “mean what they say”) without necessarily improving raw separability.
Evaluation metrics.
The table reports: hit rate on signaled bars; a Wilson confidence interval for that hit rate at a chosen confidence level; Brier score as a measure of probability accuracy; counts of long/short trades; average realized return by side; profit factor; net return; and exposure (signal density). All are computed on rolling windows consistent with the learning scheme.
Visualization.
On the chart, an arrowed projection shows the predicted direction from the current bar to the chosen horizon, with magnitude scaled by ATR (optionally scaled by the square‑root of the horizon). Labels display either the decision probability or the standardized score. Neutral states can display a configurable icon for immediate recognition.
Computational properties.
The design relies on rolling means, standard deviations, correlations, and EMAs. Per‑bar cost is constant with respect to history length, and memory is constant per tracked series. Graphical objects are updated in place to obey platform limits.
Assumptions and limitations.
The method is correlation‑based and will adapt after regime changes, not before them. Calibration improves probability reliability but not necessarily ranking power. Intrabar previews are non‑binding and should not be evaluated as historical performance.
Part 2 — Trader‑facing description
What it does.
This tool tells you how likely price is to be higher after your chosen number of bars and converts that into Long / Short / Neutral calls. It learns, in real time, which components—momentum, trend, volatility, breadth, and volume—matter now, adjusts their weights, and shows you a probability line plus a forward arrow scaled by volatility.
How to set it up.
1) Choose your horizon. Intraday scalps: 5–10 bars. Swings: 10–30 bars. The default of 14 bars is a balanced starting point.
2) Pick a feature mode.
- components: granular and fast to adapt when leadership rotates between signals.
- super: cleaner single driver; less noise, slightly slower to react.
3) Decide how signals are triggered.
- Neutral band (probability based): intuitive and easy to tune. Widen the band for fewer, higher‑quality trades; tighten to catch more moves.
- Z‑score thresholds: consistent numeric cutoffs that ignore base‑rate drift.
4) Keep reliability helpers on. Leave prior shift and calibration enabled to stabilize probabilities across bullish/bearish regimes.
5) Smoothing. A short EMA on the probability or score reduces whipsaws while preserving turns.
6) Overlay. The arrow shows the call and a volatility‑scaled reach for the next horizon. Treat it as guidance, not a promise.
Reading the stats table.
- Hit Rate with a confidence interval: your recent accuracy with an uncertainty range; trust the range, not only the point.
- Brier Score: lower is better; it checks whether a stated “70%” really behaves like 70% over time.
- Profit Factor, Net Return, Exposure: quick triage of tradability and signal density.
- Average Return by Side: sanity‑check that the long and short calls each pull their weight.
Typical adjustments.
- Too many trades? Increase the neutral band or raise the z‑threshold.
- Missing the move? Tighten the band, or switch to components mode to react faster.
- Choppy timeframe? Lengthen the z‑score and correlation windows; keep calibration on.
- Volatility regime change? Revisit the ATR multiplier and enable square‑root scaling of horizon.
Execution and risk.
- Size positions by volatility (ATR‑based sizing works well).
- Enter on confirmed values; use intrabar previews only as early signals.
- Combine with your market structure (levels, liquidity zones). This model is statistical, not clairvoyant.
What it is not.
Not a black‑box machine‑learning model. It is transparent, correlation‑weighted technical analysis with strong attention to probability reliability and repaint safety.
Suggested defaults (robust starting point).
- Horizon 14; components mode; weight EMA 10; correlation window 500; z‑length 200.
- Neutral band around seven percentage points, or z‑threshold around one‑third of a standard deviation.
- Prior shift ON, Calibration ON, Use calibrated for decisions OFF to start.
- ATR multiplier 1.0; square‑root horizon scaling ON; EMA smoothing 3.
- Confidence setting equivalent to about 95%.
Disclaimer
No indicator guarantees profits. HorizonSigma Pro is a decision aid; always combine with solid risk management and your own judgment. Backtest, forward test, and size responsibly.
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Enhance your trading precision and confidence 🚀
Best regards
Chervolino
Standardized Cumulative Deltas [LuxAlgo]The Standardized Cumulative Deltas tool allows traders to compare the cumulative standardized open-close difference for up to 10 different tickers, allowing them to visualize the general sentiment for all selected tickers.
These results allow the construction of two areas showing the average or extreme bullish and bearish cumulative change for all enabled tickers, providing a summarized view of the overall ticker group sentiment.
🔶 USAGE
This tool is meant to give a full picture of the individuals and/or overall selected tickers, and unlike classical indicators, the displayed series of values is not meant to be directly interpreted over time.
Given the selected lookback period, a majority of observations being above 0 indicate an overall bullish market for the asset.
By default, the auto lookback period feature is enabled, allowing the tool to use all the visible bars for its calculations. Traders can also set the lookback period manually. The above chart uses a fixed lookback period of 500.
Up to 10 tickers can be used. While major cryptocurrencies are set by default, the users can set a specific basket of assets, such as US equities, forex pairs, commodities, etc.
🔹 Densities
The provided areas, here called densities, can be used to get an overall sentiment of the selected tickers. The upper density (bullish) processes positive deltas, while the lower one (bearish) processes negative ones.
Interpretation is subject to the selected "Density Mode".
Average: Densities track the average bullish/bearish cumulative deltas for the selected tickers. For example, a more prominent bullish density would indicate that, on average, cumulative deltas were positive across the tickers.
Envelope: Densities track the extreme values made by bullish/bearish cumulative deltas for the selected tickers. Here, a more prominent density would indicate more volatile bullish/bearish movements, depending on the density.
🔹 Dashboard
The tool features a dashboard with active tickers and their respective colors for traders' convenience.
🔶 DETAILS
🔹 Densities
Densities are obtained by applying a forward-backward exponential moving average on the average, or the highest/lowest cumulative series, depending on the selected Density Mode.
The resulting densities are smoothed by the "Smoothing" parameter located in the Settings panel, with higher values returning smoother envelopes with less variability.
Do note that the smoothing method used here is subject to repainting.
🔶 SETTINGS
Lookback: Select the lookback period and enable/disable the Auto Lookback feature
Tickers: Enable/disable and select up to 10 tickers and their colors
Density Mode: Determine how densities are calculated
🔹 Dashboard
Show Dashboard: Enable/disable the dashboard
Position: Select the dashboard position
Size: Select the dashboard size
🔹 Style
Density: Enable/disable the density areas
Bullish Density: Select the color of the top density area
Bearish Density: Select the color of the bottom density area
Smoothing: Select the smoothing constant for the EMA calculation