Multi SMA EMA WMA HMA BB (5x8 MAs Bollinger Bands) MAX MTF - RRBMulti SMA EMA WMA HMA 4x7 Moving Averages with Bollinger Bands MAX MTF by RagingRocketBull 2019
Version 1.0
All available MAX MTF versions are listed below (They are very similar and I don't want to publish them as separate indicators):
ver 1.0: 4x7 = 28 MTF MAs + 28 Levels + 3 BB = 59 < 64
ver 2.0: 5x6 = 30 MTF MAs + 30 Levels + 3 BB = 63 < 64
ver 3.0: 3x10 = 30 MTF MAs + 30 Levels + 3 BB = 63 < 64
ver 4.0: 5(4+1)x8 = 8 CurTF MAs + 32 MTF MAs + 20 Levels + 3 BB = 63 < 64
ver 5.0: 6(5+1)x6 = 6 CurTF MAs + 30 MTF MAs + 24 Levels + 3 BB = 63 < 64
ver 6.0: 4(3+1)x10 = 10 CurTF MAs + 30 MTF MAs + 20 Levels + 3 BB = 63 < 64
Fib numbers: 8, 13, 21, 34, 55, 89, 144, 233, 377
This indicator shows multiple MAs of any type SMA EMA WMA HMA etc with BB and MTF support, can show MAs as dynamically moving levels.
There are 4 MA groups + 1 BB group, a total of 4 TFs * 7 MAs = 28 MAs. You can assign any type/timeframe combo to a group, for example: 
 - EMAs 9,12,26,50,100,200,400 x H1, H4, D1, W1 (4 TFs x 7 MAs x 1 type)
 - EMAs 8,13,21,30,34,50,55,89,100,144,200,233,377,400 x M15, H1 (2 TFs x 14 MAs x 1 type)
 - D1 EMAs and SMAs 8,13,21,30,34,50,55,89,100,144,200,233,377,400 (1 TF x 14 MAs x 2 types)
 - H1 WMAs 13,21,34,55,89,144,233; H4 HMAs 9,12,26,50,100,200,400; D1 EMAs 12,26,89,144,169,233,377; W1 SMAs 9,12,26,50,100,200,400 (4 TFs x 7 MAs x 4 types)
 - +1 extra MA type/timeframe for BB
There are several versions: Simple, MTF, Pro MTF, Advanced MTF, MAX MTF and Ultimate MTF. This is the MAX MTF version. The Differences are listed below. All versions have BB
 - Simple: you have 2 groups of MAs that can be assigned any type (5+5)
 - MTF: +2 custom Timeframes for each group (2x5 MTF) +1 TF for BB, TF XY smoothing
 - Pro MTF: 4 custom Timeframes for each group (4x3 MTF), 1 TF for BB, MA levels and show max bars back options
 - Advanced MTF: +4 extra MAs/group (4x7 MTF), custom Ticker/Symbols, Timeframe <>= filter, Remove Duplicates Option
 - MAX MTF: +2 subtypes/group, packed to the limit with max possible MAs/TFs: 4x7, 5x6, 3x10, 4(3+1)x10, 5(4+1)x8, 6(5+1)x6
 - Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
MAX MTF version tests the limits of Pinescript trying to squeeze as many MAs/TFs as possible into a single indicator. 
It's basically a maxed out Advanced version with subtypes allowing for mixed types within a group (i.e. both emas and smas in a single group/TF)
Pinescript has the following limits:
 - max 40 security calls (6 calls are reserved for dupe checks and smoothing, 2 are used for BB, so only 32 calls are available)
 - max 64 plot outputs (BB uses 3 outputs, so only 61 plot outputs are available)
 - max 50000 (50kb) size of the compiled code
Based on those limits, you can only have the following MAs/TFs combos in a single script:
  1. 4x7, 5x6, 3x10 - total number of MTF MAs must always be <= 32, and you can still have BB and Num Levels = total MAs, without any compromises
  2. 5(4+1)x8, 6(5+1)x6, 4(3+1)x10 - you can use the Current Symbol/Timeframe as an extra (+1) fixed TF with the same number of MTF MAs
    - you don't need to call security to display MAs on the Current Symbol/Timeframe, so the total number of MTF MAs remains the same and is still <= 32
    - to fit that many MAs into the max 64 plot outputs limit you need to reduce the number of levels (not every MA Group will have corresponding levels)
Features:
 - 4x7 = 28 MAs of any type
 - 4x MTF groups with XY step line smoothing
 - +1 extra TF/type for BB MAs
 - 2 MA subtypes within each group/TF
 - 4x7 = 28 MA levels with adjustable group offsets, indents and shift
 - supports any existing type of MA: SMA, EMA, WMA, Hull Moving Average (HMA)
 - custom tickers/symbols for each group
 - show max bars back option
 - show/hide both groups of MAs/levels/BB and individual MAs
 - timeframe filter: show only MAs/Levels with TFs <>= Current TF
 - hide MAs/Levels with duplicate TFs
 - support for custom TFs that are not available in free accounts: 2D, 3D etc
 - support for timeframes in H: H, 2H, 4H etc
Notes: 
 - Uses timeframe textbox instead of input resolution dropdown to allow for 240 120 and other custom TFs
 - Uses symbol textbox instead of input symbol to avoid establishing multiple dummy security connections to the current ticker - otherwise empty symbols will prevent script from running
 - Possible reasons for missing MAs on a chart:
   - there may not be enough bars in history to start plotting it. For example, W1 EMA200 needs at least 200 bars on a weekly chart.
   - for charts with low/fractional prices i.e. 0.00002 << 0.001 (default Y smoothing step) decrease Y smoothing as needed (set Y = 0.0000001) or disable it completely (set X,Y to 0,0)
   - for charts with high price values i.e. 20000 >> 0.001 increase Y smoothing as needed (set Y = 10-20). Higher values exceeding MAs point density will cause it to disappear as there will be no points to plot. Different TFs may require diff adjustments
 - TradingView Replay Mode UI and Pinescript security calls are limited to TFs >= D (D,2D,W,MN...) for free accounts
   - attempting to plot any TF < D1 in Replay Mode will only result in straight lines, but all TFs will work properly in history and real-time modes. This is not a bug.
 - Max Bars Back (num_bars) is limited to 5000 for free accounts (10000 for paid), will show error when exceeded. To plot on all available history set to 0 (default)
 - Slow load/redraw times. This indicator becomes slower, its UI less responsive when:
   - Pinescript Node.js graphics library is too slow and inefficient at plotting bars/objects in a browser window. Code optimization doesn't help much - the graphics engine is the main reason for general slowness.
   - the chart has a long history (10000+ bars) in a browser's cache (you have scrolled back a couple of screens in a max zoom mode). 
     - Reload the page/Load a fresh chart and then apply the indicator or 
     - Switch to another Timeframe (old TF history will still remain in cache and that TF will be slow)
   - in max possible zoom mode around 4500 bars can fit on 1 screen - this also slows down responsiveness. Reset Zoom level
   - initial load and redraw times after a param change in UI also depend on TF. For example: D1/W1 - 2 sec, H1/H4 - 5-6 sec, M30 - 10 sec, M15/M5 - 4 sec, M1 - 5 sec. M30 usually has the longest history (up to 16000 bars) and W1 - the shortest (1000 bars).
   - when indicator uses more MAs (plots) and timeframes it will redraw slower. Seems that up to 5 Timeframes is acceptable, but 6+ Timeframes can become very slow.
   - show_last=last_bars plot limit doesn't affect load/redraw times, so it was removed from MA plot
   - Max Bars Back (num_bars) default/custom set UI value doesn't seem to affect load/redraw times
 - In max zoom mode all dynamic levels disappear (they behave like text)
 - Dupe check includes symbol: symbol, tf, both subtypes - all must match for a duplicate group
 - For the dupe check to work correctly a custom symbol must always include an exchange prefix. BB is not checked for dupes
Good Luck! Feel free to learn from/reuse the code to build your own indicators.
스크립트에서 "a股近10年第二天溢价的股票"에 대해 찾기
APEX - WaveTrend [v1]WaveTrend is a smoothed oscillator which enables it to detect true reversals in an extremely accurate manner. The beauty of this indicator is that does not generate signals during choppy sideways markets. 
The basic settings are 10 / 3 / 4 these are very aggressive settings, that will generate a lot of signals in all even not so volatile markets. If you need high-quality signals you settings close to 10 / 3  /21. The strongest buy/sell signals are given when the cross occurs above or below the threshold. In the 10 / 3 / 4 you threshold for buy should be around -90 values. If you use the very smoothed variant the threshold will be around -45 to -50 values.
This indicator will be first available in APEX v1 currently being beta tested.
Schaff Trend Cycle 1.1 with signal codingThis is an edit of Lazy Bear's Schaff Trend Cycle original description here. I've added in the syntax so that you can generate an alert when it crosses the threshold in either direction. Just tick the box to show threshold crosses.
  
More background on the indicator is here.
 www.investopedia.com 
Other common settings are fast 23 slow 53 or  10/30, 3/10. I have also set it to 9/20 for test purposes. They have different pluses and minuses on different timeframes. 
Double EMA & ALMA StrategyThe ALMA (50 period) acts as the main trend filter, meaning that long positions are taken above the ALMA and short positions are taken below the ALMA. For instance, the 5 and 10 period exponential moving averages are added on the chart to give early signals to the trend. 
Therefore, when the 5/10 EMA triggers a bullish crossover, long signals are taken when price is above the ALMA, likewise, when the 5/10 EMA triggers a bearish crossover, short signals are taken when price is below the ALMA.
Find out optimal values by trying. May not produce accurate results in horizontal markets. Thank you.
Inverted Yield Curve with VIX Fear IndexUS 2 year and US 10 year comparison, inverted yield curve with VIX. I use this on a weekly chart with 2 moving averages, the 40 week (ma200 daily) and the 520 week (10 year median).
The bottom histogram is the VIX and the plot is the yield curve. When the VIX is above a certain level (you can set it in settings) and the ýield curve is close to or at inversion the background goes red.
The last seven recessions were preceded by an inverted yield curve. Here I combined the two main fear indexes, the VIX and the run for safe US treasuries (Inverted Yield Curve). 
This is preset to the 2 year and 10 year US bond, weekly, and the normal VIX ticker but you can set it to whatever you like. 
Published with source code for anyone to modify. Please comment below if you do so! This is the second in a series of indicators I intend to publish as a package of economic recoverty/recession symptom indicators. 
Follow me for updates, next one up is commodities with dr Copper and oil!
Advanced Larry Williams 9.2- By EduHit rate greater than Setup 9.1
However, the stop of this setup becomes more expensive in certain situations.
PURCHASE SIGN
1 - Paper comes in a bullish trend in the operational term to be operated.
2 - Exponential moving average of 9 upward periods.
3 - Wait for a candle to make the largest closing (candle reference).
4 - If the next candle CLOSES below the minimum of the candle reference the setup is armed.
5 - Mark the candle maxim that closed below the reference. It's the trigger!
6 - If the next candle exceeds this maximum by 1 cent the trade is triggered. Put the stop loss at the low of the candle that closed below (0.01 to 0.10 below)
7 - If the next candle does not fire, let's lower the trigger to the lower maximums, SINCE the mm9exp does not turn down.
8 - It exceeded the maximum we will have the entrance.
9 - Original stop-loss in the minimum of the candle we set the maximum activated.
SIGN OF SALE
1 - Paper comes in a downtrend in the operating period to be operated.
2 - Exponential moving average of 9 periods descending.
3 - Wait for a candle that makes the lowest closing (candle reference).
4 - If the next candle CLOSE above the maximum of the reference candle the setup is armed.
5 - Bookmark the candle that closed above the reference. It's the trigger!
6 - If the next candle breaks this minimum, the trade is triggered.
7 - Place the stop-loss at the maximum of the candle that closed up.
8 - If the next candle does not trigger, we will raise the trigger to the highest minimums SINCE the exponential moving average of 9 periods does not turn upwards.
9 - It broke the minimum we will have the entrance.
10 - Stop-loss original in the maximum of the candle that we set the minimum activated.
*********************************************************************************************************************************************************
Índice de acerto Superior ao Setup 9.1
Porém o stop deste setup acaba se tornando mais caro em determinadas situações.
SINAL DE COMPRA
1 - Papel vem em tendência de alta no prazo operacional a ser operado.
2 - Média móvel exponencial de 9 períodos ascendente.
3 - Aguardar um candle que faça o maior fechamento (candle referência).
4 - Se o próximo candle FECHAR abaixo da mínima do candle referência o setup está armado.
5 - Marcar a máxima do candle que fechou abaixo do referência. É o gatilho!
6 - Se o próximo candle superar essa máxima em 1 centavo o trade é acionado. Colocar o stop-loss na mínima do candle que fechou abaixo (0,01 a 0,10 abaixo)
7 - Se o próximo candle não acionar, vamos abaixando o gatilho para as máximas menores DESDE QUE a mm9exp não vire para baixo.
8 - Superou a máxima teremos a entrada.
9 - Stop-loss original na mínima do candle que marcamos a máxima ativada.
SINAL DE VENDA
1 - Papel vem em tendência de baixa no prazo operacional a ser operado.
2 - Média móvel exponencial de 9 períodos descendente.
3 - Aguardar um candle que faça o menor fechamento (candle referência).
4 - Se o próximo candle FECHAR acima da máxima do candle referência o setup está armado.
5 - Marcar a mínima do candle que fechou acima do referência. É o gatilho!
6 - Se o próximo candle romper essa mínima o trade é acionado.
7 - Colocar o stop-loss na máxima do candle que fechou acima.
8 - Se o próximo candle não acionar, vamos levantando o gatilho para as mínimas maiores DESDE QUE a média móvel exponencial de 9 períodos não vire para cima.
9 - Rompeu a mínima teremos a entrada.
10 - Stop-loss original na máxima do candle que marcamos a mínima ativada.
Reset Every (Price)Someone requested a high/low price indicator that would reset the "remembered" prices daily.  I started out doing just that, and then decided to make it much more configurable.
Choose the units (minutes, hours, days, weeks, months) and the number of those units, and this will reset the highest/lowest value remembered to the current values on your chosen time interval.
This should work with any time interval you desire, within reason...asking for resets every 4000 hours on a monthly chart will probably not work.
GE, monthly, every 7 months:
  
Ford, weekly, every 18 months:
  
Dow Jones Industrial Average, weekly, every 90 days:
  
LTCBTC, daily, every 10 days:
  
ETHUSD, 30 minutes, every 10 days:
  
BTCUSD, 1 minute, every 10 hours:
  
EURUSD, 1 minute, every 50 minutes:
  
Also, I am about to publish another version of this with just one source input that can be applied to any indicator...stay tuned!
XPloRR MA-Trailing-Stop StrategyXPloRR MA-Trailing-Stop Strategy  
 Long term MA-Trailing-Stop strategy with Adjustable Signal Strength 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 fast buy EMA (blue) crossing over the slow buy SMA curve (orange) and the fast buy EMA has a certain up strength.
 
My  sell strategy  is triggered by either one of these conditions:
 
 the EMA(6) of the close value is crossing under the trailing stop value (green) or
 the fast sell EMA (navy) is crossing under the slow sell SMA curve (red) and the fast sell EMA has a certain down strength.
 
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 the high and low values. 
 The scripts shows a lot of graphical information: 
 
 The close value is shown in light-green. When the close value is lower then the buy value, the close value is shown in light-red. This way it is possible to evaluate the virtual losses during the trade.
 the trailing stop value is shown in dark-green. When the sell value is lower then the buy value, the last color of the trade will be red (best viewed when zoomed)(in the example, there are 2 trades that end in gain and 2 in loss (red line at end))
 the EMA and SMA values for both buy and sell signals are shown as a line
 the buy and sell(close) signals are labeled in blue
 
 How to use this strategy?  
Every stock has it's own "DNA", so first thing to do is tune the right parameters to get the best strategy values voor EMA , SMA, Strength for both buy and sell and the Trailing Stop (#ATR).
Look in the strategy tester overview to optimize the values Percent Profitable and Net Profit (using the strategy settings icon, you can increase/decrease the parameters) 
Then keep using these parameters for future buy/sell signals only for that particular stock. 
Do the same for other stocks.
 Important : optimizing these parameters is no guarantee for future winning trades! 
 Here are the parameters:  
 
 Fast EMA Buy: buy trigger when Fast EMA Buy crosses over the Slow SMA Buy value (use values between 10-20) 
 Slow SMA Buy: buy trigger when Fast EMA Buy crosses over the Slow SMA Buy value (use values between 30-100) 
 Minimum Buy Strength: minimum upward trend value of the Fast SMA Buy value (directional coefficient)(use values between 0-120) 
 Fast EMA Sell: sell trigger when Fast EMA Sell crosses under the Slow SMA Sell value (use values between 10-20) 
 Slow SMA Sell: sell trigger when Fast EMA Sell crosses under the Slow SMA Sell value (use values between 30-100)
 Minimum Sell Strength: minimum downward trend value of the Fast SMA Sell value (directional coefficient)(use values between 0-120) 
 Trailing Stop (#ATR): the trailing stop value as a multiple of the ATR(15) value (use values between 2-20) 
 
 Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now) compared to the Buy&Hold Strategy(=do nothing):  
 
 BEKB(Bekaert): EMA-Buy=12, SMA-Buy=44, Strength-Buy=65, EMA-Sell=12, SMA-Sell=55, Strength-Sell=120, Stop#ATR=20 
NetProfit: 996%, #Trades: 6, %Profitable: 83%, Buy&HoldProfit: 78% 
 BAR(Barco): EMA-Buy=16, SMA-Buy=80, Strength-Buy=44, EMA-Sell=12, SMA-Sell=45, Strength-Sell=82, Stop#ATR=9 
NetProfit: 385%, #Trades: 7, %Profitable: 71%, Buy&HoldProfit: 55% 
 AAPL(Apple): EMA-Buy=12, SMA-Buy=45, Strength-Buy=40, EMA-Sell=19, SMA-Sell=45, Strength-Sell=106, Stop#ATR=8 
NetProfit: 6900%, #Trades: 7, %Profitable: 71%, Buy&HoldProfit: 2938% 
 TNET(Telenet): EMA-Buy=12, SMA-Buy=45, Strength-Buy=27, EMA-Sell=19, SMA-Sell=45, Strength-Sell=70, Stop#ATR=14 
NetProfit: 129%, #Trade
Renko Price Bars Overlay// Shows the price renko bars (or range bars) instead of the PERIOD renko
// bars that are integrated into Trading View. The normal renko bars that
// Trading View offers only consider the drawing of a new brick when the
// price closes above or below the required brick size. This can produce
// misleading charts since depending on the time interval of a chart, new
// bricks may or may not be drawn. True price renko bars will draw a new 
// brick immediately upon the price exceeding the next target brick size.
// When running this script in "Traditional" mode, the painting of the 
// brick overlay band is INDEPENDENT of the chart interval. If price
// exceeds the required target price for the next brick, the band is
// updated immediately, instead of waiting for the price bar on the chart
// interval to close first. The brick starting anchor point will attempt
// to be a "nice number" at a round interval for the chart ticker. For
// example, if viewing EURUSD with the box size equal to 50 ticks/pips,
// the open and close prices will take the form of 1.2100, 1.2150, 1.2200,
// 1.2250, and so on. This is the same behavior as the normal traditional
// Renko bars in Trading View and other major trading platforms such as 
// Meta Trader.
// Use the tick size in traditional mode to specify the block size, in 
// ticks. This may give interesting results in FOREX pairs... as the tick
// size in Trading View may be 0.00001 instead of the normal pip size of
// 0.0001, so a 10 pip block size may be '100', and not the expected '10'.
// FOREX futures should work in the manner expected, a 10 pip block size
// will indeed equal 0.0010.
// The "ATR" mode functions differently than the Trading View built in 
// version. The block size is updated each time the range is exceeded.
// In Trading View, when using the ATR mode, the ATR is the last ATR 
// value calculated on the ENTIRE data interval, and is applied to all 
// past data. You can see this when you press the '+' sign of the ticker 
// in the top left of the chart window and you will see the brick size 
// as a constant, the brick size is not a function of the ever changing 
// ATR value of the price action. The block size of this script is not
// updated for each price candle (i.e. each 1HR on a 1HR chart), instead
// it is updated only when the price thresholds are exceeded requiring a
// the band to be updated. At that point the current ATR is considered
// and the brick size is updated.
// Options exist to show the current high and low of the brick, and to
// show the required levels that the price must exceed to draw a new 
// brick and update the band.
Please leave comments if you notice any bugs or would like any new features added. I don't find much use for plotting the H/L of the current renko candle, but I have seen some request it in the past.
Cheers.
EMA Indicators with BUY sell SignalCombine 3 EMA indicators into 1. Buy and Sell signal is based on 
 - Buy signal based on 20 Days Highest High resistance
 - Sell signal based on 10 Days Lowest Low support
Input :-
1 - Short EMA (20), Mid EMA (50) and Long EMA (200)
2 - Resistance (20) = 20 Days Highest High line
3 - Support (10) = 10 Days Lowest Low line
Volume Range EventsChanges in the feelings (positive, negative, neutral) in the market concerning the valuation of an instrument are often preceded with sudden outbursts of buying and selling frenzies. The aim of this indicator is to report such outbursts. We can see them as expansions of volume, sometimes 10 times more than usual. and as extensions of the trading range, also sometimes 10 times more than usual (e.g. usual range is 10 cent suddenly a whole dollar.) The changes are calculated in such a way that these fit between plus and minus 100 percent, the bars are scaled in some sort of logarithmic way. The Emoline is the same as the one in the True Balance of Power indicator, which I already published
ONLY RISES ARE EVENTS
Sometimes analysts are tempted to give meaning to low volume or small ranges. These simply mean that the market has little interest in trading this instrument. I believe that in such cases the trader needs to wait for expansion and extension events to happen, then he can make a better guess of where the market is heading. As events often mark the beginning or ending of a trend, this indicator provides an early and clear signal, because it doesn’t bother us about non-events.
WHAT IS USUAL?
If the algorithm would use an average as a normal to scale volume or range events, then previous peaks will act as spoilers by making the average so high that a following peak is scaled too small. I developed a function, usual() , that kicks out all extremes of a ‘population of values’ and which returns the average of the non-extreme values. It can be called with any serial. This function is called by both algorithms that report volume and range peaks, which guarantees that the results are really comparable. As this function has a fixed look back of 8 periods, we might state that ‘usual’ is a short lived relative value. I think this doesn’t matter for the practical use of the indicator.
COLORING AND INTERPRETATION
I follow the categories in the ‘Better Volume Indicator’, published by LeazyBear, these are:
1. Climactic Volumes, event >40 % (this means peak is 1.5 X usual)
LIME: Climax Buying Volume, direction up, range event also > 30 %
RED: Climax Selling Volume, direction down, range event also > 30 %
AQUA: Climax Churning Volume, both directions, range event < 30%
2. Smaller Volumes, event <40 %
GREEN: Supportive Volume, both directions, if combined with range event
BLUE: Churning Volume, both directions, if not combined with range event (Professional Trading)
3. Just Range Events
BLACK histogram bars (Amateurish Trading)
Forex Master v4.0 (EUR/USD Mean-Reversion Algorithm)DESCRIPTION  
Forex Master v4.0 is a mean-reversion algorithm currently optimized for trading the EUR/USD pair on the 5M chart interval. All indicator inputs use the period's closing price and all trades are executed at the open of the period following the period where the trade signal was generated. 
There are 3 main components that make up Forex Master v4.0: 
 
I. Trend Filter 
 
The algorithm uses a version of the ADX indicator as a trend filter to trade only in certain time periods where price is more likely to be range-bound (i.e., mean-reverting). This indicator is composed of a Fast ADX and a Slow ADX, both using the same look-back period of 50. However, the Fast ADX is smoothed with a 6-period EMA and the Slow ADX is smoothed with a 12-period EMA. When the Fast ADX is above the Slow ADX, the algorithm does not trade because this indicates that price is likelier to trend, which is bad for a mean-reversion system. Conversely, when the Fast ADX is below the Slow ADX, price is likelier to be ranging so this is the only time when the algorithm is allowed to trade. 
 
II. Bollinger Bands  
When allowed to trade by the Trend Filter, the algorithm uses the Bollinger Bands indicator to enter long and short positions. The Bolliger Bands indicator has a look-back period of 20 and a standard deviation of 1.5 for both upper and lower bands. When price crosses over the lower band, a Long Signal is generated and a long position is entered. When price crosses under the upper band, a Short Signal is generated and a short position is entered. 
 III. Money Management  
Rule 1 - Each trade will use a limit order for a fixed quantity of 50,000 contracts (0.50 lot). The only exception is Rule 
Rule 2 - Order pyramiding is enabled and up to 10 consecutive orders of the same signal can be executed (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts). 
Rule 3 - Every order will include a bracket with both TP and SL set at 50 pips (note: the algorithm only closes the current open position and does not enter the opposite trade once a TP or SL has been hit). 
Rule 4 - When a new opposite trade signal is generated, the algorithm sends in a larger order to close the current open position as well as open a new one (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts. A Short Signal is generated shortly after the 14th Long Signal. The algorithm then sends in a sell order for 400,000 contracts to close the 350,000 contracts long position and open a new short position of 50,000 contracts). 
My5min1. Follow the instructions for entry and exit exactly as above. Don’t second guess, or assume/presume anything.
2. Avoid entering the trade when the price is temporarily above /below 10 day MA, but the price candle hasn’t fully formed yet. Enter the trade only after the price candle closes above/below the 10 day MA.
3. Exit the trade immediately when the price candle closes above/below 10 day MA in the direction opposite to the trade. Don’t remain in the trade wishing it to turn in your favor.
4. Never ever trade in the opposite direction of the market. i.e. don’t buy when the price is below 200 day MA and sell when the price is above 200 day MA.
5. Take profits when limit is reached. Don’t be greedy and keep on increasing the target. Remember- A bird in hand is worth two in the bush.
MACD, backtest 2015+ only, cut in half and doubledThis is only a slight modification to the existing "MACD Strategy" strategy plugin!
 found the default MACD strategy to be lacking, although impressive for its simplicity. I added "year>2014" to the IF buy/sell conditions so it will only backtest from 2015 and beyond ** . 
I also had a problem with the standard MACD trading late, per se. To that end I modified the inputs for fast/slow/signal to double. Example: my defaults are 10, 21, 10 so I put 20, 42, 20 in. This has the effect of making a 30min interval the same as 1 hour at 10,21,10. So if you want to backtest at 4hr, you would set your time interval to 2hr on the main chart. This is a handy way to make shorter time periods more useful even regardless of strategy/testing, since you can view 15min with alot less noise but a better response.
Used on BTCCNY OKcoin, with the chart set at 45 min (so really 90min in the strategy) this gave me a percent profitable of 42% and a profit factor of 1.998 on 189 trades. 
Personally, I like to set the length/signals to 30,63,30. Meaning you need to triple the time, it allows for much better use of shorter time periods and the backtests are remarkably profitable. (i.e. 15min chart view = 45min on script, 30min= 1.5hr on script)
 ** If you want more specific time periods you need to try plugging in different bar values: replace "year" with "n" and "2014" with "5500". The bars are based on unix time I believe so you will need to play around with the number for n, with n being the numbers of bars.
Serenity Model VIPI — by yuu_iuHere’s a concise, practical English guide for Serenity Model VIPI (Author: yuu_iu). It covers what it is, how to set it up for daily trading, how to tune it, and how we guarantee non-repainting.
Serenity Model VIPI — User Guide (Daily Close, Non‑Repainting)
Credits
- Author: yuu_iu
- Producer: yuu_iu
- Platform: TradingView (Pine Script v5)
1) What it is
Serenity Model VIPI is a multi‑module, context‑aware trading model that fuses signals from:
- Entry modules: VCP, Flow, Momentum, Mean Reversion, Breakout
- Exit/risk modules: Contrarian, Breakout Sell, Volume Delta Sell, Peak Detector, Overbought Exit, Profit‑Take
- Context/memory: Learns per Ticker/Sector/Market Regime and adjusts weights/aggression
- Learning engine: Runs short “fake trades” to learn safely before scaling real trades
It produces a weighted, context‑adjusted score and a final decision: BUY, SELL, TAKE_PROFIT, or WAIT.
2) How it works (high level)
- Each module computes a score per bar.
- A fusion layer combines module scores using accuracy and base weights, then adjusts by:
  - Market regime (Bull/Bear/Sideways) and optional higher‑timeframe (HTF) bias
  - Risk control neuron
  - Context memory (ticker/sector/regime)
- Optional LLM mode can override marginal cases if context supports it.
- Final decision is taken at bar close only (no intrabar repaint).
3) Non‑repainting guarantee (Daily)
- Close‑only execution: All key actions use barstate.isconfirmed, so signals/entries/exits only finalize after the daily candle closes.
- No lookahead on HTF data: request.security() reads prior‑bar values (series ) for HTF close/EMA/RSI.
- Alerts at bar close: Alerts are fired once per bar close to prevent mid‑bar changes.
What this means: Once the daily bar closes, the decision and alert won’t be repainted.
4) Setup (TradingView)
- Paste the Pine v5 code into Pine Editor, click Add to chart.
- Timeframe: 1D (Daily).
- Optional: enable a date window for training/backtest
  - Enable Custom Date Filter: ON
  - Set Start Date / End Date
- Create alert (non‑repainting)
  - Condition: AI TRADE Signal
  - Options: Once Per Bar Close
  - Webhook (optional): Paste your URL into “System Webhook URL (for AI events)”
- Watch the UI
  - On‑chart markers: AI BUY / AI SELL / AI TAKE PROFIT
  - Right‑side table: Trades, Win Rate, Avg Profit, module accuracies, memory source, HTF trend, etc.
  - “AI Thoughts” label: brief reasoning and debug lines.
5) Daily trading workflow
- The model evaluates at daily close and may:
  - Enter long (BUY) when buy votes + total score exceed thresholds, after context/risk checks
  - Exit via trailing stop, hard stop, TAKE_PROFIT, or SELL decision
- Learning mode:
  - Triggers short “fake trades” every N bars (default 3) and measures outcome after 5 bars
  - Improves module accuracies and adjusts aggression once stable (min fake win% threshold)
- Memory application:
  - When you change tickers, the model tries to apply Ticker or Sector memory for the current market regime to pre‑bias module weights/aggression.
6) Tuning (what to adjust and why)
Core controls
- Base Aggression Level (default 1.0): Higher = more trades and stronger decisions; start conservative on Daily (1.0–1.2).
- Learning Speed Multiplier (default 3): Faster adaptation after fake/real trades; too high can overreact.
- Min Fake Win Rate to Exit Learning (%) (default 10–20%): Raises the bar before trusting more real trades.
- Fake Trade Every N Bars (default 3): Frequency of learning attempts.
- Learning Threshold Win Rate (default 0.4): Governs when the learner should keep learning.
- Hard Stop Loss (%) (default 5–8%): Global emergency stop.
Multi‑Timeframe (MTF)
- Enable Multi‑Timeframe Confirmation: ON (recommended for Daily)
- HTF Trend Source: HOSE:VNINDEX for VN equities (or CURRENT_SYMBOL if you prefer)
- HTF Timeframe: D or 240 (for a strong bias)
- MTF Weight Adjustment: 0.2–0.4 (0.3 default is balanced)
Module toggles and base weights
- In strong uptrends: increase VCP, Momentum, Breakout (0.2–0.3 typical)
- In sideways low‑vol regimes: raise MeanRev (0.2–0.3)
- For exits/defense: Contrarian, Peak, Overbought Exit, Profit‑Take (0.1–0.2 each)
- Keep Flow on as a volume‑quality filter (≈0.2)
Memory and control
- Enable Shared Memory Across Tickers: ON to share learning
- Enable Sector‑Based Knowledge Transfer: ON to inherit sector tendencies
- Manual Reset Learning: Use sparingly to reset module accuracies if regime changes drastically
Risk management
- Hard Stop Loss (%): 5–8% typical on Daily
- Trailing Stop: ATR‑ and volatility‑adaptive; tightens faster in Bear/High‑Vol regimes
- Max hold bars: Shorter in Bear or Sideways High‑Vol to cut risk
Alerts and webhook
- Use AI TRADE Signal with Once Per Bar Close
- Webhook payload is JSON, including event type, symbol, time, win rates, equity, aggression, etc.
7) Recommended Daily preset (VN equities)
- MTF: Enable, Source: HOSE:VNINDEX, TF: D, Weight Adj: 0.3
- Aggression: 1.1
- Learning Speed: 3
- Min Fake Win Rate to Exit Learning: 15%
- Hard SL: 6%
- Base Weights:
  - VCP 0.25, Momentum 0.25, Breakout 0.15, Flow 0.20
  - MeanRev 0.20 (raise in sideways)
  - Contrarian/Peak/Overbought/Profit‑Take: 0.10–0.20
- Leave other defaults as is, then fine‑tune by symbol/sector.
8) Reading the UI
- Table highlights: Real Trades, Win Rate, Avg Profit, Fake Actions/Win%, VCP Acc, Aggression, Equity, Score, Status (LEARNING/TRADING/REFLECTION), Last Real, Consec Loss, Best/Worst Trade, Pattern Score, Memory Source, Current Sector, AI Health, HTF Trend, Scheduler, Memory Loaded, Fake Active.
- Shapes: AI BUY (below bar), AI SELL/TAKE PROFIT (above bar)
- “AI Thoughts”: module contributions, context notes, debug lines
9) Troubleshooting
- No trades?
  - Ensure timeframe is 1D and the date filter covers the chart range
  - Check Scheduler Cooldown (3 bars default) and that barstate.isconfirmed (only at close)
  - If MTF is ON and HTF is bearish, buy bias is reduced; relax MTF Weight Adjustment or module weights
- Too many/too few trades?
  - Lower/raise Base Aggression Level
  - Adjust base weights on key modules (raise entry modules to be more active; raise exit/defense modules to be more selective)
- Learning doesn’t end?
  - Increase Min Fake Win Rate to Exit Learning only after it’s consistently stable; otherwise lower it or reduce Fake Trade Every N Bars
10) Important notes
- The strategy is non‑repainting at bar close by design (confirmed bars + HTF series  + close‑only alerts).
- Backtest fills may differ from live fills due to slippage and broker rules; this is normal for all TradingView strategies.
- Always validate settings across multiple symbols and regimes before going live.
If you want, I can bundle this guide into a README section in your Pine code and add a small on‑chart signature (Author/Producer: yuu_iu) in the top‑right corner.
チャットGPTimport yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
# 株たんのスクリーニング結果URL(例:200日線以下)
url = "https://kabutan.jp/warning/?mode=3_1"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
# 銘柄コードと企業名を抽出
stocks =  
for link in soup.select("td a "):
    code = link .split('=') 
    name = link.text.strip()
    if code.isdigit():
        stocks.append({"code": code, "name": name})
results =  
for stock in stocks :  # ←テスト用に10銘柄まで
    ticker = f"{stock }.T"
    df = yf.download(ticker, period="1y", interval="1d")
    # EMA200
    df  = df .ewm(span=200, adjust=False).mean()
    below_ema200 = df .iloc  < df .iloc 
    # 株たんの個別ページからPER・成長率を取得
    stock_url = f"https://kabutan.jp/stock/?code={stock }"
    res = requests.get(stock_url)
    s = BeautifulSoup(res.text, "html.parser")
    try:
        per = s.find(text="PER").find_next("td").text
        growth = s.find(text="売上高増減率").find_next("td").text
    except:
        per, growth = "N/A", "N/A"
    results.append({
        "銘柄コード": stock ,
        "企業名": stock ,
        "200EMA以下": below_ema200,
        "PER": per,
        "売上成長率": growth
    })
# 結果をCSV出力
df_result = pd.DataFrame(results)
df_result.to_csv("割安EMA200以下銘柄.csv", index=False, encoding="utf-8-sig")
print(df_result)
Vwap Daily By SamsungTitle
Daily VWAP with Historical Lookback (Logic Fix)
Description
This script calculates and plots the daily Volume-Weighted Average Price (VWAP), an essential tool for intraday traders.
What makes this indicator special is its robust plotting logic. Unlike many simple VWAP scripts that struggle to show data for previous days, this version includes a crucial fix that allows you to reliably display historical VWAP lines for as many days back as you need. This allows for more comprehensive backtesting and analysis of how price has interacted with the VWAP on previous trading days.
This is an indispensable tool for traders who use VWAP as a dynamic level of support/resistance, a benchmark for trade execution quality, or a gauge of the day's trend.
Key Features
Historical VWAP Display: Easily plot VWAP for multiple past days on your chart. Simply set the number of lookback days in the settings.
Accurate Daily Calculation: The VWAP calculation correctly resets at the beginning of each new trading session (00:00 server time).
Fully Customizable: You have full control over the appearance of the VWAP line, including its color, width, and style (Solid or Stepped).
Robust Plotting Engine: This script solves the common Pine Script issue where conditionally plotted historical lines fail to render. It works reliably on all intraday timeframes.
Built-in Debug Mode: For advanced users or those curious about the inner workings, a comprehensive debug mode can be enabled to display raw VWAP values, cumulative volume, and timeframe warnings.
How to Use
Add the "Daily VWAP with Historical Lookback" indicator to your chart.
IMPORTANT: Make sure you are on an intraday timeframe (e.g., 1H, 30M, 15M, 5M, 1M). This indicator is designed for intraday analysis and will display a warning if used on a daily or higher timeframe.
Open the indicator's settings.
In the "VWAP Settings" tab, adjust the "Lookback Days to Display" to set how many previous days of VWAP you want to see. (e.g., 0 for today only, 1 for today and yesterday, 10 for the last 10 days).
Customize the line's appearance in the "Line Style" tab.
The "Logic Fix" Explained (For Developers)
A common challenge in Pine Script is conditionally plotting data for historical bars. Many scripts attempt this by dynamically changing the plot color to na (transparent) for bars that shouldn't be displayed. This method is often unreliable and can result in the entire plot failing to render.
This script employs a more robust and standard approach: manipulating the data series itself.
The Problem: plot(vwap, color = shouldPlot ? color.red : na) can be buggy.
The Solution: plot(shouldPlot ? vwap : na, color = color.red) is reliable.
Instead of changing the color, we create a new data series (plotVwap). This series contains the vwapValue only on the bars that meet our date criteria. On all other bars, its value is na (Not a Number). The plot() function is designed to handle na values by simply "lifting the pen," creating a clean break in the line. This ensures that the VWAP is drawn only for the selected days, with 100% reliability across all historical data.
Settings Explained
Lookback Days to Display: Sets the number of past days (from the last visible bar) for which to display the VWAP.
Line Color, Width, and Style: Standard cosmetic settings for the VWAP line.
Enable Debug Mode (Master Switch): Toggles all debugging features on or off. It is enabled by default to help new users.
Display Debug: Cumulative Volume: When enabled, it shows the daily cumulative volume in a gray area on a separate pane.
Display Debug: Raw VWAP Value: When enabled, it plots the raw, unfiltered VWAP calculation for all days on the chart, helping to verify the core logic.
This script is provided for educational and informational purposes. Trading involves significant risk. Always conduct your own research and analysis before making any trading decisions.
If you find this script useful, a 'Like' is always appreciated! Happy trading
MACD HTF Hardcoded (A/B Presets) + Regimes [CHE]  MACD HTF Hardcoded  (A/B Presets) + Regimes — Higher-timeframe MACD emulation with acceptance-based regime filter and on-chart diagnostics
  Summary 
This indicator emulates a higher-timeframe MACD directly on the current chart using two hardcoded preset families and a time-bucket mapping, avoiding cross-timeframe requests. It classifies four MACD regimes and applies an acceptance filter that requires several consecutive bars before a state is considered valid. A small dead-band around zero reduces noise near the axis. An on-chart table reports the active preset, the inferred time bucket, the resolved lengths, and the current regime.
Pine version: v6
Overlay: false
Primary outputs: MACD line, Signal line, Histogram columns, zero line, regime-change alert, info table
  Motivation: Why this design? 
Cross-timeframe indicators often rely on external timeframe requests, which can introduce repaint paths and added latency. This design provides a deterministic alternative: it maps the current chart’s timeframe to coarse higher-timeframe buckets and uses fixed EMA lengths that approximate those views. The dead-band suppresses flip-flops around zero, and the acceptance counter reduces whipsaw by requiring sustained agreement across bars before acknowledging a regime.
  What’s different vs. standard approaches? 
 Baseline: Classical MACD with user-selected lengths on the same timeframe, or higher-timeframe MACD via cross-timeframe requests.
 Architecture differences:
   Hardcoded A and B length families with a bucket map derived from the chart timeframe.
   No `request.security`; all calculations occur on the current series.
   Regime classification from MACD and Histogram sign, gated by an acceptance count and a small zero dead-band.
   Diagnostics table for transparency.
 Practical effect: The MACD behaves like a slower, higher-timeframe variant without external requests. Regimes switch less often due to the dead-band and acceptance logic, which can improve stability in choppy sessions.
  How it works (technical) 
The script derives a coarse bucket from the chart timeframe using `timeframe.in_seconds` and maps it to preset-specific EMA lengths. EMAs of the source build MACD and Signal; their difference is the Histogram. Signs of MACD and Histogram define four regimes: strong bull, weak bull, strong bear, and weak bear. A small, user-defined band around zero treats values near the axis as neutral. An acceptance counter checks whether the same regime persisted for a given number of consecutive bars before it is emitted as the filtered regime. A single alert condition fires when the filtered regime changes. The histogram columns change shade based on position relative to zero and whether they are rising or falling. A persistent table object shows preset, bucket tag, resolved lengths, and the filtered regime. No cross-timeframe requests are used, so repaint risk is limited to normal live-bar movement; values stabilize on close.
  Parameter Guide 
Source — Input series for MACD — Default: Close — Using a smoother source increases stability but adds lag.
Preset — A or B length family — Default: “3,10,16” — Switch to “12,26,9” for the classic family mapped to buckets.
Table Position — Anchor for the info table — Default: Top right — Choose a corner that avoids covering price action.
Table Size — Table text size — Default: Normal — Use small on dense charts, large for presentations.
Dark Mode — Table theme — Default: Enabled — Match your chart background for readability.
Show Table — Toggle diagnostics table — Default: Enabled — Disable for a cleaner pane.
Zero dead-band (epsilon) — Noise gate around zero — Default: Zero — Increase slightly when you see frequent flips near zero.
Acceptance bars (n) — Bars required to confirm a regime — Default: Three — Raise to reduce whipsaw; lower to react faster.
  Reading & Interpretation 
 Histogram columns: Above zero indicates bullish pressure; below zero indicates bearish pressure. Darker shade implies the histogram increased compared with the prior bar; lighter shade implies it decreased.
 MACD vs. Signal lines: The spread corresponds to histogram height.
 Regimes:
   Strong bull: MACD above zero and Histogram above zero.
   Weak bull: MACD above zero and Histogram below zero.
   Strong bear: MACD below zero and Histogram below zero.
   Weak bear: MACD below zero and Histogram above zero.
 Table: Inspect active preset, bucket tag, resolved lengths, and the filtered regime number with its description.
  Practical Workflows & Combinations 
 Trend following: Use strong bull to favor long exposure and strong bear to favor short exposure. Use weak states as pullback or transition context. Combine with structure tools such as swing highs and lows or a baseline moving average for confirmation.
 Exits and risk: In strong trends, consider exiting partial size on a regime downgrade to a weak state. In choppy sessions, increase the acceptance bars to reduce churn.
 Multi-asset / Multi-timeframe: Works on time-based charts across liquid futures, indices, currencies, and large-cap equities. Bucket mapping helps retain a consistent feel when moving from lower to higher timeframes.
  Behavior, Constraints & Performance 
 Repaint/confirmation: No cross-timeframe requests; values can evolve intrabar and settle on close. Alerts follow your TradingView alert timing settings.
 Resources: `max_bars_back` is set to five thousand. Very large resolved lengths require sufficient history to seed EMAs; expect a warm-up period on first load or after switching symbols.
 Known limits: Dead-band and acceptance can delay recognition at sharp turns. Extremely thin markets or large gaps may still cause brief regime reversals.
  Sensible Defaults & Quick Tuning 
Start with preset “3,10,16”, dead-band near zero, and acceptance of three bars.
 Too many flips near zero: increase the dead-band slightly or raise the acceptance bars.
 Too sluggish in clean trends: reduce the acceptance bars by one.
 Too sensitive on fast lower timeframes: switch to the “12,26,9” preset family or raise the acceptance bars.
 Want less clutter: hide the table and keep the alert.
  What this indicator is—and isn’t 
This is a visualization and regime layer for MACD using higher-timeframe emulation and stability gates. It is not a complete trading system and does not generate position sizing or risk management. Use it with market structure, execution rules, and protective stops.
 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 
OPADA//@version=5
indicator("Buy/Sell Zones – TV Style", overlay=true, timeframe="", timeframe_gaps=true)
//=====================
// الإعدادات
//=====================
len     = input.int(100,  "Length", minval=10)
useATR  = input.bool(true, "Use ATR (بدل الانحراف المعياري)")
mult    = input.float(2.0, "Band Multiplier", step=0.1)
useRSI  = input.bool(true, "تفعيل فلتر RSI")
rsiOB   = input.int(70, "RSI Overbought", minval=50, maxval=90)
rsiOS   = input.int(30, "RSI Oversold",  minval=10, maxval=50)
//=====================
// القناة: أساس + انحراف
//=====================
basis = ta.linreg(close, len, 0)
off   = useATR ? ta.atr(len) * mult : ta.stdev(close, len) * mult
upper = basis + off
lower = basis - off
// نطاق علوي/سفلي بعيد لعمل تعبئة المناطق
lookback      = math.min(bar_index, 500)
topBand       = ta.highest(high, lookback)  + 50 * syminfo.mintick
bottomBand    = ta.lowest(low, lookback)    - 50 * syminfo.mintick
//=====================
// الرسم
//=====================
pUpper   = plot(upper, "Upper", color=color.new(color.blue, 0), linewidth=1)
pLower   = plot(lower, "Lower", color=color.new(color.red,  0), linewidth=1)
pBasis   = plot(basis, "Basis", color=color.new(color.gray, 60), linewidth=2)
// تعبئة المناطق: فوق القناة (أزرق)، تحت القناة (أحمر)
pTop     = plot(topBand,    display=display.none)
pBottom  = plot(bottomBand, display=display.none)
fill(pUpper, pTop,    color=color.new(color.blue, 80))   // منطقة مقاومة/بيع
fill(pBottom, pLower, color=color.new(color.red,  80))   // منطقة دعم/شراء
//=====================
// خط أفقي من قمّة قريبة (يمثل مقاومة) – قريب من الخط المنقّط في الصورة
//=====================
resLen   = math.round(len * 0.6)
dynRes   = ta.highest(high, resLen)
plot(dynRes, "Recent Resistance", color=color.new(color.white, 0), linewidth=1)
//=====================
// إشارات BUY / SELL + فلتر RSI (اختياري)
//=====================
rsi = ta.rsi(close, 14)
touchLower = ta.crossover(close, lower) or close <= lower
touchUpper = ta.crossunder(close, upper) or close >= upper
buyOK  = useRSI ? (touchLower and rsi <= rsiOS) : touchLower
sellOK = useRSI ? (touchUpper and rsi >= rsiOB) : touchUpper
plotshape(buyOK,  title="BUY",  location=location.belowbar, style=shape.labelup,
     text="BUY",  color=color.new(color.green, 0), textcolor=color.white, size=size.tiny, offset=0)
plotshape(sellOK, title="SELL", location=location.abovebar, style=shape.labeldown,
     text="SELL", color=color.new(color.red,   0), textcolor=color.white, size=size.tiny, offset=0)
// تنبيهات
alertcondition(buyOK,  title="BUY",  message="BUY signal: price touched/closed below lower band (RSI filter may apply).")
alertcondition(sellOK, title="SELL", message="SELL signal: price touched/closed above upper band (RSI filter may apply).")
Buy/Sell Zones – TV Style//@version=5
indicator("Buy/Sell Zones – TV Style", overlay=true, timeframe="", timeframe_gaps=true)
//=====================
// الإعدادات
//=====================
len     = input.int(100,  "Length", minval=10)
useATR  = input.bool(true, "Use ATR (بدل الانحراف المعياري)")
mult    = input.float(2.0, "Band Multiplier", step=0.1)
useRSI  = input.bool(true, "تفعيل فلتر RSI")
rsiOB   = input.int(70, "RSI Overbought", minval=50, maxval=90)
rsiOS   = input.int(30, "RSI Oversold",  minval=10, maxval=50)
//=====================
// القناة: أساس + انحراف
//=====================
basis = ta.linreg(close, len, 0)
off   = useATR ? ta.atr(len) * mult : ta.stdev(close, len) * mult
upper = basis + off
lower = basis - off
// نطاق علوي/سفلي بعيد لعمل تعبئة المناطق
lookback      = math.min(bar_index, 500)
topBand       = ta.highest(high, lookback)  + 50 * syminfo.mintick
bottomBand    = ta.lowest(low, lookback)    - 50 * syminfo.mintick
//=====================
// الرسم
//=====================
pUpper   = plot(upper, "Upper", color=color.new(color.blue, 0), linewidth=1)
pLower   = plot(lower, "Lower", color=color.new(color.red,  0), linewidth=1)
pBasis   = plot(basis, "Basis", color=color.new(color.gray, 60), linewidth=2)
// تعبئة المناطق: فوق القناة (أزرق)، تحت القناة (أحمر)
pTop     = plot(topBand,    display=display.none)
pBottom  = plot(bottomBand, display=display.none)
fill(pUpper, pTop,    color=color.new(color.blue, 80))   // منطقة مقاومة/بيع
fill(pBottom, pLower, color=color.new(color.red,  80))   // منطقة دعم/شراء
//=====================
// خط أفقي من قمّة قريبة (يمثل مقاومة) – قريب من الخط المنقّط في الصورة
//=====================
resLen   = math.round(len * 0.6)
dynRes   = ta.highest(high, resLen)
plot(dynRes, "Recent Resistance", color=color.new(color.white, 0), linewidth=1)
//=====================
// إشارات BUY / SELL + فلتر RSI (اختياري)
//=====================
rsi = ta.rsi(close, 14)
touchLower = ta.crossover(close, lower) or close <= lower
touchUpper = ta.crossunder(close, upper) or close >= upper
buyOK  = useRSI ? (touchLower and rsi <= rsiOS) : touchLower
sellOK = useRSI ? (touchUpper and rsi >= rsiOB) : touchUpper
plotshape(buyOK,  title="BUY",  location=location.belowbar, style=shape.labelup,
     text="BUY",  color=color.new(color.green, 0), textcolor=color.white, size=size.tiny, offset=0)
plotshape(sellOK, title="SELL", location=location.abovebar, style=shape.labeldown,
     text="SELL", color=color.new(color.red,   0), textcolor=color.white, size=size.tiny, offset=0)
// تنبيهات
alertcondition(buyOK,  title="BUY",  message="BUY signal: price touched/closed below lower band (RSI filter may apply).")
alertcondition(sellOK, title="SELL", message="SELL signal: price touched/closed above upper band (RSI filter may apply).")
Multi-Mode Seasonality Map [BackQuant]Multi-Mode Seasonality Map  
 A fast, visual way to expose repeatable calendar patterns in returns, volatility, volume, and range across multiple granularities (Day of Week, Day of Month, Hour of Day, Week of Month). Built for idea generation, regime context, and execution timing. 
 What is “seasonality” in markets? 
 Seasonality refers to statistically repeatable patterns tied to the calendar or clock, rather than to price levels. Examples include specific weekdays tending to be stronger, certain hours showing higher realized volatility, or month-end flow boosting volumes. This tool measures those effects directly on your charted symbol.
 Why seasonality matters 
  
  It’s orthogonal alpha: timing edges independent of price structure that can complement trend, mean reversion, or flow-based setups.
  It frames expectations: when a session typically runs hot or cold, you size and pace risk accordingly.
  It improves execution: entering during historically favorable windows, avoiding historically noisy windows.
  It clarifies context: separating normal “calendar noise” from true anomaly helps avoid overreacting to routine moves.
  
 How traders use seasonality in practice 
  
  Timing entries/exits : If Tuesday morning is historically weak for this asset, a mean-reversion buyer may wait for that drift to complete before entering.
  Sizing & stops : If 13:00–15:00 shows elevated volatility, widen stops or reduce size to maintain constant risk.
  Session playbooks : Build repeatable routines around the hours/days that consistently drive PnL.
  Portfolio rotation : Compare seasonal edges across assets to schedule focus and deploy attention where the calendar favors you.
  
 Why Day-of-Week (DOW) can be especially helpful 
  
  Flows cluster by weekday (ETF creations/redemptions, options hedging cadence, futures roll patterns, macro data releases), so DOW often encodes a stable micro-structure signal.
  Desk behavior and liquidity provision differ by weekday, impacting realized range and slippage.
  DOW is simple to operationalize: easy rules like “fade Monday afternoon chop” or “press Thursday trend extension” can be tested and enforced.
  
 What this indicator does 
  
  Multi-mode heatmaps : Switch between  Day of Week, Day of Month, Hour of Day, Week of Month .
  Metric selection : Analyze  Returns ,  Volatility  ((high-low)/open),  Volume  (vs 20-bar average), or  Range  (vs 20-bar average).
  Confidence intervals : Per cell, compute mean, standard deviation, and a z-based CI at your chosen confidence level.
  Sample guards : Enforce a minimum sample size so thin data doesn’t mislead.
  Readable map : Color palettes, value labels, sample size, and an optional legend for fast interpretation.
  Scoreboard : Optional table highlights best/worst DOW and today’s seasonality with CI and a simple “edge” tag.
  
 How it’s calculated (under the hood) 
  
  Per bar, compute the chosen  metric  (return, vol, volume %, or range %) over your lookback window.
  Bucket that metric into the active calendar bin (e.g., Tuesday, the 15th, 10:00 hour, or Week-2 of month).
  For each bin, accumulate  sum ,  sum of squares , and  count , then at render compute  mean ,  std dev , and  confidence interval .
  Color scale normalizes to the observed min/max of eligible bins (those meeting the minimum sample size).
  
 How to read the heatmap 
  
  Color : Greener/warmer typically implies higher mean value for the chosen metric; cooler implies lower.
  Value label : The center number is the bin’s mean (e.g., average % return for Tuesdays).
  Confidence bracket : Optional “ ” shows the CI for the mean, helping you gauge stability.
  n = sample size : More samples = more reliability. Treat small-n bins with skepticism.
  
 Suggested workflows 
  
  Pick the lens : Start with  Analysis Type = Returns ,  Heatmap View = Day of Week ,  lookback ≈ 252 trading days . Note the best/worst weekdays and their CI width.
  Sanity-check volatility : Switch to  Volatility  to see which bins carry the most realized range. Use that to plan stop width and trade pacing.
  Check liquidity proxy : Flip to  Volume , identify thin vs thick windows. Execute risk in thicker windows to reduce slippage.
  Drill to intraday : Use  Hour of Day  to reveal opening bursts, lunchtime lulls, and closing ramps. Combine with your main strategy to schedule entries.
  Calendar nuance : Inspect  Week of Month  and  Day of Month  for end-of-month, options-cycle, or data-release effects.
  Codify rules : Translate stable edges into rules like “no fresh risk during bottom-quartile hours” or “scale entries during top-quartile hours.”
  
 Parameter guidance 
  
  Analysis Period (Days) : 252 for a one-year view. Shorten (100–150) to emphasize the current regime; lengthen (500+) for long-memory effects.
  Heatmap View : Start with DOW for robustness, then refine with Hour-of-Day for your execution window.
  Confidence Level : 95% is standard; use 90% if you want wider coverage with fewer false “insufficient data” bins.
  Min Sample Size : 10–20 helps filter noise. For Hour-of-Day on higher timeframes, consider lowering if your dataset is small.
  Color Scheme : Choose a palette with good mid-tone contrast (e.g., Red-Green or Viridis) for quick thresholding.
  
 Interpreting common patterns 
  
  Return-positive but low-vol bins : Favorable drift windows for passive adds or tight-stop trend continuation.
  Return-flat but high-vol bins : Opportunity for mean reversion or breakout scalping, but manage risk accordingly.
  High-volume bins : Better expected execution quality; schedule size here if slippage matters.
  Wide CI : Edge is unstable or sample is thin; treat as exploratory until more data accumulates.
  
 Best practices 
  
  Revalidate after regime shifts (new macro cycle, liquidity regime change, major exchange microstructure updates).
  Use multiple lenses: DOW to find the day, then Hour-of-Day to refine the entry window.
  Combine with your core setup signals; treat seasonality as a filter or weight, not a standalone trigger.
  Test across assets/timeframes—edges are instrument-specific and may not transfer 1:1.
  
 Limitations & notes 
  
  History-dependent: short histories or sparse intraday data reduce reliability.
  Not causal: a hot Tuesday doesn’t guarantee future Tuesday strength; treat as probabilistic bias.
  Aggregation bias: changing session hours or symbol migrations can distort older samples.
  CI is z-approximate: good for fast triage, not a substitute for full hypothesis testing.
  
 Quick setup 
  
  Use  Returns + Day of Week + 252d  to get a clean yearly map of weekday edge.
  Flip to  Hour of Day  on intraday charts to schedule precise entries/exits.
  Keep  Show Values  and  Confidence Intervals  on while you calibrate; hide later for a clean visual.
  
 The Multi-Mode Seasonality Map helps you convert the calendar from an afterthought into a quantitative edge, surfacing when an asset tends to move, expand, or stay quiet—so you can plan, size, and execute with intent.
Scissors&Knifes V3.1✂️ The Scissors (PAG Chop V4 Engine)
🧠 Core idea
Scissors measure market compression and breakout readiness.
They use a modified Choppiness Index that looks at the relationship between:
True Range volatility (ATR × period length)
The total high–low range over the same window.
The smaller the ratio (sum of TR vs range), the more directional and impulsive the market is.
The higher the ratio, the more “sideways” the market trades.
This version smooths the result over PAG_SMOOTHLEN bars and applies several color bands that correspond to volatility states.
🎨 Color code meaning
Range	State	Color	Interpretation
≤ 30	Strong Red	#8B0000	Momentum exhaustion on downside, sellers dominating — about to reverse or already strong down-trend.
30 – 38	Brick Red	#A52A2A	Fading downside pressure; often the “bleeding edge” of a bearish climax.
38 – 55	Transparent	black (α≈100)	Neutral chop zone — indecision, range-building.
55 – 61.8	Yellow (optional)	#DAA520	Early compression pocket where volatility starts contracting; the calm before a trend.
61.8 – 70	Bright Green	#556B2F	Energy release phase: volatility breaking out upward.
≥ 70	Strong Green	#355E3B	Sustained bullish drive, often continuation leg of a trend.
🪶 Secret nuance:
The transition bands (38–45 and 45–55) are treated as fully transparent to mark “dead zones.”
When PAG Chop sits here, all label activity pauses — the system resets its cluster memory so the next colored print begins a new “cluster”, letting you clearly see where fresh directional momentum starts.
🧩 Cluster logic
Every time a colored (non-transparent) reading appears, it belongs to a “color cluster.”
Grey labels (= count 1) mark the genesis of a new cluster, and following counts 2, 3, 4 … represent the internal continuity of that trend state.
You can optionally hide the first N grey or count 2 labels to reduce clutter on the initial stabilization bars.
✂️ Label meaning
Each label shows:
Emoji ✂️
Current count (e.g. ✂️ = 3 means 3 timeframes are simultaneously firing)
Optional list of the timeframes that contribute.
So a high count (e.g. 8–10) means many lower TFs are synchronizing volatility breakout — a multiframe alignment, often just before an acceleration burst.
🔪 The Knife (Mr Blonde V4 Engine)
🧠 Core idea
Mr Blonde converts the slope of a long EMA into an angle-of-attack metric — literally the “tilt” of market momentum.
It computes the EMA gradient relative to price span and rescales it into degrees (-5 ° to +5 °).
The steeper the angle, the stronger the directional push.
🎨 Color code meaning
Angle range	Color	Interpretation
≥ +5 °	Transparent (Black 1)	Fully over-extended up move — wait for reset.
+3.57 – +5 °	Dark Red	Strong upward slope, momentum apex.
+2.14 – +3.57 °	Orange	Medium upward slope, trend acceleration zone.
+0.71 – +2.14 °	Light Orange	Mild upward bias, pre-momentum phase.
0 to -0.71 °	Yellow	Neutral transition.
-0.71 – -2.14 °	Olive Green	Soft bearish slope.
-2.14 – -3.57 °	Olive Drab	Building bearish momentum.
-3.57 – -5 °	Hunter Green	Strong downward angle, aggressive push.
≤ -5 °	Transparent (Black 2)	Oversold/over-tilted — likely exhaustion.
🪶 Secret nuance:
Mr Blonde uses a “span normalization” factor that divides EMA slope by the dynamic range of highs and lows.
This lets it compare angles fairly across assets with different volatility profiles (e.g. BTC vs ES) — it’s one of the rare EMA-angle implementations that self-scales properly.
🗡 Label meaning
Emoji 🔪
Count = how many TFs share the same momentum angle bias.
When many TFs show the same slope polarity (e.g. knife = 8), you’re in a deep momentum cascade — a “knife trend.”
💫 Yellow knife
The yellow state marks neutrality or slope flattening.
If you enable yellow visibility (mb_show_yellow), you can see where momentum cools off — often the earliest reversal hint.
⚙️ Shared mechanics between ✂️ and 🔪
Multi-timeframe sweep
The script cycles through 1 m → 10 m by default, running both engines once per TF.
Each returning true adds +1 to the count.
So:
sc_hits = count of timeframes where PAG fires + 1
knife_hits = count of timeframes where MB fires + 1
That “+1 shift” means there’s always at least 1, letting count = 1 represent the local TF itself.
Cluster limiter
If Limit max labels per cluster is on, you cap how many total symbols (both ✂️ & 🔪, including trails) can appear within one color phase — avoiding chart spam during extended trends.
Trails
Each printed label seeds a short-lived “trail” sequence — faded copies extending N bars forward.
Trails visualize the linger effect of the last signal, useful for visually connecting bursts in momentum.
Grey or count = 1 labels can have shorter or longer trails depending on your overrides (*_trail_bars_grey).
They’re purely visual and do not affect alerting.
Alerts
Alerts fire independently of whether you hide labels — unless you enable “respect filters”.
This guarantees you never miss a structural signal even if you suppress visuals for clarity.
🌈 Interpreting Both Together
Scenario	Interpretation
✂️ = low (1–2) + 🔪 rising (red/orange)	Market just leaving chop, early thrust stage.
✂️ = high (≥ 5) + 🔪 green	Fully aligned breakout continuation — trend in progress.
✂️ = yellow cluster + 🔪 yellow	Volatility squeeze, energy buildup — next expansion near.
✂️ = green cluster → 🔪 turns red	Cross-state conflict; likely transition or correction.
✂️ = grey + 🔪 grey	Reset condition — both engines cooling; stand aside.
💡 Hidden edge:
Scissors signal potential, Knife measures kinetic force.
The perfect storm is when ✂️ goes from yellow→green one bar before 🔪 shifts from orange→green — it catches the birth of directional flow while volatility is still tight.
🧭 Reading the labels intuitively
Grey ✂️/🔪 = 1 → embryonic state, may fizzle or bloom.
✂️/🔪 = 2 or 3 → expansion taking hold.
✂️/🔪 ≥ 4 (mid black) → strong synchronized drive across TFs.
Transparent gap → cluster reset; prepare for new phase.
Trail lines → echo of previous cluster strength.
Final secret tip 🗝
Because both engines are mathematically uncorrelated (volatility vs EMA angle), when they agree in color polarity on multiple TFs, you have one of the cleanest probabilistic trend windows possible.
If you ever see ✂️ = 6 + 🔪 = 6 both pointing the same way — that’s a “knife-through-the-scissors” moment: volatility expansion and directional slope synchronized — those are the bars where institutional algorithms tend to add size.
Liquidity Grab + RSI Divergence═══════════════════════════════════════════════════════════════
LIQUIDITY GRAB + RSI DIVERGENCE INDICATOR
═══════════════════════════════════════════════════════════════
📌 OVERVIEW
This indicator identifies high-probability reversals by combining:
  • Liquidity sweeps (stop hunts)
  • RSI divergence confirmation
  • Filters false breakouts automatically
═══════════════════════════════════════════════════════════════
🟢 BUY SIGNAL (Green Triangle Up)
REQUIRES BOTH CONDITIONS:
1. Liquidity Grab Below Previous Low
   • Price breaks BELOW recent low
   • Candle CLOSES ABOVE that low
   • Traps sellers who shorted the breakdown
2. Bullish RSI Divergence
   • Price: Lower Low (LL)
   • RSI: Higher Low (HL)
   • Shows weakening downward momentum
➜ Result: Potential bullish reversal
═══════════════════════════════════════════════════════════════
🔴 SELL SIGNAL (Red Triangle Down)
REQUIRES BOTH CONDITIONS:
1. Liquidity Grab Above Previous High
   • Price breaks ABOVE recent high
   • Candle CLOSES BELOW that high
   • Traps buyers who bought the breakout
2. Bearish RSI Divergence
   • Price: Higher High (HH)
   • RSI: Lower High (LH)
   • Shows weakening upward momentum
➜ Result: Potential bearish reversal
═══════════════════════════════════════════════════════════════
📊 VISUAL INDICATORS
Main Signals:
  🔺 Large Green Triangle = BUY (Liq Grab + Bullish Div)
  🔻 Large Red Triangle = SELL (Liq Grab + Bearish Div)
Reference Levels:
  ━ Red Line = Previous High Level
  ━ Green Line = Previous Low Level
Additional Markers (Optional):
  ○ Small Green Circle = Liquidity grab low only
  ○ Small Red Circle = Liquidity grab high only
  ✕ Small Blue Cross = Bullish divergence only
  ✕ Small Orange Cross = Bearish divergence only
═══════════════════════════════════════════════════════════════
⚙️ SETTINGS
1. Lookback Period (Default: 20)
   • Range: 5-100
   • Sets how far back to identify previous highs/lows
   • Higher = fewer but stronger levels
   • Lower = more frequent but weaker levels
2. RSI Length (Default: 14)
   • Range: 5-50
   • Standard RSI calculation period
   • 14 is industry standard
3. RSI Divergence Lookback (Default: 5)
   • Range: 3-20
   • Controls pivot point sensitivity
   • Higher = fewer divergence signals
   • Lower = more divergence signals
4. Show Labels (Default: ON)
   • Toggle BUY/SELL text labels
   • Disable for cleaner chart view
═══════════════════════════════════════════════════════════════
💡 HOW TO USE
Step 1: WAIT FOR CONFIRMATION
  • Only trade LARGE TRIANGLE signals
  • Ignore small circles/crosses alone
Step 2: CHECK TIMEFRAME
  • Best on: 15min, 1H, 4H, Daily
  • Avoid: 1min, 5min (too noisy)
Step 3: CONFIRM CONTEXT
  • Check overall market trend
  • Identify key support/resistance
  • Look for confluence with price action
Step 4: ENTRY & RISK MANAGEMENT
  • Enter on signal candle close or pullback
  • Stop loss below/above the liquidity grab wick
  • Target: Previous swing high/low or key levels
  • Risk/Reward: Minimum 1:2 ratio
Step 5: SET ALERTS
  • Create alert for "BUY Signal"
  • Create alert for "SELL Signal"
  • Never miss opportunities
═══════════════════════════════════════════════════════════════
✅ BEST PRACTICES
DO:
  ✓ Use on multiple timeframes for confluence
  ✓ Combine with support/resistance zones
  ✓ Wait for both conditions (liq grab + divergence)
  ✓ Practice on demo account first
  ✓ Use proper position sizing
DON'T:
  ✗ Trade every small circle/cross
  ✗ Use on very low timeframes (<15min)
  ✗ Ignore overall market context
  ✗ Trade without stop loss
  ✗ Risk more than 1-2% per trade
═══════════════════════════════════════════════════════════════
⚠️ IMPORTANT NOTES
• This is a CONFIRMATION tool, not a holy grail
• No indicator is 100% accurate
• Combine with your trading strategy
• Backtest on your preferred instruments
• Adjust parameters for your trading style
• Higher timeframes = more reliable signals
• Always use risk management
═══════════════════════════════════════════════════════════════
🔔 ALERTS INCLUDED
Two alert conditions are built-in:
  1. "BUY Signal" - Liquidity Grab + Bullish RSI Divergence
  2. "SELL Signal" - Liquidity Grab + Bearish RSI Divergence
═══════════════════════════════════════════════════════════════
📈 RECOMMENDED SETTINGS BY TIMEFRAME
5-15 Min Charts:
  • Lookback: 10-15
  • RSI Length: 14
  • RSI Div Lookback: 3-5
1H-4H Charts:
  • Lookback: 20-30
  • RSI Length: 14
  • RSI Div Lookback: 5-7
Daily Charts:
  • Lookback: 30-50
  • RSI Length: 14
  • RSI Div Lookback: 7-10
═══════════════════════════════════════════════════════════════
Good luck and trade safe! 🚀






















