Multi SMA EMA WMA HMA BB (4x5 MAs Bollinger Bands) Adv MTF - RRBMulti SMA EMA WMA HMA 4x5 Moving Averages with Bollinger Bands Advanced MTF by RagingRocketBull 2019
Version 1.0
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 * 5 MAs = 20 MAs. You can assign any type/timeframe combo to a group, for example:
- EMAs 12,26,50,100,200 x H1, H4, D1, W1 (4 TFs x 5 MAs x 1 type)
- EMAs 8,10,13,21,30,50,55,100,200,400 x M15, H1 (2 TFs x 10 MAs x 1 type)
- D1 EMAs and SMAs 8,10,12,26,30,50,55,100,200,400 (1 TF x 10 MAs x 2 types)
- H1 WMAs 7,77,89,167,231; H4 HMAs 12,26,50,100,200; D1 EMAs 89,144,169,233,377; W1 SMAs 12,26,50,100,200 (4 TFs x 5 MAs x 4 types)
- +1 extra MA type/timeframe for BB
There are several versions: Simple, MTF, Pro MTF, Advanced MTF and Ultimate MTF. This is the Advanced 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: +2 extra MAs/group (4x5 MTF), custom Ticker/Symbols, Timeframe <>= filter, Remove Duplicates Option
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
Features:
- 4x5 = 20 MAs of any type
- 4x MTF groups with XY step line smoothing
- +1 extra TF/type for BB MAs
- 4x5 = 20 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 - you can compare MAs of the same symbol across exchanges
- 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.
- price << default Y smoothing step 5. For charts with low/fractional prices (i.e. 0.00002 << 5) adjust X Y smoothing as needed (set Y = 0.0000001) or disable it completely (set X,Y to 0,0)
- 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)
1. based on 3EmaBB, uses plot*, barssince and security functions
2. you can't set certain constants from input due to Pinescript limitations - change the code as needed, recompile and use as a private version
3. Levels = trackprice implementation
4. Show Max Bars Back = show_last implementation
5. swma has a fixed length = 4, alma and linreg have additional offset and smoothing params
6. Smoothing is applied by default for visual aesthetics on MTF. To use exact ma mtf values (lines with stair stepping) - disable it
Good Luck! You can explore, modify/reuse the code to build your own indicators.
Buscar en scripts para "马斯克+100万"
Multi SMA EMA WMA HMA BB (4x3 MAs Bollinger Bands) Pro MTF - RRBMulti SMA EMA WMA HMA 4x3 Moving Averages with Bollinger Bands Pro MTF by RagingRocketBull 2018
Version 1.0
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. You can assign any type/timeframe combo to a group, for example:
- EMAs 50,100,200 x H1, H4, D1, W1 (4 TFs x 3 MAs x 1 type)
- EMAs 8,13,21,55,100,200 x M15, H1 (2 TFs x 6 MAs x 1 type)
- D1 EMAs and SMAs 12,26,50,100,200,400 (1 TF x 6 MAs x 2 types)
- H1 WMAs 7,77,231; H4 HMAs 50,100,200; D1 EMAs 144,169,233; W1 SMAs 50,100,200 (4 TFs x 3 MAs x 4 types)
- +1 extra MA type/timeframe for BB
compile time: 25-30 sec
full redraw time after parameter change in UI: 3 sec
There are several versions: Simple, MTF, Pro MTF, Advanced MTF and Ultimate MTF. This is the Pro 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)
- Pro MTF: +4 custom Timeframes for each group (4x3 MTF), MA levels and show max bars back options
- Advanced MTF: +2 extra MAs/group (4x5 MTF), custom Ticker/Symbol, backreferences for type, TF and MA lengths in UI
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
Features:
- 4x3 = 12 MAs of any type including Hull Moving Average (HMA)
- 4x MTF groups with step line smoothing
- BB +1 extra TF/type for BB MAs
- 12 MA levels with adjustable group offsets, indents and shift
- show max bars back
- you can show/hide both groups of MAs/levels and individual MAs
Notes:
1. based on 3EmaBB, uses plot*, barssince and security functions
2. you can't set certain constants from input due to Pinescript limitations - change the code as needed, recompile and use as a private version
3. Levels = trackprice implementation
4. Show Max Bars Back = show_last implementation
5. uses timeframe textbox instead of input resolution to allow for 120 240 and other custom TFs. Also supports TFs in hours: 2H or H2
6. swma has a fixed length = 4, alma and linreg have additional offset and smoothing params
7. Smoothing is applied by default for visual aesthetics on MTF. To use exact ma mtf values (lines with stair stepping) - disable it
MTF Notes:
- uses simple timeframe textbox instead of input resolution dropdown to allow for 120, 240 and other custom TFs, also supports timeframes in H: 2H, H2
- Groups that are not assigned a Custom TF will use Current Timeframe (0).
- MTF will work for any MA type assigned to the group
- MTF works both ways: you can display a higher TF MA/BB on a lower TF or a lower TF MA/BB on a higher TF.
- MTF MA values are normally aligned at the boundary of their native timeframe. This produces stair stepping when a higher TF MA is viewed on a lower TF.
Therefore X Y Point Density/Smoothing is applied by default on MA MTF for visual aesthetics. Set both to 0 to disable and see exact ma mtf values (lines with stair stepping and original mtf alignment).
- Smoothing is disabled for BB MTF bands because fill doesn't work with smoothed MAs after duplicate values are replaced with na.
- MTF MA Value fluctuation is possible on the current bar due to default security lookahead
Smoothing:
- X,Y == 0 - X,Y smoothing disabled (stair stepping on high TFs)
- X == 0, Y > 0 - X,Y smoothing applied to all TFs
- Y == 0, X > 0 - X smoothing applied to all TFs < deltaX_max_tf, Y smoothing disabled
- X > 0, Y > 0 - Y smoothing applied to all TFs, then X smoothing applied to all TFs < deltaX_max_tf
X Smoothing with Y == 0 - shows only every deltaX-th point starting from the first bar.
X Smoothing with Y > 0 - shows only every deltaX-th point starting from the last shown Y point, essentially filling huge gaps remaining after Y Smoothing with points and preserving the curve's general shape
X Smoothing on high TFs with already scarce points produces weird curve shapes, it works best only on high density lower TFs
Y Smoothing reduces points on all TFs, removes adjacent points with prices within deltaY, while preserving the smaller curve details.
A combination of X,Y produces the most accurate smoothing. Higher delta value - larger range, more points removed.
Show Max Bars Back:
- can't set plot show_last from input -> implemented using a timenow based range check
- you can't delete/modify history once plotted, so essentially it just sets a start point for plotting (from num_bars bars back) that works only in realtime mode (not in replay)
Levels:
You can plot current MA value using plot trackprice=true or by checking Show Price Line in Style. Problem is:
- you can only change color (not the dashed line style, width), have both ma + price line (not just the line), and it's full screen wide
- you can't set plot trackprice from input => implemented using plotshape/plotchar with fixed text labels serving as levels
- there's no other way of creating a dynamic level: hline, plot, offset - nothing else works.
- you can't plot a text var - all text strings must be constants, so you can't change the style, width and text labels without recompiling.
- from input you can only adjust offset, indent and shift for each level group, and change color
- the dot below each level line is the exact MA value. If you want just the line swap plotshape with plotchar, recompile and save as your private version, adjust Y shift.
To speed up redraw times: reduce last_bars to ~2000, recompile and use as your own private version
Pinescript is a rudimentary language (should be called Painscript instead) that can basically only plot data. You can't do much else. Please see the code for tips and hints.
Certain things just can't be done or require shady workarounds and weeks of testing trying to resolve weird node.js compiler errors.
Feel free to learn from/reuse/change the code as needed and use as your own private version. See comments in code. Good Luck!
Gidra's Vchain Strategy v0.1Tested on "BTC/USD", this is a reversible strategy
If the RSI is lower than "RSI Limit" (for last "RSI Signals" candles) and there were "Open Color, Bars" green Heiken Ashi candles - close short, open long
If the RSI is higher than 100-"RSI Limit" (for last "RSI Signals" candles) and there were "Open Color, Bars" red Heiken Ashi candles - close long, open short
- timeframe: 5m (the best)
RSI Period = 14
RSI Limit = 30
RSI Signals = 3
Open Color = 2
Piramiding = 100
Lot = 100 %
- timeframe: 1h
RSI Period = 2
RSI Limit = 30
RSI Signals = 3
Open Color = 2
Piramiding = 100
Lot = 100 %
Range Oscillator Strategy + Stoch Confirm🔹 Short summary
This is a free, educational long-only strategy built on top of the public “Range Oscillator” by Zeiierman (used under CC BY-NC-SA 4.0), combined with a Stochastic timing filter, an EMA-based exit filter and an optional risk-management layer (SL/TP and R-multiple exits). It is NOT financial advice and it is NOT a magic money machine. It’s a structured framework to study how range-expansion + momentum + trend slope can be combined into one rule-based system, often with intentionally RARE trades.
────────────────────────
0. Legal / risk disclaimer
────────────────────────
• This script is FREE and public. I do not charge any fee for it.
• It is for EDUCATIONAL PURPOSES ONLY.
• It is NOT financial advice and does NOT guarantee profits.
• Backtest results can be very different from live results.
• Markets change over time; past performance is NOT indicative of future performance.
• You are fully responsible for your own trades and risk.
Please DO NOT use this script with money you cannot afford to lose. Always start in a demo / paper trading environment and make sure you understand what the logic does before you risk any capital.
────────────────────────
1. About default settings and risk (very important)
────────────────────────
The script is configured with the following defaults in the `strategy()` declaration:
• `initial_capital = 10000`
→ This is only an EXAMPLE account size.
• `default_qty_type = strategy.percent_of_equity`
• `default_qty_value = 100`
→ This means 100% of equity per trade in the default properties.
→ This is AGGRESSIVE and should be treated as a STRESS TEST of the logic, not as a realistic way to trade.
TradingView’s House Rules recommend risking only a small part of equity per trade (often 1–2%, max 5–10% in most cases). To align with these recommendations and to get more realistic backtest results, I STRONGLY RECOMMEND you to:
1. Open **Strategy Settings → Properties**.
2. Set:
• Order size: **Percent of equity**
• Order size (percent): e.g. **1–2%** per trade
3. Make sure **commission** and **slippage** match your own broker conditions.
• By default this script uses `commission_value = 0.1` (0.1%) and `slippage = 3`, which are reasonable example values for many crypto markets.
If you choose to run the strategy with 100% of equity per trade, please treat it ONLY as a stress-test of the logic. It is NOT a sustainable risk model for live trading.
────────────────────────
2. What this strategy tries to do (conceptual overview)
────────────────────────
This is a LONG-ONLY strategy designed to explore the combination of:
1. **Range Oscillator (Zeiierman-based)**
- Measures how far price has moved away from an adaptive mean.
- Uses an ATR-based range to normalize deviation.
- High positive oscillator values indicate strong price expansion away from the mean in a bullish direction.
2. **Stochastic as a timing filter**
- A classic Stochastic (%K and %D) is used.
- The logic requires %K to be below a user-defined level and then crossing above %D.
- This is intended to catch moments when momentum turns up again, rather than chasing every extreme.
3. **EMA Exit Filter (trend slope)**
- An EMA with configurable length (default 70) is calculated.
- The slope of the EMA is monitored: when the slope turns negative while in a long position, and the filter is enabled, it triggers an exit condition.
- This acts as a trend-protection exit: if the medium-term trend starts to weaken, the strategy exits even if the oscillator has not yet fully reverted.
4. **Optional risk-management layer**
- Percentage-based Stop Loss and Take Profit (SL/TP).
- Risk/Reward (R-multiple) exit based on the distance from entry to SL.
- Implemented as OCO orders that work *on top* of the logical exits.
The goal is not to create a “holy grail” system but to serve as a transparent, configurable framework for studying how these concepts behave together on different markets and timeframes.
────────────────────────
3. Components and how they work together
────────────────────────
(1) Range Oscillator (based on “Range Oscillator (Zeiierman)”)
• The script computes a weighted mean price and then measures how far price deviates from that mean.
• Deviation is normalized by an ATR-based range and expressed as an oscillator.
• When the oscillator is above the **entry threshold** (default 100), it signals a strong move away from the mean in the bullish direction.
• When it later drops below the **exit threshold** (default 30), it can trigger an exit (if enabled).
(2) Stochastic confirmation
• Classic Stochastic (%K and %D) is calculated.
• An entry requires:
- %K to be below a user-defined “Cross Level”, and
- then %K to cross above %D.
• This is a momentum confirmation: the strategy tries to enter when momentum turns up from a pullback rather than at any random point.
(3) EMA Exit Filter
• The EMA length is configurable via `emaLength` (default 70).
• The script monitors the EMA slope: it computes the relative change between the current EMA and the previous EMA.
• If the slope turns negative while the strategy holds a long position and the filter is enabled, it triggers an exit condition.
• This is meant to help protect profits or cut losses when the medium-term trend starts to roll over, even if the oscillator conditions are not (yet) signalling exit.
(4) Risk management (optional)
• Stop Loss (SL) and Take Profit (TP):
- Defined as percentages relative to average entry price.
- Both are disabled by default, but you can enable them in the Inputs.
• Risk/Reward Exit:
- Uses the distance from entry to SL to project a profit target at a configurable R-multiple.
- Also optional and disabled by default.
These exits are implemented as `strategy.exit()` OCO orders and can close trades independently of oscillator/EMA conditions if hit first.
────────────────────────
4. Entry & Exit logic (high level)
────────────────────────
A) Time filter
• You can choose a **Start Year** in the Inputs.
• Only candles between the selected start date and 31 Dec 2069 are used for backtesting (`timeCondition`).
• This prevents accidental use of tiny cherry-picked windows and makes tests more honest.
B) Entry condition (long-only)
A long entry is allowed when ALL the following are true:
1. `timeCondition` is true (inside the backtest window).
2. If `useOscEntry` is true:
- Range Oscillator value must be above `entryLevel`.
3. If `useStochEntry` is true:
- Stochastic condition (`stochCondition`) must be true:
- %K < `crossLevel`, then %K crosses above %D.
If these filters agree, the strategy calls `strategy.entry("Long", strategy.long)`.
C) Exit condition (logical exits)
A position can be closed when:
1. `timeCondition` is true AND a long position is open, AND
2. At least one of the following is true:
- If `useOscExit` is true: Oscillator is below `exitLevel`.
- If `useMagicExit` (EMA Exit Filter) is true: EMA slope is negative (`isDown = true`).
In that case, `strategy.close("Long")` is called.
D) Risk-management exits
While a position is open:
• If SL or TP is enabled:
- `strategy.exit("Long Risk", ...)` places an OCO stop/limit order based on the SL/TP percentages.
• If Risk/Reward exit is enabled:
- `strategy.exit("RR Exit", ...)` places an OCO order using a projected R-multiple (`rrMult`) of the SL distance.
These risk-based exits can trigger before the logical oscillator/EMA exits if price hits those levels.
────────────────────────
5. Recommended backtest configuration (to avoid misleading results)
────────────────────────
To align with TradingView House Rules and avoid misleading backtests:
1. **Initial capital**
- 10 000 (or any value you personally want to work with).
2. **Order size**
- Type: **Percent of equity**
- Size: **1–2%** per trade is a reasonable starting point.
- Avoid risking more than 5–10% per trade if you want results that could be sustainable in practice.
3. **Commission & slippage**
- Commission: around 0.1% if that matches your broker.
- Slippage: a few ticks (e.g. 3) to account for real fills.
4. **Timeframe & markets**
- Volatile symbols (e.g. crypto like BTCUSDT, or major indices).
- Timeframes: 1H / 4H / **1D (Daily)** are typical starting points.
- I strongly recommend trying the strategy on **different timeframes**, for example 1D, to see how the behaviour changes between intraday and higher timeframes.
5. **No “caution warning”**
- Make sure your chosen symbol + timeframe + settings do not trigger TradingView’s caution messages.
- If you see warnings (e.g. “too few trades”), adjust timeframe/symbol or the backtest period.
────────────────────────
5a. About low trade count and rare signals
────────────────────────
This strategy is intentionally designed to trade RARELY:
• It is **long-only**.
• It uses strict filters (Range Oscillator threshold + Stochastic confirmation + optional EMA Exit Filter).
• On higher timeframes (especially **1D / Daily**) this can result in a **low total number of trades**, sometimes WELL BELOW 100 trades over the whole backtest.
TradingView’s House Rules mention 100+ trades as a guideline for more robust statistics. In this specific case:
• The **low trade count is a conscious design choice**, not an attempt to cherry-pick a tiny, ultra-profitable window.
• The goal is to study a **small number of high-conviction long entries** on higher timeframes, not to generate frequent intraday signals.
• Because of the low trade count, results should NOT be interpreted as statistically strong or “proven” – they are only one sample of how this logic would have behaved on past data.
Please keep this in mind when you look at the equity curve and performance metrics. A beautiful curve with only a handful of trades is still just a small sample.
────────────────────────
6. How to use this strategy (step-by-step)
────────────────────────
1. Add the script to your chart.
2. Open the **Inputs** tab:
- Set the backtest start year.
- Decide whether to use Oscillator-based entry/exit, Stochastic confirmation, and EMA Exit Filter.
- Optionally enable SL, TP, and Risk/Reward exits.
3. Open the **Properties** tab:
- Set a realistic account size if you want.
- Set order size to a realistic % of equity (e.g. 1–2%).
- Confirm that commission and slippage are realistic for your broker.
4. Run the backtest:
- Look at Net Profit, Max Drawdown, number of trades, and equity curve.
- Remember that a low trade count means the statistics are not very strong.
5. Experiment:
- Tweak thresholds (`entryLevel`, `exitLevel`), Stochastic settings, EMA length, and risk params.
- See how the metrics and trade frequency change.
6. Forward-test:
- Before using any idea in live trading, forward-test on a demo account and observe behaviour in real time.
────────────────────────
7. Originality and usefulness (why this is more than a mashup)
────────────────────────
This script is not intended to be a random visual mashup of indicators. It is designed as a coherent, testable strategy with clear roles for each component:
• Range Oscillator:
- Handles mean vs. range-expansion states via an adaptive, ATR-normalized metric.
• Stochastic:
- Acts as a timing filter to avoid entering purely on extremes and instead waits for momentum to turn.
• EMA Exit Filter:
- Trend-slope-based safety net to exit when the medium-term direction changes against the position.
• Risk module:
- Provides practical, rule-based exits: SL, TP, and R-multiple exit, which are useful for structuring risk even if you modify the core logic.
It aims to give traders a ready-made **framework to study and modify**, not a black box or “signals” product.
────────────────────────
8. Limitations and good practices
────────────────────────
• No single strategy works on all markets or in all regimes.
• This script is long-only; it does not short the market.
• Performance can degrade when market structure changes.
• Overfitting (curve fitting) is a real risk if you endlessly tweak parameters to maximise historical profit.
Good practices:
- Test on multiple symbols and timeframes.
- Focus on stability and drawdown, not only on how high the profit line goes.
- View this as a learning tool and a basis for your own research.
────────────────────────
9. Licensing and credits
────────────────────────
• Core oscillator idea & base code:
- “Range Oscillator (Zeiierman)”
- © Zeiierman, licensed under CC BY-NC-SA 4.0.
• Strategy logic, Stochastic confirmation, EMA Exit Filter, and risk-management layer:
- Modifications by jokiniemi.
Please respect both the original license and TradingView House Rules if you fork or republish any part of this script.
────────────────────────
10. No payments / no vendor pitch
────────────────────────
• This script is completely FREE to use on TradingView.
• There is no paid subscription, no external payment link, and no private signals group attached to it.
• If you have questions, please use TradingView’s comment system or private messages instead of expecting financial advice.
Use this script as a tool to learn, experiment, and build your own understanding of markets.
────────────────────────
11. Example backtest settings used in screenshots
────────────────────────
To avoid any confusion about how the results shown in screenshots were produced, here is one concrete example configuration:
• Symbol: BTCUSDT (or similar major BTC pair)
• Timeframe: 1D (Daily)
• Backtest period: from 2018 to the most recent data
• Initial capital: 10 000
• Order size type: Percent of equity
• Order size: 2% per trade
• Commission: 0.1%
• Slippage: 3 ticks
• Risk settings: Stop Loss and Take Profit disabled by default, Risk/Reward exit disabled by default
• Filters: Range Oscillator entry/exit enabled, Stochastic confirmation enabled, EMA Exit Filter enabled
If you change any of these settings (symbol, timeframe, risk per trade, commission, slippage, filters, etc.), your results will look different. Please always adapt the configuration to your own risk tolerance, market, and trading style.
grinpapedro
pedro02599
En línea
Canal de texto
No Somos Liquidez:【📖】biblioteca
Buscar No Somos Liquidez
Hilos
Hermit.exe
Hermit.exe
hace >30 días
Notion Trade Tracker
Herramientas
0
Hermit.exe
Hermit.exe
hace >30 días
Notion Journal
Herramientas
0
9
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador Judas Swing
SMC
Herramientas
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador TV Samurái V1
SMC
Herramientas
0
2
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Hábitos Atómicos
Psicologia
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
El trading como negocio
Psicologia
0
Hilo
Hilo:Indicador TV Samurái V1
Chat de Indicador TV Samurái V1
Indicador TV Samurái V1
SMC
22 de septiembre de 2024
Hermit.exe
NSL
Senior Mod
AO
Autor(a) original — 22/09/2024 16:06domingo, 22 de septiembre de 2024 16:06
@VIP
Primero agradecer al compañero @Romulo por su generosidad y compartir el indicador para la comunidad, todos los créditos de creación para el
El indicador tal como su nombre indica sirve para marcar el horario de operativa y elementos de la estrategia Samurái V1. Este indicador no esta publico en TV por lo que tendrán que añadirlo de manera manual a través de un script a TradingView, cabe recalcar que no es nada complicado, para hacerlo aquí les dejamos un pequeño tutorial:
www.youtube.com
Indicaciones para agregarlo de manera manual:
Entramos a TV y buscamos "editor de Pine" en la parte inferior izquierda de la pantalla.,
Le damos click y aparecerá un nuevo menú,
Posteriormente eliminamos todo lo que este dentro del menú,
Ahora copiamos todo el texto del archivo del indicador y lo pegamos en el menú de TV,
Finalmente le damos a "añadir al grafico" que se encuentra en la parte derecha de la misma barra donde estaba "editor de pine".,
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST)\n - DST Start : Second Sunday in March at 2:00\n - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
... (413 líneas restantes)
Contraer
Contraer (513 líneas)
Ver todo el archivo
SAMURAI v1.txt
SAMURAI v1.txt (23 KB)
23 KB
SAMURAI v1.txt (23 KB)
Descargar SAMURAI v1.txt (23 KB)Cambiar de idioma
Reenviar
Más
2
Seguir
Añade esta publicación a tu lista de canales y recibe notificaciones sobre ella.
Copiar enlace
No tienes permiso para enviar mensajes en este canal.
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST)\n - DST Start : Second Sunday in March at 2:00\n - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
// @function get the current bar's unix time, hour and minute
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _utcTimeOffset (array) array storing the utc info
// @param _utcCity (array) array storing the major city info
// @param _inAd (int) ofsset value in minutes
// @param _tf_m (int) timeframe multiplier
// @returns A tuple containing (int) index, (int) hour and (int) minute
method f_getBarTime(string _utc, _dst, _utcTimeOffset, _utcCity, _inAd, _tf_m) =>
utcTime = (array.get(_utcTimeOffset, array.indexof(_utcCity, _utc)) + (_dst ? 1 : 0)) * 3600000 + _inAd * 60000 + time
h = math.floor(utcTime / 3600000) % 24
m = math.floor(utcTime / 60000) % 60
int idx = 0
if _tf_m == 3
if m == 48
m := m + 2
idx := 2
else if m == 9
m := m + 1
idx := 1
//else if m == 12 or m == 42
// idx := 0
else if _tf_m == 5
if (m == 0 and h == 9) or (m == 30 and h == 7)
m := m + 3
idx := 3
// @function calculate and get customized pivot points high low and time values
// @param _len (int) length for the pivot points high low calculation
// @param _loc (string) if set to 'wick' highest/lowest values of the detected pivot points high low will be calculated
// if set to 'Body' the highest/lowest values of the candel bodies will be returend as pivot points high low
// @returns A tuple containing (float) ph - pivot high, (float) pl - pivot low, (int) pht - pivot high unix time (int) plt - pivot low unix time
method f_getPivotPoint(int _len, _loc) =>
ph = ta.pivothigh(_len, _len)
if ph and _loc == 'Body'
ph := math.max(open , close )
pl = ta.pivotlow (_len, _len)
if pl and _loc == 'Body'
pl := math.min(open , close )
pht = ph ? time : na
plt = pl ? time : na
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
tf_m = timeframe.multiplier
bi = bar_index
var a_majorCity = array.new_string(), var a_utcTimeOffset = array.new_float(), var a_utcCity = array.new_string()
if barstate.isfirst
array.push(a_majorCity, 'NEW YORK'), array.push(a_utcTimeOffset, -5), array.push(a_utcCity, '(UTC-05:00) NEW YORK')
array.push(a_majorCity, 'LONDON' ), array.push(a_utcTimeOffset, 0 ), array.push(a_utcCity, '(UTC+00:00) LONDON' )
// Lower TF bar UDT array
ltfB = request.security_lower_tf(syminfo.tickerid, '1', bar.new())
// Lower TF pivotPoint UDT arrays
var pivotPoint p = pivotPoint.new()
= request.security_lower_tf(syminfo.tickerid, '1', f_getPivotPoint(pLen, pLoc))
if not na(array.min(a_pL))
p.l := array.min(a_pL)
p.lt := array.min(a_pLt)
if not na(array.max(a_pH))
p.h := array.max(a_pH)
p.ht := array.max(a_pHt)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//units and multipliers for versatility across asset classes
pUnits = syminfo.type== 'index' or syminfo.type == 'futures'? ' $':
syminfo.type=='forex'?' pips':na
mult= str.tonumber(timeframe.period)<=5? 1: str.tonumber(timeframe.period)<=240? 60: timeframe.isdwm? 1440:na
pMult = syminfo.type== 'index' or syminfo.type == 'futures'? 1:
syminfo.type=='forex'? 100:1
tUnits = mult==1? ' mins': mult==60? ' hours':mult==1440? ' days':na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------}
//Detect ICT macros
//-----------------------------------------------------------------------------{
var macro mc = macro.new()
// @function main function : detects macros, draws nad controls macro components and classifies macros
// @param _m (bool) enable/disable specific macro
// @param _msh (int) macro start hour
// @param _msm (int) macro start minute
// @param _mh (bool) macro top line control option
// @param _ml (bool) macro bottom line control option
// @param _mm (bool) macro middle line control option
// @param _me (bool) macro extended lines control option
// @param _mt (bool) macro label text value
//
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _tf_m (int) timeframe multiplier
// @param _alert (bool) next macro time start location, displays in _alertM minutes
// @param _alertM (int) alert in _alertM minutes
// @returns macro UDT components created
processMacro(_m, _msh, _msm, _mh, _ml, _mm, _me, _mt, _utc, _dst, _tf_m, _alert, _alertM) =>
if _m
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, _alertM, _tf_m)
if ha == _msh and ma == _msm
alert(_mt + ' macro will be in play in ' + str.tostring(_alertM) + ' minutes for instrument ' + syminfo.ticker)
if _alert
mc.lnf := line.new(time + _alertM * 60000 , high, time + _alertM * 60000, low, xloc.bar_time, extend.both, mc.color, line.style_solid , 1)
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, 0, _tf_m)
if h == 08 or h == 07 or h == 1 or h == 3 or h == 5
if m == 0
mc.len := 10
else
mc.len := 180
if h == 11
if m == 0
mc.len := 10
else
mc.len := 300
if h == _msh and m == _msm
mc.lnf.delete()
if ltfB.size() > idx
if not na(ltfB.get(idx).h)
mc.t := ltfB.get(idx).t
mc.o := ltfB.get(idx).o
mc.top := ltfB.get(idx).h
mc.bottom := ltfB.get(idx).l
if idx == 0
mc.x2 := bi + math.round(mc.len / _tf_m)
else
mc.x2 := bi + math.round(mc.len / _tf_m) + 1
mc.lnh := line.new(bi, mc.top, int(mc.x2), mc.top, color = _mh ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnhe := line.new(int(mc.x2), mc.top, int(mc.x2), mc.top, color = _me ? _mh ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnl := line.new(bi, mc.bottom, int(mc.x2), mc.bottom, color =_ml ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnle := line.new(int(mc.x2), mc.bottom, int(mc.x2), mc.bottom, color = _me ? _ml ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnm := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _mm ? mc.color : mc.nocolor, style = line.style_dotted, width = 1)
mc.lnme := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _me ? _mm ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 1)
mc.lf := linefill.new(mc.lnh, mc.lnl, color.new(color.gray, 100))
mc.lb := label.new(bi + int(mc.len / _tf_m / 2), mc.top, mcText != 'None' ? 'SAMURAI\n' + _mt : '', xloc.bar_index, yloc.price, #00000000, label.style_label_down, chart.fg_color, mcSize, text.align_left, '')
p.l1 := p.l
p.h1 := p.h
else if bi < int(mc.x2) and time >= mc.t
mc.top := math.max(high, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(low , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(high, mc.lnh.get_y1()), math.min(low , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(high, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if bi == int(mc.x2)
if ltfB.size() > idx
if not na(ltfB.get(idx).c)
mc.co := ltfB.get(idx).o
mc.ch := ltfB.get(idx).h
mc.cl := ltfB.get(idx).l
mc.cc := ltfB.get(idx).c
mc.top := math.max(mc.ch, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(mc.cl , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(mc.top, mc.lnh.get_y1()), math.min(mc.bottom , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(mc.top, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if mc.t == mc.t
mc.lnhe.set_x2(bi), mc.lnle.set_x2(bi), mc.lnme.set_x2(bi)
if bi == int(mc.x2) + 1 and not str.contains(mc.lb.get_text(), 'on NSL')
mc.lb.set_tooltip('mc open : '+ str.tostring(mc.o , format.mintick) +
'\nmc close : ' + str.tostring(mc.cc , format.mintick) +
'\nmc top : ' + str.tostring(mc.top , format.mintick) +
'\nmc mid : ' + str.tostring(mc.mid , format.mintick) +
'\nmc bottom : ' + str.tostring(mc.bottom, format.mintick) )
if mc.bottom < p.l1 and mc.top > p.h1
if (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(mColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else if mc.bottom < p.l1 or mc.top > p.h1
if (mc.co > mc.mid and mc.cc < mc.mid) or (mc.co < mc.mid and mc.cc > mc.mid) or (mc.o < mc.mid and mc.cc < mc.mid) or (mc.o > mc.mid and mc.cc > mc.mid) // pL > pmcPL or pmcPH < pH
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
if p.l == p.l1 and p.h == p.h1 and (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
//-----------------------------------------------------------------------------}
//Process macros
//-----------------------------------------------------------------------------{
if tf_m <= 15
processMacro(m07000710, 11, 00, m07_top, m07_bot, m07_mid, m07_ext, '07:00 AM - 07:10', '(UTC+00:00) LONDON' , lnSummerTime, tf_m, mcAlert, mcAlertM)
processMacro(m08000810, 08, 00, m08_top, m08_bot, m08_mid, m08_ext, '08:00 AM - 08:10', '(UTC-05:00) NEW YORK', nySummerTime, tf_m, mcAlert, mcAlertM)
else
var table note = table.new(position.bottom_right, 1, 1)
if barstate.islast
table.cell(note, 0, 0, 'ICT Macros are supported on:\n 1 min, 3, 5 mins and 15 mins charts\n\n', text_size=size.small, text_color=chart.fg_color)
//-----------------------------------------------------------------------------}
//OPEN RANGO DE ESTRATEGIA
// INPUTS
i_time = input.session ('0800-0801:1234567', "OPEN SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz = input ("GMT-4", "Timezone")
i_vline = input.bool (true, "VLine", inline="in1")
i_vcol = input.color (#006eff, "", inline="in1")
i_txtcol = input.color (#006eff, " Text color", inline="in1")
i_vstyle = input.string ("Solid", "Style", options= )
i_hline = label.style_none
i_linecol = label.style_none
i_linestyle = label.style_none
i_ex = label.style_none
i_ex2 = label.style_none
i_ex3 = label.style_none
// MISC
nymidz = time ("1", i_time, i_tz)
linestyle = i_linestyle == "Solid" ? line.style_solid : i_linestyle == "Dotted" ? line.style_dotted : line.style_dashed
vstyle = i_vstyle == "Solid" ? line.style_solid : i_vstyle == "Dotted" ? line.style_dotted : line.style_dashed
ex = i_ex == "1 Day" ? extend.none : i_ex == "2 Days" ? extend.none : i_ex == "Right" ? extend.right : extend.both
htime = i_ex == "2 Days" ? 172800000 : 86400000
hourtime = label.style_none
// CALC
var openprice = 0.0
if nymidz
if not nymidz
openprice := open
else
openprice := math.max(open, openprice)
// OBJECTS
var label lb = na
if openprice != openprice
var line lne = na
line.set_x2(lne, nymidz)
line.set_extend(lne, extend.none)
if i_vline and nymidz == nymidz
vl1 = line.new(nymidz, high, nymidz, low, xloc.bar_time, extend.both, i_vcol, vstyle, 1)
if line.get_y1(vl1) == line.get_y2(vl1)
line.delete(vl1)
///////////////////////////////////////////////////////////////////////////////////
//CLOSE RANGO DE ESTRATEGIA
// INPUTS
i_time0 = input.session ('0810-0811:1234567', "CLOSE SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz0 = i_tz
i_vline0 = i_vline
i_vcol0 = i_vcol
i_txtcol0 = i_txtcol
i_vstyle0 = i_vstyle
i_hline0 = label.style_none
i_linecol0 = label.style_none
i_linestyle0 = label.style_none
i_ex0 = label.style_none
i_ex20 = label.style_none
i_ex30 = label.style_none
// MISC
nymid0 = time ("1", i_time0, i_tz0)
linestyle0 = i_linestyle0 == "Solid" ? line.style_solid : i_linestyle0 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle0 = i_vstyle0 == "Solid" ? line.style_solid : i_vstyle0 == "Dotted" ? line.style_dotted : line.style_dashed
ex0 = i_ex0 == "1 Day" ? extend.none : i_ex0 == "2 Days" ? extend.none : i_ex0 == "Right" ? extend.right : extend.both
htime0 = i_ex0 == "2 Days" ? 172800000 : 86400000
hourtime0 = label.style_none
// CALC
var openprice0 = 0.0
if nymid0
if not nymid0
openprice0 := open
else
openprice0 := math.max(open, openprice0)
// OBJECTS
var label lb0 = na
if openprice0 != openprice0
var line lne0 = na
line.set_x2(lne0, nymid0)
line.set_extend(lne0, extend.none)
if i_vline0 and nymid0 == nymid0
vl10 = line.new(nymid0, high, nymid0, low, xloc.bar_time, extend.both, i_vcol0, vstyle0, 1)
if line.get_y1(vl10) == line.get_y2(vl10)
line.delete(vl10)
///////////////////////////////////////////////////////////////////////////////////////////////
//CLOSE MAX 8:45
// INPUTS
i_time1 = input.session ('0845-0846:1234567', "END", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz1 = i_tz
i_vline1 = i_vline
i_vcol1 = i_vcol
i_txtcol1 = i_txtcol
i_vstyle1 = i_vstyle
i_hline1 = label.style_none
i_linecol1 = label.style_none
i_linestyle1 = label.style_none
i_ex1 = label.style_none
i_ex21 = label.style_none
i_ex31 = label.style_none
// MISC
nymid1 = time ("1", i_time1, i_tz1)
linestyle1 = i_linestyle1 == "Solid" ? line.style_solid : i_linestyle1 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle1 = i_vstyle1 == "Solid" ? line.style_solid : i_vstyle1 == "Dotted" ? line.style_dotted : line.style_dashed
ex1 = i_ex1 == "1 Day" ? extend.none : i_ex1 == "2 Days" ? extend.none : i_ex1 == "Right" ? extend.right : extend.both
htime1 = i_ex1 == "2 Days" ? 172800000 : 86400000
hourtime1 = label.style_none
// CALC
var openprice1 = 0.0
if nymid1
if not nymid1
openprice1 := open
else
openprice1 := math.max(open, openprice1)
// OBJECTS
var label lb1 = na
if openprice1 != openprice1
var line lne1 = na
line.set_x2(lne1, nymid1)
line.set_extend(lne1, extend.none)
if i_vline1 and nymid1 == nymid1
vl11 = line.new(nymid1, high, nymid1, low, xloc.bar_time, extend.both, i_vcol1, vstyle1, 1)
if line.get_y1(vl11) == line.get_y2(vl11)
line.delete(vl11)
// EN
Choppy Lights by Stay ToxicMACD Angle Fluidity Index (MACD-AFI)
This proprietary indicator measures the stability and fluidity of momentum by analyzing the acceleration (or rate of change) of the MACD's Diff Line (Histogram). It is a non-lagging confirmation tool designed to help traders quickly identify market conditions suitable for directional trades (Green) versus those that are chaotic or trendless (Red). The score is normalized from 0 (Most Stable Angle) to 100 (Most Abrupt Angle Change).
How It Works
The indicator uses a robust background coloring system based on the calculated momentum angle change:
Angle Change Score (0-100): A custom formula calculates the difference between the current angle (slope) of the MACD Diff line and its previous angle. This "Angle Change" is then scaled from 0 to 100 based on the highest recent volatility observed, giving you a consistent fluidity reading.
Constancy Filter: A user-defined Constancy Period prevents flickering. The background color will only change if the calculated condition has been sustained for the specified number of bars.
Visual Alerts: The colors reflect your trading risk tolerance:
🟢 GREEN (Trade): Low Score (0 to Max Green). HIGH FLUIDITY. Angle is very stable. Momentum is smooth and predictable. Ideal conditions for trading.
🟡 YELLOW (Beware): Mid Score. MODERATE RISK. Angle is changing slightly. Momentum is slowing or uncertain. Exercise caution.
🔴 RED (Stay Out): High Score (Above Max Yellow). LOW FLUIDITY. Angle is abrupt (high volatility). Suggests chaotic action, whipsaws, or potential reversals. Avoid entering trades.
Customizable Inputs
The indicator provides complete control for calibration:
MACD & Angle Sensitivity: Adjust the standard MACD lengths, plus the Pente Period (for angle calculation smoothing) and Normalization Period (for setting the 0-100 scale).
Thresholds: Precise control over Max Green and Max Yellow values to define your trading zones.
Time Filter: The Constancy Period ensures changes are confirmed over a defined number of bars.
Visuals: Separate controls for color and global opacity.
MTF OB & FVG detector w/ Alerts v2# MTF OB & FVG Detector with Alerts(マルチタイムフレーム オーダーブロック&フェアバリューギャップ検出器)
## 概要
このインジケーターは、複数の時間足で**オーダーブロック(OB)**と**フェアバリューギャップ(FVG)**を検出し、これらのゾーンからの反発をリアルタイムでアラート通知します。高度なボリューム分析とマルチタイムフレーム分析を組み合わせ、高確率のサポート・レジスタンスゾーンを特定します。
## 主な機能
### 1. マルチタイムフレーム オーダーブロック検出
- **対応時間足**: 1分、3分、5分、15分、60分
- 各時間足を個別に有効/無効化可能
- 正確な価格レベルでOBゾーンを自動表示
- ブル/ベア比率の内訳を含むボリューム情報表示
- タイプ別色分け: ブリッシュ(青)/ ベアリッシュ(赤)- 反転可能
### 2. フェアバリューギャップ(FVG)検出
- 現在のチャート時間足でブリッシュ・ベアリッシュFVGパターンを検出
- ギャップ内のボリューム分布を表示
- 色分け: ブリッシュ(アクア)/ ベアリッシュ(オレンジ)- 反転可能
- ミティゲート/ブレイクされたFVGを自動削除
- **注意**: 1分足チャートではデフォルトでFVGは無効化されていますが、設定で有効化できます。
### 3. インテリジェントなブレイク検出
- **オーダーブロック**: 価格がゾーンを突破すると自動削除
- ブリッシュOB: 価格が下に抜けると削除
- ベアリッシュOB: 価格が上に抜けると削除
- **フェアバリューギャップ**: 価格がギャップを完全にミティゲートすると削除
- ブレイク方法の設定: ヒゲベースまたは実体ベース
### 4. 高度なアラートシステム
- **反発アラート**: 価格がOBまたはFVGゾーンから反発した際にトリガー
- ブリッシュとベアリッシュで個別アラート
- アラートメッセージに時間足情報を含む
- 有効化されたすべての時間足を同時監視
- **新規OB形成アラート**: 新しいオーダーブロックが形成されたときに通知
- **統合ゾーンアラート**: 複数のOBが統合されたときに通知
- **設定可能な閾値**: 最小OB統合数を設定(デフォルト: 3、範囲: 2-10)
- 複数時間足にわたる強力なコンフルエンスゾーンを示す
- 高確率のサポート/レジスタンスエリアを警告
- より多くのOBが統合 = より強力なゾーン = より高いアラート優先度
- すべてのアラートを個別に有効/無効化可能
### 5. ビジュアルカスタマイズ
- **テキスト表示**: 現在時刻の3バー右から左寄せで表示
- **ゾーン延長**: 40バー先まで延長(設定可能)
- **色の反転**:
- OB: 青/赤 または 赤/青 の切り替え
- FVG: アクア/オレンジ または オレンジ/アクア の切り替え
- **下位時間足表示**: 1分足と3分足ゾーンのオプション表示
### 6. ボリューム分析
- 各OBにブル/ベア比率を含む総ボリュームを表示
- パーセンテージ内訳で優勢なボリューム側を表示
- FVGはギャップ全体のボリューム分布を表示
#### テキスト表示の見方
**オーダーブロックのテキスト形式:** ` 5m OB 12.5M (85%)`
- ** **: 複数の時間足が統合された場合に表示(オプション表示)
- **5m OB**: 時間足の識別子(5分足オーダーブロック)
- **12.5M**: OBゾーンで取引された総ボリューム(常に百万単位で小数点第1位まで表示)
- 例: 12.5M、0.8M、156.3M
- **(85%)**: 優勢(強い側)のボリュームの割合
- ブリッシュOBの場合: ブリッシュボリュームの割合(強い側)
- ベアリッシュOBの場合: ベアリッシュボリュームの割合(強い側)
- パーセンテージが高い = より強力なOB(一方的なボリューム)
**フェアバリューギャップのテキスト形式:** `15m FVG 8.3M (85%)`
- **15m FVG**: 時間足の識別子(15分足フェアバリューギャップ)
- **8.3M**: FVGの総ボリューム(常に百万単位で小数点第1位まで表示)
- 例: 8.3M、1.2M、45.7M
- **(85%)**: 優勢(強い側)のボリュームの割合
- ブリッシュFVGの場合: ブリッシュボリュームの割合(強い側)
- ベアリッシュFVGの場合: ベアリッシュボリュームの割合(強い側)
- パーセンテージが高い = より強力なFVG(一方的なボリューム)
## 使用方法
### 基本セットアップ
1. **チャートに追加**: TradingViewのインジケーターで「MTF OB & FVG detector」を検索
2. **時間足を選択**: 希望の時間足を有効化(デフォルト: 5分、15分、60分)
3. **アラート設定**: 反発と新規OB形成のアラートを有効化
### 設定ガイド
#### マルチタイムフレーム設定
- **Show Lower Timeframes**: 1分足と3分足ゾーンを表示(デフォルト: ON)
- **各時間足**: 各時間足(1m, 3m, 5m, 15m, 60m)の個別切り替え
- 推奨: チャートの混雑を避けるため2-3個の時間足を使用
#### 一般設定
- **Zone Count**: 時間足あたりのOB数(Low/Medium/High)
- Medium(5ゾーン): 複数時間足使用時に推奨
- High(10ゾーン): 少数時間足での詳細分析用
- **Swing Length**: OB検出の感度(デフォルト: 3)
- 低い値 = より小さく、より頻繁なOB
- 高い値 = より大きく、より少数のOB
- **Break Detection Method**: OB無効化にWickまたはBodyを選択
#### フェアバリューギャップ設定
- **Show Fair Value Gaps**: FVG表示の切り替え
- デフォルト: ON(すべての時間足)
- **Show FVG on 1-Minute Charts**: 1分足チャートでのFVG表示を有効化
- デフォルト: OFF(視覚的な混雑を減らしパフォーマンスを向上させるため無効)
- 1分足でもFVGを表示したい場合は有効化してください
- **Mitigation Source**: FVG無効化に終値またはhigh/lowを選択
- **Individual Gap Types**: ブリッシュまたはベアリッシュFVGを個別に有効/無効化
#### アラート設定
- **Enable Alerts**: すべてのアラートのマスタースイッチ
- **Alert on Bullish/Bearish Bounce**: 各方向の個別切り替え
- **Alert on New OB Formation**: 新しいOBが作成されたときに通知
- **Alert on Combined OBs**: 複数のOrder Blockが1つの強力なゾーンに統合されたときに通知
- **Min OBs for Strong Zone Alert**: アラートをトリガーするために必要な最小OB統合数を設定
- デフォルト: 3(3つ以上のOB)
- 範囲: 2-10
- 値が高い = より厳選的、最も強力なコンフルエンスゾーンのみをアラート
#### スタイル設定
- **Invert Colors**:
- OB: デフォルトはブリッシュ=赤、ベアリッシュ=青
- FVG: デフォルトはブリッシュ=オレンジ、ベアリッシュ=アクア
- **Extend Zones**: ゾーンを前方に延長するバー数(デフォルト: 40)
### トレーディング戦略
#### 1. 統合ゾーンでの反転取引
- 「Combine Overlapping Order Blocks」機能を有効化
- 統合ゾーン(例:「5m & 15m & 1H」)は強力なサポート/レジスタンスを示す
- これらのゾーンは重要な転換点を示すことが多い
- 価格が高ボリュームで統合ゾーンにタッチするのを待つ
- 反転確認(ローソク足パターン、モメンタムダイバージェンス)でエントリー
- ストップロスは直近安値、直近高値を指定する等の高度な判断が必要(ゾーン端をストップロスにすると値幅が大きくなってしまうため)
#### 2. FVGフィリング
- FVGは価格の磁石として機能
- 未充填のギャップに向けてトレード
- 価格がギャップを完全に埋めたら決済
#### 3. OB/FVGを使ったトレンドフォロー
- 現在のトレンド方向を特定
- トレンド方向のOB/FVGからの反発のみを取引
- 上昇トレンド: ブリッシュ反発のみを取引
- 下降トレンド: ベアリッシュ反発のみを取引
- 上位時間足のOB(15分、60分)をトレンド確認に使用
- 下位時間足のOB(1分、3分)を精密なエントリーに使用
- 移動平均線やトレンドインジケーターと組み合わせると最良の結果
## 技術詳細
### オーダーブロックのロジック
- 設定可能なスイング長を使用してスイング高値/安値を検出
- 価格移動前のボリューム蓄積ゾーンを特定
- ブレイカーキャンドルでブレイクアウト確認を追跡
- 無効化されたゾーンを自動削除
### フェアバリューギャップのロジック
- キャンドル1と3の間にギャップがある3キャンドルパターンを識別
- 有効性のための最小ギャップサイズが必要
- 価格がギャップを通過する際のミティゲーションを追跡
- ギャップの強度のためのボリューム加重分析
### メモリ最適化
- 最大100個のボックス/ラベル/ラインを同時表示
- ブレイクされたゾーンの自動クリーンアップ
- 複数時間足でのパフォーマンスに最適化
- 効率的な配列管理
## ベストプラクティス
1. **シンプルに始める**: 最初は2-3個の時間足から始める
2. **ゾーン数を調整**: 多くの時間足を有効化する場合は「Medium」または「Low」を使用
3. **反発を確認**: アラートだけでトレードせず、価格確認を待つ
4. **ストップロスを使用**: 必ずゾーン境界を超えてストップを設定
5. **バックテスト**: ライブトレード前に過去データでテスト
6. **他のツールと組み合わせ**: トレンドインジケーター、ボリュームプロファイルなどと併用
## 制限事項
- 同時に最大100個のボックスを表示可能
- FVG検出は現在のチャート時間足に限定
- 有効化する時間足が多いほど、時間足あたりに表示できるゾーンが少なくなる
- ボックス上限に達すると、過去のゾーンが消える場合がある
## サポートとアップデート
質問、バグレポート、または機能リクエストについては、インジケーターページにコメントするか、作成者に連絡してください。
## クレジット
このインジケーターは、以下の優れたTradingViewインジケーターの機能を統合・強化しています:
- ** ()** by @fluxchart
- ボリューム情報を含むオーダーブロック検出ロジック
- マルチタイムフレームレンダリング機能
- ゾーン無効化メソッド
- ** ()** by @BigBeluga
- フェアバリューギャップ検出アルゴリズム
- ボリューム分解分析
- ミティゲーション追跡システム
その他、以下のコンセプトに基づいています:
- スマートマネーコンセプト(SMC)
- 機関投資家のオーダーフロー
- ボリュームプロファイル分析
オープンソースでトレーディングコミュニティに貢献してくださった原作者の方々に感謝いたします。
## 免責事項
このインジケーターは教育目的のみです。過去のパフォーマンスは将来の結果を示すものではありません。常に適切なリスク管理を実践し、失う余裕のない金額以上をリスクにさらさないでください。
---
**バージョン**: 1.0
**Pine Scriptバージョン**: 6
**チャートタイプ**: すべて
**時間足**: すべて(マルチタイムフレーム分析)
---
# MTF OB & FVG Detector with Alerts
## Overview
This indicator detects **Order Blocks (OB)** and **Fair Value Gaps (FVG)** across multiple timeframes and provides real-time alerts for bounces from these zones. It combines advanced volume analysis with multi-timeframe analysis to identify high-probability support and resistance zones.
## Key Features
### 1. Multi-Timeframe Order Block Detection
- **Supported Timeframes**: 1min, 3min, 5min, 15min, 60min
- Each timeframe can be independently enabled/disabled
- Automatically displays OB zones with precise price levels
- Volume information displayed with bull/bear percentage breakdown
- Color-coded by type: Bullish (Blue) / Bearish (Red) - invertible
### 2. Fair Value Gap (FVG) Detection
- Detects bullish and bearish FVG patterns on current chart timeframe
- Displays volume distribution within gaps
- Color-coded: Bullish (Aqua) / Bearish (Orange) - invertible
- Automatically removes mitigated/broken FVGs
- **Note**: FVG is disabled by default on 1-minute charts to reduce visual clutter, but can be enabled via settings.
### 3. Intelligent Break Detection
- **Order Blocks**: Automatically removed when price breaks through the zone
- Bullish OB: Removed when price breaks below
- Bearish OB: Removed when price breaks above
- **Fair Value Gaps**: Removed when price fully mitigates the gap
- Configurable break method: Wick-based or Body-based
### 4. Advanced Alert System
- **Bounce Alerts**: Triggered when price bounces from OB or FVG zones
- Separate alerts for bullish and bearish bounces
- Includes timeframe information in alert message
- Monitors all enabled timeframes simultaneously
- **New OB Formation Alerts**: Notified when a new Order Block is formed
- **Combined Zone Alerts**: Notified when multiple OBs are combined
- **Configurable threshold**: Set minimum number of OBs (default: 3, range: 2-10)
- Indicates strong confluence zones across multiple timeframes
- Signals high-probability support/resistance areas
- More OBs combined = stronger zone = higher alert priority
- All alerts can be individually enabled/disabled
### 5. Visual Customization
- **Text Display**: Left-aligned text starting 3 bars from current time
- **Zone Extension**: 40 bars forward (configurable)
- **Color Inversion**:
- OB: Toggle between Blue/Red or Red/Blue
- FVG: Toggle between Aqua/Orange or Orange/Aqua
- **Lower Timeframe Display**: Optional display of 1min and 3min zones
### 6. Volume Analysis
- Each OB displays total volume with bull/bear ratio
- Percentage breakdown shows dominant volume side
- FVG shows volume distribution across the gap
#### Understanding the Text Display
**Order Block Text Format:** ` 5m OB 12.5M (85%)`
- ** **: Appears when multiple timeframes are merged (optional display)
- **5m OB**: Timeframe identifier (5-minute Order Block)
- **12.5M**: Total volume traded in the OB zone (always in millions with 1 decimal place)
- Examples: 12.5M, 0.8M, 156.3M
- **(85%)**: Percentage of dominant (stronger) volume side
- If bullish: Shows proportion of bullish volume (stronger side)
- If bearish: Shows proportion of bearish volume (stronger side)
- Higher percentage = stronger OB (more one-sided volume)
**Fair Value Gap Text Format:** `15m FVG 8.3M (85%)`
- **15m FVG**: Timeframe identifier (15-minute Fair Value Gap)
- **8.3M**: Total volume in the FVG (always in millions with 1 decimal place)
- Examples: 8.3M, 1.2M, 45.7M
- **(85%)**: Percentage of dominant (stronger) volume side
- If bullish: Shows proportion of bullish volume (stronger side)
- If bearish: Shows proportion of bearish volume (stronger side)
- Higher percentage = stronger FVG (more one-sided volume)
## How to Use
### Basic Setup
1. **Add to Chart**: Search for "MTF OB & FVG detector" in TradingView indicators
2. **Select Timeframes**: Enable desired timeframes (default: 5min, 15min, 60min)
3. **Configure Alerts**: Enable alerts for bounces and new OB formations
### Settings Guide
#### Multi-Timeframe Settings
- **Show Lower Timeframes**: Enable to show 1min and 3min zones (default: ON)
- **Individual Timeframes**: Toggle each timeframe (1m, 3m, 5m, 15m, 60m)
- Recommended: Use 2-3 timeframes to avoid chart clutter
#### General Configuration
- **Zone Count**: Number of OBs per timeframe (Low/Medium/High)
- Medium (5 zones) recommended for multiple timeframes
- High (10 zones) for detailed analysis on fewer timeframes
- **Swing Length**: Sensitivity for OB detection (default: 3)
- Lower values = smaller, more frequent OBs
- Higher values = larger, fewer OBs
- **Break Detection Method**: Choose Wick or Body for OB invalidation
#### Fair Value Gap Settings
- **Show Fair Value Gaps**: Toggle FVG display
- Default: ON (for all timeframes)
- **Show FVG on 1-Minute Charts**: Enable FVG display on 1-minute charts
- Default: OFF (disabled to reduce visual clutter and improve performance)
- Enable if you want to see FVG on 1-minute charts
- **Mitigation Source**: Choose close price or high/low for FVG invalidation
- **Individual Gap Types**: Enable/disable bullish or bearish FVGs separately
#### Alert Settings
- **Enable Alerts**: Master switch for all alerts
- **Alert on Bullish/Bearish Bounce**: Separate toggles for each direction
- **Alert on New OB Formation**: Get notified when new OBs are created
- **Alert on Combined OBs**: Get notified when multiple Order Blocks are combined into one powerful zone
- **Min OBs for Strong Zone Alert**: Set the minimum number of OBs that must be combined to trigger the alert
- Default: 3 (three or more OBs)
- Range: 2-10
- Higher values = more selective, only alerting on the strongest confluence zones
#### Style Settings
- **Invert Colors**:
- OB: Default is Bullish=Red, Bearish=Blue
- FVG: Default is Bullish=Orange, Bearish=Aqua
- **Extend Zones**: Number of bars to extend zones forward (default: 40)
### Trading Strategies
#### 1. Reversal Trading at Combined Zones
- Enable "Combine Overlapping Order Blocks" feature
- Combined zones (e.g., "5m & 15m & 1H") indicate strong support/resistance
- These zones often mark significant turning points
- Wait for price to touch the combined zone with high volume
- Enter on reversal confirmation (candlestick patterns, momentum divergence)
- Stop-loss requires advanced judgment such as using recent lows/highs (placing stops at zone edges results in wide ranges)
#### 2. FVG Filling
- FVGs act as magnets for price
- Trade towards unfilled gaps as targets
- Exit when price fully fills the gap
#### 3. Trend Following with OB/FVG
- Identify the current trend direction
- Only take bounces from OBs/FVGs in trend direction
- In uptrend: Trade only bullish bounces
- In downtrend: Trade only bearish bounces
- Use higher timeframe OBs (15min, 60min) for trend confirmation
- Use lower timeframe OBs (1min, 3min) for precise entries
- Combine with moving averages or trend indicators for best results
## Technical Details
### Order Block Logic
- Detects swing highs/lows using configurable swing length
- Identifies volume accumulation zones before price moves
- Tracks breakout confirmation with breaker candles
- Automatically removes invalidated zones
### Fair Value Gap Logic
- Identifies 3-candle patterns with gap between candles 1 and 3
- Minimum gap size required for validity
- Tracks mitigation as price moves through the gap
- Volume-weighted analysis for gap strength
### Memory Optimization
- Maximum 100 boxes/labels/lines simultaneously
- Automatic cleanup of broken zones
- Optimized for performance with multiple timeframes
- Efficient array management
## Best Practices
1. **Start Simple**: Begin with 2-3 timeframes before adding more
2. **Adjust Zone Count**: Use "Medium" or "Low" when enabling many timeframes
3. **Confirm Bounces**: Don't trade on alerts alone - wait for price confirmation
4. **Use Stop Losses**: Always set stops beyond the zone boundaries
5. **Backtest**: Test the indicator on historical data before live trading
6. **Combine with Other Tools**: Use with trend indicators, volume profile, etc.
## Limitations
- Maximum of 100 boxes can be displayed simultaneously
- FVG detection is limited to current chart timeframe
- More timeframes enabled = fewer zones per timeframe can be shown
- Historical zones may disappear if box limit is reached
## Support and Updates
For questions, bug reports, or feature requests, please comment on the indicator page or contact the author.
## Credits
This indicator integrates and enhances features from the following excellent TradingView indicators:
- ** ()** by @fluxchart
- Order Block detection logic with volumetric information
- Multi-timeframe rendering capabilities
- Zone invalidation methods
- ** ()** by @BigBeluga
- Fair Value Gap detection algorithm
- Volume decomposition analysis
- Mitigation tracking system
Additional concepts based on:
- Smart Money Concepts (SMC)
- Institutional Order Flow
- Volume Profile Analysis
Special thanks to the original authors for their open-source contributions to the trading community.
## Disclaimer
This indicator is for educational purposes only. Past performance is not indicative of future results. Always practice proper risk management and never risk more than you can afford to lose.
---
**Version**: 1.0
**Pine Script Version**: 6
**Chart Type**: Any
**Timeframe**: Any (multi-timeframe analysis)
Dashboard — Vol & PriceDashboard for traders
Indicator Description
1. Prev Day High
What it shows: the previous trading day's high.
Why it shows: a resistance level. Many traders watch to see if the price will hold above or below this level. A breakout can signal buying strength.
2. Prev Day Low
What it shows: the previous day's low.
Why it shows: a support level. If the price breaks downwards, it signals weakness and a possible continuation of the decline.
3. Today
What it shows:
The difference between the current price and yesterday's close (in absolute values and as a percentage).
Color: green for an increase, red for a decrease.
Why it shows: immediately shows how strong a gap or movement is today relative to yesterday. This is an indicator of current momentum.
4. ADR, % (Average Daily Range)
What it shows: Average daily range (High – Low), expressed as a percentage of the closing price, for the selected period (default 7 days).
Why it's useful: To understand the "normal" volatility of an instrument. For example, if the ADR is 3%, then a 1% move is small, while a 6% move is very large.
5. ATR (Average True Range)
What it shows: Average fluctuation range (including gaps), in absolute points, for the specified period (default 7 days).
Why it's useful: A classic volatility indicator. Useful for setting stops, calculating position sizes, and identifying "noise" movements.
6. ATR (Today), %
What it shows: How much the current movement today (from yesterday's close to the current price) represents in % of the average ATR.
Why it shows: Shows whether the instrument has "played out" its average range. If the value is already >100%, there is a high probability that the movement will begin to slow.
7. Vol (Today)
What it shows:
Current trading volume for the day (in millions/billions).
Comparison with yesterday as a percentage (for example: 77.32M (-52.78%)).
Color: green if the volume is higher than yesterday; red if lower.
Why it shows:Quickly shows whether the market is active today. Volume = fuel for price movement.
8. Avg Vol (20d)
What it shows: Average daily volume over the last 20 trading days.
Why it's useful:"normal" activity level. It's a convenient backdrop for assessing today's turnover.
9. Rel. Vol (Today), % (Relative Volume)
What it shows: Deviation of the current volume from the average (20 days).
Formula: `(today / average - 1)` * 100`.
+30% = volume 30% above average, -40% = 40% below average.
Color: green for +, red for –.
Why it's useful:A key indicator for a trader. If RelVol > 100% (green), the market is "charged," and the movement is more significant. If low, activity is weak and movements are less reliable.
10. Normalized RS (Relative Strength)
What it shows: the relative strength of a stock to a selected benchmark (e.g., SPY), normalized by the period (default 7 days).
100 = same result as the market.
> 100 = the stock is stronger than the index.
<100 = weaker than the index.
Why it's needed: filtering ideas. Strong stocks rise faster when the market rises, weak stocks fall more sharply. This helps trade in the direction of the trend and select the best candidates.
In summary:
Prev High / Low — key support and resistance levels.
Today — an instant understanding of the current momentum.
ADR and ATR — volatility and potential movement.
ATR (Today) — how much the instrument has already "run."
Vol + Rel.Vol — activity and confirmation of the movement's strength.
RS — selecting strong/weak leaders against the market.
[FS] Pivot Measurements# Pivot Measurements
An advanced TradingView indicator that combines LuxAlgo's pivot point detection algorithm with automatic measurement calculations between consecutive pivots.
## Features
### Pivot Detection
- **Regular Pivots**: Detects standard pivot highs and lows using configurable pivot length
- **Missed Pivots**: Identifies missed reversal levels that occurred between regular pivots
- **Visual Indicators**:
- Regular pivot highs: Red downward triangle (▼)
- Regular pivot lows: Teal upward triangle (▲)
- Missed pivots: Ghost emoji (👻)
- **Zigzag Lines**: Connects pivots with colored lines (solid for regular, dashed for missed)
- **Ghost Levels**: Horizontal lines indicating missed pivot levels
### Measurement System
- **Automatic Measurements**: Calculates price movements between consecutive pivots
- **Visual Display**:
- Transparent colored boxes (blue for upward, red for downward movements)
- Measurement labels showing:
- Price change (absolute and percentage)
- Duration (bars, days, hours, minutes)
- Volume approximation
- **Smart Positioning**: Labels positioned outside boxes (above for upward, below for downward)
- **Color Coding**: Blue for positive movements, red for negative movements
## Parameters
### Pivot Detection
- **Pivot Length** (default: 50): Number of bars on each side to identify a pivot point
- **Regular Pivots**: Toggle and colors for regular pivot highs and lows
- **Missed Pivots**: Toggle and colors for missed pivot detection
### Measurements
- **Number of Measurements** (1-10, default: 10): Maximum number of measurements to display
- **Show Measurement Boxes**: Toggle to show/hide measurement boxes and labels
- **Box Transparency** (0-100, default: 90): Transparency level for measurement boxes
- **Border Transparency** (0-100, default: 50): Transparency level for box borders
- **Label Background Transparency** (0-100, default: 30): Transparency level for label backgrounds
- **Label Size**: Size of measurement labels (tiny, small, normal, large)
## Usage
1. Add the indicator to your chart
2. Configure the **Pivot Length** based on your timeframe:
- Lower values for shorter timeframes (e.g., 10-20 for 1-5 min)
- Higher values for longer timeframes (e.g., 50-100 for daily)
3. Adjust pivot colors and visibility as needed
4. Customize measurement display settings:
- Set the number of measurements to display
- Adjust transparency levels for boxes, borders, and labels
- Choose label size
## Technical Details
- **Pine Script Version**: v6
- **Pivot Detection**: Based on () algorithm for detecting regular and missed pivots
- **Measurement Calculation**:
- Measures between consecutive pivots (from most recent to older)
- Calculates price change, percentage change, duration, and approximate volume
- Automatically sorts pivots chronologically
- **Performance**: Optimized with helper functions to reduce code duplication
## Notes
- The indicator automatically limits the number of stored pivots to optimize performance
- Measurements are only created when there are at least 2 pivots detected
- All measurements are recalculated on each bar update
- The indicator uses `max_bars_back=5000` to ensure sufficient historical data
## License
This indicator uses LuxAlgo's pivot detection algorithm from (). Please refer to the original LuxAlgo license for pivot detection components.
Iron Condor & Butterfly VisualizerIt helps you visualize and manage your option spread by:
Plotting strike prices and breakeven lines directly on the chart.
Showing profit/loss zones, adjustment zones, and alerts when price nears critical levels.
Calculating risk/reward, probability of profit, theta decay, IV condition, and trade score.
🎯 2. Inputs & Configuration
You input your trade details as a comma-separated string:
For an Iron Condor
ShortCall, LongCall, ShortPut, LongPut, Credit, Contracts, Target%
Example: 626,628,620,618,1.20,1,30
For a Butterfly Spread
LowerWing, Body, UpperWing, Debit, Contracts, Target%
Example: 600,620,640,2.50,2,50
The indicator automatically parses this and knows which strategy type you selected.
You can also control:
Visuals (profit zones, breakevens, labels)
Risk (stop loss %, adjustment zones)
Account/risk sizing
Market conditions (IV Rank, current IV, DTE)
⚙️ 3. Data Parsing & Strategy Recognition
The code reads your pasted string, splits it by commas, and determines:
Which strikes are short vs long (or wings/body for Butterfly)
Whether the strategy is credit (Iron Condor) or debit (Butterfly)
Calculates net credit/debit, contract size, and profit target
📈 4. Profit/Loss Calculations
It dynamically calculates:
Max Profit
Iron Condor: net credit × 100 × contracts
Butterfly: (wing width − debit) × 100 × contracts
Max Loss
Iron Condor: difference between strikes minus credit
Butterfly: debit × 100 × contracts
Breakeven points
Iron Condor: short strikes ± net credit
Butterfly: body ± debit
Current P&L relative to the live price (close).
⚖️ 5. Risk & Position Sizing
It checks:
Stop-loss trigger (% of max loss)
Adjustment alert if price nears short strikes
Recommended contract size based on account size and % risk per trade
Actual % of account at risk
⏱️ 6. Time Decay & IV Analysis
If you input days to expiration, it shows:
Theta (approx daily time decay)
Decay progress bar (% of 30-day cycle)
IV condition:
Green: favorable (>50 IV Rank)
Yellow: neutral (30–50)
Red: poor (<30)
🧮 7. Trade Scoring
It gives a Trade Score (0–100) based on:
IV Rank (favorable market)
Risk/Reward ratio
Probability of profit
Default 20 baseline points
This helps gauge whether the setup is statistically attractive.
🧠 8. Visualizations
When the indicator runs, it draws on your chart:
Lines
Red = short strikes
Orange dashed = long strikes
Yellow dotted = breakeven levels
Boxes
Green = profit zone
Orange shaded = adjustment zones (approaching danger)
Labels (optional)
Strike labels (call/put prices)
Info box summarizing:
Profit, loss, risk/reward
Breakevens, theta, target, gamma risk flag
🚨 9. Alerts
The script triggers TradingView alerts when:
Price nears call or put adjustment zones
Profit target is hit
Stop loss is hit
These help you manage the trade without constant monitoring.
🧭 10. In Practice
You’d:
Copy the option strikes and trade details from your broker or analyzer.
Paste them into 📋 PASTE YOUR TRADE DATA HERE.
The indicator plots:
Profit/loss region
Adjustment warnings
Key metrics
Alerts if your trade is in danger or near target.
Simulated Fear & Greed (CNN-calibrated v2)🧭 Fear & Greed Index — TradingView Version (Simulated CNN Model)
🔍 Purpose
The Fear & Greed Index is a sentiment indicator that quantifies market emotion on a scale from 0 to 100, where:
0 represents Extreme Fear (capitulation, oversold conditions), and
100 represents Extreme Greed (euphoria, overbought conditions).
It helps traders assess whether the market is driven by fear (risk aversion) or greed (risk appetite) — giving a high-level view of potential turning points in market sentiment.
⚙️ How It Works in TradingView
Because TradingView cannot directly access CNN’s or alternative external sentiment feeds, this indicator simulates the Fear & Greed Index by analyzing in-chart technical data that reflect investor psychology.
It uses a multi-factor model, converting price and volume signals into a composite sentiment score.
🧩 Components Used (Simulated Metrics)
Category Metric Emotional Interpretation
Volatility ATR (Average True Range) High ATR = Fear, Low ATR = Greed
Momentum RSI + MACD Histogram Rising momentum = Greed, Falling = Fear
Volume Activity Volume Z-Score High positive deviation = Greed, Low = Fear
Trend Context SMA Regime Bias (50/200) Downtrend adds Fear penalty, Uptrend supports Greed
These elements are normalized into a 0–100 scale using percentile ranks (like statistical scoring) and then combined using user-adjustable weights.
⚖️ CNN-Style Calibration
The script follows CNN’s five sentiment bands for clarity:
Range Zone Colour Description
0–25 Extreme Fear 🔴 Red Panic, forced selling, capitulation risk
25–45 Fear 🟠 Orange Uncertainty, hesitation, early accumulation phase
45–55 Neutral ⚪ Gray Balanced sentiment, indecision
55–75 Greed 🟢 Light Green Optimism, trend continuation
75–100 Extreme Greed 💚 Bright Green Euphoria, risk of reversal
This structure aligns visually with CNN’s public gauge, making it easy to interpret.
Fear–Greed Index📈 Fear–Greed Index
This indicator provides a sophisticated, multi-faceted measure of market sentiment, plotting it as an oscillator that ranges from -100 (Extreme Fear) to +100 (Extreme Greed).
Unlike standard indicators like RSI or MACD, this tool is built on principles from behavioral finance and social physics to model the complex psychology of the market. It does not use any of TradingView's built-in math functions and instead calculates everything from scratch.
🤔 How It Works: The Three-Model Approach
The final index is a comprehensive blend of three different academic models, each calculated across three distinct time horizons (Short, Mid, and Long) to capture sentiment at different scales.
Prospect Theory (CPT): This model, based on Nobel Prize-winning work, evaluates how traders perceive gains and losses. It assumes that the pain of a loss is felt more strongly than the pleasure of an equal gain, modeling the market's asymmetric emotional response.
Herding (Brock–Durlauf): This component measures the "follow the crowd" instinct. It analyzes the synchronization of positive and negative returns to determine if traders are acting in a coordinated, "herd-like" manner, which is a classic sign of building fear or greed.
Social Impact Theory (SIT): This model assesses how social forces influence market participants.
It combines three factors:
Strength (S): The magnitude of recent price moves (volatility).
Immediacy (I): How recently the most significant price action occurred.
Number (N): The level of market participation (volume).
The indicator calculates all three models for a Short, Mid, and Long lookback period. It then aggregates these nine components (3 models x 3 timeframes) using customizable weights to produce a single, final Fear–Greed Index value.
Interpretar How to Read the Index
Main Line: This is the final FGI score.
Lime/Green: Indicates Greed (positive values).
Red: Indicates Fear (negative values).
Fading Color: The color becomes more transparent as the index approaches the '0' (Neutral) line, and more solid as it moves toward the extremes.
Key Zones:
+100 to +30 (Extreme Greed): The market is highly euphoric and potentially overbought. This can be a contrarian signal for caution or profit-taking.
+30 to +18 (Greed Zone): Strong bullish sentiment.
+18 to -18 (Neutral Zone): The market is undecided, or fear and greed are in balance.
-18 to -30 (Fear Zone): Strong bearish sentiment.
-30 to -100 (Extreme Fear): The market is in a state of panic and may be oversold. This can be a contrarian signal for potential buying opportunities.
Reference Plots: The indicator also plots the aggregated scores for each of the three models (Herding, Prospect, and SIT) as faint, secondary lines. This allows you to see which component is driving the overall sentiment.
⚙️ Settings & Customization
This indicator is highly tunable, allowing you to adjust its sensitivity and component makeup.
Time Windows:
Short window: Lookback period for short-term sentiment.
Mid window: Lookback for medium-term sentiment.
Long window: Lookback for long-term sentiment.
Model Aggregation Weights:
Weight CPT, Weight Herding, Weight SIT: Control how much each of the three behavioral models contributes to the final score (they should sum to 1.0).
Cross-Horizon Weights:
Weight Short, Weight Mid, Weight Long: Control the influence of each timeframe on the final score (they should also sum to 1.0).
EMA100 Breakout by shubhThis indicator is a clean, price-action-based breakout system designed for disciplined trend trading on any timeframe — especially for Nifty and Bank Nifty spot, futures, and options charts.
It uses a single 100-period EMA to define trend direction and waits for decisive candle closes across the EMA to trigger potential entries.
The logic ensures only one active trade at a time, enforcing patience and clarity in decision-making.
⚙️ Core Logic
Buy Setup
A bullish candle closes above the 100 EMA while its open was below the EMA.
Entry occurs at candle close.
Stop-Loss (SL): Low of the signal candle.
Target (TP): 4 × the SL distance (Risk : Reward = 1 : 4).
Sell Setup
A bearish candle closes below the 100 EMA while its open was above the EMA.
Entry occurs at candle close.
Stop-Loss (SL): High of the signal candle.
Target (TP): 4 × the SL distance.
Trade Management
Only one trade may run at a time (either long or short).
New signals are ignored until the current position hits SL or TP.
Transparent labels show Entry, SL, and TP levels on chart.
Dotted lines visualize active Stop-Loss (red) and Target (green).
Exit markers:
✅ Target Hit
❌ Stop Loss Hit
🧠 Key Advantages
Simple and transparent trend-following logic.
Enforces disciplined “one-trade-at-a-time” behavior.
High risk-to-reward (1 : 4).
Works across timeframes — 5 min to Daily.
Ideal for intraday and positional setups.
📊 Suggested Use
Apply on Nifty / Bank Nifty spot or futures charts.
Works on any instrument with clear momentum swings.
Best confirmation when EMA 100 acts as dynamic support/resistance.
⚠️ Disclaimer
This script is for educational and research purposes only.
It is not financial advice or an invitation to trade.
Always backtest thoroughly and manage risk responsibly before applying in live markets.
RRG Sector Snapshot RRG Sector Snapshot · Clear UI — User Guide
What this indicator does
Purpose: Visualize sector rotation by comparing each sector’s Relative Strength (RS-Ratio) and RS-Momentum versus a benchmark (e.g., VNINDEX).
Output: A quadrant map (table overlay) that positions each sector into one of four regimes:
LEADING (top-right): Strong and accelerating — leadership zone.
WEAKENING (bottom-right): Strong but decelerating — may be topping or consolidating.
LAGGING (bottom-left): Weak and decelerating — avoid unless mean-reverting.
IMPROVING (top-left): Weak but accelerating — candidates for next rotation into leadership.
How it works (under the hood)
X-axis (Strength): RS-Ratio = Sector Close / Benchmark Close, then normalized with a Z-Score over a lookback (normLen).
Y-axis (Momentum): Linear-regression slope of RS-Ratio over rsLen, then normalized with a Z-Score (normLen).
Mapping to grid: Both axes are Z-Scores scaled to a square grid (rrgSize × rrgSize) using a zoom factor (rrgScale). The center is neutral (0,0). Momentum increases upward (Y=0 is the top row in the table).
Quick start (3 minutes)
Add to chart:
TradingView → Pine Editor → paste the script → Save → Add to chart.
Set a benchmark: In inputs, choose Benchmark (X axis) — default INDEX:VNINDEX. Use VN30 or another index if it better reflects your universe.
Load sectors: Fill S1..S10 with sector or index symbols you track (up to 10). Set Slots to Use to the number you actually use.
Adjust view:
rrgSize (grid cells): 18–24 is a good starting point.
rrgScale (zoom): 2.5–3.5 typically; decrease to “zoom out” (points cluster near center), increase to “zoom in” (points spread to edges).
Read the map:
Prioritize sectors in LEADING; shortlist sectors in IMPROVING (could rotate into LEADING).
WEAKENING often marks late-cycle strength; LAGGING is typically avoid.
Inputs — what they do and how to change them
General
Analysis TF: Timeframe used to compute RRG (can be different from chart’s TF). Daily for swing, 1H/4H for tactical rotation, Weekly for macro view.
Benchmark (X axis): The index used for RS baseline (e.g., INDEX:VNINDEX, INDEX:VN30, major ETFs, or a custom composite).
RRG Calculation
RS Lookback (rsLen): Bars used for slope of RS (momentum).
Daily: 30–60 (default 40)
Intraday (1H/4H): 20–40
Weekly: 26–52
Normalization Lookback (Z-Score) (normLen): Window for Z-Score on both axes.
Daily: 80–120 (default 100)
Intraday: 40–80
Weekly: 52–104
Tip: Shorter lookbacks = more responsive but noisier; longer = smoother but slower.
RRG HUD (Table)
Show RRG Snapshot (rrgEnable): Toggle the table on/off.
Position (rrgPos): top_right | top_left | bottom_right | bottom_left.
Grid Size (Cells) (rrgSize): Table dimensions (N×N). Larger = more resolution but takes more space.
Z-Scale (Zoom) (rrgScale): Maps Z-Scores to the grid.
Smaller (2.0–2.5): Zoom out (more points near center).
Larger (3.5–4.0): Zoom in (emphasize outliers).
Appearance
Tag length (tagLen): Characters per sector tag. Use 4–6 for clarity.
Text size (textSizeOp): Tiny | Small | Normal | Large. Use Large for presentation screens or dense lists.
Axis thickness (axisThick): 1 = thin axis; 2 = thicker double-strip axis.
Quadrant alpha (bgAlpha): Transparency of quadrant backgrounds. 80–90 makes text pop.
Sectors (Max 10)
Slots to Use (sectorSlots): How many sector slots are active (≤10).
S1..S10: Each slot is a symbol (index, sector index, or ETF). Replace defaults to fit your market/universe.
How to interpret the map
Quadrants:
Leading (top-right): Relative strength above average and improving — trend-follow candidates.
Weakening (bottom-right): Still strong but momentum cooling — watch for distribution or pauses.
Lagging (bottom-left): Underperforming and still losing momentum — avoid unless doing mean-reversion.
Improving (top-left): Early recovery — candidates to transition into Leading if the move persists.
Overlapping sectors in one cell: The indicator shows “TAG +n” where TAG is the first tag, +n is the number of additional sectors sharing that cell. If many overlap:
Increase rrgSize, or
Decrease rrgScale to zoom out, or
Reduce Slots to Use to a smaller selection.
Suggested workflows
Daily swing
Benchmark: VNINDEX or VN30
rsLen 40–60, normLen 100–120, rrgSize 18–24, rrgScale 2.5–3.5
Routine:
Identify Leading sectors (top-right).
Spot Improving sectors near the midline moving toward top-right.
Confirm with price/volume/breakout on sector charts or top components.
Intraday (1H/4H) tactical
rsLen 20–40, normLen 60–100, rrgScale 2.0–3.0
Expect faster rotations and more noise; tighten filters with your own entry rules.
Weekly (macro rotation)
rsLen 26–52, normLen 52–104, rrgScale 3.0–4.0
Great for portfolio tilts and sector allocation.
Tuning tips
If everything clusters near center: Increase rrgScale (zoom in) or reduce normLen (more contrast).
If points are too spread: Decrease rrgScale (zoom out) or increase normLen (smoother normalization).
If the table is too big/small: Change rrgSize (cells).
If tags are hard to read: Increase textSizeOp to Large, tagLen to 5–6, and consider bgAlpha ~80–85.
Troubleshooting
No table on chart:
Ensure Show RRG Snapshot is enabled.
Change Position to a different corner.
Reduce Grid Size if the table exceeds the chart area.
Many sectors “missing”:
They’re likely overlapping in the same cell; the cell will show “TAG +n”.
Increase rrgSize, decrease rrgScale, or reduce Slots to Use.
Early bars show nothing:
You need enough data for rsLen and normLen. Scroll back or reduce lookbacks temporarily.
Best practices
Use RRG for context and rotation scouting, then confirm with your execution tools (trend structure, breakouts, volume, risk metrics).
Benchmark selection matters. If most of your watchlist tracks VN30, use INDEX:VN30 as the benchmark to get a truer relative read.
Revisit settings per timeframe. Intraday needs more responsiveness (shorter lookbacks, smaller Z-Scale); weekly needs stability (longer lookbacks, larger Z-Scale).
FAQ
Can I use ETFs or custom indices as sectors? Yes. Any symbol supported by TradingView works.
Can I track individual stocks instead of sectors? Yes (up to 10); just replace the S1..S10 symbols.
Why Z-Score? It standardizes each axis to “how unusual” the value is versus its own history — more robust than raw ratios across different scales.
[ i]
How to Set Up (Your Market Template)
This is the most important part for customizing the indicator to any market.
Step 1: Choose Your TF & Benchmark
Open the indicator's Settings.
Analysis TF: Set the timeframe you want to analyze (e.g., D for medium-term, W for long-term).
Benchmark (Trục X): This is the index you want to compare against.
Vietnamese Market: Leave the default INDEX:VNINDEX.
US Market: Change to SP:SPX or NASDAQ:NDX.
Crypto Market: Change to TOTAL (entire market cap) or BTC.D (Bitcoin Dominance).
Step 2: Input Your "Universe" (The 10 Slots)
This is where you decide what to track. You have 10 slots (S1 to S10).
For Vietnamese Sectors (Default):
Leave the default sector codes like INDEX:VNFINLEAD (Finance), INDEX:VNREAL (Real Estate), INDEX:VNIND (Industry), etc.
Template for Crypto "Sectors":
S1: BTC.D
S2: ETH.D
S3: TOTAL2 (Altcoin Market Cap)
S4: TOTAL.DEFI (DeFi)
S5: CRYPTOCAP:GAME (GameFi)
...and so on.
Template for Blue Chip Stocks:
Benchmark: INDEX:VN30
S1: HOSE:FPT
S2: HOSE:VCB
S3: HOSE:HPG
S4: HOSE:MWG
...and so on.
Template for Commodities:
Benchmark: TVC:DXY (US Dollar Index)
S1: TVC:GOLD
S2: TVC:USOIL
S3: TVC:SILVER
S4: COMEX:HG1! (Copper)
...and so on.
Step 3: Fine-Tuning
RS Lookback: A larger number (e.g., 100) gives a smoother, long-term view. A smaller number (e.g., 20) is more sensitive to short-term changes.
Z-Scale (Zoom): This is the "magnification" of the map.
If all your sectors are crowded in the middle, increase this number (e.g., 4.0) to "zoom in."
If your sectors are stuck on the edges, decrease this number (e.g., 2.0) to "zoom out."
Tag length: How many letters to display for the ticker (e.g., 4 will show VNFI).
Lot Size Calculator - Gold🥇 Lot Size Calculator for Gold (XAU/USD)
Description:
A professional and accurate lot size calculator specifically designed for Gold (XAU/USD) trading. This indicator helps traders calculate the optimal position size based on account balance, risk percentage, and stop loss distance, ensuring proper risk management for every trade.
Key Features:
Accurate Gold Calculations - Properly accounts for Gold pip values ($10 per pip for standard 100oz lots)
Multi-Currency Support - Works with USD, EUR, and GBP account currencies
Flexible Contract Sizes - Supports Standard (100 oz), Mini (10 oz), and Micro (1 oz) lots
Customizable Decimal Places - Display lot sizes with 2-8 decimal precision (no rounding)
Clean Visual Design - Modern, professional info panel with gold-themed styling
Adjustable Display - Position panel anywhere on chart with customizable colors and sizes
Real-Time Calculations - Instantly updates as you adjust your risk parameters
How It Works:
The calculator uses the standard forex position sizing formula optimized for Gold:
Lot Size = Risk Amount / (Stop Loss in Pips × Pip Value Per Lot)
For Gold (XAU/USD):
Standard Lot (100 oz): 1 pip = $10
Mini Lot (10 oz): 1 pip = $1
Micro Lot (1 oz): 1 pip = $0.10
Settings:
Account Settings:
Account Balance: Your trading capital
Account Currency: USD, EUR, or GBP
Risk Percentage: How much to risk per trade (default: 2%)
Contract Size: 100 oz (Standard), 10 oz (Mini), or 1 oz (Micro)
Display Currency: Choose how to display risk amounts
Trade Settings:
Stop Loss: Your SL distance in pips
Display Settings:
Label Position: Top/Bottom, Left/Right, Middle Right
Label Size: Tiny to Huge
Decimal Places: 2-8 decimals
Custom Colors: Background, text, and accent colors
Perfect For:
Gold (XAU/USD) day traders and swing traders
Position sizing and risk management
Traders using fixed percentage risk models
Anyone trading Gold CFDs or spot markets
Scalpers to long-term Gold investors
What Makes This Different:
Unlike generic lot size calculators, this tool correctly calculates Gold's pip values based on contract size. Many calculators get this wrong, leading to incorrect position sizing. This indicator ensures you're always trading the right lot size for your risk tolerance.
Example Usage:
Account Balance: $10,000
Risk: 1% = $100
Stop Loss: 60 pips
Contract Size: 100 oz (Standard)
Result: 0.1667 lots (exact, no rounding)
Perfect for maintaining consistent risk management in your Gold trading strategy!
Fixed High Timeframe Moving AveragesFixed High Timeframe Moving Averages (W/D/4H)
Summary
This indicator plots essential, high-timeframe (HTF) Moving Averages onto your chart, **no matter which timeframe you are currently viewing**.
It is designed for traders who need multi-timeframe context at a glance. Stop switching charts to see where the 200-Week or 50-Day MA is—now you can see all critical HTF levels directly on your 5-minute (or any other) chart.
---
Who it’s for
Traders who rely on moving averages but like to work on lower chart timeframes while keeping higher timeframe context in sight. If you scalp on 1–15m yet want Weekly/Daily/4H MAs always visible, this is for you.
---
What it shows
Pinned (“fixed”) moving averages from higher timeframes—Weekly (20/100/200) , Daily (50/100/200/365) and 4H (200) —rendered on any chart timeframe. Your favorite HTF MAs stay on screen no matter what TF you’re currently analyzing.
---
Features
* **MA types:** SMA, EMA, VWMA, Hull.
* **Fully configurable:** toggle each line, set periods, colors, and thickness.
* **Two alert modes (see below):** intrabar vs confirmed HTF close.
* **Works on any symbol & chart TF** using `request.security` to fetch HTF data.
---
Alerts & Modes
This indicator solves the biggest problem with MTF alerts: false signals. You can choose one of two modes:
1. **Intrabar mode** — compares current chart price to the HTF MA. Triggers as soon as price crosses the HTF line; great for early signals but may update until the HTF bar closes.
2. **Confirmed mode** — checks HTF close vs HTF MA. Signals only on the higher-TF bar close; fewer false starts, no intrabar repainting on that TF.
Per-line *Cross Above / Cross Below* conditions are provided for all enabled MAs (e.g., “20W — Cross Above”, “365D — Cross Below”, etc.).
**How to use alerts:** add the script → “Create Alert” → pick any condition from the script’s list.
---
Why this helps
* Keeps Weekly/Daily structure visible while you execute on LTF.
* Classic anchors (e.g., 200D, 20W/100W/200W) are popular for trend bias, dynamic support/resistance, and pullback context.
* Lets you standardize MA references across all your lower-TF playbooks.
---
Notes on confirmation & repainting
* Intrabar signals can change until the higher-TF bar closes (that’s expected with multi-TF data).
* Confirmed mode waits for the HTF close—cleaner, but later. Choose what fits your workflow.
---
Quick setup
1. Pick `MA Type` (SMA/EMA/VWMA/Hull).
2. Enable the HTF lines you want (Weekly 20/100/200; Daily 50/100/200/365; 4H 200).
3. Choose `Alert Mode` (Intrabar vs Confirmed).
4. Style colors/widths to taste and set alerts on the lines you care about.
---
Good practice
* Combine HTF MAs with price action (swings, structure, liquidity grabs) rather than using them in isolation.
* Always validate signals in your execution TF and use a risk plan tailored to volatility.
* Protect your capital: position sizing, stops, and disciplined risk management matter more than any single line on the chart.
---
Disclaimer
For educational/informational purposes only; not financial advice. Trading involves risk—manage it responsibly.
Trend Catch STFR - whipsaw Reduced### Summary of the Setup
This trading system combines **SuperTrend** (a trend-following indicator based on ATR for dynamic support/resistance), **Range Filter** (a smoothed median of the last 100 candles to identify price position relative to a baseline), and filters using **VIX Proxy** (a volatility measure: (14-period ATR / 14-period SMA of Close) × 100) and **ADX** (Average Directional Index for trend strength). It's designed for trend trading with volatility safeguards.
- **Entries**: Triggered only in "tradeable" markets (VIX Proxy ≥ 15 OR ADX ≥ 20) when SuperTrend aligns with direction (green for long, red for short), price crosses the Range Filter median accordingly, and you're not already in that position.
- **Exits**: Purely price-based—exit when SuperTrend flips or price crosses back over the Range Filter median. No forced exits from low volatility/trend.
- **No Trade Zone**: Blocks new entries if both VIX Proxy < 15 AND ADX < 20, but doesn't affect open positions.
- **Overall Goal**: Enter trends with confirmed strength/volatility, ride them via price action, and avoid ranging/choppy markets for new trades.
This creates a filtered trend-following strategy that prioritizes quality entries while letting winners run.
### Advantages
- **Reduces Noise in Entries**: The VIX Proxy and ADX filters ensure trades only in volatile or strongly trending conditions, avoiding low-momentum periods that often lead to false signals.
- **Lets Winners Run**: Exits based solely on price reversal (SuperTrend or Range Filter) allow positions to stay open during temporary lulls in volatility/trend, potentially capturing longer moves.
- **Simple and Balanced**: Combines trend (SuperTrend/ADX), range (Filter), and volatility (VIX Proxy) without overcomplicating—easy to backtest and adapt to assets like stocks, forex, or crypto.
- **Adaptable to Markets**: The "OR" logic for VIX/ADX provides flexibility (e.g., enters volatile sideways markets if ADX is low, or steady trends if VIX is low).
- **Risk Control**: Implicitly limits exposure by blocking entries in calm markets, which can preserve capital during uncertainty.
### Disadvantages
- **Whipsaws in Choppy Markets**: As you noted, SuperTrend can flip frequently in ranging conditions, leading to quick entries/exits and small losses, especially if the Range Filter isn't smoothing enough noise.
- **Missed Opportunities**: Strict filters (e.g., requiring VIX ≥ 15 or ADX ≥ 20) might skip early-stage trends or low-volatility grinds, reducing trade frequency and potential profits in quiet bull/bear markets.
- **Lagging Exits**: Relying only on price flips means you might hold losing trades longer if volatility drops without a clear reversal, increasing drawdowns.
- **Parameter Sensitivity**: Values like VIX 15, ADX 20, or Range Filter's 100-candle lookback need tuning per asset/timeframe; poor choices could amplify whipsaws or over-filter.
- **No Built-in Risk Management**: Lacks explicit stops/targets, so it relies on user-added rules (e.g., ATR-based stops), which could lead to oversized losses if not implemented.
### How to Use It
This system can be implemented in platforms like TradingView (via Pine Script), Python (e.g., with TA-Lib or Pandas), or MT4/5. Here's a step-by-step guide, assuming TradingView for simplicity—adapt as needed. (If coding in Python, use libraries like pandas_ta for indicators.)
1. **Set Up Indicators**:
- Add SuperTrend (default: ATR period 10, multiplier 3—adjust as suggested in prior tweaks).
- Create Range Filter: Use a 100-period SMA of (high + low)/2, smoothed (e.g., via EMA if desired).
- Calculate VIX Proxy: Custom script for (ATR(14) / SMA(close, 14)) * 100.
- Add ADX (period 14, standard).
2. **Define Rules in Code/Script**:
- **Long Entry**: If SuperTrend direction < 0 (green), close > RangeFilterMedian, (VIX Proxy ≥ 15 OR ADX ≥ 20), and not already long—buy on bar close.
- **Short Entry**: If SuperTrend direction > 0 (red), close < RangeFilterMedian, (VIX Proxy ≥ 15 OR ADX ≥ 20), and not already short—sell short.
- **Exit Long**: If in long and (SuperTrend > 0 OR close < RangeFilterMedian)—sell.
- **Exit Short**: If in short and (SuperTrend < 0 OR close > RangeFilterMedian)—cover.
- Monitor No Trade Zone visually (e.g., plot yellow background when VIX < 15 AND ADX < 20).
3. **Backtest and Optimize**:
- Use historical data on your asset (e.g., SPY on 1H chart).
- Test metrics: Win rate, profit factor, max drawdown. Adjust thresholds (e.g., ADX to 25) to reduce whipsaws.
- Forward-test on demo account to validate.
4. **Live Trading**:
- Apply to a chart, set alerts for entries/exits.
- Add risk rules: Position size 1-2% of capital, stop-loss at SuperTrend line.
- Monitor manually or automate via bots—avoid overtrading; use on trending assets.
For the adjustments I suggested earlier (e.g., ADX 25, 2-bar confirmation), integrate them into entries only—test one at a time to isolate improvements. If whipsaws persist, combine 2-3 tweaks.
Mean Reversion Oscillator [Alpha Extract]An advanced composite oscillator system specifically designed to identify extreme market conditions and high-probability mean reversion opportunities, combining five proven oscillators into a single, powerful analytical framework.
By integrating multiple momentum and volume-based indicators with sophisticated extreme level detection, this oscillator provides precise entry signals for contrarian trading strategies while filtering out false reversals through momentum confirmation.
🔶 Multi-Oscillator Composite Framework
Utilizes a comprehensive approach that combines Bollinger %B, RSI, Stochastic, Money Flow Index, and Williams %R into a unified composite score. This multi-dimensional analysis ensures robust signal generation by capturing different aspects of market extremes and momentum shifts.
// Weighted composite (equal weights)
normalized_bb = bb_percent
normalized_rsi = rsi
normalized_stoch = stoch_d_val
normalized_mfi = mfi
normalized_williams = williams_r
composite_raw = (normalized_bb + normalized_rsi + normalized_stoch + normalized_mfi + normalized_williams) / 5
composite = ta.sma(composite_raw, composite_smooth)
🔶 Advanced Extreme Level Detection
Features a sophisticated dual-threshold system that distinguishes between moderate and extreme market conditions. This hierarchical approach allows traders to identify varying degrees of mean reversion potential, from moderate oversold/overbought conditions to extreme levels that demand immediate attention.
🔶 Momentum Confirmation System
Incorporates a specialized momentum histogram that confirms mean reversion signals by analyzing the rate of change in the composite oscillator. This prevents premature entries during strong trending conditions while highlighting genuine reversal opportunities.
// Oscillator momentum (rate of change)
osc_momentum = ta.mom(composite, 5)
histogram = osc_momentum
// Momentum confirmation
momentum_bullish = histogram > histogram
momentum_bearish = histogram < histogram
// Confirmed signals
confirmed_bullish = bullish_entry and momentum_bullish
confirmed_bearish = bearish_entry and momentum_bearish
🔶 Dynamic Visual Intelligence
The oscillator line adapts its color intensity based on proximity to extreme levels, providing instant visual feedback about market conditions. Background shading creates clear zones that highlight when markets enter moderate or extreme territories.
🔶 Intelligent Signal Generation
Generates precise entry signals only when the composite oscillator crosses extreme thresholds with momentum confirmation. This dual-confirmation approach significantly reduces false signals while maintaining sensitivity to genuine mean reversion opportunities.
How It Works
🔶 Composite Score Calculation
The indicator simultaneously tracks five different oscillators, each normalized to a 0-100 scale, then combines them into a smoothed composite score. This approach eliminates the noise inherent in single-oscillator analysis while capturing the consensus view of multiple momentum indicators.
// Mean reversion entry signals
bullish_entry = ta.crossover(composite, 100 - extreme_level) and composite < (100 - extreme_level)
bearish_entry = ta.crossunder(composite, extreme_level) and composite > extreme_level
// Bollinger %B calculation
bb_basis = ta.sma(src, bb_length)
bb_dev = bb_mult * ta.stdev(src, bb_length)
bb_percent = (src - bb_lower) / (bb_upper - bb_lower) * 100
🔶 Extreme Zone Identification
The system automatically identifies when markets reach statistically significant extreme levels, both moderate (65/35) and extreme (80/20). These zones represent areas where mean reversion has the highest probability of success based on historical market behavior.
🔶 Momentum Histogram Analysis
A specialized momentum histogram tracks the velocity of oscillator changes, helping traders distinguish between healthy corrections and potential trend reversals. The histogram's color-coded display makes momentum shifts immediately apparent.
🔶 Divergence Detection Framework
Built-in divergence analysis identifies situations where price and oscillator movements diverge, often signaling impending reversals. Diamond-shaped markers highlight these critical divergence patterns for enhanced pattern recognition.
🔶 Real-Time Information Dashboard
An integrated information table provides instant access to current oscillator readings, market status, and individual component values. This dashboard eliminates the need to manually check multiple indicators while trading.
🔶 Individual Component Display
Optional display of individual oscillator components allows traders to understand which specific indicators are driving the composite signal. This transparency enables more informed decision-making and deeper market analysis.
🔶 Adaptive Background Coloring
Intelligent background shading automatically adjusts based on market conditions, creating visual zones that correspond to different levels of mean reversion potential. The subtle color gradations make pattern recognition effortless.
1D
3D
🔶 Comprehensive Alert System
Multi-tier alert system covers confirmed entry signals, divergence patterns, and extreme level breaches. Each alert type provides specific context about the detected condition, enabling traders to respond appropriately to different signal strengths.
🔶 Customizable Threshold Management
Fully adjustable extreme and moderate levels allow traders to fine-tune the indicator's sensitivity to match different market volatilities and trading timeframes. This flexibility ensures optimal performance across various market conditions.
🔶 Why Choose AE - Mean Reversion Oscillator?
This indicator provides the most comprehensive approach to mean reversion trading by combining multiple proven oscillators with advanced confirmation mechanisms. By offering clear visual hierarchies for different extreme levels and requiring momentum confirmation for signals, it empowers traders to identify high-probability contrarian opportunities while avoiding false reversals. The sophisticated composite methodology ensures that signals are both statistically significant and practically actionable, making it an essential tool for traders focused on mean reversion strategies across all market conditions.
Volatility Channel Oscillator█ OVERVIEW
"Volatility Channel Oscillator" is a technical indicator that analyzes price volatility relative to dynamic price channels, displaying an oscillator, its moving average, and signals based on crossovers and divergences. The indicator offers customizable overbought and oversold levels, gradient visualization, and divergence detection, supported by alerts for key signals.
█ CONCEPTS
The VCO indicator creates dynamic price channels based on a moving average of the price (calculated as the arithmetic mean of the high and low prices: (high + low) / 2) and market volatility (measured as the average candle range and body size). These channels are not displayed on the chart but are used to calculate the oscillator value, which reflects the position of the closing price relative to the channel width, scaled to a range from -100 to +100, with the zero line as the central point. A moving average of the oscillator (SMA) smooths its values, enabling signals based on crossovers with the zero line or overbought/oversold levels. The indicator also detects divergences between price and the oscillator, which may indicate potential trend reversals. VCO is useful for identifying market momentum, reversal points, and trend confirmation, especially when combined with other technical analysis tools.
█ FEATURES
- Volatility Channels: Calculates invisible chart boundaries based on a simple moving average (SMA) of the price (high + low) / 2 and volatility (average candle range and body). The length parameter (default 30) sets the SMA length, and scale (default 200%) adjusts the channel width.
- Oscillator: Determines the oscillator value in the range of -100 to +100, indicating the closing price's position relative to the volatility channel. Displayed with dynamic coloring (green for positive values, red for negative).
- Oscillator Moving Average: A simple moving average (SMA) of the oscillator values, smoothing its movements. The signalLength parameter (default 20) defines the SMA length. Displayed in yellow with an optional gradient.
- Overbought/Oversold Levels: Configurable thresholds for the oscillator (overbought, default 50; oversold, default -50) and its moving average (maOverbought, default 30; maOversold, default -30), shown as horizontal lines with optional gradients. Band colors change dynamically (red for overbought, green for oversold, gray for neutral) based on the moving average's position relative to maOverbought/maOversold, reinforcing other signals.
- Divergences: Detects bullish (price forms a lower low, oscillator a higher low) and bearish (price forms a higher high, oscillator a lower high) divergences using pivots (pivotLength, default 2). Divergences are displayed with a delay equal to the pivot length; larger lengths increase reliability but delay signals. Use as additional confirmation.
Signals:
- Overbought/Oversold Crossovers: Green triangles (buy) when the oscillator crosses above the oversold level, red triangles (sell) when it crosses below the overbought level.
- Zero Line Crossovers: Buy/sell signals when the oscillator crosses the zero line upward (buy) or downward (sell).
- Moving Average Crossovers: Buy/sell signals when the oscillator's moving average crosses the zero line or the maOverbought/maOversold levels. Dynamic band color changes (red/green) at these crossovers reinforce other signals.
- Visualization: Gradient lines for the oscillator, its moving average, overbought/oversold levels, and zero line, with adjustable transparency. Gradient fill between the oscillator and zero line.
Divergence Labels: "Bull" (bullish) and "Bear" (bearish) labels with customizable color and transparency.
- Alerts: Built-in alerts for divergences, overbought/oversold crossovers, and zero line crossovers by the oscillator and its moving average.
█ HOW TO USE
Add to Chart: Apply the indicator via Pine Editor or the Indicators menu on TradingView.
Configure Settings:
- Channel and Oscillator Settings: Adjust the channel SMA length (length, default 30) and channel scaling (scale, default 200%). Increase scale for high-volatility markets.
- Threshold Levels: Set oscillator overbought (overbought, default 50) and oversold (oversold, default -50) levels, and moving average thresholds (maOverbought, default 30; maOversold, default -30).
- Divergence Settings: Enable/disable divergence detection (calculateDivergence) and set pivot length (pivotLength, default 2). Larger values increase reliability but delay signals.
- Signal Settings: Choose signal types (signalType): overbought/oversold, zero line, moving average, or all.
- Styling: Customize colors for the oscillator, moving average, horizontal levels, and divergence labels. Adjust gradient and fill transparency.
Interpreting Signals:
- Buy Signals: Green triangles below the bar when the oscillator or its moving average crosses above the oversold level or zero line.
- Sell Signals: Red triangles above the bar when the oscillator or its moving average crosses below the overbought level or zero line.
- Moving Average Signals: Green/red triangles when the moving average crosses maOverbought/maOversold levels, indicating potential reversals or trend continuation. Dynamic band color changes (red for overbought, green for oversold) at these crossovers reinforce other signals.
- Divergences: "Bull" (bullish) and "Bear" (bearish) labels indicate potential trend reversals with a delay based on pivot length. Use as confirmation.
- Overbought/Oversold Levels: Monitor price reactions in these zones as potential reversal points. Dynamic band color changes based on the moving average reinforce signals.
Signal Confirmation: Use VCO with other tools, such as pivot levels (for key turning points) or Fibonacci levels (for support/resistance zones).
█ APPLICATIONS
- Trend Trading: Zero line crossovers by the oscillator or its moving average identify momentum in uptrends or downtrends.
- Range Trading: Overbought/oversold levels help identify entry/exit points in sideways markets.
- Divergences: Use bullish/bearish divergences as additional confirmation of reversals, especially near key price levels.
- Trend Identification: To analyze trends over a longer perspective, increase the moving average length (signalLength) for more stable signals.
█ NOTES
- Test the indicator across different timeframes and markets to optimize parameters, such as length and scale, for your trading style.
- In strong trends, overbought/oversold levels may persist, requiring additional signal verification.
- Divergences are more reliable on higher timeframes (H4, D1), where market noise is reduced, but their delay requires caution.
- In low-liquidity markets, signals may be less effective, so use on high-liquidity assets is recommended.
Seasonality Heatmap [QuantAlgo]🟢 Overview
The Seasonality Heatmap analyzes years of historical data to reveal which months and weekdays have consistently produced gains or losses, displaying results through color-coded tables with statistical metrics like consistency scores (1-10 rating) and positive occurrence rates. By calculating average returns for each calendar month and day-of-week combination, it identifies recognizable seasonal patterns (such as which months or weekdays tend to rally versus decline) and synthesizes this into actionable buy low/sell high timing possibilities for strategic entries and exits. This helps traders and investors spot high-probability seasonal windows where assets have historically shown strength or weakness, enabling them to align positions with recurring bull and bear market patterns.
🟢 How It Works
1. Monthly Heatmap
How % Return is Calculated:
The indicator fetches monthly closing prices (or Open/High/Low based on user selection) and calculates the percentage change from the previous month:
(Current Month Price - Previous Month Price) / Previous Month Price × 100
Each cell in the heatmap represents one month's return in a specific year, creating a multi-year historical view
Colors indicate performance intensity: greener/brighter shades for higher positive returns, redder/brighter shades for larger negative returns
What Averages Mean:
The "Avg %" row displays the arithmetic mean of all historical returns for each calendar month (e.g., averaging all Januaries together, all Februaries together, etc.)
This metric identifies historically recurring patterns by showing which months have tended to rise or fall on average
Positive averages indicate months that have typically trended upward; negative averages indicate historically weaker months
Example: If April shows +18.56% average, it means April has averaged a 18.56% gain across all years analyzed
What Months Up % Mean:
Shows the percentage of historical occurrences where that month had a positive return (closed higher than the previous month)
Calculated as:
(Number of Months with Positive Returns / Total Months) × 100
Values above 50% indicate the month has been positive more often than negative; below 50% indicates more frequent negative months
Example: If October shows "64%", then 64% of all historical Octobers had positive returns
What Consistency Score Means:
A 1-10 rating that measures how predictable and stable a month's returns have been
Calculated using the coefficient of variation (standard deviation / mean) - lower variation = higher consistency
High scores (8-10, green): The month has shown relatively stable behavior with similar outcomes year-to-year
Medium scores (5-7, gray): Moderate consistency with some variability
Low scores (1-4, red): High variability with unpredictable behavior across different years
Example: A consistency score of 8/10 indicates the month has exhibited recognizable patterns with relatively low deviation
What Best Means:
Shows the highest percentage return achieved for that specific month, along with the year it occurred
Reveals the maximum observed upside and identifies outlier years with exceptional performance
Useful for understanding the range of possible outcomes beyond the average
Example: "Best: 2016: +131.90%" means the strongest January in the dataset was in 2016 with an 131.90% gain
What Worst Means:
Shows the most negative percentage return for that specific month, along with the year it occurred
Reveals maximum observed downside and helps understand the range of historical outcomes
Important for risk assessment even in months with positive averages
Example: "Worst: 2022: -26.86%" means the weakest January in the dataset was in 2022 with a 26.86% loss
2. Day-of-Week Heatmap
How % Return is Calculated:
Calculates the percentage change from the previous day's close to the current day's price (based on user's price source selection)
Returns are aggregated by day of the week within each calendar month (e.g., all Mondays in January, all Tuesdays in January, etc.)
Each cell shows the average performance for that specific day-month combination across all historical data
Formula:
(Current Day Price - Previous Day Close) / Previous Day Close × 100
What Averages Mean:
The "Avg %" row at the bottom aggregates all months together to show the overall average return for each weekday
Identifies broad weekly patterns across the entire dataset
Calculated by summing all daily returns for that weekday across all months and dividing by total observations
Example: If Monday shows +0.04%, Mondays have averaged a 0.04% change across all months in the dataset
What Days Up % Mean:
Shows the percentage of historical occurrences where that weekday had a positive return
Calculated as:
(Number of Positive Days / Total Days Observed) × 100
Values above 50% indicate the day has been positive more often than negative; below 50% indicates more frequent negative days
Example: If Fridays show "54%", then 54% of all Fridays in the dataset had positive returns
What Consistency Score Means:
A 1-10 rating measuring how stable that weekday's performance has been across different months
Based on the coefficient of variation of daily returns for that weekday across all 12 months
High scores (8-10, green): The weekday has shown relatively consistent behavior month-to-month
Medium scores (5-7, gray): Moderate consistency with some month-to-month variation
Low scores (1-4, red): High variability across months, with behavior differing significantly by calendar month
Example: A consistency score of 7/10 for Wednesdays means they have performed with moderate consistency throughout the year
What Best Means:
Shows which calendar month had the strongest average performance for that specific weekday
Identifies favorable day-month combinations based on historical data
Format shows the month abbreviation and the average return achieved
Example: "Best: Oct: +0.20%" means Mondays averaged +0.20% during October months in the dataset
What Worst Means:
Shows which calendar month had the weakest average performance for that specific weekday
Identifies historically challenging day-month combinations
Useful for understanding which month-weekday pairings have shown weaker performance
Example: "Worst: Sep: -0.35%" means Tuesdays averaged -0.35% during September months in the dataset
3. Optimal Timing Table/Summary Table
→ Best Month to BUY: Identifies the month with the lowest average return (most negative or least positive historically), representing periods where prices have historically been relatively lower
Based on the observation that buying during historically weaker months may position for subsequent recovery
Shows the month name, its average return, and color-coded performance
Example: If May shows -0.86% as "Best Month to BUY", it means May has historically averaged -0.86% in the analyzed period
→ Best Month to SELL: Identifies the month with the highest average return (most positive historically), representing periods where prices have historically been relatively higher
Based on historical strength patterns in that month
Example: If July shows +1.42% as "Best Month to SELL", it means July has historically averaged +1.42% gains
→ 2nd Best Month to BUY: The second-lowest performing month based on average returns
Provides an alternative timing option based on historical patterns
Offers flexibility for staged entries or when the primary month doesn't align with strategy
Example: Identifies the next-most favorable historical buying period
→ 2nd Best Month to SELL: The second-highest performing month based on average returns
Provides an alternative exit timing based on historical data
Useful for staged profit-taking or multiple exit opportunities
Identifies the secondary historical strength period
Note: The same logic applies to "Best Day to BUY/SELL" and "2nd Best Day to BUY/SELL" rows, which identify weekdays based on average daily performance across all months. Days with lowest averages are marked as buying opportunities (historically weaker days), while days with highest averages are marked for selling (historically stronger days).
🟢 Examples
Example 1: NVIDIA NASDAQ:NVDA - Strong May Pattern with High Consistency
Analyzing NVIDIA from 2015 onwards, the Monthly Heatmap reveals May averaging +15.84% with 82% of months being positive and a consistency score of 8/10 (green). December shows -1.69% average with only 40% of months positive and a low 1/10 consistency score (red). The Optimal Timing table identifies December as "Best Month to BUY" and May as "Best Month to SELL." A trader recognizes this high-probability May strength pattern and considers entering positions in late December when prices have historically been weaker, then taking profits in May when the seasonal tailwind typically peaks. The high consistency score in May (8/10) provides additional confidence that this pattern has been relatively stable year-over-year.
Example 2: Crypto Market Cap CRYPTOCAP:TOTALES - October Rally Pattern
An investor examining total crypto market capitalization notices September averaging -2.42% with 45% of months positive and 5/10 consistency, while October shows a dramatic shift with +16.69% average, 90% of months positive, and an exceptional 9/10 consistency score (blue). The Day-of-Week heatmap reveals Mondays averaging +0.40% with 54% positive days and 9/10 consistency (blue), while Thursdays show only +0.08% with 1/10 consistency (yellow). The investor uses this multi-layered analysis to develop a strategy: enter crypto positions on Thursdays during late September (combining the historically weak month with the less consistent weekday), then hold through October's historically strong period, considering exits on Mondays when intraweek strength has been most consistent.
Example 3: Solana BINANCE:SOLUSDT - Extreme January Seasonality
A cryptocurrency trader analyzing Solana observes an extraordinary January pattern: +59.57% average return with 60% of months positive and 8/10 consistency (teal), while May shows -9.75% average with only 33% of months positive and 6/10 consistency. August also displays strength at +59.50% average with 7/10 consistency. The Optimal Timing table confirms May as "Best Month to BUY" and January as "Best Month to SELL." The Day-of-Week data shows Sundays averaging +0.77% with 8/10 consistency (teal). The trader develops a seasonal rotation strategy: accumulate SOL positions during May weakness, hold through the historically strong January period (which has shown this extreme pattern with reasonable consistency), and specifically target Sunday exits when the weekday data shows the most recognizable strength pattern.
Stochastic Enhanced [DCAUT]█ Stochastic Enhanced
📊 ORIGINALITY & INNOVATION
The Stochastic Enhanced indicator builds upon George Lane's classic momentum oscillator (developed in the late 1950s) by providing comprehensive smoothing algorithm flexibility. While traditional implementations limit users to Simple Moving Average (SMA) smoothing, this enhanced version offers 21 advanced smoothing algorithms, allowing traders to optimize the indicator's characteristics for different market conditions and trading styles.
Key Improvements:
Extended from single SMA smoothing to 21 professional-grade algorithms including adaptive filters (KAMA, FRAMA), zero-lag methods (ZLEMA, T3), and advanced digital filters (Kalman, Laguerre)
Maintains backward compatibility with traditional Stochastic calculations through SMA default setting
Unified smoothing algorithm applies to both %K and %D lines for consistent signal processing characteristics
Enhanced visual feedback with clear color distinction and background fill highlighting for intuitive signal recognition
Comprehensive alert system covering crossovers and zone entries for systematic trade management
Differentiation from Traditional Stochastic:
Traditional Stochastic indicators use fixed SMA smoothing, which introduces consistent lag regardless of market volatility. This enhanced version addresses the limitation by offering adaptive algorithms that adjust to market conditions (KAMA, FRAMA), reduce lag without sacrificing smoothness (ZLEMA, T3, HMA), or provide superior noise filtering (Kalman Filter, Laguerre filters). The flexibility helps traders balance responsiveness and stability according to their specific needs.
📐 MATHEMATICAL FOUNDATION
Core Stochastic Calculation:
The Stochastic Oscillator measures the position of the current close relative to the high-low range over a specified period:
Step 1: Raw %K Calculation
%K_raw = 100 × (Close - Lowest Low) / (Highest High - Lowest Low)
Where:
Close = Current closing price
Lowest Low = Lowest low over the %K Length period
Highest High = Highest high over the %K Length period
Result ranges from 0 (close at period low) to 100 (close at period high)
Step 2: Smoothed %K Calculation
%K = MA(%K_raw, K Smoothing Period, MA Type)
Where:
MA = Selected moving average algorithm (SMA, EMA, etc.)
K Smoothing = 1 for Fast Stochastic, 3+ for Slow Stochastic
Traditional Fast Stochastic uses %K_raw directly without smoothing
Step 3: Signal Line %D Calculation
%D = MA(%K, D Smoothing Period, MA Type)
Where:
%D acts as a signal line and moving average of %K
D Smoothing typically set to 3 periods in traditional implementations
Both %K and %D use the same MA algorithm for consistent behavior
Available Smoothing Algorithms (21 Options):
Standard Moving Averages:
SMA (Simple): Equal-weighted average, traditional default, consistent lag characteristics
EMA (Exponential): Recent price emphasis, faster response to changes, exponential decay weighting
RMA (Rolling/Wilder's): Smoothed average used in RSI, less reactive than EMA
WMA (Weighted): Linear weighting favoring recent data, moderate responsiveness
VWMA (Volume-Weighted): Incorporates volume data, reflects market participation intensity
Advanced Moving Averages:
HMA (Hull): Reduced lag with smoothness, uses weighted moving averages and square root period
ALMA (Arnaud Legoux): Gaussian distribution weighting, minimal lag with good noise reduction
LSMA (Least Squares): Linear regression based, fits trend line to data points
DEMA (Double Exponential): Reduced lag compared to EMA, uses double smoothing technique
TEMA (Triple Exponential): Further lag reduction, triple smoothing with lag compensation
ZLEMA (Zero-Lag Exponential): Lag elimination attempt using error correction, very responsive
TMA (Triangular): Double-smoothed SMA, very smooth but slower response
Adaptive & Intelligent Filters:
T3 (Tilson T3): Six-pass exponential smoothing with volume factor adjustment, excellent smoothness
FRAMA (Fractal Adaptive): Adapts to market fractal dimension, faster in trends, slower in ranges
KAMA (Kaufman Adaptive): Efficiency ratio based adaptation, responds to volatility changes
McGinley Dynamic: Self-adjusting mechanism following price more accurately, reduced whipsaws
Kalman Filter: Optimal estimation algorithm from aerospace engineering, dynamic noise filtering
Advanced Digital Filters:
Ultimate Smoother: Advanced digital filter design, superior noise rejection with minimal lag
Laguerre Filter: Time-domain filter with N-order implementation, adjustable lag characteristics
Laguerre Binomial Filter: 6-pole Laguerre filter, extremely smooth output for long-term analysis
Super Smoother: Butterworth filter implementation, removes high-frequency noise effectively
📊 COMPREHENSIVE SIGNAL ANALYSIS
Absolute Level Interpretation (%K Line):
%K Above 80: Overbought condition, price near period high, potential reversal or pullback zone, caution for new long entries
%K in 70-80 Range: Strong upward momentum, bullish trend confirmation, uptrend likely continuing
%K in 50-70 Range: Moderate bullish momentum, neutral to positive outlook, consolidation or mild uptrend
%K in 30-50 Range: Moderate bearish momentum, neutral to negative outlook, consolidation or mild downtrend
%K in 20-30 Range: Strong downward momentum, bearish trend confirmation, downtrend likely continuing
%K Below 20: Oversold condition, price near period low, potential bounce or reversal zone, caution for new short entries
Crossover Signal Analysis:
%K Crosses Above %D (Bullish Cross): Momentum shifting bullish, faster line overtakes slower signal, consider long entry especially in oversold zone, strongest when occurring below 20 level
%K Crosses Below %D (Bearish Cross): Momentum shifting bearish, faster line falls below slower signal, consider short entry especially in overbought zone, strongest when occurring above 80 level
Crossover in Midrange (40-60): Less reliable signals, often in choppy sideways markets, require additional confirmation from trend or volume analysis
Multiple Failed Crosses: Indicates ranging market or choppy conditions, reduce position sizes or avoid trading until clear directional move
Advanced Divergence Patterns (%K Line vs Price):
Bullish Divergence: Price makes lower low while %K makes higher low, indicates weakening bearish momentum, potential trend reversal upward, more reliable when %K in oversold zone
Bearish Divergence: Price makes higher high while %K makes lower high, indicates weakening bullish momentum, potential trend reversal downward, more reliable when %K in overbought zone
Hidden Bullish Divergence: Price makes higher low while %K makes lower low, indicates trend continuation in uptrend, bullish trend strength confirmation
Hidden Bearish Divergence: Price makes lower high while %K makes higher high, indicates trend continuation in downtrend, bearish trend strength confirmation
Momentum Strength Analysis (%K Line Slope):
Steep %K Slope: Rapid momentum change, strong directional conviction, potential for extended moves but also increased reversal risk
Gradual %K Slope: Steady momentum development, sustainable trends more likely, lower probability of sharp reversals
Flat or Horizontal %K: Momentum stalling, potential reversal or consolidation ahead, wait for directional break before committing
%K Oscillation Within Range: Indicates ranging market, sideways price action, better suited for range-trading strategies than trend following
🎯 STRATEGIC APPLICATIONS
Mean Reversion Strategy (Range-Bound Markets):
Identify ranging market conditions using price action or Bollinger Bands
Wait for Stochastic to reach extreme zones (above 80 for overbought, below 20 for oversold)
Enter counter-trend position when %K crosses %D in extreme zone (sell on bearish cross above 80, buy on bullish cross below 20)
Set profit targets near opposite extreme or midline (50 level)
Use tight stop-loss above recent swing high/low to protect against breakout scenarios
Exit when Stochastic reaches opposite extreme or %K crosses %D in opposite direction
Trend Following with Momentum Confirmation:
Identify primary trend direction using higher timeframe analysis or moving averages
Wait for Stochastic pullback to oversold zone (<20) in uptrend or overbought zone (>80) in downtrend
Enter in trend direction when %K crosses %D confirming momentum shift (bullish cross in uptrend, bearish cross in downtrend)
Use wider stops to accommodate normal trend volatility
Add to position on subsequent pullbacks showing similar Stochastic pattern
Exit when Stochastic shows opposite extreme with failed cross or bearish/bullish divergence
Divergence-Based Reversal Strategy:
Scan for divergence between price and Stochastic at swing highs/lows
Confirm divergence with at least two price pivots showing divergent Stochastic readings
Wait for %K to cross %D in direction of anticipated reversal as entry trigger
Enter position in divergence direction with stop beyond recent swing extreme
Target profit at key support/resistance levels or Fibonacci retracements
Scale out as Stochastic reaches opposite extreme zone
Multi-Timeframe Momentum Alignment:
Analyze Stochastic on higher timeframe (4H or Daily) for primary trend bias
Switch to lower timeframe (1H or 15M) for precise entry timing
Only take trades where lower timeframe Stochastic signal aligns with higher timeframe momentum direction
Higher timeframe Stochastic in bullish zone (>50) = only take long entries on lower timeframe
Higher timeframe Stochastic in bearish zone (<50) = only take short entries on lower timeframe
Exit when lower timeframe shows counter-signal or higher timeframe momentum reverses
Zone Transition Strategy:
Monitor Stochastic for transitions between zones (oversold to neutral, neutral to overbought, etc.)
Enter long when Stochastic crosses above 20 (exiting oversold), signaling momentum shift from bearish to neutral/bullish
Enter short when Stochastic crosses below 80 (exiting overbought), signaling momentum shift from bullish to neutral/bearish
Use zone midpoint (50) as dynamic support/resistance for position management
Trail stops as Stochastic advances through favorable zones
Exit when Stochastic fails to maintain momentum and reverses back into prior zone
📋 DETAILED PARAMETER CONFIGURATION
%K Length (Default: 14):
Lower Values (5-9): Highly sensitive to price changes, generates more frequent signals, increased false signals in choppy markets, suitable for very short-term trading and scalping
Standard Values (10-14): Balanced sensitivity and reliability, traditional default (14) widely used,适合 swing trading and intraday strategies
Higher Values (15-21): Reduced sensitivity, smoother oscillations, fewer but potentially more reliable signals, better for position trading and lower timeframe noise reduction
Very High Values (21+): Slow response, long-term momentum measurement, fewer trading signals, suitable for weekly or monthly analysis
%K Smoothing (Default: 3):
Value 1: Fast Stochastic, uses raw %K calculation without additional smoothing, most responsive to price changes, generates earliest signals with higher noise
Value 3: Slow Stochastic (default), traditional smoothing level, reduces false signals while maintaining good responsiveness, widely accepted standard
Values 5-7: Very slow response, extremely smooth oscillations, significantly reduced whipsaws but delayed entry/exit timing
Recommendation: Default value 3 suits most trading scenarios, active short-term traders may use 1, conservative long-term positions use 5+
%D Smoothing (Default: 3):
Lower Values (1-2): Signal line closely follows %K, frequent crossover signals, useful for active trading but requires strict filtering
Standard Value (3): Traditional setting providing balanced signal line behavior, optimal for most trading applications
Higher Values (4-7): Smoother signal line, fewer crossover signals, reduced whipsaws but slower confirmation, better for trend trading
Very High Values (8+): Signal line becomes slow-moving reference, crossovers rare and highly significant, suitable for long-term position changes only
Smoothing Type Algorithm Selection:
For Trending Markets:
ZLEMA, DEMA, TEMA: Reduced lag for faster trend entry, quick response to momentum shifts, suitable for strong directional moves
HMA, ALMA: Good balance of smoothness and responsiveness, effective for clean trend following without excessive noise
EMA: Classic choice for trending markets, faster than SMA while maintaining reasonable stability
For Ranging/Choppy Markets:
Kalman Filter, Super Smoother: Superior noise filtering, reduces false signals in sideways action, helps identify genuine reversal points
Laguerre Filters: Smooth oscillations with adjustable lag, excellent for mean reversion strategies in ranges
T3, TMA: Very smooth output, filters out market noise effectively, clearer extreme zone identification
For Adaptive Market Conditions:
KAMA: Automatically adjusts to market efficiency, fast in trends and slow in congestion, reduces whipsaws during transitions
FRAMA: Adapts to fractal market structure, responsive during directional moves, conservative during uncertainty
McGinley Dynamic: Self-adjusting smoothing, follows price naturally, minimizes lag in trending markets while filtering noise in ranges
For Conservative Long-Term Analysis:
SMA: Traditional choice, predictable behavior, widely understood characteristics
RMA (Wilder's): Smooth oscillations, reduced sensitivity to outliers, consistent behavior across market conditions
Laguerre Binomial Filter: Extremely smooth output, ideal for weekly/monthly timeframe analysis, eliminates short-term noise completely
Source Selection:
Close (Default): Standard choice using closing prices, most common and widely tested
HLC3 or OHLC4: Incorporates more price information, reduces impact of sudden spikes or gaps, smoother oscillator behavior
HL2: Midpoint of high-low range, emphasizes intrabar volatility, useful for markets with wide intraday ranges
Custom Source: Can use other indicators as input (e.g., Heikin Ashi close, smoothed price), creates derivative momentum indicators
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
Responsiveness Characteristics:
Traditional SMA-Based Stochastic:
Fixed lag regardless of market conditions, consistent delay of approximately (K Smoothing + D Smoothing) / 2 periods
Equal treatment of trending and ranging markets, no adaptation to volatility changes
Predictable behavior but suboptimal in varying market regimes
Enhanced Version with Adaptive Algorithms:
KAMA and FRAMA reduce lag by up to 40-60% in strong trends compared to SMA while maintaining similar smoothness in ranges
ZLEMA and T3 provide near-zero lag characteristics for early entry signals with acceptable noise levels
Kalman Filter and Super Smoother offer superior noise rejection, reducing false signals in choppy conditions by estimations of 30-50% compared to SMA
Performance improvements vary by algorithm selection and market conditions
Signal Quality Improvements:
Adaptive algorithms help reduce whipsaw trades in ranging markets by adjusting sensitivity dynamically
Advanced filters (Kalman, Laguerre, Super Smoother) provide clearer extreme zone readings for mean reversion strategies
Zero-lag methods (ZLEMA, DEMA, TEMA) generate earlier crossover signals in trending markets for improved entry timing
Smoother algorithms (T3, Laguerre Binomial) reduce false extreme zone touches for more reliable overbought/oversold signals
Comparison with Standard Implementations:
Versus Basic Stochastic: Enhanced version offers 21 smoothing options versus single SMA, allowing optimization for specific market characteristics and trading styles
Versus RSI: Stochastic provides range-bound measurement (0-100) with clear extreme zones, RSI measures momentum speed, Stochastic offers clearer visual overbought/oversold identification
Versus MACD: Stochastic bounded oscillator suitable for mean reversion, MACD unbounded indicator better for trend strength, Stochastic excels in range-bound and oscillating markets
Versus CCI: Stochastic has fixed bounds (0-100) for consistent interpretation, CCI unbounded with variable extremes, Stochastic provides more standardized extreme readings across different instruments
Flexibility Advantages:
Single indicator adaptable to multiple strategies through algorithm selection rather than requiring different indicator variants
Ability to optimize smoothing characteristics for specific instruments (e.g., smoother for crypto volatility, faster for forex trends)
Multi-timeframe analysis with consistent algorithm across timeframes for coherent momentum picture
Backtesting capability with algorithm as optimization parameter for strategy development
Limitations and Considerations:
Increased complexity from multiple algorithm choices may lead to over-optimization if parameters are curve-fitted to historical data
Adaptive algorithms (KAMA, FRAMA) have adjustment periods during market regime changes where signals may be less reliable
Zero-lag algorithms sacrifice some smoothness for responsiveness, potentially increasing noise sensitivity in very choppy conditions
Performance characteristics vary significantly across algorithms, requiring understanding and testing before live implementation
Like all oscillators, Stochastic can remain in extreme zones for extended periods during strong trends, generating premature reversal signals
USAGE NOTES
This indicator is designed for technical analysis and educational purposes to provide traders with enhanced flexibility in momentum analysis. The Stochastic Oscillator has limitations and should not be used as the sole basis for trading decisions.
Important Considerations:
Algorithm performance varies with market conditions - no single smoothing method is optimal for all scenarios
Extreme zone signals (overbought/oversold) indicate potential reversal areas but not guaranteed turning points, especially in strong trends
Crossover signals may generate false entries during sideways choppy markets regardless of smoothing algorithm
Divergence patterns require confirmation from price action or additional indicators before trading
Past indicator characteristics and backtested results do not guarantee future performance
Always combine Stochastic analysis with proper risk management, position sizing, and multi-indicator confirmation
Test selected algorithm on historical data of specific instrument and timeframe before live trading
Market regime changes may require algorithm adjustment for optimal performance
The enhanced smoothing options are intended to provide tools for optimizing the indicator's behavior to match individual trading styles and market characteristics, not to create a perfect predictive tool. Responsible usage includes understanding the mathematical properties of selected algorithms and their appropriate application contexts.
Natural Gas Intraday Strategy [15m] with Partial Profit & TrailBuy when:
1. Close > EMA 100 and EMA 20 > EMA 100
2. MACD (8,21,5) > Signal and histogram rising
3. RSI > 60
4. ATR > threshold (avoid flat market)
Sell when:
1. Close < EMA 100 and EMA 20 < EMA 100
2. MACD (8,21,5) < Signal and histogram falling
3. RSI < 40
4. ATR > threshold
Exit:
• SL = recent swing ± 0.5 ATR
• TP1 = 1 ATR, trail rest with EMA 20
Multi-Timeframe Trend Table - EMA Based Trend Analysis📊 Stay Aligned with Higher Timeframe Trends While Scalping
This powerful indicator displays real-time trend direction for 1-hour and 4-hour timeframes in a clean, easy-to-read table format. Perfect for traders who want to align their short-term trades with higher timeframe momentum.
🎯 Key Features
Multi-Timeframe Analysis: Monitor 1H and 4H trends while trading on any timeframe (3min, 5min, 15min, etc.)
EMA-Based Logic: Uses proven EMA 50 and EMA 100 crossover methodology
Visual Clarity: Color-coded table with green (uptrend) and red (downtrend) indicators
Customizable Display: Toggle EMA values and adjust table position
Real-Time Updates: Automatically refreshes with each bar close
Lightweight: Minimal resource usage with efficient data requests
📈 How It Works
The indicator determines trend direction using a simple but effective rule:
UPTREND: Price is above both EMA 50 AND EMA 100
DOWNTREND: Price is below either EMA 50 OR EMA 100
🔧 Settings
Show EMA Values: Display actual EMA 50/100 values in the table
Table Position: Choose from 4 corner positions (Top Right, Top Left, Bottom Right, Bottom Left)
Plot Current EMAs: Optional display of EMA lines on your current chart
💡 Trading Applications
✅ Trend Confirmation: Ensure your trades align with higher timeframe direction
✅ Risk Management: Avoid counter-trend trades in strong directional markets
✅ Entry Timing: Use lower timeframe for entries while respecting higher timeframe bias
✅ Scalping Enhancement: Perfect for 1-5 minute scalping with higher timeframe context
🎨 Visual Design
Clean, professional table design
Intuitive color coding (Green = Up, Red = Down)
Compact size that doesn't obstruct your chart
Clear typography for quick reading
📋 Perfect For
Day traders and scalpers
Swing traders seeking trend confirmation
Multi-timeframe analysis enthusiasts
Traders who want simple, effective trend identification
🚀 Easy Setup
Add to any chart (works on all timeframes)
Customize table position and settings
Start trading with higher timeframe awareness
Watch the table update automatically
No complex configurations needed - just add and trade!
This indicator is designed for educational and informational purposes. Always combine with proper risk management and your own analysis.






















