VPoC per barThis study prints the current bar VPoC as an horizontal line.
It's aimed originally at BTCUSDT pair and 15m timeframe.
HOW IT WORKS
Zoom In mode: This is the default mode.
The study zooms in into the latest 15 1-minute bar candles in order to calculate the 15 minute candle VPoC.
Zoom Out mode: The VPoC from the last n bars from the current timeframe that match desired timeframe is shown on each bar.
In either case you are recommended to click on the '...' button associated to this study
and select 'Visual Order. Bring to Front.' so that it's properly shown in your chart.
HOW IT WORKS - Zoom In mode
Make sure that '(VP) Zoom into the VP timeframe' setting is set to true.
Choose the zoomed in timeframe where to calculate VPoC from thanks to the '(VP) Zoomed timeframe {1 minute}' setting.
Change '(VP) Zoomed in timeframe bars per current timeframe bar {15}' to its appropiated value. You just need to divide the current timeframe minutes per the zoomed in timeframe minutes per bar. E.g. If you are in 60 minute timeframe and you want to zoom in into 5 minute timeframe: 60 / 5 = 12 . You will write 12 here.
HOW IT WORKS - Zoom Out mode
Make sure that '(VP) Zoom into the VP timeframe' setting is set to false.
If you are using the Zoom out mode you might want to set '(VP) Print VPoC price as discrete lines {True}' to false.
Either choose the zoommed out timeframe where to calculate VPoC from thanks to the '(VP) Zoomed timeframe {1 minute}' setting or turn on the '(VP) Use number of bars (not VP timeframe)' setting in order to use '(VP) Number of bars {100}' as a custom number of bars.
WARNING - Zoom In mode last bar
The way that PineScript handles security function in last bar might result on the last bar not being accurate enough.
SETTINGS
__ SETTINGS - Volume Profile
(VP) Zoomed timeframe {1 minute}: Timeframe in which to zoom in or zoom out to calculate an accurate VPoC for the current timeframe.
(VP) Zoomed in timeframe bars per current timeframe bar {15}: Check 'HOW IT WORKS - Zoom In mode' above. Note : It is only used in 'Zoom in' mode.
(VP) Number of bars {100}: If 'Use number of bars (not VP timeframe)' is turned on this setting is used to calculate session VPoC. Note : It is only used in 'Zoom out' mode.
(VP) Price levels {24}: Price levels for calculating VPoC.
__ SETTINGS - MAIN TURN ON/OFF OPTIONS
(VP) Print VPoC price {True}: Show VPoC price
(VP) Zoom into the VP timeframe: When set to true the VPoC is calculated by zooming into the lower timeframe. When set to false a higher timeframe (or number of bars) is used.
(VP) Realtime Zoom in (Beta): Enable real time zoom for the last bar. It's beta because it would only work with zoomed in timeframe under 60 minutes. And when ratio between zoomout and zoomin is less than 60. Note : It is only used in 'Zoom in' mode.
(VP) Use number of bars (not VP timeframe): Uses 'Number of bars {100}' setting instead of 'Volume Profile timeframe' setting for calculating session VPoC. Note : It is only used in 'Zoom out' mode.
(VP) Print VPoC price as discrete lines {True}: When set to true the VPoC is shown as an small line in the center of each bar. When set to the false the VPoC line is printed as a normal line.
__ SETTINGS - EXTRA
(VP) VPoC color: Change the VPoC color
(VP) VPoC line width {1}: Change VPoC line width (in pixels).
(VP) Use number of bars (not VP timeframe): Uses 'Number of bars {100}' setting instead of 'Volume Profile timeframe' setting for calculating session VPoC. Note : It is only used in 'Zoom out' mode.
(VP) Print VPoC price as discrete lines {True}: When set to true the VPoC is shown as an small line in the center of each bar. When set to the false the VPoC line is printed as a normal line.
CREDITS
I have reused and adapted some code from
"Poor man's volume profile" study
which it's from TradingView IldarAkhmetgaleev user.
在脚本中搜索"100年国际黄金价格"
[Strategy] Simple Golden CrossSimple Golden Cross Strategy.
Works best on a daily chart on "Blue Chip" cryptos such as BTC, ETH, and LTC.
Entry Signal:
-50 day moving average crosses over the 100 day moving average.
Exit Signal:
-50 day moving average crosses under the 100 day moving average.
-Daily candle closes under the 100 day moving average (support).
-100 day moving average crosses under the 200 day moving average.
STRATEGY TESTER ENGINE - ON CHART DISPLAY - PLUG & PLAYSo i had this idea while ago when @alexgrover published a script and dropped a nugget in between which replicates the result of strategy tester on chart as an indicator.
So it seemed fair to use one of his strategy to display the results.
This strategy tester can now be used in replay mode like an indicator and you can see what happen at a particular section of the chart which was is not possible in default strategy tester results of TV.
Please read how each result is calculated so you will know what you are using.
This engine shows most common results of strategy tester in a single screen, which are as follows:
1. Starting Capital
2. Current Profit Percentage
3. Max Profit Percentage
4. Gross Profit
5. Gross Loss
6. Total Closed Trades
7. Total Trades Won
8. Total Trades Lost
9. Percentage Profitable
10. Profit Factor
11. Current Drawdown
12. Max Drawdown
13. Liquidation
So elaborating on what is what:
1. Starting Capital - This stays 0, which signifies your starting balance as 0%. It is set to 0 so we can compare all other results without any change in variables. If set to 100, then all the results will be increased by 100. Some users might find it useful to set it to 100, then they can change code on line 41 from to and it should show starting balance as 100%.
2. Current Profit Percentage - This shows your current profit adjusted to current price of the candle, not like TV which shows after candle is close. There is a comment on the line 38 which can be removed and your can see unrealized profit as well in this section. Please note that this will affect Draw-down calculations later in this section.
3. Max Profit Percentage - This will show you your max profit achieved during your strategy run, which was not possible yet to see via strategy tester. So, now you can see how much profit was achieved by your strategy during the run and you can compare it with chart to see what happens during bull-run or bear-run, so you can further optimize your strategy to best suit your desired results.
4. Gross Profit - This is total percentage of profit your strategy achieved during entire run as if you never had any losses.
5. Gross Loss - This is total percentage of loss your strategy achieved during entire run as if you never had any profits.
6. Total Closed Trades - This is total number of trades that your strategy has executed so far.
7. Total Trades Won - This is the total number of trades that your strategy has executed that resulted in positive increase in equity.
8. Totals Trades Lost - This is the total number of trades that your strategy has executed that resulted in decrease in equity.
9. Percentage Profitable - This is the ratio between your current total winning trades divided by total closed trades, and finally multiplied by 100 to get percentage results.
10. Profit Factor - This is the ratio between Gross Profit and Gross Loss, so if profit factor is 2, then it indicates that you are set to gain 2 times per your risk per trade on average when total trades are executed.
11. Current Drawdown - This is important section and i want you to read this carefully. Here draw-down is calculated very differently than what TV shows. TV has access to candle data and calculates draw-down accordingly as per number of trades closed, but here DD is calculated as difference between max profit achieved and current profit. This way you can see how much percentage you are down from max peak of equity at current point in time. You can do back-test of the data and see when peak was achieved and how much your strategy did a draw-down candle by candle.
12. Max Drawdown - This is also calculated differently same as above, current draw-down. Here you can see how much max DD your strategy did from a peak profit of equity. This is not set as max profit percentage is set because you will see single number on display, while idea is to keep it custom. I will explain.
So lets say, your max DD on TV is 30%. Here this is of no use to see Max DD , as some people might want to see what was there max DD 1000 candles back or 10 candle back. So this will show you your max DD from the data you select. TV shows 25000 candle data in a chart if you go back, you can set the counter to 24999 and it will show you max DD as shown on TV, but if you want custom section to show max DD , it is now possible which was not possible before.
Also, now let's say you put DD as 24999 and open a chart of an asset that was listed 1 week ago, now on 1H chart max DD will never show up until you reach 24999 candle in data history, but with this you can now enter a manual number and see the data.
13. Liquidation - This is an interesting feature, so now when your equity balance is less than 0 and your draw-down goes to -100, it will show you where and at what point in time you got liquidated by adding a red background color in the entire section. This is the most fun part of this script, while you can only see max DD on TV.
------------------------------------------------------------------------------
How to Use -
1 word, plug and play. Yes. Actual codes start from line 33.
select overlay=false or remove it from the title in your strategy on first line,
Just copy the codes from line 33 to 103,
then go to end section of your strategy and paste the entire code from line 33 to line 103,
see if you have any duplicate variable, edit it,
Add to chart.
What you see above is very contracted view. Here is how it looks when zoomed in.
imgur.com
----------------------------------------------------------------------------------
Feel free to edit and share and use. If you use it in your scripts, drop me tag. Cheers.
EulerMethod: CryptoCapEN
Shows the cryptocurrency market capitalization balance for the period
Initial data
Bitcoin Capitalization - CRYPTOCAP: BTC
Altcoin Capitalization - CRYPTOCAP: TOTAL2
Money circulates from fiat to bitcoin, from bitcoin to altcoins, from altcoins to fiat
This indicator applies the RSI algorithm to changes in capitalization
The divergence of indices shows an imbalance
Balance level: 0, Maximum: +100, Minimum: -100
(!) Artifacts of indicator readings may occur due to incorrect input data
RU
Показывает баланс капитализации крипторынка за период
Исходные данные
Капитализация Биткоина — CRYPTOCAP:BTC
Капитализация Альткоинов — CRYPTOCAP:TOTAL2
Деньги циркулируют из фиата в биткоин, из биткоина в альткоины, из альткоинов в фиат
В этом индикаторе применяется алгоритм RSI к изменениям капитализации
Расхождения индексов показывают дисбаланс
Балансовый уровень: 0, Максимум: +100, Минимум: -100
(!) Могут возникать артефакты показаний индикатора из-за неправильных исходных данных
Correlation MatrixIn financial terms, 'correlation' is the numerical measure of the relationship between two variables (in this case, the variables are Forex pairs).
The range of the correlation coefficient is between -1 and +1. A correlation of +1 indicates that two currency pairs will flow in the same direction.
A correlation of -1 indicates that two currency pairs will move in the opposite direction.
Here, I multiplied correlation coefficient by 100 so that it is easier to read. Range between 100 and -100.
Color Coding:-
The darker the color, the higher the correlation positively or negatively.
Extra Light Blue (up to +29) : Weak correlation. Positions on these symbols will tend to move independently.
Light Blue (up to +49) : There may be similarity between positions on these symbols.
Medium Blue (up to +75) : Medium positive correlation.
Navy Blue (up to +100) : Strong positive correlation.
Extra Light Red (up to -30) : Weak correlation. Positions on these symbols will tend to move independently
Light Red (up to -49) : There may be similarity between positions on these symbols.
Dark Red: (up to -75) : Medium negative correlation.
Maroon: (up to -100) : Strong negative correlation.
BO - CCI Arrow with AlertBO - CCI Arrow with Alert base on CCI indicator to get signal for trade Binary Option.
Rules of BO - CCI Arrow with Alert below:
A. Setup Menu
1. cciLength:
* Default CCI lenght = 14
2. Linear Regression Length:
* Periods to calculate Linear Regression of CCI,
* Default value = 5
3. Extreme Level:
* Default top extreme level = 100
* Default bottom extreme level = -100
4. Filter Length:
* Periods to define highest or lowest Linear Regression
* Default value = 6
B. Rule Of Alert Bar
1. Put Alert Bar
* Current Linear Regression Line created temporrary peak
* Peak of Linear Regression Line greater than Top Extreme Level (100)
* Previous Linear Regression is highest of Filter Length (6)
* Previous Linear Regression is greater than previous peak of Linear Regression Line
* Current price greater than previous low
* CCI(14) less than Linear Regression Line
2. Call Alert Bar
* Current Linear Regression Line created temporrary bottom
* Bottom of Linear Regression Line less than Bottom Extreme Level (-100)
* Previous Linear Regression is lowest of Filter Length (6)
* Previous Linear Regression is less than previous bottom of Linear Regression Line
* Current price less than previous lhigh
* CCI(14) greater than Linear Regression Line
B. Rule Of Entry Bar and Epiry.
1. Put Entry with expiry 3 bars:
* After Put Alert Bar close with signal confirmed, put Arrow appear, and after 3 bars, result label will appear to show win trade, loss trade or draw trade
2. Call Entry with expiry 3 bars:
* After Call Alert Bar close with signal confirmed, call Arrow appear, and after 3 bars, result label will appear to show win trade, loss trade or draw trade.
3. While 1 trade is opening no more any signal
C. Popup Alert/Mobile Alert
1. Signal alert: Put Alert or Call Alert will send to mobile or show popup on chart
2. Put Alert: only Put Alert will send to mobile or show popup on chart
3. Call Alert: only Call Alert will send to mobile or show popup on chart
Point and Figure (PnF) CCIThis is live and non-repainting Point and Figure Chart Commodity Channel Index - CCI tool. The script has it’s own P&F engine and not using integrated function of Trading View.
Point and Figure method is over 150 years old. It consist of columns that represent filtered price movements. Time is not a factor on P&F chart but as you can see with this script P&F chart created on time chart.
P&F chart provide several advantages, some of them are filtering insignificant price movements and noise, focusing on important price movements and making support/resistance levels much easier to identify.
Commodity Channel Index – CCI was developed by Donalt Lambert. CCI can be used to identify overbought or oversold, a new trend or warn of extreme conditions. CCI measures the difference between a security's price change and its average price change. High positive readings indicate that prices are well above their average, which is a show of strength. Low negative readings indicate that prices are well below their average, which is a show of weakness.
The Formula for the Commodity Channel Index ( CCI ) Is:
CCI = (Typical Price – L-period SMA of TP) / (0.015 * Mean Deviation)
Mean Deviation = (SumOf 1->L ( |TP – MA| )) / L
L = Length
TP = Typical Price
If you are new to Point & Figure Chart then you better get some information about it before using this tool. There are very good web sites and books. Please PM me if you need help about resources.
Options in the Script
Box size is one of the most important part of Point and Figure Charting. Chart price movement sensitivity is determined by the Point and Figure scale. Large box sizes see little movement across a specific price region, small box sizes see greater price movement on P&F chart. There are four different box scaling with this tool: Traditional, Percentage, Dynamic (ATR), or User-Defined
4 different methods for Box size can be used in this tool.
User Defined: The box size is set by user. A larger box size will result in more filtered price movements and fewer reversals. A smaller box size will result in less filtered price movements and more reversals.
ATR: Box size is dynamically calculated by using ATR, default period is 20.
Percentage: uses box sizes that are a fixed percentage of the stock's price. If percentage is 1 and stock’s price is $100 then box size will be $1
Traditional: uses a predefined table of price ranges to determine what the box size should be.
Price Range Box Size
Under 0.25 0.0625
0.25 to 1.00 0.125
1.00 to 5.00 0.25
5.00 to 20.00 0.50
20.00 to 100 1.0
100 to 200 2.0
200 to 500 4.0
500 to 1000 5.0
1000 to 25000 50.0
25000 and up 500.0
Default value is “ATR”, you may use one of these scaling method that suits your trading strategy.
If ATR or Percentage is chosen then there is rounding algorithm according to mintick value of the security. For example if mintick value is 0.001 and box size (ATR/Percentage) is 0.00124 then box size becomes 0.001.
And also while using dynamic box size (ATR or Percentage), box size changes only when closing price changed.
Reversal : It is the number of boxes required to change from a column of Xs to a column of Os or from a column of Os to a column of Xs. Default value is 3 (most used). For example if you choose reversal = 2 then you get the chart similar to Renko chart.
Source: Closing price or High-Low prices can be chosen as data source for P&F charting.
Upper Band : as default, Upper band is 100
Lower Band : as default, Lower band is -100
There are alerts when P&F CCI moves above Upper Band or moves below Lower Band.
Double MA CCI"What is the Commodity Channel Index (CCI)?
Developed by Donald Lambert, the Commodity Channel Index (CCI) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold. It is also used to assess price trend direction and strength. This information allows traders to determine if they want to enter or exit a trade, refrain from taking a trade, or add to an existing position. In this way, the indicator can be used to provide trade signals when it acts in a certain way.
KEY TAKEAWAYS
• The CCI measures the difference between the current price and the historical average price.
• When the CCI is above zero it indicates the price is above the historic average. When CCI is below zero, the price is below the hsitoric average.
• High readings of 100 or above, for example, indicate the price is well above the historic average and the trend has been strong to the upside.
• Low readings below -100, for example, indicate the price is well below the historic average and the trend has been strong to the downside.
• Going from negative or near-zero readings to +100 can be used as a signal to watch for an emerging uptrend.
• Going from positive or near-zero readings to -100 may indicate an emerging downtrend.
• CCI is an unbounded indicator meaning it can go higher or lower indefinitely. For this reason, overbought and oversold levels are typically determined for each individual asset by looking at historical extreme CCI levels where the price reversed from." ----> 1
SOURCE
1: (SINCE IM NOT A "PRO" MEMBER I C'ANT POST THE SOUCRE URL..., webpage consulted at : 8:50 GMT -5 ; the 2020-01-18)
I- Added a 2nd MA length and changed the default values of the source type and switched the SMA to a MA.
II- In process to add analytic MACD histogram correlation and if possible, ploting a relative histogram between the CCI upper and lower band.
P.S.:
Don't set your moving averages lengths to far from each other... This could result in fewer convergence and divergence, also in fewer crossing MA's.
Have a good year 2020 !!
//----CODER----//
R.V.
Multi momentum indicatorScript contains couple momentum oscillators all in one pane
List of indicators:
RSI
Stochastic RSI
MACD
CCI
WaveTrend by LazyBear
MFI
Default active indicators are RSI and Stochastic RSI
Other indicators are disabled by default
RSI, StochRSI and MFI are modified to be bounded to range from 100 to -100. That's why overbought is 40 and 60 instead 70 and 80 while oversold -40 and -60 instead 30 and 20.
MACD and CCI as they are not bounded to 100 or 200 range, they are limited to 100 - -100 by default when activated (extras are simply hidden) but there is an option to show full indicator.
In settings there are couple more options like show crosses or show only histogram.
Default source for all indicators is close (except WaveTrend and MFI which use hlc3) and it could be changed but for all indicators.
There is an option for 2nd RSI which can be set for any timeframe and background calculated by Fibonacci levels.
Open Interest Rank-BuschiEnglish:
One part of the "Commitment of Traders-Report" is the Open Interest which is shown in this indicator (source: Quandl database).
Unlike my also published indicator "Open Interest-Buschi", the values here are not absolute but in a ranking system from 0 to 100 with individual time frames-
The following futures are included:
30-year Bonds (ZB)
10-year Notes ( ZN )
Soybeans (ZS)
Soybean Meal (ZM)
Soybean Oil (ZL)
Corn ( ZC )
Soft Red Winter Wheat (ZW)
Hard Red Winter Wheat (KE)
Lean Hogs (HE)
Live Cattle ( LE )
Gold ( GC )
Silver (SI)
Copper (HG)
Crude Oil ( CL )
Heating Oil (HO)
RBOB Gasoline ( RB )
Natural Gas ( NG )
Australian Dollar (A6)
British Pound (B6)
Canadian Dollar (D6)
Euro (E6)
Japanese Yen (J6)
Swiss Franc (S6)
Sugar ( SB )
Coffee (KC)
Cocoa ( CC )
Cotton ( CT )
S&P 500 E-Mini (ES)
Russell 2000 E-Mini (RTY)
Dow Jones Industrial Mini (YM)
Nasdaq 100 E-Mini (NQ)
Platin (PL)
Palladium (PA)
Aluminium (AUP)
Steel ( HRC )
Ethanol (AEZ)
Brent Crude Oil (J26)
Rice (ZR)
Oat (ZO)
Milk (DL)
Orange Juice (JO)
Lumber (LS)
Feeder Cattle (GF)
S&P 500 ( SP )
Dow Jones Industrial Average Index (DJIA)
New Zealand Dollar (N6)
Deutsch:
Ein Bestandteil des "Commitment of Traders-Report" ist das Open Interest, das in diesem Indikator dargestellt wird (Quelle: Quandl Datenbank).
Anders als in meinem ebenfalls veröffentlichten Indikator "Open Interest-Buschi" werden hier nicht die absoluten Werte dargestellt, sondern in einem Ranking-System von 0 bis 100 mit individuellen Zeitrahmen.
Folgende Futures sind enthalten:
30-jährige US-Staatsanleihen (ZB)
10-jährige US-Staatsanleihen ( ZN )
Sojabohnen(ZS)
Sojabohnen-Mehl (ZM)
Sojabohnen-Öl (ZL)
Mais( ZC )
Soft Red Winter-Weizen (ZW)
Hard Red Winter-Weizen (KE)
Magerschweine (HE)
Lebendrinder ( LE )
Gold ( GC )
Silber (SI)
Kupfer(HG)
Rohöl ( CL )
Heizöl (HO)
Benzin ( RB )
Erdgas ( NG )
Australischer Dollar (A6)
Britisches Pfund (B6)
Kanadischer Dollar (D6)
Euro (E6)
Japanischer Yen (J6)
Schweizer Franken (S6)
Zucker ( SB )
Kaffee (KC)
Kakao ( CC )
Baumwolle ( CT )
S&P 500 E-Mini (ES)
Russell 2000 E-Mini (RTY)
Dow Jones Industrial Mini (YM)
Nasdaq 100 E-Mini (NQ)
Platin (PL)
Palladium (PA)
Aluminium (AUP)
Stahl ( HRC )
Ethanol (AEZ)
Brent Rohöl (J26)
Reis (ZR)
Hafer (ZO)
Milch (DL)
Orangensaft (JO)
Holz (LS)
Mastrinder (GF)
S&P 500 ( SP )
Dow Jones Industrial Average Index (DJIA)
Neuseeland Dollar (N6)
Well Rounded Moving AverageIntroduction
There are tons of filters, way to many, and some of them are redundant in the sense they produce the same results as others. The task to find an optimal filter is still a big challenge among technical analysis and engineering, a good filter is the Kalman filter who is one of the more precise filters out there. The optimal filter theorem state that : The optimal estimator has the form of a linear observer , this in short mean that an optimal filter must use measurements of the inputs and outputs, and this is what does the Kalman filter. I have tried myself to Kalman filters with more or less success as well as understanding optimality by studying Linear–quadratic–Gaussian control, i failed to get a complete understanding of those subjects but today i present a moving average filter (WRMA) constructed with all the knowledge i have in control theory and who aim to provide a very well response to market price, this mean low lag for fast decision timing and low overshoots for better precision.
Construction
An good filter must use information about its output, this is what exponential smoothing is about, simple exponential smoothing (EMA) is close to a simple moving average and can be defined as :
output = output(1) + α(input - output(1))
where α (alpha) is a smoothing constant, typically equal to 2/(Period+1) for the EMA.
This approach can be further developed by introducing more smoothing constants and output control (See double/triple exponential smoothing - alpha-beta filter) .
The moving average i propose will use only one smoothing constant, and is described as follow :
a = nz(a ) + alpha*nz(A )
b = nz(b ) + alpha*nz(B )
y = ema(a + b,p1)
A = src - y
B = src - ema(y,p2)
The filter is divided into two components a and b (more terms can add more control/effects if chosen well) , a adjust itself to the output error and is responsive while b is independent of the output and is mainly smoother, adding those components together create an output y , A is the output error and B is the error of an exponential moving average.
Comparison
There are a lot of low-lag filters out there, but the overshoots they induce in order to reduce lag is not a great effect. The first comparison is with a least square moving average, a moving average who fit a line in a price window of period length .
Lsma in blue and WRMA in red with both length = 100 . The lsma is a bit smoother but induce terrible overshoots
ZLMA in blue and WRMA in red with both length = 100 . The lag difference between each moving average is really low while VWRMA is way more precise.
Hull MA in blue and WRMA in red with both length = 100 . The Hull MA have similar overshoots than the LSMA.
Reduced overshoots moving average (ROMA) in blue and WRMA in red with both length = 100 . ROMA is an indicator i have made to reduce the overshoots of a LSMA, but at the end WRMA still reduce way more the overshoots while being smoother and having similar lag.
I have added a smoother version, just activate the extra smooth option in the indicator settings window. Here the result with length = 200 :
This result is a little bit similar to a 2 order Butterworth filter. Our filter have more overshoots which in this case could be useful to reduce the error with edges since other low pass filters tend to smooth their amplitude thus reducing edge estimation precision.
Conclusions
I have presented a well rounded filter in term of smoothness/stability and reactivity. Try to add more terms to have different results, you could maybe end up with interesting results, if its the case share them with the community :)
As for control theory i have seen neural networks integrated to Kalman flters which leaded to great accuracy, AI is everywhere and promise to be a game a changer in real time data smoothing. So i asked myself if it was possible for a neural networks to develop pinescript indicators, if yes then i could be replaced by AI ? Brrr how frightening.
Thanks for reading :)
Quadruple Kaufman Adaptive Moving AverageFour Kaufman Adaptive Moving Averages in one script. Useful for identifying trends and setting points to add to positions / exit trades. KAMA's are great for keeping you in trending markets and avoiding sideways chops and ranges. Try them out by tweaking the fast/slow ma's and lengths to get the right set for your charts that removes the thinking about whether to be long or short and when to add to positions.
A suggested trading strategy is to tweak the ma's (often you'll want larger values) until they span the price action well on past trends. Then each time price action closes and crosses one of your KAMA lines is an opportunity to add to your position. Once all lines are cleared and you've loaded up your position, hopefully your average price of entry falls short of the highest KAMA line's value. Once this happens you don't need to get out the trade until such time as a price close crosses again that largest KAMA line. For eager profit takers, close positions once any KAMA line is crossed once you're successfully loaded up on a direction.
I use this script with a renko chart and values -> 26 length 6 fast ma 100 slow ma, 26 8 100, 26 10 100, 26 12 100 and it's good to see these moving averages, unlike regular moving averages, bend around choppy action that come when trends pause, keeping me successfully in winning trades. Give it a try.
cci based potential buy/sell signal
Commodity Channel Index Potential Buy Signal
Commodity Channel Index (CCI) is below oversold line (-200).
CCI then crosses above -100 line
Commodity Channel Index Potential Sell Signal
Commodity Channel Index (CCI) is above overbought line (+200).
CCI then crosses below +100 line.
Türkçe Açıklama;
CCI Potansiyel Al Sinyali
CCI indikatörünün -200 altında bulunduğu bölgeler aşırı satış bölgeleri,
Sonrasında aşağıdan gelerek -100 çizgisinin üzerine çıktığı yada çıkmak üzere olduğu noktalar al sinyali
CCI Potansiyel Satl Sinyali
CCI indikatörünün +200 üzerinde bulunduğu bölgeler aşırı alım bölgeleri,
Sonrasında yukarıdan inerek +100 çizgisinin altına indiği yada inmek üzere olduğu noktalar sat sinyali
Not: Tek başına kullanılması son derece hatalı sonuçlar verebilir. Sadece olabilirlik potansiyeli taşımaktadır.
Aroon Single Line This indicator converts double lined Aroon indicator into a single line oscillator.
It is simply obtained by subtracting Aroon down from Aroon Up.
*If Oscillator points 100 value, it means there is a Strong Uptrend.
*If Oscillator points values between 100 and 40, it means there is an uptrend.
*If Oscillator points values between 20 and -20, it means no trend, it is sideways.But, when it is sideways; generally, oscillator makes FLAT LINES
between 20 and -20 values. 0 value is pointed out when the trend is downward as well, which means aroon up=aroon down.
*If Oscillator points values between -40 and -100, it means there is a downtrend.
*If Oscillator points -100 value, it means there is a Strong downtrend.
(20, 40) and (-20, -40) intervals are not mentioned, because; generally these are transition values and hard to comment, it will be more certain to
wait till values are between or at the reference values given.
CCI 0Trend Strategy (by Marcoweb) v1.0Hi guys,
I am trying to create a strategy that consists in the crossover/under of the 0 line of the Commodity Channel Index . Every time the price crosses over the 0 line in the CCI the strategy has to long getting short on the cross under and viceversa.
I have published here another script strategy (consists in a crossover/under of the Overbought/Oversold levels of the CCI) that works so I could have the opportunity to share with you the main idea that as per now is mistaken:
//@version=2
strategy(title="CCI 0Trend Strategy (by Marcoweb) v1.0", shorttitle="CCI_0T_Stra_v1.0", overlay=true)
///////////// CCI
length = input(20, minval=1)
src = input(close, title="Source")
ma = sma(src, length)
cci = (src - ma) / (0.015 * dev(src, length))
plot(cci, color=black)
band1 = hline(100, color=blue, linestyle=solid)
band0 = hline(-100, color=red, linestyle=solid)
bandl = hline(0, color=orange, linestyle=solid)
fill(band1, band0, color=olive)
p1 = plot(band0, color=red,title="-100")
p2 = plot(band1, color=blue,title="100")
p3 = plot(bandl, color=orange,title="0")
///////////// CCI 0Trend Strategy (by Marcoweb) v1.0 Strategy
if (not na(cci))
if (crossover(cci, bandl)
strategy.entry("CCI_L", strategy.long, stop=bandl, oca_type=strategy.oca.cancel, comment="CCI_L")
else
strategy.cancel(id="CCI_L")
if (crossunder(cci, bandl)
strategy.entry("CCI_S", strategy.short, stop=bandl, oca_type=strategy.oca.cancel, comment="CCI_S")
else
strategy.cancel(id="CCI_S")
//plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
With this coding I get the error : line 24 (if (crossover(cci, bandl): mismatched input '|E|' expecting RPAR
Hope you like the idea ;)
How to automate this strategy for free using a chrome extension.Hey everyone,
Recently we developed a chrome extension for automating TradingView strategies using the alerts they provide. Initially we were charging a monthly fee for the extension, but we have now decided to make it FREE for everyone. So to display the power of automating strategies via TradingView, we figured we would also provide a profitable strategy along with the custom alert script and commands for the alerts so you can easily cut and paste to begin trading for profit while you sleep.
Step 1:
You are going to need to download the Chrome Extension called AutoView. You can get the extension for free by following this link: bit.ly ( I had to shorten the link as it contains Google and TV automatically converts it to a symbol)
Step 2: Go to your chrome extension page, and under the new extension you'll see a "settings" button. In the setting you will have to connect and give permission to the exchange 1broker allowing the extension to place your orders automatically when triggered by an alert.
Step 3: Setup the strategy and custom script for the alerts in TradingView. The attached script is the strategy, you can play with the settings yourself to try and get better numbers/performance if you please.
This following script is for the custom alerts:
//@version=2
study("4All-Alert", shorttitle="Alerts")
src = close
len = input(4, minval=1, title="Length")
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsin = input(5)
sn = 100 - rsin
ln = 0 + rsin
short = crossover(rsi, sn) ? 1 : 0
long = crossunder(rsi, ln) ? 1 : 0
plot(long, "Long", color=green)
plot(short, "Short", color=red)
Now that you have the extension installed, the custom strategy and alert scripts in place, you simply need to create the alerts.
To get the alerts to communicate with the extension properly, there is a specific syntax that you will need to put in the message of the alert. You can find more details about the syntax here : gist.github.com
For this specific strategy, I use the Alerts script, long/short greater than 0.9 on close.
In the message for a long place this as your message:
Long
c=order b=short
c=position b=short l=200 t=market
b=long q=0.01 l=200 t=market tp=13 sl=25
and for the short...
Short
c=order b=long
c=position b=long l=200 t=market
b=short q=0.01 l=200 t=market tp=13 sl=25
If you'll notice in my above messages, compared to the strategy my tp and sl (take profit and stop loss) vary by a few pips. This is to cover the market opens and spread on 1broker. You can change the tp and sl in the strategy to the above and see that the overall profit will not vary much at all.
I hope this all makes sense and it is enough to not only make some people money, but to show the power of coming up with your own strategy and automating it using TradingView alerts and the free Chrome Extension AutoView.
ps. I highly recommend upgrading your TradingView account so you have access to back testing and multiple alerts.
There is really no reason you won't cover the cost and then some on a monthly basis using the tools provided.
Best of luck and happy trading.
Note: The extension currently allows for automation on 2 exchanges; 1broker and Okcoin. If you do not have accounts there, we'd appreciate you signing up using our referral links.
www.okcoin.com
1broker.com
Indicator: Trend Trigger FactorIntroduced by M.H.Pee, Trend Trigger Factor is designed to keep the trader trading with the trend.
System rules according to the developer:
* If the 15-day TTF is above 100 (indicating an uptrend), you will want to be in long positions.
* If the 15-day TTF is below -100, you will want to be short.
* If it is between -100 and 100, you should remain with the current position.
More info:
Original Article by Mr.Pee: drive.google.com
내 스크립트//@version=5
indicator('RSI+BB+이격도', overlay=false)
// 매개변수 초기화
src = input(title='Source', defval=close) // 계산에 대한 가격 유형 설정
for_rsi = input(title='RSI_period', defval=14) // RSI 기간
for_ma = input(title='Basis_BB', defval=20) // BB 내 MA 기간
for_mult = input.float(title='Stdev', defval=2, minval=1, maxval=5) // BB의 표준 편차 수
for_sigma = input.float(title='Dispersion', defval=0.1, minval=0.01, maxval=1) // MA 주변 이격도
// 스크립트의 작업 조건
current_rsi = ta.rsi(src, for_rsi) // RSI 표시기의 현재 위치
basis = ta.ema(current_rsi, for_ma)
dev = for_mult * ta.stdev(current_rsi, for_ma)
upper = basis + dev
lower = basis - dev
disp_up = basis + (upper - lower) * for_sigma // RSI가 통과해야 하는 이동 영역의 최소 허용 임계값(상단)
disp_down = basis - (upper - lower) * for_sigma // RSI가 극복해야 하는 이동 영역의 최소 허용 임계값(하단)
color_rsi = current_rsi >= disp_up ? color.rgb(0, 255, 132) : current_rsi <= disp_down ? color.rgb(255, 0, 0) : #ffea00 // BB 내 위치에 따른 RSI의 현재 색상
short_l1 = input(5, title='Short - L1')
short_l2 = input(20, title='Short - L2')
short_l3 = input(15, title='Short - L3')
long_l1 = input(20, title='Long - L1')
long_l2 = input(15, title='Long - L2')
shortTermXtrender = ta.rsi(ta.ema(close, short_l1) - ta.ema(close, short_l2), short_l3) - 50
longTermXtrender = ta.rsi(ta.ema(close, long_l1), long_l2) - 50
shortXtrenderCol = shortTermXtrender > 0 ? shortTermXtrender > shortTermXtrender ? color.lime : #228B22 : shortTermXtrender > shortTermXtrender ? color.red : #8B0000
t3(src, len) =>
xe1_1 = ta.ema(src, len)
xe2_1 = ta.ema(xe1_1, len)
xe3_1 = ta.ema(xe2_1, len)
xe4_1 = ta.ema(xe3_1, len)
xe5_1 = ta.ema(xe4_1, len)
xe6_1 = ta.ema(xe5_1, len)
b_1 = 0.7
c1_1 = -b_1 * b_1 * b_1
c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
nT3Average_1 = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
nT3Average_1
maShortTermXtrender = t3(shortTermXtrender, 5)
colShortTermXtrender = maShortTermXtrender > maShortTermXtrender ? color.lime : color.red
plotshape(maShortTermXtrender > maShortTermXtrender and maShortTermXtrender < maShortTermXtrender ? maShortTermXtrender : na, location=location.bottom, style=shape.circle, color=color.new(color.lime, 10), size=size.tiny)
plotshape(maShortTermXtrender < maShortTermXtrender and maShortTermXtrender > maShortTermXtrender ? maShortTermXtrender : na, location=location.top, style=shape.circle, color=color.new(color.red, 10), size=size.tiny)
longXtrenderCol = longTermXtrender > 0 ? longTermXtrender > longTermXtrender ? color.lime : #228B22 : longTermXtrender > longTermXtrender ? color.red : #8B0000
macollongXtrenderCol = longTermXtrender > longTermXtrender ? color.lime : color.red
// 단기 추세 이동 평균을 기반으로 한 롱 및 숏 신호에 대한 경고 조건
alertcondition(maShortTermXtrender > maShortTermXtrender and maShortTermXtrender < maShortTermXtrender , title='매수추세감지', message='잠재적 매수 포지션 이격도 보고 진입.')
alertcondition(maShortTermXtrender < maShortTermXtrender and maShortTermXtrender > maShortTermXtrender , title='매도추세감지', message='잠재적 매도 포지션 이격도 보고 진입.')
left = input.int(5, "left")
right = input.int(5, "right")
// 1. 지표
osc = ta.rsi(close, 14)
plot(osc, linewidth = 2)
// 2. 피봇 찾기 (상승div-피봇로우, 하락div-피봇하이)
pivotlow = ta.pivotlow(osc, left, right)
pivothigh = ta.pivothigh(osc, left, right)
is_pivotlow = not na(pivotlow)
is_pivothigh = not na(pivothigh)
// 3. 다이버전스 찾기
// 상승 다이버전스
prev_pivotlow = ta.valuewhen(is_pivotlow, pivotlow, 1)
osc_higher_low = is_pivotlow ? pivotlow > prev_pivotlow : false
prev_low = ta.valuewhen(is_pivotlow, low , 1)
price_lower_low = is_pivotlow ? low < prev_low : false
is_regular_bullish_divergence = osc_higher_low and price_lower_low
plotshape(is_regular_bullish_divergence ? is_pivotlow : na, offset = -right, title="상승 다이버전스", text = "Bull", style = shape.labelup, color = color.green, textcolor = color.white, location = location.bottom)
plot(is_pivotlow ? pivotlow : na, color = is_regular_bullish_divergence ? color.green : na, offset = -right, linewidth = 2)
// 히든 상승다이버전스
osc_lower_low = is_pivotlow ? pivotlow < prev_pivotlow : false
price_higher_low = is_pivotlow ? low > prev_low : false
is_hidden_bullish_divergence = osc_lower_low and price_higher_low
plotshape(is_hidden_bullish_divergence ? is_pivotlow : na, offset = -right, title="히든 상승 다이버전스", text = "H Bull", style = shape.labelup, color = color.green, textcolor = color.white, location = location.bottom)
plot(is_pivotlow ? pivotlow : na, color = is_hidden_bullish_divergence ? color.green : na, offset = -right, linewidth = 2)
// 하락다이버전스
prev_pivothigh = ta.valuewhen(is_pivothigh, pivothigh, 1)
osc_lower_high = is_pivothigh ? pivothigh < prev_pivothigh : false
prev_high = ta.valuewhen(is_pivothigh, high , 1)
price_higher_high = is_pivothigh ? high > prev_high : false
is_regular_bearish_divergence = osc_lower_high and price_higher_high
plotshape(is_regular_bearish_divergence ? is_pivothigh : na, offset = -right, title="하락 다이버전스", text = "Bear", style = shape.labeldown, color = color.red, textcolor = color.white, location = location.top)
plot(is_pivothigh ? pivothigh : na, color = is_regular_bearish_divergence ? color.red : na, offset = -right, linewidth = 2)
// 히든 하락 다이버전스
osc_higher_high = is_pivothigh ? pivothigh > prev_pivothigh : false
price_lower_high = is_pivothigh ? high < prev_high : false
is_hidden_bearish_divergence = osc_higher_high and price_lower_high
plotshape(is_hidden_bearish_divergence ? is_pivothigh : na, offset = -right, title="히든 하락 다이버전스", text = "H Bear", style = shape.labeldown, color = color.red, textcolor = color.white, location = location.top)
plot(is_pivothigh ? pivothigh : na, color = is_hidden_bearish_divergence ? color.red : na, offset = -right, linewidth = 2)
// RSI 영역에 대한 추가 줄 및 채우기
h1 = hline(70, color=#d4d4d4, linestyle=hline.style_dotted, linewidth=1)
h2 = hline(50, color=#d4d4d4, linestyle=hline.style_dotted, linewidth=1)
h3 = hline(30, color=#d4d4d4, linestyle=hline.style_dotted, linewidth=1)
rsiPlot = plot(ta.rsi(close,14), "RSI", color=na, editable = false, display = display.none)
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(#ff0000, 0), bottom_color = color.new(#ff0000, 100), title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(#48ff00, 100), bottom_color = color.new(#66ff00, 0), title = "Oversold Gradient Fill")
// 사용자 입력값
lengthBB1 = input.int(20, title='BB1', minval=1)
lengthBB2 = input.int(4, title='BB2', minval=1)
multBB1 = input.float(2, title='BB1', minval=0.1)
multBB2 = input.float(4, title='BB2', minval=0.1)
lengthMA = input.int(20, title='MA Length', minval=1)
// 볼린저 밴드 계산
basisBB1 = ta.sma(close, lengthBB1)
upperBB1 = basisBB1 + multBB1 * ta.stdev(close, lengthBB1)
lowerBB1 = basisBB1 - multBB1 * ta.stdev(close, lengthBB1)
basisBB2 = ta.sma(open, lengthBB2)
upperBB2 = basisBB2 + multBB2 * ta.stdev(open, lengthBB2)
lowerBB2 = basisBB2 - multBB2 * ta.stdev(open, lengthBB2)
// 이동평균선 추가
maClose = ta.sma(close, lengthMA)
// 표시할 조건 정의
showAboveTriangle = high >= upperBB1 and high >= upperBB2
showBelowTriangle = low <= lowerBB1 and low <= lowerBB2
showAboveTriangle1 = high >= upperBB2
showBelowTriangle1 = low <= lowerBB2
// 상단에 역삼각형 표시 (빨간색)
plotshape(series=showAboveTriangle, title='더블비 매도', color=color.rgb(255, 0, 0), style=shape.triangledown, text='DS', textcolor= color.white,size=size.small, location=location.top)
// 하단에 삼각형 표시 (초록색)
plotshape(series=showBelowTriangle, title='더블비 매수', color=color.rgb(4, 253, 12), style=shape.triangleup, text='DB', textcolor= color.white,size=size.small, location=location.bottom)
// 알림 및 트리거 조건
rsi_Green = ta.crossover(current_rsi, disp_up)
rsi_Red = ta.crossunder(current_rsi, disp_down)
alertcondition(condition=rsi_Green, title='이격도 밴드 매수', message='이격도 밴드 매수')
alertcondition(condition=rsi_Red, title='이격도 밴드 매도', message='이격도 밴드 매도')
rsi_Red1 = ta.crossover(current_rsi, lower)
rs9_Green1 = ta.crossunder(current_rsi, upper)
// 매수 매도 표시기
plotshape(rsi_Red1,color=color.green, style=shape.cross, location=location.bottom, size=size.small, title='(매수) signal')
plotshape(rs9_Green1,color= color.red, style=shape.cross, location=location.top, size=size.small, title='(매도) signal')
// 삼각형 표시된 위치에 알람 설정
alertcondition(showAboveTriangle, title='더블비 매도감지', message='더블비 매도감지')
alertcondition(showBelowTriangle, title='더블비 매수감지', message='더블비 매수감지')
// 결과 및 색상 지정
plot(basis, color=color.new(#080808, 0))
plot(upper, color=color.new(#00fff0, 0), linewidth=2)
plot(lower, color=color.new(#00fff0, 0), linewidth=2)
s1 = plot(disp_up, color=color.new(color.white, 0))
s2 = plot(disp_down, color=color.new(color.white, 0))
fill(s1, s2, color=color.new(color.white, 80))
plot(current_rsi, color=color_rsi, linewidth=2)
Squeeze Weekday Frequency [CHE] Squeeze Weekday Frequency — Tracks historical frequency of low-volatility squeezes by weekday to inform timing of low-risk setups.
Summary
This indicator monitors periods of unusually low volatility, defined as when the average true range falls below a percentile threshold, and tallies their occurrences across each weekday. By aggregating these counts over the chart's history, it reveals patterns in squeeze frequency, helping traders avoid or target specific days for reduced noise. The approach uses persistent counters to ensure accurate daily tallies without duplicates, providing a robust view of weekday biases in volatility regimes.
Motivation: Why this design?
Traders often face inconsistent signal quality due to varying volatility patterns tied to the trading calendar, such as quieter mid-week sessions or busier Mondays. This indicator addresses that by binning low-volatility events into weekday buckets, allowing users to spot recurring low-activity days where trends may develop with less whipsaw. It focuses on historical aggregation rather than real-time alerts, emphasizing pattern recognition over prediction.
What’s different vs. standard approaches?
- Reference baseline: Traditional volatility trackers like simple moving averages of range or standalone Bollinger Band squeezes, which ignore temporal distribution.
- Architecture differences:
- Employs array-based persistent counters for each weekday to accumulate events without recounting.
- Includes duplicate prevention via day-key tracking to handle sparse data.
- Features on-demand sorting and conditional display modes for focused insights.
- Practical effect: Charts show a persistent table of ranked weekdays instead of transient plots, making it easier to glance at biases like higher squeezes on Fridays, which reduces the need for manual logging and highlights calendar-driven edges.
How it works (technical)
The indicator first computes the average true range over a specified lookback period to gauge recent volatility. It then ranks this value against its own history within a sliding window to identify squeezes when the rank drops below the threshold. Each bar's timestamp is resolved to a weekday using the selected timezone, and a unique day identifier is generated from the date components.
On detecting a squeeze and valid price data, it checks against a stored last-marked day for that weekday to avoid multiple counts per day. If it's a new occurrence, the corresponding weekday counter in an array increments. Total days and data-valid days are tracked separately for context.
At the chart's last bar, it sums all counters to compute shares, sorts weekdays by their squeeze proportions, and populates a table with the selected subset. The table alternates row colors and highlights the peak weekday. An info label above the final bar summarizes totals and the top day. Background shading applies a faint red to squeeze bars for visual confirmation. State persists via variable arrays initialized once, ensuring counts build incrementally without resets.
Parameter Guide
ATR Length — Sets the lookback for measuring average true range, influencing squeeze sensitivity to short-term swings. Default: 14. Trade-offs/Tips: Shorter values increase responsiveness but raise false positives in chop; longer smooths for stability, potentially missing early squeezes.
Percentile Window (bars) — Defines the history length for ranking the current ATR, balancing recent relevance with sample size. Default: 252. Trade-offs/Tips: Narrower windows adapt faster to regime shifts but amplify noise; wider ones stabilize ranks yet lag in fast markets—aim for 100-500 bars on daily charts.
Squeeze threshold (PR < x) — Determines the cutoff for low-volatility classification; lower values flag rarer, tighter squeezes. Default: 10.0. Trade-offs/Tips: Tighter thresholds (under 5) yield fewer but higher-quality signals, reducing clutter; looser (over 20) captures more events at the cost of relevance.
Timezone — Selects the reference for weekday assignment; exchange default aligns with asset's session. Default: Exchange. Trade-offs/Tips: Use custom for cross-market analysis, but verify alignment to avoid offset errors in global pairs.
Show — Toggles the results table visibility for quick on/off of the display. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to save screen space; re-enable for periodic reviews.
Pos — Positions the table on the chart pane for optimal viewing. Default: Top Right. Trade-offs/Tips: Bottom options suit long-term charts; test placements to avoid overlapping price action.
Font — Adjusts text size in the table for readability at different zooms. Default: normal. Trade-offs/Tips: Smaller fonts fit more data but strain eyes on small screens; larger for presentations.
Dark — Applies a dark color scheme to the table for contrast against chart backgrounds. Default: true. Trade-offs/Tips: Toggle false for light themes; ensures legibility without manual recoloring.
Display — Filters table rows to show all, top three, or bottom three weekdays by squeeze share. Default: All. Trade-offs/Tips: Use "Top 3" for focus on high-frequency days in active trading; "All" for full audits.
Reading & Interpretation
Red-tinted backgrounds mark individual squeeze bars, indicating current low-volatility conditions. The table's summary row shows the highest squeeze count, its percentage of total events, and the associated weekday in teal. Detail rows list selected weekdays with their absolute counts, proportional shares, and a left arrow for the peak day—higher percentages signal days where squeezes cluster, suggesting potential for calmer trend development. The info label reports overall days observed, valid data days, and reiterates the top weekday with its count. Drifting counts toward zero on a weekday imply rarity, while elevated ones point to habitual low-activity sessions.
Practical Workflows & Combinations
- Trend following: Scan for squeezes on high-frequency weekdays as entry filters, confirming with higher highs or lower lows in the structure; pair with momentum oscillators to time breaks.
- Exits/Stops: On low-squeeze days, widen stops for breathing room, tightening them during peak squeeze periods to guard against false breaks—use the table's percentages as a regime proxy.
- Multi-asset/Multi-TF: Defaults work across forex and indices on hourly or daily frames; for stocks, adjust percentile window to 100 for shorter histories. Scale thresholds up by 5-10 points for high-vol assets like crypto to maintain signal sparsity.
Behavior, Constraints & Performance
- Repaint/confirmation: Counts update only on confirmed bars via day-key changes, with no future references—live bars may shade red tentatively but tallies finalize at session close.
- security()/HTF: Not used, so no higher-timeframe repaint risks; all computations stay in the chart's resolution.
- Resources: Relies on a fixed-size array of seven elements and small loops for sorting and table fills, capped at 5000 bars back—efficient for most charts but may slow on very long intraday histories.
- Known limits: Ignores weekends and holidays implicitly via data presence; early chart bars lack full percentile context, leading to initial undercounting; assumes continuous sessions, so gaps in data (e.g., news halts) skew totals.
Sensible Defaults & Quick Tuning
Start with the built-in values for broad-market daily charts: ATR at 14, window at 252, threshold at 10. For noisier environments, lower the threshold to 5 and shorten the window to 100 to prioritize rare squeezes. If too few events appear, raise the threshold to 15 and extend ATR to 20 for broader capture. To combat overcounting in sparse data, widen the window to 500 while keeping others stock—monitor the info label's data-days count before trusting patterns.
What this indicator is—and isn’t
This serves as a statistical overlay for spotting calendar-based volatility biases, aiding in session selection and filter design. It is not a standalone signal generator, predictive model, or risk manager—integrate it with price action, volume, and broader strategy rules for decisions.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Squeeze Hour Frequency [CHE]Squeeze Hour Frequency (ATR-PR) — Standalone — Tracks daily squeeze occurrences by hour to reveal time-based volatility patterns
Summary
This indicator identifies periods of unusually low volatility, defined as squeezes, and tallies their frequency across each hour of the day over historical trading sessions. By aggregating counts into a sortable table, it helps users spot hours prone to these conditions, enabling better scheduling of trading activity to avoid or target specific intraday regimes. Signals gain robustness through percentile-based detection that adapts to recent volatility history, differing from fixed-threshold methods by focusing on relative lowness rather than absolute levels, which reduces false positives in varying market environments.
Motivation: Why this design?
Traders often face uneven intraday volatility, with certain hours showing clustered low-activity phases that precede or follow breakouts, leading to mistimed entries or overlooked calm periods. The core idea of hourly squeeze frequency addresses this by binning low-volatility events into 24 hourly slots and counting distinct daily occurrences, providing a historical profile of when squeezes cluster. This reveals time-of-day biases without relying on real-time alerts, allowing proactive adjustments to session focus.
What’s different vs. standard approaches?
- Reference baseline: Classical volatility tools like simple moving average crossovers or fixed ATR thresholds, which flag squeezes uniformly across the day.
- Architecture differences:
- Uses persistent arrays to track one squeeze per hour per day, preventing overcounting within sessions.
- Employs custom sorting on ratio arrays for dynamic table display, prioritizing top or bottom performers.
- Handles timezones explicitly to ensure consistent binning across global assets.
- Practical effect: Charts show a persistent table ranking hours by squeeze share, making intraday patterns immediately visible—such as a top hour capturing over 20 percent of total events—unlike static overlays that ignore temporal distribution, which matters for avoiding low-liquidity traps in crypto or forex.
How it works (technical)
The indicator first computes a rolling volatility measure over a specified lookback period. It then derives a relative ranking of the current value against recent history within a window of bars. A squeeze is flagged when this ranking falls below a user-defined cutoff, indicating the value is among the lowest in the recent sample.
On each bar, the local hour is extracted using the selected timezone. If a squeeze occurs and the bar has price data, the count for that hour increments only if no prior mark exists for the current day, using a persistent array to store the last marked day per hour. This ensures one tally per unique trading day per slot.
At the final bar, arrays compile counts and ratios for all 24 hours, where the ratio represents each hour's share of total squeezes observed. These are sorted ascending or descending based on display mode, and the top or bottom subset populates the table. Background shading highlights live squeezes in red for visual confirmation. Initialization uses zero-filled arrays for counts and negative seeds for day tracking, with state persisting across bars via variable declarations.
No higher timeframe data is pulled, so there is no repaint risk from external fetches; all logic runs on confirmed bars.
Parameter Guide
ATR Length — Controls the lookback for the volatility measure, influencing sensitivity to short-term fluctuations; shorter values increase responsiveness but add noise, longer ones smooth for stability — Default: 14 — Trade-offs/Tips: Use 10-20 for intraday charts to balance quick detection with fewer false squeezes; test on historical data to avoid over-smoothing in trending markets.
Percentile Window (bars) — Sets the history depth for ranking the current volatility value, affecting how "low" is defined relative to past; wider windows emphasize long-term norms — Default: 252 — Trade-offs/Tips: 100-300 bars suit daily cycles; narrower for fast assets like crypto to catch recent regimes, but risks instability in sparse data.
Squeeze threshold (PR < x) — Defines the cutoff for flagging low relative volatility, where values below this mark a squeeze; lower thresholds tighten detection for rarer events — Default: 10.0 — Trade-offs/Tips: 5-15 percent for conservative signals reducing false positives; raise to 20 for more frequent highlights in high-vol environments, monitoring for increased noise.
Timezone — Specifies the reference for hourly binning, ensuring alignment with market sessions — Default: Exchange — Trade-offs/Tips: Set to "America/New_York" for US assets; mismatches can skew counts, so verify against chart timezone.
Show Table — Toggles the results display, essential for reviewing frequencies — Default: true — Trade-offs/Tips: Disable on mobile for performance; pair with position tweaks for clean overlays.
Pos — Places the table on the chart pane — Default: Top Right — Trade-offs/Tips: Bottom Left avoids candle occlusion on volatile charts.
Font — Adjusts text readability in the table — Default: normal — Trade-offs/Tips: Tiny for dense views, large for emphasis on key hours.
Dark — Applies high-contrast colors for visibility — Default: true — Trade-offs/Tips: Toggle false in light themes to prevent washout.
Display — Filters table rows to focus on extremes or full list — Default: All — Trade-offs/Tips: Top 3 for quick scans of risky hours; Bottom 3 highlights safe low-squeeze periods.
Reading & Interpretation
Red background shading appears on bars meeting the squeeze condition, signaling current low relative volatility. The table lists hours as "H0" to "H23", with columns for daily squeeze counts, percentage share of total squeezes (summing to 100 percent across hours), and an arrow marker on the top hour. A summary row above details the peak count, its share, and the leading hour. A label at the last bar recaps total days observed, data-valid days, and top hour stats. Rising shares indicate clustering, suggesting regime persistence in that slot.
Practical Workflows & Combinations
- Trend following: Scan for hours with low squeeze shares to enter during stable regimes; confirm with higher highs or lower lows on the 15-minute chart, avoiding top-share hours post-news like tariff announcements.
- Exits/Stops: Tighten stops in high-share hours to guard against sudden vol spikes; use the table to shift to conservative sizing outside peak squeeze times.
- Multi-asset/Multi-TF: Defaults work across crypto pairs on 5-60 minute timeframes; for stocks, widen percentile window to 500 bars. Combine with volume oscillators—enter only if squeeze count is below average for the asset.
Behavior, Constraints & Performance
Logic executes on closed bars, with live bars updating counts provisionally but finalizing on confirmation; table refreshes only at the last bar, avoiding intrabar flicker. No security calls or higher timeframes, so no repaint from external data. Resources include a 5000-bar history limit, loops up to 24 iterations for sorting and totals, and arrays sized to 24 elements; labels and table are capped at 500 each for efficiency. Known limits: Skips hours without bars (e.g., weekends), assumes uniform data availability, and may undercount in sparse sessions; timezone shifts can alter profiles without warning.
Sensible Defaults & Quick Tuning
Start with ATR Length at 14, Percentile Window at 252, and threshold at 10.0 for broad crypto use. If too many squeezes flag (noisy table), raise threshold to 15.0 and narrow window to 100 for stricter relative lowness. For sluggish detection in calm markets, drop ATR Length to 10 and threshold to 5.0 to capture subtler dips. In high-vol assets, widen window to 500 and threshold to 20.0 for stability.
What this indicator is—and isn’t
This is a historical frequency tracker and visualization layer for intraday volatility patterns, best as a filter in multi-tool setups. It is not a standalone signal generator, predictive model, or risk manager—pair it with price action, news filters, and position sizing rules.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Thanks to Duyck
for the ma sorter
💰 Akıllı Para Akışı v4 (Güç Skorlu - Temiz)🎨 Nasıl Görünür:
Arka plan sade, alan yumuşak geçişli.
Güçlü sinyaller sadece “ışıklı nokta” olarak belirir.
Sağ alt köşede canlı “Para Akışı Gücü” barı.
Skor: 0–30 kırmızı (zayıf), 30–70 turuncu (nötr), 70–100 yeşil (güçlü).
💰 Smart Money Flow v5 – Concept & Logic
Overview:
The Smart Money Flow v5 indicator combines price action, volume behavior, and momentum strength to detect true money inflows and outflows in the market.
It is designed to help traders identify when institutional (smart) money is entering or leaving an asset, while filtering out noise from normal retail fluctuations.
🔹 Core Logic
Money Flow Calculation:
The core formula is based on the Money Flow Multiplier:
𝑀
𝐹
=
(
𝐶
𝑙
𝑜
𝑠
𝑒
−
𝐿
𝑜
𝑤
)
−
(
𝐻
𝑖
𝑔
ℎ
−
𝐶
𝑙
𝑜
𝑠
𝑒
)
𝐻
𝑖
𝑔
ℎ
−
𝐿
𝑜
𝑤
×
𝑉
𝑜
𝑙
𝑢
𝑚
𝑒
MF=
High−Low
(Close−Low)−(High−Close)
×Volume
This measures how strong the buying or selling pressure is within each bar.
The result is then smoothed with a simple moving average (SMA) to track consistent trends.
RSI & Momentum Filter:
To validate the money flow signals, the indicator combines RSI (Relative Strength Index) and short-term price change (%).
RSI > 50 and price ↑ → confirms positive momentum.
RSI < 50 and price ↓ → confirms negative momentum.
Smart Money Zones:
When both volume and money flow increase in the same direction, it signals a potential Smart Money accumulation or distribution zone:
🟩 Green background → institutional accumulation (buy pressure).
🟥 Red background → institutional distribution (sell pressure).
Flow Trend Line (EMA):
An EMA line of the money flow is plotted to visualize trend direction and strength over time.
This helps identify when money flow momentum is shifting.
Fund Flow Histogram:
Volume-based histogram bars display the actual strength of buying and selling flows.
This gives an immediate visual cue for periods of heavy inflow or outflow.
Strength Score (0–100):
The indicator calculates a “Money Flow Strength Score” based on the relative magnitude of money flow, RSI, and price change:
70–100 → strong inflow (bullish pressure)
30–70 → neutral zone
0–30 → strong outflow (bearish pressure)
Smart Buy/Sell Signals:
🟢 Strong Buy (GÜÇLÜ AL): money inflow + positive RSI + price rising >2%
🔴 Strong Sell (GÜÇLÜ SAT): money outflow + negative RSI + price falling >2%
⚙️ Alerts
Real-time alerts can be configured for:
🚀 Strong Money Inflow (Smart Buy)
⚠️ Strong Money Outflow (Smart Sell)
This allows traders to automate notifications or integrate the signals into Telegram/Discord bots.
🎯 Why It Works
Unlike standard volume indicators, Smart Money Flow v5 focuses on the relationship between price position within the candle and traded volume, giving a more accurate representation of whether large players are entering or exiting positions.
It’s not just about volume — it’s about who controls the price action behind that volume.
Aladin Pair Trading System v1Aladin Pair Trading System v1
What is This Indicator?
The Aladin Pair Trading System is a sophisticated tool designed to help traders identify profitable opportunities by comparing two related stocks that historically move together. Think of it as finding when one twin is running ahead or lagging behind the other - these moments often present trading opportunities as they tend to return to moving together.
Who Should Use This?
Beginners: Learn about statistical arbitrage and pair trading
Intermediate Traders: Execute mean-reversion strategies with confidence
Advanced Traders: Fine-tune parameters for optimal pair relationships
Portfolio Managers: Implement market-neutral strategies
💡 What is Pair Trading?
Imagine two ice cream shops next to each other. They usually have similar customer traffic because they're in the same area. If one day Shop A is packed while Shop B is empty, you might expect this imbalance to correct itself soon.
Pair trading works the same way:
You find two stocks that normally move together (like TCS and Infosys)
When one stock moves too far from the other, you trade expecting them to realign
You buy the lagging stock and sell the leading stock
When they come back together, you profit from both sides
Key Features
1. Z-Score Analysis
What it is: A statistical measure showing how far the price relationship has deviated from normal
What it means:
Z-Score near 0 = Normal relationship
Z-Score at +2 = Stock A is expensive relative to Stock B (Sell A, Buy B)
Z-Score at -2 = Stock A is cheap relative to Stock B (Buy A, Sell B)
2. Multiple Timeframe Analysis
Long-term Z-Score (300 bars): Shows the big picture trend
Short-term Z-Score (100 bars): Shows recent movements
Signal Z-Score (20 bars): Generates quick trading signals
3. Statistical Validation
The indicator checks if the pair is suitable for trading:
Correlation (must be > 0.7): Confirms the stocks move together
1.0 = Perfect positive correlation
0.7 = Strong correlation
Below 0.7 = Warning: pair may not be reliable
ADF P-Value (should be < 0.05): Tests if the relationship is stable
Low value = Good for pair trading
High value = Relationship may be random
Cointegration: Confirms long-term equilibrium relationship
YES = Pair tends to revert to mean
NO = Pair may drift apart permanently
Visual Elements Explained
Chart Zones (Color-Coded Areas)
Yellow Zone (-1.5 to +1.5)
Normal Zone: Relationship is stable
Action: Wait for better opportunities
Blue Zone (±1.5 to ±2.0)
Entry Zone: Deviation is significant
Action: Prepare for potential trades
Green/Red Zone (±2.0 to ±3.0)
Opportunity Zone: Strong deviation
Action: High-probability trade setups
Beyond ±3.0
Risk Limit: Extreme deviation
Action: Either maximum opportunity or structural break
Signal Arrows
Green Arrow Up (Buy A + Sell B):
Stock A is undervalued relative to B
Buy Stock A, Short Stock B
Red Arrow Down (Sell A + Buy B):
Stock A is overvalued relative to B
Sell Stock A, Buy Stock B
Settings Guide
Symbol Inputs
Pair Symbol (Symbol B): Choose the second stock to compare
Default: NSE:INFY (Infosys)
Example pairs: TCS/INFY, HDFCBANK/ICICIBANK, RELIANCE/ONGC
Z-Score Parameters
Long Z-Score Period (300): Historical context
Short Z-Score Period (100): Recent trend
Signal Period (20): Trading signals
Z-Score Threshold (2.0): Entry trigger level
Higher = Fewer but stronger signals
Lower = More frequent signals
Statistical Parameters
Correlation Period (240): How many bars to check correlation
Hurst Exponent Period (50): Measures mean-reversion tendency
Probability Lookback (100): Historical probability calculations
Trading Parameters
Entry Threshold (0.0): Minimum Z-score for entry
Risk Threshold (1.5): Warning level
Risk Limit (3.0): Maximum deviation to trade
How to Use (Step-by-Step)
Step 1: Choose Your Pair
Add the indicator to your chart (this becomes Stock A)
In settings, select Stock B (the comparison stock)
Choose stocks from the same sector for best results
Step 2: Verify Pair Quality
Check the Statistics Table (top-right corner):
✅ Correlation > 0.70 (Green = Good)
✅ ADF P-value < 0.05 (Green = Good)
✅ Cointegrated = YES (Green = Good)
If all three are green, the pair is suitable for trading!
Step 3: Wait for Signals
BUY SIGNAL (Green Arrow Up)
Z-Score crosses above -2.0
Action: Buy Stock A, Sell Stock B
Exit: When Z-Score returns to 0
SELL SIGNAL (Red Arrow Down)
Z-Score crosses below +2.0
Action: Sell Stock A, Buy Stock B
Exit: When Z-Score returns to 0
Step 4: Risk Management
Yellow Zone: Monitor only
Blue Zone: Prepare for entry
Green/Red Zone: Active trading zone
Beyond ±3.0: Maximum risk - use caution
⚠️ Important Warnings
Not All Pairs Work: Always check the statistics table first
Market Conditions Matter: Correlation can break during market stress
Use Stop Losses: Set stops at Z-Score ±3.5 or beyond
Position Sizing: Trade both legs with appropriate hedge ratios
Transaction Costs: Factor in brokerage and slippage for both stocks
Example Trade
Scenario: TCS vs INFOSYS
Correlation: 0.85 ✅
Z-Score: -2.3 (TCS is cheap vs INFY)
Action to be taken:
Buy 1lot of TCS Future
Sell 1lot of INFOSYS Future
Expected Outcome:
As Z-Score moves toward 0, TCS outperforms INFOSYS
Close both positions when Z-Score crosses 0
Profit from the convergence
Best Practices
Test Before Trading: Use paper trading first
Sector Focus: Choose pairs from the same industry
Monitor Statistics: Check correlation daily
Avoid News Events: Don't trade pairs during earnings/major news
Size Appropriately: Start small, scale with experience
Be Patient: Wait for high-quality setups (±2.0 or beyond)
What Makes This Indicator Unique?
Multi-timeframe Z-Score analysis: Three different perspectives
Statistical validation: Built-in correlation and cointegration tests
Visual risk zones: Easy-to-understand color-coded areas
Real-time statistics: Live pair quality monitoring
Beginner-friendly: Clear signals with educational zones
Technical Background
The indicator uses:
Engle-Granger Cointegration Test: Validates pair relationship
ADF (Augmented Dickey-Fuller) Test: Tests stationarity
Pearson Correlation: Measures linear relationship
Z-Score Normalization: Standardizes deviations
Log Returns: Handles price differences properly
Support & Community
For questions, suggestions, or to share your pair trading experiences:
Comment below the indicator
Share your successful pair combinations
Report any issues for quick fixes
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Pair trading involves risk, including the risk of loss.
Always:
Do your own research
Understand the risks
Trade with money you can afford to lose
Consider consulting a financial advisor
📌 Quick Reference Card
Z-ScoreInterpretationAction-3.0 to -2.0A very cheap vs BStrong Buy A, Sell B-2.0 to -1.5A cheap vs BBuy A, Sell B-1.5 to +1.5Normal rangeHold/Wait+1.5 to +2.0A expensive vs BSell A, Buy B+2.0 to +3.0A very expensive vs BStrong Sell A, Buy B
Good Pair Statistics:
Correlation: > 0.70
ADF P-value: < 0.05
Cointegration: YES
Version: 1.0
Last Updated: 10th October 2025
Compatible: TradingView Pine Script v6
Happy Trading!