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.
3Ema-Gann_Swing_V2-ICT Killzones_Pivots_TFO3ema
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © meomeo105
//@version=5
indicator('3Ema-Gann_Swing_V2-ICT Killzones_Pivots_TFO', shorttitle='3Ema-GSv2-Killzones_Pivots', overlay=true, max_lines_count=500)
//Gann Swing V2
//-----Input-------
customTF = input.timeframe(defval="",title = "Show Other TimeFrame")
GroupGann = "Gann"
showGann = input.bool(true, 'Show Gann/Style', group = GroupGann,inline = "Gann/Style")
lineGann = input.string(title="",options= ,defval='(╌)', group = GroupGann, inline = "Gann/Style")
lineStyleGann = lineGann == "(┈)" ? line.style_dotted : lineGann == "(╌)" ? line.style_dashed : line.style_solid
colorGann = input.color(color.white, 'Color/Width', group = GroupGann, inline = "Color/Width")
widthGann = input.int(defval=1,title = "",minval=1, step=1, group = GroupGann, inline = "Color/Width")
ignoreISB = input.bool(true, 'Ignore Inside Bar', group = GroupGann, inline = "ignoreISB")
GroupSGann = "Swing of Gann"
showSGann = input.bool(true, 'Show Swing/Style', group = GroupSGann, inline = "Swing/Style")
lineSGann = input.string(title="",options= ,defval="(─)", group = GroupSGann, inline = "Swing/Style")
lineStyleSGann = lineSGann == "(┈)" ? line.style_dotted : lineSGann == "(╌)" ? line.style_dashed : line.style_solid
colorSGann = input.color(color.aqua, 'Color/Width', group = GroupSGann, inline = "Color/Width")
widthSGann = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann, inline = "Color/Width")
showChoCh = input.bool(false, 'Show ChoCh', group = GroupSGann,inline = "Choch")
show2ChoCh = input.bool(true, 'Show 2Choch/Color', group = GroupSGann,inline = "2Choch")
color2Choch = input.color(color.aqua, '', group = GroupSGann,inline = "2Choch")
showLabel = input.bool(true, 'Show Label TimeFrame',group = GroupSGann)
//////////////////////////Global//////////////////////////
var arrayLineTemp = array.new_line()
// Converts a resolution expressed in minutes into a string usable by "security()"
f_resFromMinutes(_minutes) =>
_minutes < 1 ? str.tostring(math.round(_minutes*60)) + "S" :
_minutes < 60 ? str.tostring(math.round(_minutes)) + "m" :
_minutes < 1440 ? str.tostring(math.round(_minutes/60)) + "H" :
_minutes < 10080 ? str.tostring(math.round(math.min(_minutes / 1440, 7))) + "D" :
_minutes < 43800 ? str.tostring(math.round(math.min(_minutes / 10080, 4))) + "W" :
str.tostring(math.round(math.min(_minutes / 43800, 12))) + "M"
var arrayLineChoCh = array.new_line()
var label labelTF = label.new(time, close, text = "",color = color.new(showSGann ? colorSGann : colorGann,95), textcolor = showSGann ? colorSGann : colorGann,xloc = xloc.bar_time, textalign = text.align_left)
//////////////////////////Gann//////////////////////////
styleGann = showSGann ? line.style_dashed : line.style_solid
var arrayXGann = array.new_int(5,time)
var arrayYGann = array.new_float(5,close)
var arrayLineGann = array.new_line()
int drawLineGann = 0
secondCustomTF = request.security(syminfo.tickerid,customTF,timeframe.in_seconds(),lookahead=barmerge.lookahead_on)
_high = request.security(syminfo.tickerid,customTF,high,lookahead=barmerge.lookahead_on)
_low = request.security(syminfo.tickerid,customTF,low,lookahead=barmerge.lookahead_on)
_close = request.security(syminfo.tickerid,customTF,close,lookahead=barmerge.lookahead_on)
_open = request.security(syminfo.tickerid,customTF,open,lookahead=barmerge.lookahead_on)
highPrev = _high
lowPrev = _low
// drawLineGann => 2:Tiếp tục 1:Đảo chiều; // Outsidebar 2:Tiếp tục 3:Tiếp tục và Đảo chiều 4 : Đảo chiều 2 lần
drawLineGann := 0
if(_high > highPrev and _low > lowPrev )
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(_high > array.get(arrayYGann,0))
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
drawLineGann := 2
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 1
else if(_high < highPrev and _low < lowPrev )
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 1
else
if(_low < array.get(arrayYGann,0))
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
drawLineGann := 2
else if((_high >= highPrev and _low < lowPrev ) or (_high > highPrev and _low <= lowPrev ))
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(_high >= array.get(arrayYGann,0) and array.get(arrayYGann,1) <= _low )
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
drawLineGann := 2
else if(_high >= array.get(arrayYGann,0) and array.get(arrayYGann,1) >= _low )
if(_close < _open)
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 3
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 4
else if(array.get(arrayYGann,0) < array.get(arrayYGann,1))
if(_low <= array.get(arrayYGann,0) and _high <= array.get(arrayYGann,1))
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
drawLineGann := 2
else if(_low <= array.get(arrayYGann,0) and _high >= array.get(arrayYGann,1))
if(_close > _open)
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 3
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 4
else if((_high <= highPrev and _low >= lowPrev ) and ignoreISB)
highPrev := highPrev
lowPrev := lowPrev
if(timeframe.in_seconds() < secondCustomTF and drawLineGann == 0)
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(array.get(arrayYGann,0) <= high)
array.set(arrayXGann, 0, time)
drawLineGann := 2
else
if(array.get(arrayYGann,0) >= low)
array.set(arrayXGann, 0, time)
drawLineGann := 2
if(showGann and timeframe.in_seconds() <= secondCustomTF)
if(drawLineGann == 2)
if(array.size(arrayLineGann) >0)
line.set_xy2(array.get(arrayLineGann,0),array.get(arrayXGann,0),array.get(arrayYGann,0))
else
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
else if(drawLineGann == 1)
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
else if(drawLineGann == 3)
if(array.size(arrayLineGann) >0)
line.set_xy2(array.get(arrayLineGann,0),array.get(arrayXGann,1),array.get(arrayYGann,1))
else
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,2),array.get(arrayYGann,2),array.get(arrayXGann,1),array.get(arrayYGann,1), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
else if(drawLineGann == 4)
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,2),array.get(arrayYGann,2),array.get(arrayXGann,1),array.get(arrayYGann,1), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleGann))
//////////////////////////Swing Gann//////////////////////////
var arrayXSGann = array.new_int(5,time)
var arrayYSGann = array.new_float(5,close)
var arrayLineSGann = array.new_line()
int drawLineSGann = 0
int drawLineSGann1 = 0
bool runCheckChoChSGann = false
runCheckChoChSGann := runCheckChoChSGann
if(showSGann)
if(math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1)) < math.min(array.get(arrayYGann,0),array.get(arrayYGann,1)) or math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1)) > math.max(array.get(arrayYGann,0),array.get(arrayYGann,1)))
//Khởi tạo bắt đầu
drawLineSGann1 := 5
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
array.set(arrayYSGann, 0, array.get(arrayYGann,1))
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
// drawLineSGann kiểm tra điểm 1 => 13:Tiếp tục có sóng hồi // 12|19(reDraw):Tiếp tục không có sóng hồi // 14:Đảo chiều
if(array.get(arrayXGann,0) == array.get(arrayXGann,1))
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,2) and array.get(arrayYSGann,0) != array.get(arrayYGann,1) and ((array.get(arrayYGann,1) > array.get(arrayYGann,2) and array.get(arrayYSGann,0) > array.get(arrayYSGann,1)) or (array.get(arrayYGann,1) < array.get(arrayYGann,2) and array.get(arrayYSGann,0) < array.get(arrayYSGann,1))))
drawLineSGann1 := 12
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
array.set(arrayYSGann, 0, array.get(arrayYGann,1))
else if(array.get(arrayXSGann,0) <= array.get(arrayXGann,2))
if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,1) < array.get(arrayYSGann,1)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,1) > array.get(arrayYSGann,1)))
drawLineSGann1 := 14
runCheckChoChSGann := true
array.unshift(arrayXSGann,array.get(arrayXGann,1))
array.unshift(arrayYSGann,array.get(arrayYGann,1))
else if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,1) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,1) < array.get(arrayYSGann,0)))
drawLineSGann1 := 13
_max = math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_min = math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_max_idx = 0
_min_idx = 0
for i = 2 to array.size(arrayXGann)
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,i))
break
if(_min > array.get(arrayYGann,i))
_min := array.get(arrayYGann,i)
_min_idx := array.get(arrayXGann,i)
if(_max < array.get(arrayYGann,i))
_max := array.get(arrayYGann,i)
_max_idx := array.get(arrayXGann,i)
if(array.get(arrayYSGann,0) > array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_min_idx)
array.unshift(arrayYSGann,_min)
else if(array.get(arrayYSGann,0) < array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_max_idx)
array.unshift(arrayYSGann,_max)
array.unshift(arrayXSGann,array.get(arrayXGann,1))
array.unshift(arrayYSGann,array.get(arrayYGann,1))
if(timeframe.in_seconds() < secondCustomTF)
if(array.get(arrayYSGann,0) == array.get(arrayYGann,1) and array.get(arrayXSGann,0) != array.get(arrayXGann,1))
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
drawLineSGann1 := 19
if(timeframe.in_seconds() <= secondCustomTF)
if(drawLineSGann1 == 12 or drawLineSGann1 == 19)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,0),array.get(arrayYSGann,0))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
else if(drawLineSGann1 == 14)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
else if(drawLineSGann1 == 13)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
if(runCheckChoChSGann)
runCheckChoChSGann := false
// ChoCh Trường hợp chữ N ngược, chữ N
if((array.get(arrayYSGann,3) > array.get(arrayYSGann,2) and array.get(arrayYSGann,3) < array.get(arrayYSGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,2)) or (array.get(arrayYSGann,3) < array.get(arrayYSGann,2) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,2)))
alert(syminfo.ticker + " : " + timeframe.period + " => Swing of Gann ChoCh" + (array.get(arrayYSGann,0) > array.get(arrayYSGann,1) ? "+ ⇑" : "- ⇓"))
if(showChoCh)
array.unshift(arrayLineChoCh,line.new(x1= array.get(arrayXSGann,2) , y1=array.get(arrayYSGann,2),x2=array.get(arrayXSGann,0), y2=array.get(arrayYSGann,2),color = colorSGann,xloc = xloc.bar_time,style = line.style_dotted))
// ChoCh 2 Đầu Trường hợp chữ N ngược, chữ N
if(show2ChoCh and ((array.get(arrayYSGann,1) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1))))
line.set_width(array.get(arrayLineSGann,1),widthGann + 1)
line.set_style(array.get(arrayLineSGann,1),line.style_dashed)
line.set_color(array.get(arrayLineSGann,1),color2Choch)
// drawLineSGann kiểm tra điểm 0 => 3:Tiếp tục có sóng hồi // 2|9(reDraw):Tiếp tục không có sóng hồi // 4:Đảo chiều
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,1) and array.get(arrayYSGann,0) != array.get(arrayYGann,0) and ((array.get(arrayYGann,0) > array.get(arrayYGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,1)) or (array.get(arrayYGann,0) < array.get(arrayYGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,1))))
drawLineSGann := 2
array.set(arrayXSGann, 0, array.get(arrayXGann,0))
array.set(arrayYSGann, 0, array.get(arrayYGann,0))
else if(array.get(arrayXSGann,0) <= array.get(arrayXGann,1))
if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,0) < array.get(arrayYSGann,1)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,0) > array.get(arrayYSGann,1)))
drawLineSGann := 4
runCheckChoChSGann := true
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
else if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,0) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,0) < array.get(arrayYSGann,0)))
drawLineSGann := 3
_max = math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_min = math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_max_idx = 0
_min_idx = 0
for i = 1 to array.size(arrayXGann)
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,i))
break
if(_min > array.get(arrayYGann,i))
_min := array.get(arrayYGann,i)
_min_idx := array.get(arrayXGann,i)
if(_max < array.get(arrayYGann,i))
_max := array.get(arrayYGann,i)
_max_idx := array.get(arrayXGann,i)
if(array.get(arrayYSGann,0) > array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_min_idx)
array.unshift(arrayYSGann,_min)
else if(array.get(arrayYSGann,0) < array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_max_idx)
array.unshift(arrayYSGann,_max)
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
if(timeframe.in_seconds() < secondCustomTF)
if(array.get(arrayYSGann,0) == array.get(arrayYGann,0) and array.get(arrayXSGann,0) != array.get(arrayXGann,0))
array.set(arrayXSGann, 0, array.get(arrayXGann,0))
drawLineSGann := 9
if(timeframe.in_seconds() <= secondCustomTF)
if(drawLineSGann == 2 or drawLineSGann == 9)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,0),array.get(arrayYSGann,0))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
else if(drawLineSGann == 4)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
else if(drawLineSGann == 3)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthGann,style=lineStyleSGann))
if(runCheckChoChSGann)
runCheckChoChSGann := false
// ChoCh Trường hợp chữ N ngược, chữ N
if((array.get(arrayYSGann,3) > array.get(arrayYSGann,2) and array.get(arrayYSGann,3) < array.get(arrayYSGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,2)) or (array.get(arrayYSGann,3) < array.get(arrayYSGann,2) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,2)))
alert(syminfo.ticker + " : " + timeframe.period + " => Swing of Gann ChoCh" + (array.get(arrayYSGann,0) > array.get(arrayYSGann,1) ? "+ ⇑" : "- ⇓"))
if(showChoCh)
array.unshift(arrayLineChoCh,line.new(x1= array.get(arrayXSGann,2) , y1=array.get(arrayYSGann,2),x2=array.get(arrayXSGann,0), y2=array.get(arrayYSGann,2),color = colorSGann,xloc = xloc.bar_time,style = line.style_dotted))
// ChoCh 2 Đầu Trường hợp chữ N ngược, chữ N
if(show2ChoCh and ((array.get(arrayYSGann,1) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1))))
line.set_width(array.get(arrayLineSGann,1),widthGann+1)
line.set_style(array.get(arrayLineSGann,1),line.style_dashed)
line.set_color(array.get(arrayLineSGann,1),color2Choch)
///////////////////////Other//////////////////////////////////
if(timeframe.in_seconds() <= secondCustomTF)
if(showSGann)
if(showLabel and (barstate.islast or barstate.islastconfirmedhistory))
texLabel = timeframe.in_seconds() == secondCustomTF ? f_resFromMinutes(timeframe.in_seconds()/60) : f_resFromMinutes(secondCustomTF/60)
label.set_xy(labelTF,array.get(arrayXSGann,0),array.get(arrayYSGann,0))
label.set_text(labelTF,texLabel)
label.set_style(labelTF,array.get(arrayYSGann,0) < array.get(arrayYSGann,1) ? label.style_label_upper_right : label.style_label_lower_right)
else if(showGann)
if(showLabel and (barstate.islast or barstate.islastconfirmedhistory))
texLabel = timeframe.in_seconds() == secondCustomTF ? f_resFromMinutes(timeframe.in_seconds()/60) : f_resFromMinutes(secondCustomTF/60)
label.set_xy(labelTF,array.get(arrayXGann,0),array.get(arrayYGann,0))
label.set_text(labelTF,texLabel)
label.set_style(labelTF,array.get(arrayYGann,0) < array.get(arrayYGann,1) ? label.style_label_upper_right : label.style_label_lower_right)
if(showSGann and showGann and array.size(arrayLineGann) > 9 and array.size(arrayLineSGann) > 9 and drawLineGann != 2 and drawLineSGann != 2 and drawLineSGann != 9 and drawLineSGann != 12 and drawLineSGann != 19)
for i = 1 to 9
if(line.get_x1(array.get(arrayLineGann,i)) == line.get_x1(array.get(arrayLineSGann,0)) and line.get_y1(array.get(arrayLineGann,i)) == line.get_y1(array.get(arrayLineSGann,0)) and line.get_x2(array.get(arrayLineGann,i)) == line.get_x2(array.get(arrayLineSGann,0)) and line.get_y2(array.get(arrayLineGann,i)) == line.get_y2(array.get(arrayLineSGann,0)))
line.delete(array.get(arrayLineGann,i))
array.remove(arrayLineGann,i)
break
else if(line.get_x1(array.get(arrayLineGann,i)) == line.get_x1(array.get(arrayLineSGann,1)) and line.get_y1(array.get(arrayLineGann,i)) == line.get_y1(array.get(arrayLineSGann,1)) and line.get_x2(array.get(arrayLineGann,i)) == line.get_x2(array.get(arrayLineSGann,1)) and line.get_y2(array.get(arrayLineGann,i)) == line.get_y2(array.get(arrayLineSGann,1)))
line.delete(array.get(arrayLineGann,i))
array.remove(arrayLineGann,i)
break
else if(line.get_x1(array.get(arrayLineGann,i)) == line.get_x1(array.get(arrayLineSGann,2)) and line.get_y1(array.get(arrayLineGann,i)) == line.get_y1(array.get(arrayLineSGann,2)) and line.get_x2(array.get(arrayLineGann,i)) == line.get_x2(array.get(arrayLineSGann,2)) and line.get_y2(array.get(arrayLineGann,i)) == line.get_y2(array.get(arrayLineSGann,2)))
line.delete(array.get(arrayLineGann,i))
array.remove(arrayLineGann,i)
break
//EMA
// EMA 2
EMA1len = input.int(21, minval=1, title="EMA1>Length")
EMA1src = input(close, title="EMA1>Source")
EMA1offset = input.int(title="EMA1>Offset", defval=0, minval=-500, maxval=500)
EMA1out = ta.ema(EMA1src, EMA1len)
plot(EMA1out, title="EMA1", color=color.black, offset=EMA1offset)
// EMA 3
EMA2len = input.int(50, minval=1, title="EMA2>Length")
EMA2src = input(close, title="EMA2>Source")
EMA2offset = input.int(title="EMA2>Offset", defval=0, minval=-500, maxval=500)
EMA2out = ta.ema(EMA2src, EMA2len)
plot(EMA2out, title="EMA2", color=color.blue, offset=EMA2offset)
// EMA 4
EMA3len = input.int(200, minval=1, title="EMA3>Length")
EMA3src = input(close, title="EMA3>Source")
EMA3offset = input.int(title="EMA3>Offset", defval=0, minval=-500, maxval=500)
EMA3out = ta.ema(EMA3src, EMA3len)
plot(EMA3out, title="EMA3", color=color.red, offset=EMA3offset)
// ICT Killzones & Pivots
// ---------------------------------------- Inputs --------------------------------------------------
var g_SETTINGS = "Settings"
max_days = input.int(3, "Session Drawing Limit", 1, tooltip = "Only this many drawings will be kept on the chart, for each selected drawing type (killzone boxes, pivot lines, open lines, etc.)", group = g_SETTINGS)
tf_limit = input.timeframe("30", "Timeframe Limit", tooltip = "Drawings will not appear on timeframes greater than or equal to this", group = g_SETTINGS)
gmt_tz = input.string('GMT-4', "Timezone", options = , tooltip = "Note GMT is not adjusted to reflect Daylight Saving Time changes", group = g_SETTINGS)
lb_size = input.string('Normal', "Label Size", options = , group = g_SETTINGS)
lb_color = input.color(color.black, "Label Text Color", group = g_SETTINGS)
use_cutoff = input.bool(true, "Drawing Cutoff Time", inline = "CO", tooltip = "When enabled, all highs and lows will stop extending after this time", group = g_SETTINGS)
cutoff = input.session("1200-1201", "", inline = "CO", group = g_SETTINGS)
var g_KZ = "Killzones"
show_kz = input.bool(true, "Show Killzone Boxes", inline = "KZ", group = g_KZ)
show_kz_text = input.bool(true, "Display Text", inline = "KZ", group = g_KZ)
box_transparency = input.int(70, "Box Transparency", 0, 100, group = g_KZ)
text_transparency = input.int(50, "Text Transparency", 0, 100, group = g_KZ)
use_asia = input.bool(true, "", inline = "ASIA", group = g_KZ)
asia_text = input.string("Asia", "", inline = "ASIA", group = g_KZ)
asia = input.session("2000-0000", "", inline = "ASIA", group = g_KZ)
as_color = input.color(color.blue, "", inline = "ASIA", group = g_KZ)
use_london = input.bool(true, "", inline = "LONDON", group = g_KZ)
london_text = input.string("London", "", inline = "LONDON", group = g_KZ)
london = input.session("0200-0500", "", inline = "LONDON", group = g_KZ)
lo_color = input.color(color.red, "", inline = "LONDON", group = g_KZ)
use_nyam = input.bool(true, "", inline = "NYAM", group = g_KZ)
nyam_text = input.string("NY AM", "", inline = "NYAM", group = g_KZ)
nyam = input.session("0930-1100", "", inline = "NYAM", group = g_KZ)
na_color = input.color(#089981, "", inline = "NYAM", group = g_KZ)
use_nylu = input.bool(true, "", inline = "NYLU", group = g_KZ)
nylu_text = input.string("NY Lunch", "", inline = "NYLU", group = g_KZ)
nylu = input.session("1200-1300", "", inline = "NYLU", group = g_KZ)
nl_color = input.color(color.yellow, "", inline = "NYLU", group = g_KZ)
use_nypm = input.bool(true, "", inline = "NYPM", group = g_KZ)
nypm_text = input.string("NY PM", "", inline = "NYPM", group = g_KZ)
nypm = input.session("1330-1600", "", inline = "NYPM", group = g_KZ)
np_color = input.color(color.purple, "", inline = "NYPM", group = g_KZ)
var g_LABELS = "Killzone Pivots"
show_pivots = input.bool(true, "Show Pivots", inline = "PV", group = g_LABELS)
show_labels = input.bool(true, "Show Labels", inline = "PV", group = g_LABELS)
ash_str = input.string("AS.H", "Session 1 Labels", inline = "L_AS", group = g_LABELS)
asl_str = input.string("AS.L", "", inline = "L_AS", group = g_LABELS)
as_alert = input.bool(false, "Alerts", inline = "L_AS", group = g_LABELS)
loh_str = input.string("LO.H", "Session 2 Labels", inline = "L_LO", group = g_LABELS)
lol_str = input.string("LO.L", "", inline = "L_LO", group = g_LABELS)
lo_alert = input.bool(false, "Alerts", inline = "L_LO", group = g_LABELS)
nah_str = input.string("NYAM.H", "Session 3 Labels", inline = "L_NA", group = g_LABELS)
nal_str = input.string("NYAM.L", "", inline = "L_NA", group = g_LABELS)
na_alert = input.bool(false, "Alerts", inline = "L_NA", group = g_LABELS)
nlh_str = input.string("NYL.H", "Session 4 Labels", inline = "L_NL", group = g_LABELS)
nll_str = input.string("NYL.L", "", inline = "L_NL", group = g_LABELS)
nl_alert = input.bool(false, "Alerts", inline = "L_NL", group = g_LABELS)
nph_str = input.string("NYPM.H", "Session 5 Labels", inline = "L_NP", group = g_LABELS)
npl_str = input.string("NYPM.L", "", inline = "L_NP", group = g_LABELS)
np_alert = input.bool(false, "Alerts", inline = "L_NP", group = g_LABELS)
s_style = input.string(defval = 'Solid', title = "Style", options = , inline = "L_0", group = g_LABELS)
s_width = input.int(1, "", inline = "L_0", group = g_LABELS)
var g_DWM = "DWM Open"
dow_labels = input.bool(true, "Day of Week Labels", inline = "DOW", group = g_DWM)
dow_yloc = input.string('Bottom', "", options = , inline = "DOW", group = g_DWM)
dow_xloc = input.string('Midnight', "", options = , inline = "DOW", group = g_DWM)
dow_color = input.color(color.black, "", inline = "DOW", group = g_DWM)
show_d_open = input.bool(false, "", inline = "DO", group = g_DWM)
d_open_str = input.string("D.OPEN", "", inline = "DO", group = g_DWM)
ds = input.bool(false, "Separators", inline = "DO", tooltip = "Mark where a new day begins. Unlimited will override the drawing limit", group = g_DWM)
ds_unlimited = input.bool(true, "Unlimited", inline = "DO", group = g_DWM)
d_color = input.color(color.blue, "", inline = "DO", group = g_DWM)
show_w_open = input.bool(false, "", inline = "WO", group = g_DWM)
w_open_str = input.string("W.OPEN", "", inline = "WO", group = g_DWM)
ws = input.bool(false, "Separators", inline = "WO", tooltip = "Mark where a new week begins. Unlimited will override the drawing limit", group = g_DWM)
ws_unlimited = input.bool(true, "Unlimited", inline = "WO", group = g_DWM)
w_color = input.color(#089981, "", inline = "WO", group = g_DWM)
show_m_open = input.bool(false, "", inline = "MO", group = g_DWM)
m_open_str = input.string("M.OPEN", "", inline = "MO", group = g_DWM)
ms = input.bool(false, "Separators", inline = "MO", tooltip = "Mark where a new month begins. Unlimited will override the drawing limit", group = g_DWM)
ms_unlimited = input.bool(true, "Unlimited", inline = "MO", group = g_DWM)
m_color = input.color(color.red, "", inline = "MO", group = g_DWM)
dwm_style = input.string(defval = 'Solid', title = "Style", options = , inline = "D0", group = g_DWM)
dwm_width = input.int(1, "", inline = "D0", group = g_DWM)
var g_OPEN = "Opening Price"
use_h1 = input.bool(true, "", inline = "H1", group = g_OPEN)
h1_text = input.string("True Day Open", "", inline = "H1", group = g_OPEN)
h1 = input.session("0000-0001", "", inline = "H1", group = g_OPEN)
h1_color = input.color(color.black, "", inline = "H1", group = g_OPEN)
use_h2 = input.bool(false, "", inline = "H2", group = g_OPEN)
h2_text = input.string("06:00", "", inline = "H2", group = g_OPEN)
h2 = input.session("0600-0601", "", inline = "H2", group = g_OPEN)
h2_color = input.color(color.black, "", inline = "H2", group = g_OPEN)
use_h3 = input.bool(false, "", inline = "H3", group = g_OPEN)
h3_text = input.string("10:00", "", inline = "H3", group = g_OPEN)
h3 = input.session("1000-1001", "", inline = "H3", group = g_OPEN)
h3_color = input.color(color.black, "", inline = "H3", group = g_OPEN)
use_h4 = input.bool(false, "", inline = "H4", group = g_OPEN)
h4_text = input.string("14:00", "", inline = "H4", group = g_OPEN)
h4 = input.session("1400-1401", "", inline = "H4", group = g_OPEN)
h4_color = input.color(color.black, "", inline = "H4", group = g_OPEN)
h_style = input.string(defval = 'Dotted', title = "Style", options = , inline = "H0", group = g_OPEN)
h_width = input.int(1, "", inline = "H0", group = g_OPEN)
var g_VERTICAL = "Timestamps"
use_v1 = input.bool(false, "", inline = "V1", group = g_VERTICAL)
v1 = input.session("0000-0001", "", inline = "V1", group = g_VERTICAL)
v1_color = input.color(color.black, "", inline = "V1", group = g_VERTICAL)
use_v2 = input.bool(false, "", inline = "V2", group = g_VERTICAL)
v2 = input.session("0800-0801", "", inline = "V2", group = g_VERTICAL)
v2_color = input.color(color.black, "", inline = "V2", group = g_VERTICAL)
use_v3 = input.bool(false, "", inline = "V3", group = g_VERTICAL)
v3 = input.session("1000-1001", "", inline = "V3", group = g_VERTICAL)
v3_color = input.color(color.black, "", inline = "V3", group = g_VERTICAL)
use_v4 = input.bool(true, "", inline = "V4", group = g_VERTICAL)
v4 = input.session("1200-1201", "", inline = "V4", group = g_VERTICAL)
v4_color = input.color(color.black, "", inline = "V4", group = g_VERTICAL)
v_style = input.string(defval = 'Dotted', title = "Style", options = , inline = "V0", group = g_VERTICAL)
v_width = input.int(1, "", inline = "V0", group = g_VERTICAL)
// ---------------------------------------- Inputs --------------------------------------------------
// ---------------------------------------- Variables & Constants --------------------------------------------------
t_as = not na(time("", asia, gmt_tz))
t_lo = not na(time("", london, gmt_tz))
t_na = not na(time("", nyam, gmt_tz))
t_nl = not na(time("", nylu, gmt_tz))
t_np = not na(time("", nypm, gmt_tz))
t_co = not na(time("", cutoff, gmt_tz))
t_h1 = not na(time("", h1, gmt_tz))
t_h2 = not na(time("", h2, gmt_tz))
t_h3 = not na(time("", h3, gmt_tz))
t_h4 = not na(time("", h4, gmt_tz))
t_v1 = not na(time("", v1, gmt_tz))
t_v2 = not na(time("", v2, gmt_tz))
t_v3 = not na(time("", v3, gmt_tz))
t_v4 = not na(time("", v4, gmt_tz))
var as_hi_line = array.new_line()
var as_lo_line = array.new_line()
var lo_hi_line = array.new_line()
var lo_lo_line = array.new_line()
var na_hi_line = array.new_line()
var na_lo_line = array.new_line()
var nl_hi_line = array.new_line()
var nl_lo_line = array.new_line()
var np_hi_line = array.new_line()
var np_lo_line = array.new_line()
var d_sep_line = array.new_line()
var w_sep_line = array.new_line()
var m_sep_line = array.new_line()
var d_line = array.new_line()
var w_line = array.new_line()
var m_line = array.new_line()
var h1_line = array.new_line()
var h2_line = array.new_line()
var h3_line = array.new_line()
var h4_line = array.new_line()
var v1_line = array.new_line()
var v2_line = array.new_line()
var v3_line = array.new_line()
var v4_line = array.new_line()
var d_label = array.new_label()
var w_label = array.new_label()
var m_label = array.new_label()
var h1_label = array.new_label()
var h2_label = array.new_label()
var h3_label = array.new_label()
var h4_label = array.new_label()
var as_hi_label = array.new_label()
var as_lo_label = array.new_label()
var lo_hi_label = array.new_label()
var lo_lo_label = array.new_label()
var na_hi_label = array.new_label()
var na_lo_label = array.new_label()
var nl_hi_label = array.new_label()
var nl_lo_label = array.new_label()
var np_hi_label = array.new_label()
var np_lo_label = array.new_label()
var as_box = array.new_box()
var lo_box = array.new_box()
var na_box = array.new_box()
var nl_box = array.new_box()
var np_box = array.new_box()
transparent = #ffffff00
d_o = request.security(syminfo.tickerid, "D", open, barmerge.gaps_off, barmerge.lookahead_on)
w_o = request.security(syminfo.tickerid, "W", open, barmerge.gaps_off, barmerge.lookahead_on)
m_o = request.security(syminfo.tickerid, "M", open, barmerge.gaps_off, barmerge.lookahead_on)
// ---------------------------------------- Variables & Constants --------------------------------------------------
// ---------------------------------------- Functions --------------------------------------------------
get_label_size(_size) =>
result = switch _size
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
result
get_line_type(_style) =>
result = switch _style
'Solid' => line.style_solid
'Dotted' => line.style_dotted
'Dashed' => line.style_dashed
result
get_box_color(_color, _transparency) =>
result = color.new(_color, _transparency)
adjust(_hline, _lline, _hlabel, _llabel, _ulabel, _box) =>
_hline.set_x2(bar_index)
_lline.set_x2(bar_index)
_box.set_right(bar_index)
_top = show_kz ? _box.get_top() : _hline.get_y1()
_bot = show_kz ? _box.get_bottom() : _lline.get_y1()
if high > _top
_hline.set_xy1(bar_index, high)
_hline.set_y2(high)
_box.set_top(high)
_hlabel.set_x(bar_index)
_hlabel.set_y(high)
if low < _bot
_lline.set_xy1(bar_index, low)
_lline.set_y2(low)
_box.set_bottom(low)
_llabel.set_x(bar_index)
_llabel.set_y(low)
check_high(_line) =>
result = false
broke = false
_line.set_x2(bar_index)
if high > _line.get_y1()
result := true
broke := true
else if (use_cutoff ? t_co : false)
result := true
check_low(_line) =>
result = false
broke = false
_line.set_x2(bar_index)
if low < _line.get_y1()
result := true
broke := true
else if (use_cutoff ? t_co : false)
result := true
check_open(_line, _label) =>
result = false
_line.set_x2(bar_index)
_label.set_x(bar_index)
if (use_cutoff ? t_co : false)
result := true
result
check_array(_arr) =>
if _arr.size() > max_days
_arr.pop().delete()
// ---------------------------------------- Functions --------------------------------------------------
// ---------------------------------------- Core Logic --------------------------------------------------
s_style := get_line_type(s_style)
dwm_style := get_line_type(dwm_style)
h_style := get_line_type(h_style)
v_style := get_line_type(v_style)
lb_size := get_label_size(lb_size)
var color as_box_color = get_box_color(as_color, box_transparency)
var color lo_box_color = get_box_color(lo_color, box_transparency)
var color na_box_color = get_box_color(na_color, box_transparency)
var color nl_box_color = get_box_color(nl_color, box_transparency)
var color np_box_color = get_box_color(np_color, box_transparency)
var color as_text_color = get_box_color(as_color, text_transparency)
var color lo_text_color = get_box_color(lo_color, text_transparency)
var color na_text_color = get_box_color(na_color, text_transparency)
var color nl_text_color = get_box_color(nl_color, text_transparency)
var color np_text_color = get_box_color(np_color, text_transparency)
var h1_co = false
var h2_co = false
var h3_co = false
var h4_co = false
var as_stop_hi = false
var as_stop_lo = false
var lo_stop_hi = false
var lo_stop_lo = false
var na_stop_hi = false
var na_stop_lo = false
var nl_stop_hi = false
var nl_stop_lo = false
var np_stop_hi = false
var np_stop_lo = false
as_broke_hi = false
as_broke_lo = false
lo_broke_hi = false
lo_broke_lo = false
na_broke_hi = false
na_broke_lo = false
nl_broke_hi = false
nl_broke_lo = false
np_broke_hi = false
np_broke_lo = false
// day_str = switch dayofweek
// if dayofweek != dayofweek
// label.new(time, high, str.tostring(dayofweek))
if timeframe.in_seconds("") <= timeframe.in_seconds(tf_limit)
// Asia
if use_asia
if t_as and not t_as
as_stop_hi := false
as_stop_lo := false
if show_kz
as_box.unshift(box.new(bar_index, high, bar_index, low, border_color = as_box_color, bgcolor = as_box_color, text = show_kz_text ? asia_text : na, text_color = as_text_color))
if show_pivots
as_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = as_color, width = s_width))
as_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = as_color, width = s_width))
if show_labels
as_hi_label.unshift(label.new(bar_index, high, ash_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
as_lo_label.unshift(label.new(bar_index, low, asl_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_as
adjust(show_pivots ? as_hi_line.get(0) : na, show_pivots ? as_lo_line.get(0) : na, show_labels ? as_hi_label.get(0) : na, show_labels ? as_lo_label.get(0) : na, show_labels, show_kz ? as_box.get(0) : na)
else if not t_as and as_hi_line.size() > 0
if not as_stop_hi
= check_high(as_hi_line.get(0))
if _r
as_stop_hi := true
if _b
as_broke_hi := true
if as_alert
alert("Broke " + str.tostring(ash_str), alert.freq_once_per_bar)
if not as_stop_lo
= check_low(as_lo_line.get(0))
if _r
as_stop_lo := true
if _b
as_broke_lo := true
if as_alert
alert("Broke " + str.tostring(asl_str), alert.freq_once_per_bar)
// London
if use_london
if t_lo and not t_lo
lo_stop_hi := false
lo_stop_lo := false
if show_kz
lo_box.unshift(box.new(bar_index, high, bar_index, low, border_color = lo_box_color, bgcolor = lo_box_color, text = show_kz_text ? london_text : na, text_color = lo_text_color))
if show_pivots
lo_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = lo_color, width = s_width))
lo_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = lo_color, width = s_width))
if show_labels
lo_hi_label.unshift(label.new(bar_index, high, loh_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
lo_lo_label.unshift(label.new(bar_index, low, lol_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_lo
adjust(show_pivots ? lo_hi_line.get(0) : na, show_pivots ? lo_lo_line.get(0) : na, show_labels ? lo_hi_label.get(0) : na, show_labels ? lo_lo_label.get(0) : na, show_labels, show_kz ? lo_box.get(0) : na)
else if not t_lo and lo_hi_line.size() > 0
if not lo_stop_hi
= check_high(lo_hi_line.get(0))
if _r
lo_stop_hi := true
if _b
lo_broke_hi := true
if lo_alert
alert("Broke " + str.tostring(loh_str), alert.freq_once_per_bar)
if not lo_stop_lo
= check_low(lo_lo_line.get(0))
if _r
lo_stop_lo := true
if _b
lo_broke_lo := true
if lo_alert
alert("Broke " + str.tostring(lol_str), alert.freq_once_per_bar)
// NY AM
if use_nyam
if t_na and not t_na
na_stop_hi := false
na_stop_lo := false
if show_kz
na_box.unshift(box.new(bar_index, high, bar_index, low, border_color = na_box_color, bgcolor = na_box_color, text = show_kz_text ? nyam_text : na, text_color = na_text_color))
if show_pivots
na_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = na_color, width = s_width))
na_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = na_color, width = s_width))
if show_labels
na_hi_label.unshift(label.new(bar_index, high, nah_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
na_lo_label.unshift(label.new(bar_index, low, nal_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_na
adjust(show_pivots ? na_hi_line.get(0) : na, show_pivots ? na_lo_line.get(0) : na, show_labels ? na_hi_label.get(0) : na, show_labels ? na_lo_label.get(0) : na, show_labels, show_kz ? na_box.get(0) : na)
else if not t_na and na_hi_line.size() > 0
if not na_stop_hi
= check_high(na_hi_line.get(0))
if _r
na_stop_hi := true
if _b
na_broke_hi := true
if na_alert
alert("Broke " + str.tostring(nah_str), alert.freq_once_per_bar)
if not na_stop_lo
= check_low(na_lo_line.get(0))
if _r
na_stop_lo := true
if _b
na_broke_lo := true
if na_alert
alert("Broke " + str.tostring(nal_str), alert.freq_once_per_bar)
// NY Lunch
if use_nylu
if t_nl and not t_nl
nl_stop_hi := false
nl_stop_lo := false
if show_kz
nl_box.unshift(box.new(bar_index, high, bar_index, low, border_color = nl_box_color, bgcolor = nl_box_color, text = show_kz_text ? nylu_text : na, text_color = nl_text_color))
if show_pivots
nl_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = nl_color, width = s_width))
nl_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = nl_color, width = s_width))
if show_labels
nl_hi_label.unshift(label.new(bar_index, high, nlh_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
nl_lo_label.unshift(label.new(bar_index, low, nll_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_nl
adjust(show_pivots ? nl_hi_line.get(0) : na, show_pivots ? nl_lo_line.get(0) : na, show_labels ? nl_hi_label.get(0) : na, show_labels ? nl_lo_label.get(0) : na, show_labels, show_kz ? nl_box.get(0) : na)
else if not t_nl and nl_hi_line.size() > 0
if not nl_stop_hi
= check_high(nl_hi_line.get(0))
if _r
nl_stop_hi := true
if _b
nl_broke_hi := true
if nl_alert
alert("Broke " + str.tostring(nlh_str), alert.freq_once_per_bar)
if not nl_stop_lo
= check_low(nl_lo_line.get(0))
if _r
nl_stop_lo := true
if _b
nl_broke_lo := true
if nl_alert
alert("Broke " + str.tostring(nll_str), alert.freq_once_per_bar)
// NY PM
if use_nypm
if t_np and not t_np
np_stop_hi := false
np_stop_lo := false
if show_kz
np_box.unshift(box.new(bar_index, high, bar_index, low, border_color = np_box_color, bgcolor = np_box_color, text = show_kz_text ? nypm_text : na, text_color = np_text_color))
if show_pivots
np_hi_line.unshift(line.new(bar_index, high, bar_index, high, style = s_style, color = np_color, width = s_width))
np_lo_line.unshift(line.new(bar_index, low, bar_index, low, style = s_style, color = np_color, width = s_width))
if show_labels
np_hi_label.unshift(label.new(bar_index, high, nph_str, color = transparent, textcolor = lb_color, style = label.style_label_down, size = lb_size))
np_lo_label.unshift(label.new(bar_index, low, npl_str, color = transparent, textcolor = lb_color, style = label.style_label_up, size = lb_size))
else if t_np
adjust(show_pivots ? np_hi_line.get(0) : na, show_pivots ? np_lo_line.get(0) : na, show_labels ? np_hi_label.get(0) : na, show_labels ? np_lo_label.get(0) : na, show_labels, show_kz ? np_box.get(0) : na)
else if not t_np and np_hi_line.size() > 0
if not np_stop_hi
= check_high(np_hi_line.get(0))
if _r
np_stop_hi := true
if _b
np_broke_hi := true
if np_alert
alert("Broke " + str.tostring(nph_str), alert.freq_once_per_bar)
if not np_stop_lo
= check_low(np_lo_line.get(0))
if _r
np_stop_lo := true
if _b
np_broke_lo := true
if np_alert
alert("Broke " + str.tostring(npl_str), alert.freq_once_per_bar)
// Vertical Lines
if use_v1
if t_v1 and not t_v1
v1_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v1_color))
if use_v2
if t_v2 and not t_v2
v2_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v2_color))
if use_v3
if t_v3 and not t_v3
v3_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v3_color))
if use_v4
if t_v4 and not t_v4
v4_line.unshift(line.new(bar_index, high, bar_index, low, style = v_style, width = v_width, extend = extend.both, color = v4_color))
// Horizontal Lines
if use_h1
if t_h1 and not t_h1
h1_co := false
h1_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h1_color))
h1_label.unshift(label.new(bar_index, open, h1_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h1 and h1_line.size() > 0
if not h1_co
if not check_open(h1_line.get(0), h1_label.get(0))
h1_label.get(0).set_x(bar_index)
else
h1_co := true
if use_h2
if t_h2 and not t_h2
h2_co := false
h2_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h2_color))
h2_label.unshift(label.new(bar_index, open, h2_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h2 and h2_line.size() > 0
if not h2_co
if not check_open(h2_line.get(0), h2_label.get(0))
h2_label.get(0).set_x(bar_index)
else
h2_co := true
if use_h3
if t_h3 and not t_h3
h3_co := false
h3_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h3_color))
h3_label.unshift(label.new(bar_index, open, h3_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h3 and h3_line.size() > 0
if not h3_co
if not check_open(h3_line.get(0), h3_label.get(0))
h3_label.get(0).set_x(bar_index)
else
h3_co := true
if use_h4
if t_h4 and not t_h4
h4_co := false
h4_line.unshift(line.new(bar_index, open, bar_index, open, style = h_style, width = h_width, color = h4_color))
h4_label.unshift(label.new(bar_index, open, h4_text, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if not t_h4 and h4_line.size() > 0
if not h4_co
if not check_open(h4_line.get(0), h4_label.get(0))
h4_label.get(0).set_x(bar_index)
else
h4_co := true
// DWM - Separators
if ds
if d_o != d_o
d_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = d_color))
if ws
if w_o != w_o
w_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = w_color))
if ms
if m_o != m_o
m_sep_line.unshift(line.new(bar_index, high, bar_index, low, style = dwm_style, width = dwm_width, extend = extend.both, color = m_color))
// DWM - Open Lines
if show_d_open
if d_o != d_o
d_line.unshift(line.new(bar_index, d_o, bar_index, d_o, style = dwm_style, width = dwm_width, color = d_color))
d_label.unshift(label.new(bar_index, d_o, d_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if d_line.size() > 0
if not check_open(d_line.get(0), d_label.get(0))
d_label.get(0).set_x(bar_index)
if show_w_open
if w_o != w_o
w_line.unshift(line.new(bar_index, w_o, bar_index, w_o, style = dwm_style, width = dwm_width, color = w_color))
w_label.unshift(label.new(bar_index, w_o, w_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if w_line.size() > 0
if not check_open(w_line.get(0), w_label.get(0))
w_label.get(0).set_x(bar_index)
if show_m_open
if m_o != m_o
m_line.unshift(line.new(bar_index, m_o, bar_index, m_o, style = dwm_style, width = dwm_width, color = m_color))
m_label.unshift(label.new(bar_index, m_o, m_open_str, style = label.style_label_left, color = transparent, textcolor = lb_color, size = lb_size))
else if m_line.size() > 0
if not check_open(m_line.get(0), m_label.get(0))
m_label.get(0).set_x(bar_index)
new_dow_time = dow_xloc == 'Midday' ? time - timeframe.in_seconds("D") / 2 * 1000 : time
new_day = dayofweek(new_dow_time, gmt_tz) != dayofweek(new_dow_time, gmt_tz)
dow_top = dow_yloc == 'Top'
monday = "MONDAY"
tuesday = "TUESDAY"
wednesday = "WEDNESDAY"
thursday = "THURSDAY"
friday = "FRIDAY"
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 2 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = monday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 3 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = tuesday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 4 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = wednesday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 5 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = thursday)
plotchar(dow_labels and timeframe.isintraday and dayofweek(new_dow_time, gmt_tz) == 6 and new_day, location = dow_top ? location.top : location.bottom, char = "", textcolor = dow_color, text = friday)
check_array(as_hi_line)
check_array(as_lo_line)
check_array(as_hi_label)
check_array(as_lo_label)
check_array(as_box)
check_array(lo_hi_line)
check_array(lo_lo_line)
check_array(lo_hi_label)
check_array(lo_lo_label)
check_array(lo_box)
check_array(na_hi_line)
check_array(na_lo_line)
check_array(na_hi_label)
check_array(na_lo_label)
check_array(na_box)
check_array(nl_hi_line)
check_array(nl_lo_line)
check_array(nl_hi_label)
check_array(nl_lo_label)
check_array(nl_box)
check_array(np_hi_line)
check_array(np_lo_line)
check_array(np_hi_label)
check_array(np_lo_label)
check_array(np_box)
check_array(v1_line)
check_array(v2_line)
check_array(v3_line)
check_array(v4_line)
check_array(h1_line)
check_array(h2_line)
check_array(h3_line)
check_array(h4_line)
check_array(h1_label)
check_array(h2_label)
check_array(h3_label)
check_array(h4_label)
if not ds_unlimited
check_array(d_sep_line)
check_array(d_line)
check_array(d_label)
if not ws_unlimited
check_array(w_sep_line)
check_array(w_line)
check_array(w_label)
if not ms_unlimited
check_array(m_sep_line)
check_array(m_line)
check_array(m_label)
// ---------
ZScore Plot with Ranked TableVersion 0.1
ZScore Plot with Ranked Table — Overview
This indicator visualizes the rolling ZScores of up to 10 crypto assets, giving traders a normalized view of log return deviations over time. It's designed for volatility analysis, anomaly detection, and clustering of asset behavior.
🎯 Purpose
• Show how each asset's performance deviates from its historical mean
• Identify potential overbought/oversold conditions across assets
• Provide a ranked leaderboard to compare asset behavior instantly
⚙️ Inputs
• Lookback: Number of bars to calculate mean and standard deviation
• Asset 1–10: Choose up to 10 symbols (e.g. BTCUSDT, ETHUSDT)
📈 Outputs
• ZScore Lines: Each asset plotted on a normalized scale (mean = 0, SD = 1)
• End-of-Line Labels: Asset names displayed at latest bar
• Leaderboard Table: Ranked list (top-right) showing:
◦ Asset name (color-matched)
◦ Final ZScore (rounded to 3 decimals)
🧠 Use Cases
• Quantitative traders seeking cross-asset momentum snapshots
• Signal engineers tracking volatility clusters
• Risk managers monitoring outliers and systemic shifts
거래량 지표 전략 (최종)"Leverage 100x, 10% of capital committed, 0.3% profit target, 0.2% stop loss."
레버리지 100배 이용, 10프로 자본금 투입, 0.3프로 수익 , 0.2프로 손해
"Volume Indicator Strategy (Final)" Summary
This Pine Script strategy is designed to integrate volume data from multiple cryptocurrency exchanges (Binance, Bitget, OKX, Bybit) across spot and futures markets. It then uses this consolidated volume data to identify volume spikes and apply an RSI filter to generate buy/sell signals.
Key Features and Logic:
Multi-Exchange/Asset Volume Consolidation:
Based on user settings, it fetches and sums up spot and perpetual futures volume data from Binance, Bitget, OKX, and Bybit.
It uses the request.security function to query volume data from each specified exchange.
NA (Not Available) data points are safely handled and treated as 0 to prevent calculation errors.
Volume Spike Detection:
It calculates the Simple Moving Average (avg_volume) of the combined_volume over a lookback period (default 70 bars).
A vol_7x condition is met when the combined_volume is equal to or greater than 7 times (vol_multiplier_7x, user-configurable) the avg_volume.
RSI Filter (Optional):
An RSI (Relative Strength Index) filter (enable_rsi_filter, user-configurable) can be applied in conjunction with the volume spike condition.
Short Entry Condition: vol_7x (volume spike) & price_up (current bar's close is higher than the previous close) & RSI is 73 or greater (if filter is enabled).
Long Entry Condition: vol_7x (volume spike) & price_down (current bar's close is lower than the previous close) & RSI is 28 or less (if filter is enabled).
Strategy Entry/Exit:
When entry conditions are met, the strategy enters a position at market price.
It includes a re-entry cooldown period (default 10 bars) to prevent immediate re-entry in the same direction.
Fixed Take Profit and Stop Loss percentages (0.3% Take Profit, 0.2% Stop Loss) are set to manage open positions.
Visualization:
The combined_volume is plotted as columns (plot.style_columns) in a lower pane, changing color when the 7x volume spike condition is met.
The avg_volume is plotted as a line.
Volume values on the plot (and intended for the Y-axis scale) are formatted using format=format.volume to display in K (thousands), M (millions), B (billions) units.
The chart background color changes to indicate RSI overbought (>= 70, red) and oversold (<= 30, blue) zones.
Labels are displayed on the chart for individual trade P/L (Profit/Loss), and an info panel shows the total P/L over a user-defined period.
This strategy aims to capture significant market movements by aggregating volume data across various sources and combining it with price action and momentum (RSI) analysis to generate automated trading signals.
-------------------------------------------------------------------------------------------------------------
"거래량 지표 전략 (최종)" 요약
이 전략은 여러 암호화폐 거래소(바이낸스, 비트겟, OKX, 바이비트)의 현물(Spot) 및 선물(Futures) 거래량 데이터를 통합하여 사용하는 것을 핵심으로 합니다. 통합된 거래량 데이터를 바탕으로 거래량 급등을 포착하고 RSI 필터를 적용하여 매수/매도 신호를 생성하는 전략입니다.
주요 기능 및 로직:
다중 거래소/자산 거래량 통합:
사용자 설정에 따라 바이낸스, 비트겟, OKX, 바이비트의 현물 및 선물(무기한) 거래량을 개별적으로 가져와 합산합니다.
request.security 함수를 사용하여 각 거래소의 거래량 데이터를 요청합니다.
데이터가 없는 경우(NA)는 0으로 처리하여 계산 오류를 방지합니다.
거래량 급등 감지:
통합된 거래량(combined_volume)의 lookback 기간(기본 70봉) 이동평균(avg_volume)을 계산합니다.
combined_volume이 avg_volume의 7배(vol_multiplier_7x, 사용자 설정 가능) 이상으로 급등하면 vol_7x 조건을 만족합니다.
RSI 필터 (옵션):
거래량 급등 조건과 함께 RSI(상대 강도 지수) 필터(enable_rsi_filter, 사용자 설정 가능)를 적용할 수 있습니다.
매도(Short) 진입 조건: vol_7x (거래량 급등) & price_up (현재 봉 종가가 이전 봉보다 상승) & RSI가 73 이상일 때.
매수(Long) 진입 조건: vol_7x (거래량 급등) & price_down (현재 봉 종가가 이전 봉보다 하락) & RSI가 28 이하일 때.
전략 진입/청산:
위 진입 조건이 충족되면 시장가로 포지션에 진입합니다.
동일 방향으로 10봉 이내 재진입을 제한합니다.
고정 익절(Take Profit) 및 손절(Stop Loss) 비율(각각 0.3%, 0.2%)을 설정하여 포지션을 관리합니다.
시각화:
통합 거래량(combined_volume)은 차트 하단에 막대그래프(plot.style_columns)로 표시되며, 7배 급등 시 색상이 변경됩니다.
평균 거래량(avg_volume)은 선으로 표시됩니다.
거래량 값은 format=format.volume을 사용하여 K(천), M(백만), B(십억) 단위로 간소화되어 표시됩니다.
차트 배경색으로 RSI 과매수(70 이상, 빨간색) 및 과매도(30 이하, 파란색) 구간을 시각적으로 표시합니다.
개별 거래의 P/L(손익) 라벨과 지정된 기간 동안의 총 P/L을 차트 상단에 표시합니다.
이 전략은 여러 거래소의 거래량 데이터를 취합하여 시장의 전반적인 거래 활동을 파악하고, 이를 바탕으로 특정 패턴(거래량 급등 + 가격 방향 + RSI 필터)에 따라 매매 결정을 내리도록 설계되었습니다.
Aggregated VolumeHow to Read the “Aggregated Volume” Signal
This indicator combines normalized volume, short-term volume bursts, pivot levels, VWAP, and a 200-period EMA to give you a multi-dimensional view of trading activity. Here’s how to interpret each component and synthesize them into actionable insights.
1. Custom Volume Signal (vSignal)
• Calculation
• vSignal = Sum of over bars, divided by the current price.
• A rising vSignal means more volume is being traded per unit of price, signaling growing interest relative to price level.
• Plot styling
• Bars are lime when (bullish volume days)
• Bars are orange when (bearish volume days)
How to read it
• Trend confirmation: Increasing lime bars alongside rising price suggests buyers in control.
• Warning sign: Rising orange bars on a down move indicate accelerating selling pressure.
• Divergence:
• Price making new highs while vSignal stalls or drops → potential top.
• Price making new lows while vSignal holds → potential bottom.
2. Short-Term Volume Bursts
Three semi-transparent histograms show how much the last 2, 5, and 10-bar raw volumes exceed (or fall below) the current vSignal:
• Blue = vol(2) – vSignal
• Green = vol(5) – vSignal
• Red = vol(10) – vSignal
If a colored bar sits above zero, that lookback’s volume is surging relative to the longer-term average (vSignal).
How to read it
• Clustered bursts:
• Blue + Green + Red above zero → strong, broad-based volume surge.
• Great for confirming breakouts and shakeouts.
• Isolated burst:
• Only Blue (> 0) on a small range bar → might be a false breakout or intrabar squeeze.
• Only Red (> 0) on a wide range → institutional involvement; act with caution.
3. Pivot Volume Levels (v & t)
• Every 21 bars, the script finds the highest and lowest vSignal values and plots them as shaded price levels:
• Magenta area = recent vSignal high (resistance)
• Cyan area = recent vSignal low (support)
How to read it
• Rejection/Break:
• Price approaches magenta zone and stalls → sellers defending that volume high.
• Break above magenta with high vSignal → likely sustained rally.
• Support flip:
• Cyan zone hold → buyers stepping in at heavy-volume lows.
• Break below cyan with rising vSignal → bearish conviction.
4. Midline Cross (Volume Equilibrium)
• A 10-bar SMA of
• Drawn as a faint white cross on price
How to read it
• Above midline → overall volume bias is skewed bullish.
• Below midline → bearish volume bias.
Crossovers of vSignal through this midline can signal shifts in underlying conviction.
5. VWAP & 200-Period EMA Overlays
• VWAP (transparent red if above price, green if below)
• EMA(200) plotted as aqua circles
How to read them
• VWAP tells you the intraday “value area.”
• Price above VWAP + rising vSignal = intraday buyers in charge.
• Price below VWAP + rising vSignal = aggressive sellers.
• EMA(200) gives you the longer-term trend.
• Above EMA200 = bullish regime
• Below EMA200 = bearish regime
6. Putting It All Together: Example Scenarios
1. Bullish Entry
• Price > EMA200 & VWAP is green
• vSignal rising in lime
• All three short-term bursts above zero
• Price near or breaking the magenta pivot with volume confirmation
2. Bearish Entry
• Price < EMA200 & VWAP is red
• vSignal rising in orange
• Two-bar burst (blue) spikes on a down bar
• Price failing at magenta pivot or breaking cyan support
3. Divergence Play
• Price makes new high, but vSignal peaks lower than last high → look for a reversal.
• Price drops to new low, but vSignal stays above its last low → prepare for a bounce.
By combining these layers—normalized volume, burst indicators, pivot levels, VWAP, and EMA—you get a clear map of where volume is clustering, which lets you anticipate support/resistance, gauge real interest, and spot potential reversals or breakouts with greater confidence.
Multi SMA AnalyzerMulti SMA Analyzer with Custom SMA Table & Advanced Session Logic
A feature-rich SMA analysis suite for traders, offering up to 7 configurable SMAs, in-depth trend detection, real-time table, and true session-aware calculations.
Ideal for those who want to combine intraday, swing, and higher-timeframe trend analysis with maximum chart flexibility.
Key Features
📊 Multi-SMA Overlay
- 7 SMAs (default: 5, 20, 50, 100, 200, 21, 34)—individually configurable (period, source, color, line style)
- Show/hide each SMA, custom line style (solid, stepline, circles), and color logic
- Dynamic color: full opacity above SMA, reduced when below
⏰ Session-Aware SMAs
- Each SMA can be calculated using only user-defined session hours/days/timezone
- “Ignore extended hours” option for accurate intraday trend
📋 Smart Data Table
- Live SMA values, % distance from price, and directional arrows (↑/↓/→)
- Bull/Bear/Sideways trend classification
- Custom table position, size, colors, transparency
- Table can run on chart or custom (higher) timeframe for multi-TF analysis
🎯 Golden/Death Cross Detection
- Flexible crossover engine: select any two from (5, 10, 20, 50, 100, 200) for fast/slow SMA cross signals
- Plots icons (★ Golden, 💀 Death), optional crossover labels with custom size/colors
🏷️ SMA Labels
- Optional on-chart SMA period labels
- Custom placement (above/below/on line), size, color, offset
🚨 Signal & Trend Engine
- Bull/Bear/Sideways logic: price vs. multiple SMAs (not just one pair)
- Volume spike detection (2x 20-period SMA)
- Bullish engulfing candlestick detection
- All signals can use chart or custom table timeframe
🎨 Visual Customization
- Dynamic background color (Bull: green, Bear: red, Neutral: gray)
- Every visual aspect is customizable: label/table colors, transparency, size, position
🔔 Built-in Alerts
- Crossovers (SMA20/50, Golden/Death)
- Bull trend, volume spikes, engulfing pattern—all alert-ready
How It Works
- Session Filtering:
- SMAs can be set to count only bars from your chosen market session, for true intraday/trading-hour signals
Dynamic Table & Signals:
- Table and all signal logic run on your selected chart or custom timeframe
Flexible Crossover:
- Choose any pair (5, 10, 20, 50, 100, 200) for cross detection—SMA 10 is available for crossover even if not shown as an SMA line
Everything is modular:
- Toggle features, set visuals, and alerts to your workflow
🚨 How to Use Alerts
- All key signals (crossovers, trend shifts, volume spikes, engulfing patterns) are available as alert conditions.
To enable:
- Click the “Alerts” (clock) icon at the top of TradingView.
- Select your desired signal (e.g., “Golden Cross”) from the condition dropdown.
- Set your alert preferences and create the alert.
- Now, you’ll get notified automatically whenever a signal occurs!
Perfect For
- Multi-timeframe and swing traders seeking higher timeframe SMA confirmation
- Intraday traders who want to ignore pre/post-market data
- Anyone wanting a modern, powerful, fully customizable multi-SMA overlay
// P.S: Experiment with Golden Cross where Fast SMA is 5 and Slow SMA is 20.
// Set custom timeframe for 4 hr while monitoring your chart on 15 min time frame.
// Enable Background Color and Use Table Timeframe for Background.
// Uncheck Pine labels in Style tab.
Clean, open-source, and loaded with pro features—enjoy!
Like, share, and let me know if you'd like any new features added.
NQ Position Size CalculatorNQ Position Size Line Calculator is designed specifically for Nasdaq 100 futures (NQ) and micro futures (MNQ) traders who want to maintain disciplined risk management. This visual tool eliminates the guesswork from position sizing by displaying distance lines and contract calculations directly on your chart.
The indicator creates horizontal lines at 10-tick intervals from your stop loss level, showing you exactly how many contracts to trade at each distance to maintain your predetermined risk amount. Whether you're trading regular NQ contracts or micro MNQ contracts, this calculator ensures you never risk more than intended while providing instant visual feedback for optimal position sizing decisions.
How to Use the Indicator
Step 1: Configure Your Settings
Stop Loss Price: Enter your exact stop loss level (e.g., 20000.00)
Risk Amount ($): Set your maximum dollar risk per trade (e.g., $500)
Contract Type: Choose between:
NQ (Regular): $5 per tick - for larger accounts
MNQ (Micro): $0.50 per tick - for smaller accounts or conservative sizing
Display Options:
Max Lines: Number of distance lines to show (default: 30)
Show Labels: Toggle tick distance and contract count labels
Line Color: Customize the color of distance lines
Label Size: Choose tiny, small, or normal label sizes
Step 2: Read the Visual Display
Once configured, the indicator displays:
Stop Loss Line:
Thick yellow line marking your exact stop loss level
Yellow label showing the stop loss price
Distance Lines:
Dashed red lines at 10-tick intervals above and below your stop loss
Lines appear on both sides for long and short position planning
Labels (if enabled):
Green labels (right side): For long positions above your stop loss
Red labels (left side): For short positions below your stop loss
Format: "20T 5x" means 20 ticks distance, 5 contracts maximum
Step 3: Use the Information Tables
The indicator provides two helpful tables:
Position Size Table (top-right):
Shows common tick distances (10, 20, 40, 80, 160 ticks)
Displays risk per contract at each distance
Contract count for your specified risk amount
Total risk with rounded contract numbers
Settings Table (bottom-right):
Confirms your current risk amount
Shows selected contract type
Displays current settings for quick reference
Step 4: Apply to Your Trading
For Long Positions:
Look at the green labels on the right side of your chart
Find your desired entry level
Read the label to see: distance in ticks and maximum contracts
Example: "30T 8x" = 30 ticks from stop, buy 8 contracts maximum
For Short Positions:
Look at the red labels on the left side of your chart
Find your desired entry level
Read the label for tick distance and contract count
Example: "40T 6x" = 40 ticks from stop, sell 6 contracts maximum
Step 5: Trading Execution
Before Entering a Trade:
Identify your stop loss level and input it into the indicator
Choose your entry point by looking at the distance lines
Note the contract count from the corresponding label
Verify the risk amount matches your trading plan
Execute your trade with the calculated position size
Risk Management Features:
Contract rounding: All position sizes are rounded down (never up) to ensure you don't exceed your risk limit
Zero position filtering: Lines only show where position size is at least 1 contract
Dual-sided display: Plan both long and short opportunities simultaneously
Adiyogi Trend🟢🔴 “Adiyogi” Trend — Market Alignment Visualizer
“Adiyogi” Trend is a powerful, non-intrusive trend detection system built for traders who seek clarity, discipline, and alignment with true market flow. Inspired by the meditative stillness of Adiyogi and the need for mindful, high-probability decisions, this tool offers a clean and intuitive visual guide to trending environments — without cluttering the chart or pushing forced trades.
This is not a buy/sell signal generator. Instead, it is designed as a background confirmation engine that helps you stay on the right side of the market by identifying moments of true directional strength.
🧠 Core Logic
The “Adiyogi” Trend indicator highlights the background of your chart in green or red when multiple layers of strength and structure align — including momentum, market positioning, and relative force. Only when these internal components agree does the system activate a directional state.
It’s built on three foundational energies of trend confirmation:
Strength of movement
Structure in price action
Conviction in momentum
By combining these into one visual background, the indicator filters out indecision and helps you stay focused during real trend phases — whether you're day trading, swing trading, or holding longer-term positions.
📌 Core Concepts Behind the Tool
The indicator integrates three essential market filters—each confirming a different dimension of trend strength:
ADX (Average Directional Index) – Measures trend momentum.
You’ve chosen a very responsive setting (ADX Length = 2), which helps catch the earliest possible signs of momentum emergence.
The threshold is ADX ≥ 22, ensuring that weak or sideways markets are filtered out.
SuperTrend (10,1) – Captures short-term trend direction.
This setup follows price closely and reacts quickly to reversals, making it ideal for fast-moving assets or intraday strategies.
SuperTrend acts as the structural confirmation of directional bias.
RSI (Relative Strength Index) – Measures strength based on recent price closes.
You’ve configured RSI > 50 for bullish zones and < 50 for bearish—a neutral midpoint standard often used by professional traders.
This ensures that only trades in sync with momentum and recent strength are highlighted.
🌈 How It Visually Works
Background turns GREEN when:
ADX ≥ 22, indicating strong momentum
Price is above the 20 EMA and above SuperTrend (10,1)
RSI > 50, confirming recent strength
Background turns RED when:
ADX ≥ 22, indicating strong momentum
Price is below the 20 EMA and below SuperTrend (10,1)
RSI < 50, confirming recent weakness
The background remains neutral (transparent) when trend conditions are not clearly aligned—this is the tool's way of keeping you out of indecisive markets.
A label (BULL / BEAR) appears only when the bias flips from the previous one. This helps avoid repeated or redundant alerts, focusing your attention only when something changes.
📊 Practical Uses & Benefits
✅ Stay with the trend: Perfectly filters out choppy or sideways markets by only activating when conditions align across momentum, structure, and strength.
✅ Pre-trade confirmation: Use this tool to confirm trade setups from other indicators or price action patterns.
✅ Avoid noise: Prevent overtrading by focusing only on high-quality trend conditions.
✅ Visual clarity: Unlike arrows or plots that clutter the chart, this tool subtly highlights trend conditions in the background, preserving your price action view.
📍 Important Notes
This is not a buy/sell signal generator. It is a trend-confirmation system.
Use it in conjunction with your existing entry setups—such as breakouts, order blocks, retests, or candlestick patterns.
The tool helps you stay in sync with the dominant direction, especially when combining multiple timeframes.
Can be used on any market (stocks, forex, crypto, indices) and on any timeframe.
Frahm Factor Position Size CalculatorThe Frahm Factor Position Size Calculator is a powerful evolution of the original Frahm Factor script, leveraging its volatility analysis to dynamically adjust trading risk. This Pine Script for TradingView uses the Frahm Factor’s volatility score (1-10) to set risk percentages (1.75% to 5%) for both Margin-Based and Equity-Based position sizing. A compact table on the main chart displays Risk per Trade, Frahm Factor, and Average Candle Size, making it an essential tool for traders aligning risk with market conditions.
Calculates a volatility score (1-10) using true range percentile rank over a customizable look-back window (default 24 hours).
Dynamically sets risk percentage based on volatility:
Low volatility (score ≤ 3): 5% risk for bolder trades.
High volatility (score ≥ 8): 1.75% risk for caution.
Medium volatility (score 4-7): Smoothly interpolated (e.g., 4 → 4.3%, 5 → 3.6%).
Adjustable sensitivity via Frahm Scale Multiplier (default 9) for tailored volatility response.
Position Sizing:
Margin-Based: Risk as a percentage of total margin (e.g., $175 for 1.75% of $10,000 at high volatility).
Equity-Based: Risk as a percentage of (equity - minimum balance) (e.g., $175 for 1.75% of ($15,000 - $5,000)).
Compact 1-3 row table shows:
Risk per Trade with Frahm score (e.g., “$175.00 (Frahm: 8)”).
Frahm Factor (e.g., “Frahm Factor: 8”).
Average Candle Size (e.g., “Avg Candle: 50 t”).
Toggles to show/hide Frahm Factor and Average Candle Size rows, with no empty backgrounds.
Four sizes: XL (18x7, large text), L (13x6, normal), M (9x5, small, default), S (8x4, tiny).
Repositionable (9 positions, default: top-right).
Customizable cell color, text color, and transparency.
Set Frahm Factor:
Frahm Window (hrs): Pick how far back to measure volatility (e.g., 24 hours). Shorter for fast markets, longer for chill ones.
Frahm Scale Multiplier: Set sensitivity (1-10, default 9). Higher makes the score jumpier; lower smooths it out.
Set Margin-Based:
Total Margin: Enter your account balance (e.g., $10,000). Risk auto-adjusts via Frahm Factor.
Set Equity-Based:
Total Equity: Enter your total account balance (e.g., $15,000).
Minimum Balance: Set to the lowest your account can go before liquidation (e.g., $5,000). Risk is based on the difference, auto-adjusted by Frahm Factor.
Customize Display:
Calculation Method: Pick Margin-Based or Equity-Based.
Table Position: Choose where the table sits (e.g., top_right).
Table Size: Select XL, L, M, or S (default M, small text).
Table Cell Color: Set background color (default blue).
Table Text Color: Set text color (default white).
Table Cell Transparency: Adjust transparency (0 = solid, 100 = invisible, default 80).
Show Frahm Factor & Show Avg Candle Size: Check to show these rows, uncheck to hide (default on).