Improved Z-ScoreStandard Z-Score scripts lack customization of parameters that I personally desire when doing quantitative analysis. This is an improved Z-Score Indicator to add to your charts that lets you customize various inputs.
Below are the current features:
1) Ticker Type - which data would you like to use for the ticker input - Open, High, Low, Close, OHLC4
2) Ticker Smoothing? - sometimes if you have noisy data, it could be useful to smooth the ticker with a very fast EMA. If this is set to true, the ticker data will be smoothed with an EMA with period that you specify.
3) Ticker Smoothing Period - if Ticker Smoothing? is set to true, this will allow you to specify the smoothing period of the fast EMA - I usually use a 3-period for all of my quantitative analysis, if I am using smoothing.
4) MA Type - Z-Scores are normalized by subtracting a moving average. This allows you to select either a Simple Moving Average (SMA) or an Exponential Moving Average (EMA) - the standard is to use SMA.
5) MA Period - the previous X number of bars that you would like to use for normalization. The default is set to 21 (this is roughly 1 month of trading days data for a daily chart).
5) Standard Deviation Period - Z-Scores are normalized by dividing by the standard deviation over X previous periods. This allows you the chance to customize. Default is 252 (this is roughly 1 year of trading days data for a daily chart).
I can add more features if folks are interested, let me know! I hope you like the script.
Best regards,
-Jim Bosse-
Cari dalam skrip untuk "文华财经tick价格"
myAlertsLibrary   "myAlerts" 
My Alerts Functions - To use with autoview
 f_order(_price, _qty, _position, _account, _exchange, _i, i_qtyTypeOrder, typeMsg, syminfoticker) 
  - Write the entry order message
  Parameters:
     _price : - The order price
     _qty : - The order quantity
     _position : - The order side
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_qtyTypeOrder : - String used to set Thether or Bitcoin Type Orders
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
 f_stop(_stop_price, _slLimit_price, _account, _exchange, _i, i_delayOrders, typeMsg, syminfoticker) 
  - Write the stop order message
  Parameters:
     _stop_price : - The order stop price
     _slLimit_price : - The order stop limit price
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_delayOrders : - Time in seconds to delay command on autoview
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
 f_take(_take_price, _account, _exchange, _i, i_delayOrders, typeMsg, syminfoticker) 
  - Write the stop order message
  Parameters:
     _take_price : - The order stop price
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_delayOrders : - Time in seconds to delay command on autoview
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
 f_update(_account, _exchange, _i, i_delayOrders, typeMsg, syminfoticker) 
  - Write the update order message
  Parameters:
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_delayOrders : - Time in seconds to delay command on autoview
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
 f_exit(_account, _exchange, _i, i_delayOrders, typeMsg, syminfoticker) 
  - Write the exit order message
  Parameters:
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_delayOrders : - Time in seconds to delay command on autoview
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
 f_hedge(_account, _exchange, _i, i_delayOrders, typeMsg, syminfoticker) 
  - Write the exit order message
  Parameters:
     _account : - The user account
     _exchange : - The user exchange
     _i : - Used for multi-accounts, this represents the index of accounts
     i_delayOrders : - Time in seconds to delay command on autoview
     typeMsg : - True = Autoview; False = Metatrader
     syminfoticker : - Ticker
  Returns: - Returns the open order message
PlurexSignalIntegrationLibrary   "PlurexSignalIntegration" 
Provides tools for integrating Strategies and Alerts into plurex.io signals.
 plurexMarket()  Build a Plurex market from a base and quote asset symbol.
  Returns: A market string that can be used in Plurex Signal messages.
 tickerToPlurexMarket()  Builds simple Plurex market string from the syminfo
  Returns: A market string that can be used in Plurex Signal messages.
 simpleMessage(secret, action, marketOverride)  Builds simple Plurex Signal Messages
  Parameters:
     secret : The secret for your Signal on plurex
     action : The action of the message. One of  .
     marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
  Returns: A json string message that can be used in alerts to send messages to Plurex.
 executeStrategy(secret, openLong, openShort, closeLongs, closeShorts, marketOverride)  Executes strategy actions with Plurex Signal messages
  Parameters:
     secret : The secret for your Signal on plurex
     openLong : Strategy should open long if true, aggregated with other boolean values
     openShort : Strategy should open short if true, aggregated with other boolean values
     closeLongs : Strategy should close longs if true, aggregated with other boolean values
     closeShorts : Strategy should close shorts if true, aggregated with other boolean values
     marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
RVSILibrary  "RVSI" 
This Library contains functions that calculate all types of " Relative Volume Strength Index (MZ  RVSI ) " depending upon unique volume oscillator. Achieved RVSI value can be used for divergence detection in volume or to adapt dynamic length in Moving Averages or other functions.
 rvsi_tfs(vol_src, vol_Len, rvsiLen, _open, _close)  Relative Volume Strength Index based on TFS Volume Oscillator
  Parameters:
     vol_src : Volume Source
     vol_Len : Volume Legth for TFS Volume Oscillato
     rvsiLen : Period of Relative Volume Strength Index
     _open : Ticker Open Value
     _close : Ticker Close Value
  Returns: Relative Volume Strength Index value based on TFS Volume Oscillator
 rvsi_obv(vol_src, rvsiLen, _close)  Relative Volume Strength Index based on On Balance Volume
  Parameters:
     vol_src : Volume Source to Calculate On Balance Volume
     rvsiLen : Period of Relative Volume Strength Index
     _close : Ticker Close Value
  Returns: Relative Volume Strength Index value based on On Balance Volume
 rvsi_kvo(vol_src, FastX, SlowX, rvsiLen, _close)  Relative Volume Strength Index based on Klinger Volume Oscillator
  Parameters:
     vol_src : Volume Source
     FastX : Volume Fast Length
     SlowX : Volume Slow Length
     rvsiLen : Period of Relative Volume Strength Index
     _close : Ticker Close Value
  Returns: Relative Volume Strength Index value based on Klinger Volume Oscillator
 rvsi_vzo(vol_src, zLen, rvsiLen, _close)  Relative Volume Strength Index based on Volume Zone Oscillator
  Parameters:
     vol_src : Volume Source
     zLen : Volume Legth for Volume Zone Oscillator
     rvsiLen : Period of Relative Volume Strength Index
     _close : Ticker Close Value
  Returns: Relative Volume Strength Index value based on Volume Zone Oscillator
 rvsi_cvo_obv(vol_src, ema1len, ema2len, rvsiLen)  Relative Volume Strength Index based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
  Parameters:
     vol_src : Volume Source
     ema1len : EMA Fast Length
     ema2len : EMA Slow Length
     rvsiLen : Period of Relative Volume Strength Index
  Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
 rvsi_cvo_pvt(vol_src, FastX, SlowX, rvsiLen)  Relative Volume Strength Index based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
  Parameters:
     vol_src : Volume Source
     FastX : EMA Fast Length
     SlowX : EMA Slow Length
     rvsiLen : Period of Relative Volume Strength Index
  Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
 rvsi_cvo_cvd(vol_src, FastX, SlowX, rvsiLen, _open, _close, _high, _low)  Relative Volume Strength Index based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
  Parameters:
     vol_src : Volume Source
     FastX : EMA Fast Length
     SlowX : EMA Slow Length
     rvsiLen : Period of Relative Volume Strength Index
     _open : Ticker Open Value
     _close : Ticker Close Value
     _high : Ticker High Value
     _low : Ticker Low Value
  Returns: Relative Volume Strength Index value based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
Double wave-trend Oscillator Buy/Sell signalsBINANCE:ROSEUSDT 
This script attempts to use Wave Trend Oscillator's of different lengths in order to identify trade entries and exits for bullish trades. This indicator is strongly recommended to be used with volatile assets or on large time interval charts. You use this script by entering a trade when it signals a green block and exiting when it signals red although these signals could potentially be used as trend reversal signals instead. The script uses two wave trend oscillator's the lengths of which can be edited in the settings, but the general idea is that one is fast and one is slow and these indicate when to buy/sell when they crossover the overbought/sold lines. In the setting you can choose whether the fast or the slow line will be used for buy signal and the other is then used to signal selling. By default this will be ticked on indicating that the fast line crossing over the oversold level will be used for buy signals, if it is ticked off the slow line will be used. The other tickbox is for whether the line used for selling will signal when it first crosses over the overbought line or whether it should signal then it crosses back under the overbought line after having crossed over it, the default value is off indicating that it will signal when it crosses back under the overbought level. The overbought/sold levels should be tweaked on a per asset basis to get the best quality signals.
The original code for the Wave Trend Oscillator comes from LazyBear and was modified and built on to create this indicator.
SeasonalityThis is my attempt to bring an open source Seasonality indicator to TradingView. 
There are still outstanding issues I couldn't figure out, so I am hoping some more seasoned Pine Script coders can take the lead from here.
What is Seasonality:  www.investopedia.com 
 How to Use 
 
  The indicator plots the avg % change per bar for all complete years, up to 20 years back.
  It will only show in the daily resolution.
  For charts with more data, you need to scroll back a bit to get the line to display.
  Use Offset Adjust in the menu for charts that do not align perfectly to the start of the year.
  Use Smoothing in the menu to apply an EMA to the line.
  The panel shows YTD % gain, 5-day rolling seasonality, and 20-day rolling seasonality.
 
 Known Issues 
 
  Does not work for tickers with over 10,000 bars of data.
  Some tickers do not align correctly.
  Only works with tickers that have ~252 bars a year.
 
 Areas for Improvement 
 
  Figure out a way to use barssince() to get the precise amount of bars for each year. This will make the seasonality calculation and automatic offset more accurate.
  Have an option for calendar week, month, and year seasonality.
Webhook Starter Kit [HullBuster] 
  
 Introduction 
This is an open source strategy which provides a framework for webhook enabled projects. It is designed to work out-of-the-box on any instrument triggering on an intraday bar interval. This is a full featured script with an emphasis on actual trading at a brokerage through the TradingView alert mechanism and without requiring browser plugins. 
The source code is written in a self documenting style with clearly defined sections. The sections “communicate” with each other through state variables making it easy for the strategy to evolve and improve. This is an excellent place for Pine Language beginners to start their strategy building journey. The script exhibits many Pine Language features which will certainly ad power to your script building abilities.
This script employs a basic trend follow strategy utilizing a forward pyramiding technique. Trend detection is implemented through the use of two higher time frame series. The market entry setup is a Simple Moving Average crossover. Positions exit by passing through conditional take profit logic. The script creates ten indicators including a Zscore oscillator to measure support and resistance levels. The indicator parameters are exposed through 47 strategy inputs segregated into seven sections. All of the inputs are equipped with detailed tool tips to help you get started.
To improve the transition from simulation to execution, strategy.entry and strategy.exit calls show enhanced message text with embedded keywords that are combined with the TradingView placeholders at alert time. Thereby, enabling a single JSON message to generate multiple execution events. This is genius stuff from the Pine Language development team. Really excellent work!
This document provides a sample alert message that can be applied to this script with relatively little modification. Without altering the code, the strategy inputs can alter the behavior to generate thousands of orders or simply a few dozen. It can be applied to crypto, stocks or forex instruments. A good way to look at this script is as a webhook lab that can aid in the development of your own endpoint processor, impress your co-workers and have hours of fun.
By no means is a webhook required or even necessary to benefit from this script. The setups, exits, trend detection, pyramids and DCA algorithms can be easily replaced with more sophisticated versions. The modular design of the script logic allows you to incrementally learn and advance this script into a functional trading system that you can be proud of.
 Design 
This is a trend following strategy that enters long above the trend line and short below. There are five trend lines that are visible by default but can be turned off in Section 7. Identified, in frequency order, as follows:
1.    - EMA in the chart time frame. Intended to track price pressure. Configured in Section 3.
2.    - ALMA in the higher time frame specified in Section 2 Signal Line Period.
3.    - Linear Regression in the higher time frame specified in Section 2 Signal Line Period.
4.    - Linear Regression in the higher time frame specified in Section 2 Signal Line Period.
5.    - DEMA in the higher time frame specified in Section 2 Trend Line Period.
The Blue, Green and Orange lines are signal lines are on the same time frame. The time frame selected should be at least five times greater than the chart time frame. The Purple line represents the trend line for which prices above the line suggest a rising market and prices below a falling market. The time frame selected for the trend should be at least five times greater than the signal lines.
Three oscillators are created as follows:
1.  Stochastic - In the chart time frame. Used to enter forward pyramids.
2.  Stochastic - In the Trend period. Used to detect exit conditions.
3.  Zscore - In the Signal period. Used to detect exit conditions.
The Stochastics are configured identically other than the time frame. The period is set in Section 2.
Two Simple Moving Averages provide the trade entry conditions in the form of a crossover. Crossing up is a long entry and down is a short. This is in fact the same setup you get when you select a basic strategy from the Pine editor. The crossovers are configured in Section 3. You can see where the crosses are occurring by enabling Show Entry Regions in Section 7.
The script has the capacity for pyramids and DCA. Forward pyramids are enabled by setting the Pyramid properties tab with a non zero value. In this case add on trades will enter the market on dips above the position open price. This process will continue until the trade exits. Downward pyramids are available in Crypto and Range mode only. In this case add on trades are placed below the entry price in the drawdown space until the stop is hit. To enable downward pyramids set the Pyramid Minimum Span In Section 1 to a non zero value.
This implementation of Dollar Cost Averaging (DCA) triggers off consecutive losses. Each loss in a run increments a sequence number. The position size is increased as a multiple of this sequence. When the position eventually closes at a profit the sequence is reset. DCA is enabled by setting the Maximum DCA Increments In Section 1 to a non zero value.
It should be noted that the pyramid and DCA features are implemented using a rudimentary design and as such do not perform with the precision of my invite only scripts. They are intended as a feature to stress test your webhook endpoint. As is, you will need to buttress the logic for it to be part of an automated trading system. It is for this reason that I did not apply a Martingale algorithm to this pyramid implementation. But, hey, it’s an open source script so there is plenty of room for learning and your own experimentation.
 How does it work 
The overall behavior of the script is governed by the Trading Mode selection in Section 1. It is the very first input so you should think about what behavior you intend for this strategy at the onset of the configuration. As previously discussed, this script is designed to be a trend follower. The trend being defined as where the purple line is predominately heading. In BiDir mode, SMA crossovers above the purple line will open long positions and crosses below the line will open short.  If pyramiding is enabled add on trades will accumulate on dips above the entry price. The value applied to the Minimum Profit input in Section 1 establishes the threshold for a profitable exit. This is not a hard number exit. The conditional exit logic must be satisfied in order to permit the trade to close. This is where the effort put into the indicator calibration is realized. There are four ways the trade can exit at a profit:
1.  Natural exit. When the blue line crosses the green line the trade will close. For a long position the blue line must cross under the green line (downward). For a short the blue must cross over the green (upward).
2.  Alma / Linear Regression event. The distance the blue line is from the green and the relative speed the cross is experiencing determines this event. The activation thresholds are set in Section 6 and relies on the period and length set in Section 2. A long position will exit on an upward thrust which exceeds the activation threshold. A short will exit on a downward thrust.
3.  Exponential event. The distance the yellow line is from the blue and the relative speed the cross is experiencing determines this event. The activation thresholds are set in Section 3 and relies on the period and length set in the same section.
4.  Stochastic event. The purple line stochastic is used to measure overbought and over sold levels with regard to position exits. Signal line positions combined with a reading over 80 signals a long profit exit. Similarly, readings below 20 signal a short profit exit.
Another, optional, way to exit a position is by Bale Out. You can enable this feature in Section 1. This is a handy way to reduce the risk when carrying a large pyramid stack. Instead of waiting for the entire position to recover we exit early (bale out) as soon as the profit value has doubled.
There are lots of ways to implement a bale out but the method I used here provides a succinct example. Feel free to improve on it if you like. To see where the Bale Outs occur, enable Show Bale Outs in Section 7. Red labels are rendered below each exit point on the chart.
There are seven selectable Trading Modes available from the drop down in Section 1:
1.  Long - Uses the strategy.risk.allow_entry_in to execute long only trades. You will still see shorts on the chart.
2.  Short - Uses the strategy.risk.allow_entry_in to execute short only trades. You will still see long trades on the chart.
3.  BiDir - This mode is for margin trading with a stop. If a long position was initiated above the trend line and the price has now fallen below the trend, the position will be reversed after the stop is hit. Forward pyramiding is available in this mode if you set the Pyramiding value in the Properties tab. DCA can also be activated.
4.  Flip Flop - This is a bidirectional trading mode that automatically reverses on a trend line crossover. This is distinctively different from BiDir since you will get a reversal even without a stop which is advantageous in non-margin trading.
5.  Crypto - This mode is for crypto trading where you are buying the coins outright. In this case you likely want to accumulate coins on a crash. Especially, when all the news outlets are talking about the end of Bitcoin and you see nice deep valleys on the chart. Certainly, under these conditions, the market will be well below the purple line. No margin so you can’t go short. Downward pyramids are enabled for Crypto mode when two conditions are met. First the Pyramiding value in the Properties tab must be non zero. Second the Pyramid Minimum Span in Section 1 must be non zero.
6.  Range - This is a counter trend trading mode. Longs are entered below the purple trend line and shorts above. Useful when you want to test your webhook in a market where the trend line is bisecting the signal line series. Remember that this strategy is a trend follower. It’s going to get chopped out in a range bound market. By turning on the Range mode you will at least see profitable trades while stuck in the range. However, when the market eventually picks a direction, this mode will sustain losses. This range trading mode is a rudimentary implementation that will need a lot of improvement if you want to create a reliable switch hitter (trend/range combo).
7.  No Trade. Useful when setting up the trend lines and the entry and exit is not important.
Once in the trade, long or short, the script tests the exit condition on every bar. If not a profitable exit then it checks if a pyramid is required. As mentioned earlier, the entry setups are quite primitive. Although they can easily be replaced by more sophisticated algorithms, what I really wanted to show is the diminished role of the position entry in the overall life of the trade. Professional traders spend much more time on the management of the trade beyond the market entry. While your trade entry is important, you can get in almost anywhere and still land a profitable exit.
If DCA is enabled, the size of the position will increase in response to consecutive losses. The number of times the position can increase is limited by the number set in Maximum DCA Increments of Section 1. Once the position breaks the losing streak the trade size will return the default quantity set in the Properties tab. It should be noted that the Initial Capital amount set in the Properties tab does not affect the simulation in the same way as a real account. In reality, running out of money will certainly halt trading. In fact, your account would be frozen long before the last penny was committed to a trade. On the other hand, TradingView will keep running the simulation until the current bar even if your funds have been technically depleted.
Entry and exit use the strategy.entry and strategy.exit calls respectfully. The alert_message parameter has special keywords that the endpoint expects to properly calculate position size and message sequence. The alert message will embed these keywords in the JSON object through the {{strategy.order.alert_message}} placeholder. You should use whatever keywords are expected from the endpoint you intend to webhook in to.
 Webhook Integration 
The TradingView alerts dialog provides a way to connect your script to an external system which could actually execute your trade. This is a fantastic feature that enables you to separate the data feed and technical analysis from the execution and reporting systems. Using this feature it is possible to create a fully automated trading system entirely on the cloud. Of course, there is some work to get it all going in a reliable fashion. Being a strategy type script place holders such as {{strategy.position_size}} can be embedded in the alert message text. There are more than 10 variables which can write internal script values into the message for delivery to the specified endpoint. 
Entry and exit use the strategy.entry and strategy.exit calls respectfully. The alert_message parameter has special keywords that my endpoint expects to properly calculate position size and message sequence. The alert message will embed these keywords in the JSON object through the {{strategy.order.alert_message}} placeholder. You should use whatever keywords are expected from the endpoint you intend to webhook in to.
Here is an excerpt of the fields I use in my webhook signal:
"broker_id": "kraken",
"account_id": "XXX XXXX XXXX XXXX",
"symbol_id": "XMRUSD",
"action": "{{strategy.order.action}}",
"strategy": "{{strategy.order.id}}",
"lots": "{{strategy.order.contracts}}",
"price": "{{strategy.order.price}}",
"comment": "{{strategy.order.alert_message}}",
"timestamp": "{{time}}"
Though TradingView does a great job in dispatching your alert this feature does come with a few idiosyncrasies. Namely, a single transaction call in your script may cause multiple transmissions to the endpoint. If you are using placeholders each message describes part of the transaction sequence. A good example is closing a pyramid stack. Although the script makes a single strategy.close() call, the endpoint actually receives a close message for each pyramid trade. The broker, on the other hand, only requires a single close. The incongruity of this situation is exacerbated by the possibility of messages being received out of sequence. Depending on the type of order designated in the message, a close or a reversal. This could have a disastrous effect on your live account. This broker simulator has no idea what is actually going on at your real account. Its just doing the job of running the simulation and sending out the computed results. If your TradingView simulation falls out of alignment with the actual trading account lots of really bad things could happen. Like your script thinks your are currently long but the account is actually short. Reversals from this point forward will always be wrong with no one the wiser. Human intervention will be required to restore congruence. But how does anyone find out this is occurring? In closed systems engineering this is known as entropy. In practice your webhook logic should be robust enough to detect these conditions. Be generous with the placeholder usage and give the webhook code plenty of information to compare states. Both issuer and receiver. Don’t blindly commit incoming signals without verifying system integrity.
 Setup 
The following steps provide a very brief set of instructions that will get you started on your first configuration. After you’ve gone through the process a couple of times, you won’t need these anymore. It’s really a simple script after all. I have several example configurations that I used to create the performance charts shown. I can share them with you if you like. Of course, if you’ve modified the code then these steps are probably obsolete.
There are 47 inputs divided into seven sections. For the most part, the configuration process is designed to flow from top to bottom. Handy, tool tips are available on every field to help get you through the initial setup.
Step 1. Input the Base Currency and Order Size in the Properties tab. Set the Pyramiding value to zero.
Step 2. Select the Trading Mode you intend to test with from the drop down in Section 1. I usually select No Trade until I’ve setup all of the trend lines, profit and stop levels.
Step 3. Put in your Minimum Profit and Stop Loss in the first section. This is in pips or currency basis points (chart right side scale). Remember that the profit is taken as a conditional exit not a fixed limit. The actual profit taken will almost always be greater than the amount specified. The stop loss, on the other hand, is indeed a hard number which is executed by the TradingView broker simulator when the threshold is breached.
Step 4. Apply the appropriate value to the Tick Scalar field in Section 1. This value is used to remove the pipette from the price. You can enable the Summary Report in Section 7 to see the TradingView minimum tick size of the current chart.
Step 5. Apply the appropriate Price Normalizer value in Section 1. This value is used to normalize the instrument price for differential calculations. Basically, we want to increase the magnitude to significant digits to make the numbers more meaningful in comparisons. Though I have used many normalization techniques, I have always found this method to provide a simple and lightweight solution for less demanding applications. Most of the time the default value will be sufficient. The Tick Scalar and Price Normalizer value work together within a single calculation so changing either will affect all delta result values.
Step 6. Turn on the trend line plots in Section 7. Then configure Section 2. Try to get the plots to show you what’s really happening not what you want to happen. The most important is the purple trend line. Select an interval and length that seem to identify where prices tend to go during non-consolidation periods. Remember that a natural exit is when the blue crosses the green line.
Step 7.  Enable Show Event Regions in Section 7. Then adjust Section 6. Blue background fills are spikes and red fills are plunging prices. These measurements should be hard to come by so you should see relatively few fills on the chart if you’ve set this up as intended. Section 6 includes the Zscore oscillator the state of which combines with the signal lines to detect statistically significant price movement. The Zscore is a zero based calculation with positive and negative magnitude readings. You want to input a reasonably large number slightly below the maximum amplitude seen on the chart. Both rise and fall inputs are entered as a positive real number. You can easily use my code to create a separate indicator if you want to see it in action. The default value is sufficient for most configurations.
Step 8.  Turn off Show Event Regions and enable Show Entry Regions in Section 7. Then adjust Section 3. This section contains two parts. The entry setup crossovers and EMA events. Adjust the crossovers first. That is the Fast Cross Length and Slow Cross Length. The frequency of your trades will be shown as blue and red fills. There should be a lot. Then turn off Show Event Regions and enable Display EMA Peaks. Adjust all the fields that have the word EMA. This is actually the yellow line on the chart. The blue and red fills should show much less than the crossovers but more than event fills shown in Step 7.
Step 9. Change the Trading Mode to BiDir if you selected No Trades previously. Look on the chart and see where the trades are occurring. Make adjustments to the Minimum Profit and Stop Offset in Section 1 if necessary. Wider profits and stops reduce the trade frequency.
Step 10.  Go to Section 4 and 5 and make fine tuning adjustments to the long and short side.
 Example Settings 
To reproduce the performance shown on the chart please use the following configuration: (Bitcoin on the Kraken exchange)
1. Select XBTUSD Kraken as the chart symbol.
2. On the properties tab set the Order Size to: 0.01 Bitcoin
3. On the properties tab set the Pyramiding to: 12
4.   In Section 1: Select “Crypto” for the Trading Model
5.   In Section 1: Input 2000 for the Minimum Profit
6.   In Section 1: Input 0 for the Stop Offset (No Stop)
7.   In Section 1: Input 10 for the Tick Scalar
8.   In Section 1: Input 1000 for the Price Normalizer
9.   In Section 1: Input 2000 for the Pyramid Minimum Span
10. In Section 1: Check mark the Position Bale Out
11. In Section 2: Input 60 for the Signal Line Period
12. In Section 2: Input 1440 for the Trend Line Period
13. In Section 2: Input 5 for the Fast Alma Length
14. In Section 2: Input 22 for the Fast LinReg Length
15. In Section 2: Input 100 for the Slow LinReg Length
16. In Section 2: Input 90 for the Trend Line Length
17. In Section 2: Input 14 Stochastic Length
18. In Section 3: Input 9 Fast Cross Length
19. In Section 3: Input 24 Slow Cross Length
20. In Section 3: Input 8 Fast EMA Length
21. In Section 3: Input 10 Fast EMA Rise NetChg
22. In Section 3: Input 1 Fast EMA Rise ROC
23. In Section 3: Input 10 Fast EMA Fall NetChg
24. In Section 3: Input 1 Fast EMA Fall ROC
25. In Section 4: Check mark the Long Natural Exit
26. In Section 4: Check mark the Long Signal Exit
27. In Section 4: Check mark the Long Price Event Exit
28. In Section 4: Check mark the Long Stochastic Exit
29. In Section 5: Check mark the Short Natural Exit
30. In Section 5: Check mark the Short Signal Exit
31. In Section 5: Check mark the Short Price Event Exit
32. In Section 5: Check mark the Short Stochastic Exit
33. In Section 6: Input 120 Rise Event NetChg
34. In Section 6: Input 1 Rise Event ROC
35. In Section 6: Input 5 Min Above Zero ZScore
36. In Section 6: Input 120 Fall Event NetChg
37. In Section 6: Input 1 Fall Event ROC
38. In Section 6: Input 5 Min Below Zero ZScore
In this configuration we are trading in long only mode and have enabled downward pyramiding. The purple trend line is based on the day (1440) period. The length is set at 90 days so it’s going to take a while for the trend line to alter course should this symbol decide to node dive for a prolonged amount of time. Your trades will still go long under those circumstances. Since downward accumulation is enabled, your position size will grow on the way down.
The performance example is Bitcoin so we assume the trader is buying coins outright. That being the case we don’t need a stop since we will never receive a margin call. New buy signals will be generated when the price exceeds the magnitude and speed defined by the Event Net Change and Rate of Change.
Feel free to PM me with any questions related to this script. Thank you and happy trading!
 CFTC RULE 4.41 
These results are based on simulated or hypothetical performance results that have certain inherent limitations. Unlike the results shown in an actual performance record, these results do not represent actual trading. Also, because these trades have not actually been executed, these results may have under-or over-compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated or hypothetical trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profits or losses similar to these being shown.
Using `varip` variables [PineCoders]█  OVERVIEW 
The new  varip  keyword in Pine can be used to declare variables that escape the rollback process, which is explained in the Pine User Manual's page on the  execution model . This publication explains how Pine coders can use variables declared with  varip  to implement logic that was impossible to code in Pine before, such as timing events during the realtime bar, or keeping track of sequences of events that occur during successive realtime updates. We present code that allows you to calculate for how much time a given condition is true during a realtime bar, and show how this can be used to generate alerts.
█  WARNINGS 
1.  varip  is an advanced feature which should only be used by coders already familiar with Pine's  execution model  and  bar states .
2. Because  varip  only affects the behavior of your code in the realtime bar, it follows that backtest results on strategies built using logic based on  varip  will be meaningless,
  as  varip  behavior cannot be simulated on historical bars. This also entails that plots on historical bars will not be able to reproduce the script's behavior in realtime.
3. Authors publishing scripts that behave differently in realtime and on historical bars should imperatively explain this to traders.
█  CONCEPTS 
 Escaping the rollback process 
Whereas scripts only execute once at the close of historical bars, when a script is running in realtime, it executes every time the chart's feed detects a price or volume update. At every realtime update, Pine's runtime normally resets the values of a script's variables to their last  committed  value, i.e., the value they held when the previous bar closed. This is generally handy, as each realtime script execution starts from a known state, which simplifies script logic.
Sometimes, however, script logic requires code to be able to save states  between  different executions in the realtime bar. Declaring variables with  varip  now makes that possible. The "ip" in  varip  stands for "intrabar persist".
Let's look at the following code, which does not use  varip :
 
//@version=4
study("")
int updateNo = na
if barstate.isnew
    updateNo := 1
else
    updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
 
On historical bars,  barstate.isnew  is always true, so the plot shows a value of "1". On realtime bars,  barstate.isnew  is only true when the script first executes on the bar's opening. The plot will then briefly display "1" until subsequent executions occur. On the next executions during the realtime bar, the second branch of the  if  statement is executed because  barstate.isnew  is no longer true. Since `updateNo` is initialized to `na` at each execution, the `updateNo + 1` expression yields `na`, so nothing is plotted on further realtime executions of the script.
If we now use  varip  to declare the `updateNo` variable, the script behaves very differently:
 
//@version=4
study("")
varip int updateNo = na
if barstate.isnew
    updateNo := 1
else
    updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
 
The difference now is that `updateNo` tracks the number of realtime updates that occur on each realtime bar. This can happen because the  varip  declaration allows the value of `updateNo` to be preserved between realtime updates; it is no longer rolled back at each realtime execution of the script. The test on  barstate.isnew  allows us to reset the update count when a new realtime bar comes in.
█  OUR SCRIPT 
Let's move on to our script. It has three parts:
 — Part 1 demonstrates how to generate alerts on timed conditions.
 — Part 2 calculates the average of realtime update prices using a  varip  array.
 — Part 3 presents a function to calculate the up/down/neutral volume by looking at price and volume variations between realtime bar updates.
Something we could not do in Pine before  varip  was to time the duration for which a condition is continuously true in the realtime bar. This was not possible because we could not save the beginning time of the first occurrence of the true condition.
One use case for this is a strategy where the system modeler wants to exit before the end of the realtime bar, but only if the exit condition occurs for a specific amount of time. One can thus design a strategy running on a 1H timeframe but able to exit if the exit condition persists for 15 minutes, for example. REMINDER: Using such logic in strategies will make backtesting their complete logic impossible, and backtest results useless, as historical behavior will not match the strategy's behavior in realtime, just as using `calc_on_every_tick = true` will do. Using `calc_on_every_tick = true` is necessary, by the way, when using  varip  in a strategy, as you want the strategy to run like a study in realtime, i.e., executing on each price or volume update.
Our script presents an `f_secondsSince(_cond, _resetCond)` function to calculate the time for which a condition is continuously true during, or even across multiple realtime bars. It only works in realtime. The abundant comments in the script hopefully provide enough information to understand the details of what it's doing. If you have questions, feel free to ask in the Comments section.
 Features 
The script's inputs allow you to:
 • Specify the number of seconds the tested conditions must last before an alert is triggered (the default is 20 seconds).
 • Determine if you want the duration to reset on new realtime bars.
 • Require the direction of alerts (up or down) to alternate, which minimizes the number of alerts the script generates.
The inputs showcase the new `tooltip` parameter, which allows additional information to be displayed for each input by hovering over the "i" icon next to it.
The script only displays useful information on realtime bars. This information includes:
 • The MA against which the current price is compared to determine the bull or bear conditions.
 • A dash which prints on the chart when the bull or bear condition is true.
 • An up or down triangle that prints when an alert is generated. The triangle will only appear on the update where the alert is triggered, 
  and unless that happens to be on the last execution of the realtime bar, it will not persist on the chart.
 • The log of all triggered alerts to the right of the realtime bar.
 • A gray square on top of the elapsed realtime bars where one or more alerts were generated. The square's tooltip displays the alert log for that bar.
 • A yellow dot corresponding to the average price of all realtime bar updates, which is calculated using a  varip  array in "Part 2" of the script.
 • Various key values in the Data Window for each parts of the script.
Note that the directional volume information calculated in Part 3 of the script is not plotted on the chart—only in the Data Window.
 Using the script 
You can try running the script on an open market with a 30sec timeframe. Because the default settings reset the duration on new realtime bars and require a 20 second delay, a reasonable amount of alerts will trigger.
 Creating an alert on the script 
You can create a  script alert  on the script. Keep in mind that when you create an alert from this script, the duration calculated by the instance of the script running the alert will not necessarily match that of the instance running on your chart, as both started their calculations at different times. Note that we use  alert.freq_all  in our  alert()  calls, so that alerts will trigger on all instances where the associated condition is met. If your alert is being paused because it reaches the maximum of 15 triggers in 3 minutes, you can configure the script's inputs so that up/down alerts must alternate. Also keep in mind that alerts run a distinct instance of your script on different servers, so discrepancies between the behavior of scripts running on charts and alerts can occur, especially if they trigger very often.
 Challenges 
Events detected in realtime using variables declared with  varip  can be transient and not leave visible traces at the close of the realtime bar, as is the case with our script, which can trigger multiple alerts during the same realtime bar, when the script's inputs allow for this. In such cases, elapsed realtime bars will be of no use in detecting past realtime bar events unless dedicated code is used to save traces of events, as we do with our alert log in this script, which we display as a tooltip on elapsed realtime bars.
█  NOTES 
 Realtime updates 
We have no control over when realtime updates occur. A realtime bar can open, and then no realtime updates can occur until the open of the next realtime bar. The time between updates can vary considerably.
 Past values 
There is no mechanism to refer to past values of a  varip  variable across realtime executions in the same bar. Using the history-referencing operator   will, as usual, return the variable's committed value on previous bars. If you want to preserve past values of a  varip  variable, they must be saved in other variables or in an  array .
 Resetting variables 
Because varip variables not only preserve their values across realtime updates, but also across bars, you will typically need to plan conditions that will at some point reset their values to a known state. Testing on  barstate.isnew , as we do, is a good way to achieve that.
 Repainting 
The fact that a script uses  varip  does not make it necessarily repainting. A script could conceivably use  varip  to calculate values saved when the realtime bar closes, and then use confirmed values of those calculations from the previous bar to trigger alerts or display plots, avoiding repaint.
 timenow  resolution 
Although the variable is expressed in milliseconds it has an actual resolution of seconds, so it only increments in multiples of 1000 milliseconds.
 Warn script users 
When using  varip  to implement logic that cannot be replicated on historical bars, it's really important to explain this to traders in published script descriptions, even if you publish open-source. Remember that most TradingViewers do not know Pine.
 New Pine features used in this script 
This script uses three new Pine features:
 •  varip  
 • The `tooltip` parameter in  input() .
 • The new  +=  assignment operator. See these also:  -= ,  *= ,  /=  and  %= .
 Example scripts 
These are other scripts by PineCoders that use  varip :
 •  Tick Delta Volume , by  RicadoSantos .
 •  Tick Chart  and  Volume Info from Lower Time Frames  by  LonesomeTheBlue .
 Thanks 
Thanks to the PineCoders who helped improve this publication—especially to  bmistiaen .
 Look first. Then leap.  
sDEFI Synthetix ExchangeTradingView allows combining/summing up to a maximum of only 10 tickers in its search field. Their support staff suggested I could combine up to 40 by using Pine Script, so here it is, for a specific 'basket' of crypto tokens.
This study displays the combination of price history for Synthetix Exchange’s sDEFI index.
Tokens included in the index are COMP, MKR, KNC, SNX, ZRX, REP, LEND, REN, LRC, BNT, BAL and UMA. You will see the prices only go back as far as July 31st 2020, which is when the most recent of the compilation (UMA) started its trading history on TradingView. (The study can only display prices for days that *all* the tickers were trading.)
The price history will display as a study, below an existing chart. You will need to resize the windows, to see this study at a larger size. (Grab the window border and move it up, once you have added this study to a chart)
Unfortunately you will not be able to interact with it like a normal chart, i.e. drawing trendlines, adding moving averages, notes or annotations, etc.
May I suggest you send a support request to TradingView, asking for them to allow us to enter more than 10 (perhaps up to 40) tickers with + symbol between them, in the search field, which gives a ‘proper’ chart to analyse?
Please note that when publishing this script, I was required to choose a category from a list that does not contain a relevant category. Given that I had to choose something from the list to proceed, I used 'Support and Resistance', since chartists can see S and R levels by looking at this study.
I trust this study is useful for you sDEFI traders.
 
Price Action and 3 EMAs Momentum plus Sessions FilterThis indicator plots on the chart the parameters and signals of the Price Action and 3 EMAs Momentum plus Sessions Filter Algorithmic Strategy.  The strategy trades based on time-series (absolute) and relative momentum of price close, highs, lows and 3 EMAs.
I am still learning PS and therefore I have only been able to write the indicator up to the Signal generation.  I plan to expand the indicator to Entry Signals as well as the full Strategy.  
The strategy works best on EURUSD in the 15 minutes TF during London and New York sessions with 1 to 1 TP and SL of 30 pips with lots resulting in 3% risk of the account per trade.  I have already written the full strategy in another language and platform and back tested it for ten years and it was profitable for 7 of the 10 years with average profit of 15% p.a which can be easily increased by increasing risk per trade.  I have been trading it live in that platform for over two years and it is profitable. 
Contributions from experienced PS coders in completing the Indicator as well as writing the Strategy and back testing it on Trading View will be appreciated.
STRATEGY AND INDICATOR PARAMETERS
Three periods of 12, 48 and 96 in the 15 min TF which are equivalent to 3, 12 and 24 hours i.e (15 min * period / 60 min) are the foundational inputs for all the parameters of the PA & 3 EMAs Momentum + SF Algo Strategy and its Indicator.
3 EMAs momentum parameters and conditions
•	FastEMA = ema of 12 periods
•	MedEMA = ema of 48 periods
•	SlowEMA = ema of 96 periods
•	All the EMAs analyse price close for up to 96 (15 min periods) equivalent to 24 hours
•	There’s Upward EMA momentum if price close > FastEMA and FastEMA > MedEMA and MedEMA > SlowEMA
•	There’s Downward EMA momentum if price close < FastEMA and FastEMA < MedEMA and MedEMA < SlowEMA
PA momentum parameters and conditions
•	HH = Highest High of 48 periods from 1st closed bar before current bar
•	LL = Lowest Low of 48 periods from 1st closed bar from current bar
•	Previous HH = Highest High of 84 periods from 12th closed bar before current bar
•	Previous LL = Lowest Low of 84 periods from 12th closed bar before current bar
•	All the HH & LL and prevHH & prevLL are within the 96 periods from the 1st closed bar before current bar and therefore indicative of momentum during the past 24 hours
•	There’s Upward PA momentum if price close > HH and HH > prevHH and  LL > prevLL
•	There’s Downward PA momentum if price close < LL and LL < prevLL and HH < prevHH
Signal conditions and Status (BuySignal, SellSignal or Neutral)
•	The strategy generates Buy or Sell Signals if both 3 EMAs and PA momentum conditions are met for each direction and these occur during the London and New York sessions
•	BuySignal if price close > FastEMA and FastEMA > MedEMA and MedEMA > SlowEMA and price close > HH and HH > prevHH and  LL > prevLL and timeinrange (LDN&NY) else Neutral
•	SellSignal if price close < FastEMA and FastEMA < MedEMA and MedEMA < SlowEMA and price close < LL and LL < prevLL and HH < prevHH and timeinrange (LDN&NY) else Neutral
Entry conditions and Status (EnterBuy, EnterSell or Neutral)(NOT CODED YET)
•	ENTRY IS NOT AT THE SIGNAL BAR but at the current bar tick price retracement to FastEMA after the signal
•	EnterBuy if current bar tick price <= FastEMA and current bar tick price > prevHH at the time of the Buy Signal
•	EnterSell if current bar tick price >= FastEMA and current bar tick price > prevLL at the time of the Sell Signal
Delta Volume Candles [LucF]█  OVERVIEW 
This indicator plots on-chart volume delta information using candles that can replace your normal candles, tops and bottoms appended to normal candles, optional MAs of those tops and bottoms levels, a divergence channel and a chart background. The indicator calculates volume delta using intrabar analysis, meaning that it uses the lower timeframe bars constituting each chart bar.
█  CONCEPTS 
 Volume Delta 
The volume delta concept divides a bar's volume in "up" and "down" volumes. The delta is calculated by subtracting down volume from up volume. Many calculation techniques exist to isolate up and down volume within a bar. The simplest use the polarity of interbar price changes to assign their volume to up or down slots, e.g.,  On Balance Volume  or the  Klinger Oscillator . Others such as  Chaikin Money Flow  use assumptions based on a bar's OHLC values. The most precise calculation method uses tick data and assigns the volume of each tick to the up or down slot depending on whether the transaction occurs at the bid or ask price. While this technique is ideal, it requires huge amounts of data on historical bars, which considerably limits the historical depth of charts and the number of symbols for which tick data is available. Furthermore, historical tick data is not yet available on TradingView.
This indicator uses  intrabar analysis  to achieve a compromise between the simplest and most precise methods of calculating volume delta. It is currently the most precise method usable on TradingView charts. TradingView's  Volume Profile built-in indicators  use it, as do the  CVD - Cumulative Volume Delta Candles  and  CVD - Cumulative Volume Delta (Chart)  indicators published from the  TradingView account . My  Delta Volume Channels  and  Volume Delta Columns Pro  indicators also use intrabar analysis. Other volume delta indicators such as my  Realtime 5D Profile  use realtime chart updates to calculate volume delta without intrabar analysis, but that type of indicator only works in real time; they cannot calculate on historical bars.
This is the logic I use to determine the polarity of intrabars, which determines the up or down slot where its volume is added:
 • If the intrabar's  open  and  close  values are different, their relative position is used.
 • If the intrabar's  open  and  close  values are the same, the difference between the intrabar's  close  and the previous intrabar's  close  is used.
 • As a last resort, when there is no movement during an intrabar, and it closes at the same price as the previous intrabar, the last known polarity is used.
Once all intrabars making up a chart bar have been analyzed and the up or down property of each intrabar's volume determined, the up volumes are added, and the down volumes subtracted. The resulting value is volume delta for that chart bar, which can be used as an estimate of the buying/selling pressure on an instrument. Not all markets have volume information. Without it, this indicator is useless.
 Intrabar analysis 
 Intrabars  are chart bars at a lower timeframe than the chart's. The timeframe used to access intrabars determines the number of intrabars accessible for each chart bar. On a 1H chart, each chart bar of an active market will, for example, usually contain 60 bars at the lower timeframe of 1min, provided there was market activity during each minute of the hour.
This indicator automatically calculates an appropriate lower timeframe using the chart's timeframe and the settings you use in the script's "Intrabars" section of the inputs. As it can access lower timeframes as small as seconds when available, the indicator can be used on charts at relatively small timeframes such as 1min, provided the market is active enough to produce bars at second timeframes.
The quantity of intrabars analyzed in each chart bar determines:
 • The precision of calculations (more intrabars yield more precise results).
 • The chart coverage of calculations (there is a 100K limit to the quantity of intrabars that can be analyzed on any chart, 
  so the more intrabars you analyze per chart bar, the less chart bars can be calculated by the indicator).
The information box displayed at the bottom right of the chart shows the lower timeframe used for intrabars, as well as the average number of intrabars detected for chart bars and statistics on chart coverage.
 Balances 
This indicator calculates five balances from volume delta values. The balances are oscillators with a zero centerline; positive values are bullish, and negative values are bearish. It is important to understand the balances as they can be used to:
 • Color candle bodies.
 • Calculate body and top and bottom divergences.
 • Color an EMA channel.
 • Color the chart's background.
 • Configure markers and alerts.
The five balances are:
1 —  Bar Balance : This is the only balance using instant values; it is simply the subtraction of the down volume from the up volume on the bar, so the instant volume delta for that bar.
2 —  Average Balance : Calculates a distinct EMA for both the up and down volumes, and subtracts the down EMA from the up EMA.
  The result is akin to MACD's histogram because it is the subtraction of two moving averages.
3 —  Momentum Balance : Starts by calculating, separately for both up and down volumes, the difference between the same EMAs used in "Average Balance" and
  an SMA of twice the period used for the "Average Balance" EMAs. The difference for the up side is subtracted from the difference for the down side, 
  and an RSI of that value is calculated and brought over the −50/+50 scale.
4 —  Relative Balance : The reference values used in the calculation are the up and down EMAs used in the "Average Balance".
  From those, we calculate two intermediate values using how much the instant up and down volumes on the bar exceed their respective EMA — but with a twist.
  If the bar's up volume does not exceed the EMA of up volume, a zero value is used. The same goes for the down volume with the EMA of down volume.
  Once we have our two intermediate values for the up and down volumes exceeding their respective MA, we subtract them. The final value is an ALMA of that subtraction.
  The rationale behind using zero values when the bar's up/down volume does not exceed its EMA is to only take into account the more significant volume.
  If both instant volume values exceed their MA, then the difference between the two is the signal's value.
  The signal is called "relative" because the intermediate values are the difference between the instant up/down volumes and their respective MA.
  This balance flatlines when the bar's up/down volumes do not exceed their EMAs, which makes it useful to spot areas where trader interest dwindles, such as consolidations.
  The smaller the period of the final value's ALMA, the more easily it will flatline. These flat zones should be considered no-trade zones. 
5 —  Percent Balance : This balance is the ALMA of the ratio of the "Bar Balance" over the total volume for that bar.
From the balances and marker conditions, two more values are calculated:
1 —  Marker Bias : This sums the up/down (+1/‒1) occurrences of the markers 1 to 4 over a period you define, so it ranges from −4 to +4, times the period.
  Its calculation will depend on the modes used to calculate markers 3 and 4.
2 —  Combined Balances : This is the sum of the bull/bear (+1/−1) states of each of the five balances, so it ranges from −5 to +5.
The periods for all of these balances can be configured in the "Periods" section at the bottom of the script's inputs. As you cannot see the balances on the chart, you can use my  Volume Delta Columns Pro  indicator in a pane; it can plot the same balances, so you will be able to analyze them.
 Divergences 
In the context of this indicator, a divergence is any bar where the bear/bull state of a balance (above/below its zero centerline) diverges from the polarity of a chart bar. No directional bias is assigned to divergences when they occur. Candle bodies and tops/bottoms can each be colored differently on divergences detected from distinct balances.
 Divergence Channel 
The divergence channel is the space between two levels (by default, the bar's  open  and  close ) saved when divergences occur. When price (by default the  close ) has breached a channel and a new divergence occurs, a new channel is created. Until that new channel is breached, bars where additional divergences occur will expand the channel's levels if the bar's price points are outside the channel.
Prices breaches of the divergence channel will change its state. Divergence channels can be in one of three different states:
 •  Bull  (green): Price has breached the channel to the upside.
 •  Bear  (red): Price has breached the channel to the downside.
 •  Neutral  (gray): The channel has not yet been breached.
█  HOW TO USE THE INDICATOR 
I do not make videos to explain how to use my indicators. I do, however, try hard to include in their description everything one needs to understand what they do. From there, it's up to you to explore and figure out if they can be useful in your trading practice. Communicating in videos what this description and the script's tooltips contain would make for very long videos that would likely exceed the attention span of most people who find this description too long. There is no quick way to understand an indicator such as this one because it uses many different concepts and has quite a bit of settings one can use to modify its visuals and behavior — thus how one uses it. I will happily answer questions on the inner workings of the indicator, but I do not answer questions like "How do I trade using this indicator?" A useful answer to that question would require an in-depth analysis of who you are, your trading methodology and objectives, which I do not have time for. I do not teach trading.
Start by loading the indicator on an active chart containing volume information. See  here  if you need help.
The default configuration displays:
 • Normal candles where the bodies are only colored if the bar's volume has increased since the last bar.
  If you want to use this indicator's candles, you may want to disable your chart's candles by clicking the eye icon to the right of the symbol's name in the top left of the chart.
 • A top or bottom appended to the normal candles. It represents the difference between up and down volume for that bar 
  and is positioned at the top or bottom, depending on its polarity. If up volume is greater than down volume, a top is displayed. If down volume is greater, a bottom is plotted. 
  The size of tops and bottoms is determined by calculating a factor which is the proportion of volume delta over the bar's total volume. 
  That factor is then used to calculate the top or bottom size relative to a baseline of the average candle body size of the last 100 bars.
 • An information box in the bottom right displaying intrabar and chart coverage information.
 • A light red background when the intrabar volume differs from the chart's volume by more than 1%.
The script's inputs contain tooltips explaining most of the fields. I will not repeat them here. Following is a brief description of each section of the indicator's inputs which will give you an idea of what the indicator can do:
 Normal Candles  is where you configure the replacement candles plotted by the script. You can choose from different coloring schemes for their bodies and specify a unique color for bodies where a divergence calculated using the method you choose occurs.
 Volume Tops & Botttoms  is where you configure the display of tops and bottoms, and their EMAs. The EMAs are calculated from the high point of tops and the low point of bottoms. They can act as a channel to evaluate price, and you can choose to color the channel using a gradient reflecting the advances/declines in the balance of your choice.
 Divergence Channel  is where you set up the appearance and behavior of the divergence channel. These areas represent levels where price and volume delta information do not converge. They can be interpreted as regions with no clear direction from where one will look for breaches. You can configure the channel to take into account one or both types of divergences you have configured for candle bodies and tops/bottoms.
 Background  allows you to configure a gradient background color that reflects the advances/declines in the balance of your choice. You can use this to provide context to the volume delta values from bars. You can also control the background color displayed on volume discrepancies between the intrabar and the chart's timeframe.
 Intrabars  is where you choose the calculation mode determining the lower timeframe used to access intrabars. The indicator uses the chart's timeframe and the type of market you are on to calculate the lower timeframe. Your setting there should reflect which compromise you prefer between the precision of calculations and chart coverage. This is also where you control the display of the information box in the lower right corner of the chart.
 Markers  allows you to control the plotting of chart markers on different conditions. Their configuration determines when alerts generated from the indicator will fire. Note that in order to generate alerts from this script, they must be created from your chart. See this  Help Center page  to learn how. Only the last 500 markers will be visible on the chart, but this will not affect the generation of alerts.
 Periods  is where you configure the periods for the balances and the EMAs used in the indicator.
The raw values calculated by this script can be inspected using the Data Window.
█  INTERPRETATION 
Rightly or wrongly, volume delta is considered by many a useful complement to the interpretation of price action. I use it extensively in an attempt to find convergence between my read of volume delta and price movement — not so much as a predictor of future price movement. No system or person can predict the future. Accordingly, I consider people who speak or act as if they know the future with certainty to be dangerous to themselves and others; they are charlatans, imprudent or blissfully ignorant.
I try to avoid elaborate volume delta interpretation schemes involving too many variables and prefer to keep things simple:
 • Trends that have more chances of continuing should be accompanied by VD of the same polarity.
  In trends, I am looking for "slow and steady". I work from the assumption that traders and systems often overreact, which translates into unproductive volatility. 
  Wild trends are more susceptible to overreactions. 
 • I prefer steady VD values over wildly increasing ones, as large VD increases often come with increased price volatility, which can backfire.
  Large VD values caused by stopping volume will also often occur on trend reversals with abnormally high candles.
 • Prices escaping divergence channels may be leading a trend in that direction, although there is no telling how long that trend will last; could be just a few bars or hundreds.
  When price is in a channel, shifts in VD balances can sometimes give us an idea of the direction where price has the most chance of breaking.
 • Dwindling VD will often indicate trend exhaustion and predate reversals by many bars, but the problem is that mere pauses in a trend will often produce the same behavior in VD.
  I think it is too perilous to infer rigidly from VD decreases.
 Divergence Channel 
Here I have configured the divergence channels to be visible. First, I set the bodies to display divergences on the default Bar Balance. They are indicated by yellow bodies. Then I activated the divergence channels by choosing to draw levels on body divergences and checked the "Fill" checkbox to fill the channel with the same color as the levels. The divergence channel is best understood as a direction-less area from where a breach can be acted on if other variables converge with the breach's direction:
 Tops and Bottoms EMAs 
I find these EMAs rather interesting. They have no equivalent elsewhere, as they are calculated from the top and bottom values this indicator plots. The only similarity they have with volume-weighted MAs, including VWAP, is that they use price and volume. This indicator's Tops and Bottoms EMAs, however, use the price and volume delta. While the channel differs from other channels in how it is calculated, it can be used like others, as a baseline from which to evaluate price movement or, alternatively, as stop levels. Remember that you can change the period used for the EMAs in the "Periods" section of the inputs.
This chart shows the EMAs in action, filled with a gradient representing the advances/decline from the Momentum balance. Notice the anomaly in the chart's latest bars where the Momentum balance gradient has been indicating a bullish bias for some time, during which price was mostly below the EMAs. Price has just broken above the channel on positive VD. My interpretation of this situation would be that it is a risky opportunity for a long trade in the larger context where the market has been in a downtrend since the 5th. Intrepid traders choosing to enter here could do so with a "make or break" tight stop that will minimize their losses should the market continue its downtrend while hopefully preserving the potential upside of price continuing on the longer-term uptrend prevalent since the 28th:
█  NOTES 
 Volume 
If you use indicators such as this one which depends on volume information, it is important to realize that the volume data they consume comes from data feeds, and that all data feeds are NOT created equally. Those who create the data feeds we use must make decisions concerning the nature of the transactions they tally and the way they are tallied in each feed, and these decisions affect the nature of our volume data. My  Volume X-ray   publication discusses some of the reasons why volume information from different timeframes, brokers/exchanges or sectors may vary considerably. I encourage you to read it. This indicator's display of a warning through a background color on volume discrepancies between the timeframe used to access intrabars and the chart's timeframe is an attempt to help you realize these variations in feeds. Don't take things for granted, and understand that the quality of a given feed's volume information affects the quality of the results this indicator calculates.
 Markets as ecosystems 
I believe it is perilous to think that behavioral patterns you discover in one market through the lens of this or any other indicator will necessarily port to other markets. While this may sometimes be the case, it will often not. Why is that? Because each market is its own ecosystem. As cities do, all markets share some common characteristics, but they also all have their idiosyncrasies. A proportion of a city's inhabitants is always composed of outsiders who come and go, but a core population of regulars and systems is usually the force that actually defines most of the city's observable characteristics. I believe markets work somewhat the same way; they may look the same, but if you live there for a while and pay attention, you will notice the idiosyncrasies. Some things that work in some markets will, accordingly, not work in others. Please keep that in mind when you draw conclusions.
 On Up/Down or Buy/Sell Volume 
Buying or selling volume are misnomers, as every unit of volume transacted is both bought and sold by two different traders. While this does not keep me from using the terms, there is no such thing as “buy only” or “sell only” volume. Trader lingo is riddled with peculiarities. Without access to order book information, traders work with the assumption that when price moves up during a bar, there was more buying pressure than selling pressure, just as when buy market orders take out limit ask orders in the order book at successively higher levels. The built-in volume indicator available on TradingView uses this logic to color the volume columns green or red. While this script’s calculations are more precise because it analyses intrabars to calculate its information, it uses pretty much the same imperfect logic. Until Pine scripts can have access to how much volume was transacted at the bid/ask prices, our volume delta calculations will remain a mere proxy.
 Repainting 
 • The values calculated on the realtime bar will update as new information comes from the feed.
 • Historical values may recalculate if the historical feed is updated or when calculations start from a new point in history.
 • Markers and alerts will not repaint as they only occur on a bar's close. Keep this in mind when viewing markers on historical bars, 
  where one could understandably and incorrectly assume they appear at the bar's open.
To learn more about repainting, see the  Pine Script™ User Manual's page on the subject .
 Superfluity 
In "The Bed of Procrustes", Nassim Nicholas Taleb writes:  To bankrupt a fool, give him information . This indicator can display a lot of information. The inevitable adaptation period you will need to figure out how to use it should help you eliminate all the visuals you do not need. The more you eliminate, the easier it will be to focus on those that are the most useful to your trading practice. Don't be a fool.
█  THANKS 
Thanks to  alexgrover  for his  Dekidaka-Ashi  indicator. His volume plots on candles were the inspiration for my top/bottom plots.
Kudos to PineCoders for their libraries. I use two of them in this script:  Time  and  lower_tf .
The first versions of this script used functionality that I would not have known about were it not for these two guys:
— A guy called Kuan who commented on a  Backtest Rookies presentation   of their  Volume Profile  indicator.
—  theheirophant , my partner in the exploration of the sometimes weird abysses of  request.security() ’s behavior at lower timeframes.
ATR in %Muh indicator :)
Simple but so useful little script. I work in percents because this is what makes sense not "pips" and "ticks" my account grows or diminishes a certain percentage I risk "1%" for example not ticks, ticks is what bad dogs have.
Was tired of calculating manually every time.
Makes it easier to set stop losses, get an idea of what to expect, risk in a kind of worse case scneario, backtest strategies, compare charts etc quickly. More quick now.
Example.
Bitcoin and NatGas, you do NOT need leverage...
optionsellers.com that somehow got surprised by Natgas volatility and squeezed, I think he did not bother doing this...
Happens all the time on NatGas, that "short seller catastrophy" that made the headlines was not even that big of a spike...
Plenty of way worse ones not long ago
BUY LOW, BUY MORE, SELL HIGH -BUFFET  STRATEGY LITE__________________________________________________________________________
 Buy Low, Buy More, Sell High With Buffett Meter (LITE – JTMarketAI) 
__________________________________________________________________________
Category: Quantitative Momentum & Liquidity Flow
Author: JTMarketAI
Architecture: Non-Repainting
This strategy accumulates into validated pullbacks during fear cycles, scales intelligently as price declines into liquidity support, and exits when momentum weakens after meaningful run-ups. It uses synthetic higher-timeframe OHLC data (non-repainting), liquidity imbalance confirmation, adaptive KAMA trend logic, RSI validation, and a live Buffett macro valuation gauge.
This is a patient, conviction-based accumulation engine designed for equities. 
It is not a scalp bot.
__________________________________________________________________________
 Core Features 
__________________________________________________________________________
Non-repainting (confirmed bars only)
Synthetic HTF OHLC (no lookahead)
Dynamic trailing exit preserves ~80–87% of peak profit
Bull vs Bear liquidity dominance and flow imbalance
Rolling lowest-low tracking (LLL)
NY-session alignment (default)
Buffett Macro Meter integration
Technical Highlights
Flow-confidence derived from volume-order pressure
Adaptive KAMA smoothing for lower-lag confirmation
Daily > Weekly > Monthly synthetic aggregation
LLL progression display for trend exhaustion
Fully profiler-optimized
Supports averaging down when pyramiding enabled
__________________________________________________________________________
Why It Does Not Repaint
__________________________________________________________________________
All state updates occur only on confirmed bars
Synthetic HTFs built without lookahead
Persistent arrays freeze historical values
Trailing highs updated only after confirmation
No forward-reference to future bars
__________________________________________________________________________
Lite Edition Notes
__________________________________________________________________________
Manual trading focused
Buffett Meter enabled
Up to 20 trades per session
Visual dashboard included
No alerts, automation, or webhooks (PRO unlocks IBKR + TradersPost)
__________________________________________________________________________
Limitations
__________________________________________________________________________
Best on intraday equities (1m–4h)
Designed for US stocks only
High-resource if full visuals enabled
Avoid penny stocks and extremely low-volume tickers
Does not guard against after-hours gaps or major news moves
__________________________________________________________________________
Warnings
__________________________________________________________________________
Contrarian scaling requires discipline and patience
Expect longer-duration trades, not rapid scalps
Use on quality tickers unlikely to permanently collapse
Confirm price behavior outside cash session
Test manually before automating anything
Not suitable for every market environment or asset
Notes on Philosophy
This strategy attempts to accumulate when markets overshoot lower, and distribute after recovery momentum fades. It reflects a patient, value-driven approach built on the principle of buying fear and reducing exposure into strength.
__________________________________________________________________________
 Disclaimer 
__________________________________________________________________________
For research and educational use only. Not financial advice. Past performance does not guarantee future results. Test thoroughly and use appropriate risk management.
__________________________________________________________________________
 Hashtags 
__________________________________________________________________________
#buffett #quantstrategy #valuemomentum #accumulation #contrarian #nonrepaint #equitystrategy #swingtrading #liquidityanalysis #synthetichtf #tradingviewstrategy
BUY LOW, BUY MORE, SELL HIGH - MARKET FLOW STRATEGY LITE
TV Description - Buffett Meter Lite
body{font-family:Arial,Helvetica,sans-serif;max-width:900px;margin:32px auto;line-height:1.4} h1,h2{margin:16px 0 8px}
Buy Low, Buy More, Sell High With Buffett Meter (Lite v1283 – JTM)
Category: Quantitative Momentum & Liquidity Flow
Author: JTM
Architecture: Non-Repainting
This strategy accumulates into validated pullbacks during fear cycles, scales intelligently as price declines into liquidity support, and exits when momentum weakens after meaningful run-ups. It uses synthetic higher-timeframe OHLC data (non-repainting), liquidity imbalance confirmation, adaptive KAMA trend logic, RSI validation, and a live Buffett macro valuation gauge.
This is a patient, conviction-based accumulation engine designed for equities. 
It is not a scalp bot.
Core Features
Non-repainting (confirmed bars only)
Synthetic HTF OHLC (no lookahead)
Dynamic trailing exit preserves ~80–87% of peak profit
Bull vs Bear liquidity dominance and flow imbalance
Rolling lowest-low tracking (LLL)
NY-session alignment (default)
Buffett Macro Meter integration
Technical Highlights
Flow-confidence derived from volume-order pressure
Adaptive KAMA smoothing for lower-lag confirmation
Daily > Weekly > Monthly synthetic aggregation
LLL progression display for trend exhaustion
Fully profiler-optimized
Supports averaging down when pyramiding enabled
Why It Does Not Repaint
All state updates occur only on confirmed bars
Synthetic HTFs built without lookahead
Persistent arrays freeze historical values
Trailing highs updated only after confirmation
No forward-reference to future bars
Lite Edition Notes
Manual trading focused
Buffett Meter enabled
Limit of 20 trades per session
Buffet Meter dashboard included
No alerts, automation, or webhooks (PRO unlocks IBKR + TradersPost)
Limitations
Best on intraday equities (1m–4h)
Designed for US stocks only
High-resource if full visuals enabled
Avoid penny stocks and extremely low-volume tickers
Does not guard against after-hours gaps or major news moves
Warnings
Contrarian scaling requires discipline and patience
Expect longer-duration trades, not rapid scalps
Use on quality tickers unlikely to permanently collapse
Confirm price behavior outside cash session
Test manually before automating anything
Not suitable for every market environment or asset
Notes on Philosophy
This strategy attempts to accumulate when markets overshoot lower, and distribute after recovery momentum fades. It reflects a patient, value-driven approach built on the principle of buying fear and reducing exposure into strength.
This is edge-based, not “trade every wiggle” logic
“Be fearful when others are greedy, and greedy when others are fearful.” — Buffett
“The stock market transfers money from the impatient to the patient.” — Buffett
Disclaimer
For research and educational use only. Not financial advice. Past performance does not guarantee future results. Test thoroughly and use appropriate risk management.
Hashtags
#buffett #quantstrategy #valuemomentum #accumulation #contrarian #nonrepaint #equitystrategy #swingtrading #liquidityanalysis #synthetichtf #tradingviewstrategy
Pinbar MTF - No Repaint# Pinbar MTF - No Repaint Indicator
## Complete Technical Documentation
---
## 📊 Overview
**Pinbar MTF (Multi-Timeframe) - No Repaint** is a professional-grade TradingView Pine Script indicator designed to detect high-probability pinbar reversal patterns with advanced filtering systems. The indicator is specifically engineered to be **100% non-repainting**, making it reliable for both live trading and backtesting.
### Key Features
✅ **Non-Repainting** - Signals only appear AFTER bar closes, never disappear
✅ **Three-Layer Filter System** - ATR, SWING, and RSI filters
✅ **Automatic SL/TP Calculation** - Based on risk:reward ratios
✅ **Real-time Alerts** - TradingView notifications for all signals
✅ **Visual Trade Management** - Lines, labels, and areas for entries, stops, and targets
✅ **Backtesting Ready** - Reliable historical data for strategy testing
---
## 🎯 What is a Pinbar?
A **Pinbar (Pin Bar/Pinocchio Bar)** is a single candlestick pattern that indicates a potential price reversal:
### Bullish Pinbar (BUY Signal)
- **Long lower wick** (rejection of lower prices)
- **Small body at the top** of the candle
- Shows buyers rejected sellers' attempt to push price down
- Forms at support levels or swing lows
- Entry signal for LONG positions
### Bearish Pinbar (SELL Signal)
- **Long upper wick** (rejection of higher prices)
- **Small body at the bottom** of the candle
- Shows sellers rejected buyers' attempt to push price up
- Forms at resistance levels or swing highs
- Entry signal for SHORT positions
---
## 🔧 How the Indicator Works
### 1. **Pinbar Detection Logic**
The indicator analyzes the **previous closed bar  ** to identify pinbar patterns:
```
Bullish Pinbar Requirements:
- Lower wick > 72% of total candle range (adjustable)
- Upper wick < 28% of total candle range
- Close > Open (bullish candle body)
Bearish Pinbar Requirements:
- Upper wick > 72% of total candle range (adjustable)
- Lower wick < 28% of total candle range
- Close < Open (bearish candle body)
```
**Why check  ?** By analyzing the previous completed bar, we ensure the pattern is fully formed and won't change, preventing repainting.
---
### 2. **Three-Layer Filter System**
#### 🔍 **Filter #1: ATR (Average True Range) Filter**
- **Purpose**: Ensures the pinbar has significant size
- **Function**: Only signals if pinbar range ≥ ATR value
- **Benefit**: Filters out small, insignificant pinbars
- **Settings**:
  - Enable/Disable toggle
  - ATR Period (default: 7)
**Example**: If ATR = 50 pips, only pinbars with 50+ pip range will signal.
---
#### 🔍 **Filter #2: SWING Filter** (Always Active)
- **Purpose**: Confirms pinbar forms at swing highs/lows
- **Function**: Validates the pinbar is an absolute high/low
- **Benefit**: Identifies true reversal points
- **Settings**:
  - Swing Candles (default: 3)
**How it works**: 
- For bullish pinbar: Checks if low is lowest of past 3 bars
- For bearish pinbar: Checks if high is highest of past 3 bars
**Example**: With 3 swing candles, a bullish pinbar must have the lowest low among the last 3 bars.
---
#### 🔍 **Filter #3: RSI (Relative Strength Index) Filter**
- **Purpose**: Confirms momentum conditions
- **Function**: Prevents signals in extreme momentum zones
- **Benefit**: Avoids counter-trend trades
- **Settings**:
  - Enable/Disable toggle
  - RSI Period (default: 7)
  - RSI Source (Close, Open, High, Low, HL2, HLC3, OHLC4)
  - Overbought Level (default: 70)
  - Oversold Level (default: 30)
**Logic**:
- Bullish Pinbar: Only signals if RSI < 70 (not overbought)
- Bearish Pinbar: Only signals if RSI > 30 (not oversold)
---
### 3. **Stop Loss Calculation**
Two methods available:
#### Method A: ATR-Based Stop Loss (Recommended)
```
Bullish Pinbar:
SL = Pinbar Low - (1 × ATR)
Bearish Pinbar:
SL = Pinbar High + (1 × ATR)
```
**Benefit**: Dynamic stops that adapt to market volatility
#### Method B: Fixed Pips Stop Loss
```
Bullish Pinbar:
SL = Pinbar Low - (Fixed Pips)
Bearish Pinbar:
SL = Pinbar High + (Fixed Pips)
```
**Settings**:
- Calculate Stop with ATR (toggle)
- Stop Pips without ATR (default: 5)
---
### 4. **Take Profit Calculation**
Take Profit is calculated based on Risk:Reward ratio:
```
Bullish Trade:
TP = Entry + (Entry - SL) × Risk:Reward Ratio
Bearish Trade:
TP = Entry - (SL - Entry) × Risk:Reward Ratio
```
**Example**:
- Entry: 1.2000
- SL: 1.1950 (50 pip risk)
- RR: 2:1
- TP: 1.2100 (100 pip reward = 50 × 2)
**Settings**:
- Risk:Reward Ratio (default: 1.0, range: 0.1 to 10.0)
---
## 📈 Visual Elements
### On-Chart Displays
1. **Signal Markers**
   - 🟢 **Green Triangle Up** = Bullish Pinbar (BUY)
   - 🔴 **Red Triangle Down** = Bearish Pinbar (SELL)
   - Placed directly on the pinbar candle
2. **Entry Labels**
   - Green "BUY" label with entry price
   - Red "SELL" label with entry price
   - Shows exact entry level
3. **Stop Loss Lines**
   - 🔴 Red horizontal line
   - "SL" label
   - Extends 20 bars forward
4. **Take Profit Lines**
   - 🟢 Green horizontal line
   - "TP" label
   - Extends 20 bars forward
5. **Risk/Reward Areas** (Optional)
   - Red shaded box = Risk zone (Entry to SL)
   - Green shaded box = Reward zone (Entry to TP)
   - Visual risk:reward visualization
6. **Info Table** (Top Right)
   - Displays current settings
   - Shows filter status (ON/OFF)
   - Real-time RSI value
   - Quick reference panel
---
## 🔔 Alert System
Three alert types available:
### 1. Combined Alert: "Pinbar Signal (Any Direction)"
- Fires for BOTH bullish and bearish pinbars
- **Best for**: General monitoring
- **Message**: "Pinbar Signal Detected on {TICKER} at {PRICE}"
### 2. Bullish Alert: "Bullish Pinbar Alert"
- Fires ONLY for BUY signals
- **Best for**: Long-only strategies
- **Message**: "BUY Signal on {TICKER} at {PRICE}"
### 3. Bearish Alert: "Bearish Pinbar Alert"
- Fires ONLY for SELL signals
- **Best for**: Short-only strategies
- **Message**: "SELL Signal on {TICKER} at {PRICE}"
---
## ⚙️ Input Parameters Reference
### **Filters Group**
| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| ATR Filter on Pinbar Range? | ✅ ON | Boolean | Enable/disable ATR filter |
| ATR Period | 7 | 1+ | Lookback period for ATR calculation |
| Swing Candles | 3 | 1+ | Bars to check for swing high/low |
| RSI Filter on Pinbar? | ❌ OFF | Boolean | Enable/disable RSI filter |
| RSI Period | 7 | 2+ | Lookback period for RSI calculation |
| RSI Source | Close | Multiple | Price data for RSI (Close/Open/High/Low/etc) |
| RSI Overbought Level | 70 | 50-100 | Upper threshold for RSI filter |
| RSI Oversold Level | 30 | 0-50 | Lower threshold for RSI filter |
### **Pinbar Detection Group**
| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| Shadow % vs Body | 72 | 50-95 | Minimum wick size as % of total range |
### **Visualization Group**
| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| Show SL and TP Lines? | ✅ ON | Boolean | Display stop loss and take profit lines |
| Show SL and TP Area? | ❌ OFF | Boolean | Show shaded risk/reward boxes |
### **Risk Management Group**
| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| Risk:Reward Ratio | 1.0 | 0.1-10.0 | Target profit vs risk (1.0 = 1:1, 2.0 = 1:2) |
| Calculate Stop with ATR? | ✅ ON | Boolean | Use ATR for stop calculation |
| Stop Pips without ATR | 5 | 1+ | Fixed pip stop when ATR disabled |
---
## 🚫 Non-Repainting Architecture
### What is Repainting?
**Repainting** occurs when an indicator's historical signals differ from what appeared in real-time. This makes backtesting unreliable and can lead to false confidence in a strategy.
### How This Indicator Prevents Repainting
1. **Closed Bar Analysis**
   - All calculations use ` ` offset (previous bar)
   - Only analyzes COMPLETED candles
   - Signals appear on the bar AFTER the pinbar closes
2. **Confirmed Swing Points**
   - Waits for sufficient bar history before signaling
   - Only checks historical bars that cannot change
   - Prevents premature swing detection
3. **Static Alert Timing**
   - Alerts fire only after bar completion
   - No conditional logic that changes historically
   - Same results in replay mode and live trading
### Verification Method
To verify non-repainting behavior:
1. Apply indicator to chart
2. Note signal locations and prices
3. Refresh browser / reload chart
4. **Signals remain in exact same locations**
---
## 💼 Trading Strategy Guidelines
### Entry Rules
**For Bullish Pinbar (LONG):**
1. Wait for green triangle to appear
2. Enter at close of pinbar (shown in label)
3. Alternative: Enter on break of pinbar high
4. Place stop loss at red SL line
5. Set target at green TP line
**For Bearish Pinbar (SHORT):**
1. Wait for red triangle to appear
2. Enter at close of pinbar (shown in label)
3. Alternative: Enter on break of pinbar low
4. Place stop loss at red SL line
5. Set target at green TP line
### Risk Management
- **Position Sizing**: Risk only 1-2% of account per trade
- **Stop Loss**: Always use the calculated SL (never move it wider)
- **Take Profit**: Use calculated TP or trail stop after 1:1 RR
- **Multiple Timeframes**: Confirm signals on higher timeframe
### Best Practices
✅ **DO:**
- Wait for bar to close before entering
- Trade in direction of higher timeframe trend
- Use on liquid markets with clear support/resistance
- Combine with price action analysis
- Keep a trading journal
❌ **DON'T:**
- Enter before bar closes (prevents seeing full pattern)
- Trade against strong trends
- Ignore the filters (they improve win rate)
- Risk more than 2% per trade
- Trade every signal (be selective)
---
## 📊 Backtesting & Data Export
### Available Data Points
The indicator exports these values for strategy development:
| Output | Description |
|--------|-------------|
| Bullish Signal | 1 = BUY signal, 0 = No signal |
| Bearish Signal | 1 = SELL signal, 0 = No signal |
| Bull SL | Stop loss level for long trades |
| Bull TP | Take profit level for long trades |
| Bull Entry | Entry price for long trades |
| Bear SL | Stop loss level for short trades |
| Bear TP | Take profit level for short trades |
| Bear Entry | Entry price for short trades |
### How to Use in Strategy
These values can be accessed by Pine Script strategies using:
```pine
indicator_values = request.security(syminfo.tickerid, timeframe.period, 
                    )
```
---
## 🎓 Understanding the Filters
### Why Use Multiple Filters?
Single-indicator systems often generate too many false signals. This indicator uses a **confluence approach**:
1. **Pinbar Pattern** = Price rejection detected
2. **+ SWING Filter** = Rejection at key level
3. **+ ATR Filter** = Significant move
4. **+ RSI Filter** = Favorable momentum
**Result**: Higher probability setups with better risk:reward
### Filter Optimization
**Conservative Settings** (Fewer, Higher Quality Signals):
- ATR Filter: ON
- Swing Candles: 5
- RSI Filter: ON
- Shadow %: 75%
**Aggressive Settings** (More Signals, More Noise):
- ATR Filter: OFF
- Swing Candles: 2
- RSI Filter: OFF
- Shadow %: 65%
**Balanced Settings** (Recommended):
- ATR Filter: ON
- Swing Candles: 3
- RSI Filter: OFF (or ON for trending markets)
- Shadow %: 72%
---
## 🔍 Troubleshooting
### "No Signals Appearing"
**Possible Causes:**
1. Filters are too strict
2. No pinbars forming on chart
3. Insufficient bar history
**Solutions:**
- Reduce Shadow % to 65%
- Reduce Swing Candles to 2
- Disable ATR or RSI filters temporarily
- Check that chart has enough data loaded
### "Too Many Signals"
**Solutions:**
- Enable ATR filter
- Increase Swing Candles to 4-5
- Enable RSI filter
- Increase Shadow % to 75-80%
### "Signals Appearing Late"
**This is normal behavior!** The indicator:
- Analyzes previous closed bar  
- Signals appear on the bar AFTER the pinbar
- This is what prevents repainting
- Signal latency is 1 bar (by design)
---
## 📝 Technical Specifications
**Indicator Type:** Overlay (displays on price chart)
**Pine Script Version:** 5
**Max Labels:** 500
**Max Lines:** 500
**Repainting:** None (100% non-repainting)
**Data Window Values:** 8 exported values
**Alert Types:** 3 (Combined, Bullish, Bearish)
**Performance:**
- Lightweight script (fast execution)
- Works on all timeframes
- Compatible with all markets (Forex, Crypto, Stocks, Futures)
- No data snooping bias
---
## 🎯 Use Cases
### 1. **Swing Trading**
- Timeframe: Daily, 4H
- Filter Settings: All enabled
- Best for: Catching major reversals
### 2. **Day Trading**
- Timeframe: 15m, 1H
- Filter Settings: ATR + SWING only
- Best for: Intraday reversals
### 3. **Scalping**
- Timeframe: 5m, 15m
- Filter Settings: SWING only (aggressive)
- Best for: Quick reversals (requires experience)
### 4. **Position Trading**
- Timeframe: Weekly, Daily
- Filter Settings: All enabled + high RR (2:1 or 3:1)
- Best for: Long-term trend reversal catches
---
## 🏆 Advantages Over Other Pinbar Indicators
✅ **Guaranteed Non-Repainting** - Many pinbar indicators repaint; this one never does
✅ **Automatic SL/TP** - No manual calculation needed
✅ **Multi-Layer Filtering** - Reduces false signals significantly
✅ **Visual Trade Management** - Clear entry, stop, and target levels
✅ **Flexible Configuration** - Adaptable to any trading style
✅ **Alert System** - Never miss a setup
✅ **Backtesting Ready** - Reliable historical data
✅ **Professional Grade** - Suitable for live trading
---
## 📚 Educational Resources
### Recommended Reading on Pinbars
- "The Pin Bar Trading Strategy" by Nial Fuller
- "Price Action Trading" by Al Brooks
- TradingView Education: Price Action Patterns
### Practice Recommendations
1. Paper trade signals for 20+ trades before live trading
2. Backtest on different timeframes and markets
3. Keep detailed records of all trades
4. Analyze winning vs losing setups
5. Refine filter settings based on results
---
## ⚖️ Disclaimer
This indicator is a tool for technical analysis and does not guarantee profits. Trading involves substantial risk of loss. Past performance is not indicative of future results. 
- Always use proper risk management
- Never risk more than you can afford to lose
- Consider your trading experience and objectives
- Seek independent financial advice if needed
---
## 📧 Version Information
**Current Version:** 1.0
**Last Updated:** 2024
**Compatibility:** TradingView Pine Script v5
**Status:** Production Ready
---
## 🔄 Future Enhancements (Potential)
Possible future additions:
- Multi-timeframe confirmation option
- Volume filter integration
- Customizable color schemes
- Win rate statistics display
- Partial profit taking levels
- Trailing stop functionality
---
## 📖 Quick Start Guide
### 5-Minute Setup
1. **Add to Chart**
   - Open TradingView
   - Go to Pine Editor
   - Paste the code
   - Click "Add to Chart"
2. **Configure Settings**
   - Open indicator settings (gear icon)
   - Start with default settings
   - Enable "Show SL and TP Lines"
3. **Set Alert**
   - Right-click indicator name
   - Click "Add Alert"
   - Select "Pinbar Signal (Any Direction)"
   - Configure notification method
4. **Test**
   - Scroll back on chart
   - Verify signals make sense
   - Check that signals don't repaint
5. **Trade** (After Practice!)
   - Wait for alert
   - Verify signal quality
   - Enter, place SL/TP
   - Manage trade
---
## 🎯 Final Thoughts
The **Pinbar MTF - No Repaint** indicator is designed for serious traders who value:
- **Reliability** over flashy signals
- **Quality** over quantity
- **Honesty** over false promises
This indicator will NOT:
- Make you rich overnight
- Win every trade
- Replace proper trading education
This indicator WILL:
- Identify high-probability reversal setups
- Save you analysis time
- Provide consistent, non-repainting signals
- Help you develop a systematic trading approach
**Success in trading comes from:**
1. Proper education (60%)
2. Risk management (30%)
3. Technical tools like this indicator (10%)
Use this tool as part of a complete trading plan, not as a standalone solution.
3D Session Clock | Live Time with Sessions [CHE]  3D Session Clock | Live Time with Sessions   — Projects a perspective clock face onto the chart to display current time and market session periods for enhanced situational awareness during trading hours.
  Summary 
This indicator renders a three-dimensional clock projection directly on the price chart, showing analog hands for hours, minutes, and seconds alongside a digital time readout. It overlays session arcs for major markets like New York, London, Tokyo, and Sydney, highlighting the active one with thicker lines and contrasting labels. By centralizing time and session visibility, it reduces the need to reference external clocks, allowing traders to maintain focus on price action while noting overlaps or transitions that influence volatility.
The design uses perspective projection to simulate depth, making the clock appear tilted for better readability on varying chart scales. Sessions are positioned radially outward from the main clock, with the current time marker pulsing on the relevant arc. This setup provides a static yet live-updating view, confirmed on bar close to avoid intrabar shifts.
  Motivation: Why this design? 
Traders often miss subtle session shifts amid fast-moving charts, leading to entries during low-liquidity periods or exits before peak activity. Standard chart tools lack integrated time visualization, forcing constant tab-switching. This indicator addresses that by embedding a customizable clock with session rings, ensuring time context is always in view without disrupting workflow.
  What’s different vs. standard approaches? 
- Reference baseline: Traditional session highlighters use simple background fills or vertical lines, which clutter the chart and ignore global time zones.
- Architecture differences:
  - Perspective projection rotates and scales points to mimic 3D depth, unlike flat 2D drawings.
  - Nested radial arcs for sessions, with dynamic radius assignment to avoid overlap.
  - Live time calculation adjusted for user-selected time zones, including optional daylight savings offset.
- Practical effect: The tilted view prevents labels from bunching at chart edges, and active session emphasis draws the eye to liquidity hotspots, making multi-session overlaps immediately apparent for better timing.
  How it works (technical) 
The indicator calculates current time in the selected time zone by adjusting the system timestamp with a fixed offset, plus an optional one-hour bump for daylight savings. This yields hour, minute, and second values that drive hand positions: the hour hand advances slowly with fractional minute input, the minute hand ticks per 60 seconds, and the second hand sweeps fully each minute.
Points for the clock face and arcs are generated as arrays of coordinates, transformed via rotation around the x-axis to apply tilt, then projected onto chart space using a scaling factor based on depth. Radial lines mark every hour from zero to 23, extending to the outermost session ring. Session arcs span user-defined hour ranges, drawn as open polylines with step interpolation for smoothness.
On the last bar, all prior drawings are cleared, and new elements are added: filled clock circles, hand lines from center to tip, a small orbiting circle at the current time position, and centered labels for hours, sessions, and time. The active session is identified by checking if the current time falls within its range, then its arc thickens and label inverts colors. Initialization populates a timezone array once, with persistent bar time tracking for horizontal positioning.
  Parameter Guide 
Clock Size — Controls overall radius in pixels, affecting visibility on dense charts — Default: 200 — Larger values suit wide screens but may crowd small views; start smaller for mobile.
Camera Angle — Sets tilt from top-down (zero) to side (90 degrees), altering projection depth — Default: 45 — Steeper angles enhance readability on sloped trends but flatten at extremes.
Resolution — Defines polygon sides for circles and arcs, balancing smoothness and draw calls — Default: 64 — Higher improves curves on large clocks; lower aids performance on slow devices.
Hour/Minute/Second Hand Length — Scales each hand from center, with seconds longest for precision — Defaults: 100/150/180 — Proportional sizing prevents overlap; shorten for compact layouts.
Clock Base Color — Tints face and frame — Default: blue — Neutral shades reduce eye strain; match chart theme.
Hand Colors — Assigns distinct hues to each hand — Defaults: red/green/yellow — High contrast aids quick scans; avoid chart-matching to stand out.
Hour Label Size — Text scale for 1-12 markers — Default: normal — Larger for distant views, but risks clutter.
Digital Time Size — Scale for HH:MM:SS readout — Default: large — Matches clock for balance; tiny for minimalism.
Digital Time Vertical Offset — Shifts readout up (negative) or down — Default: -50 — Positions above clock to avoid hand interference.
Timezone — Selects reference city/offset — Default: New York (UTC-05) — Matches trading locale; verify offsets manually.
Summer Time (DST) — Adds one hour if active — Default: false — Enable for regions observing it; test transitions.
Show/Label/Session/Color for Each Market — Toggles arc, sets name, time window, and hue per session (New York/London/Tokyo/Sydney) — Defaults: true/"New York"/1300-2200/orange, etc. — Customize windows to local exchange hours; colors differentiate overlaps.
  Reading & Interpretation 
The analog face shows a blue-tinted circle with white 1-12 labels and gray hour ticks; hands extend from center in assigned colors, pointing to current positions. A white dot with orbiting ring marks exact time on the session arc. Digital readout below displays padded HH:MM:SS in white on black.
Active sessions glow with bold arcs and white labels on colored backgrounds; inactive ones use thin lines and colored text on light fills. Overlaps stack outward, with the innermost (New York) closest to the clock. If no session is active, the marker sits on the base ring.
  Practical Workflows & Combinations 
- Trend following: Enter longs during London-New York overlap (thicker dual arcs) confirmed by higher highs; filter with volume spikes.
- Exits/Stops: Tighten stops pre-Tokyo open if arc thickens, signaling volatility ramp; trail during Sydney for overnight holds.
- Multi-asset/Multi-TF: Defaults work across forex/stocks; on higher timeframes, enlarge clock size to counter bar spacing. Pair with session volume oscillators for confirmation.
  Behavior, Constraints & Performance 
Rendering occurs only on the last bar, using confirmed history for stable display; live bars update hands and marker without repainting prior elements. No security calls or higher timeframe fetches, so no lookahead bias.
Resource limits include 2000 bars back for positioning, 500 each for lines, labels, and boxes—sufficient for full sessions without overflow. Arrays hold timezone data statically. On very wide charts, projection may skew slightly due to fixed scale.
Known limits: Visual positioning drifts on extreme zooms; daylight savings assumes manual toggle, risking one-hour errors during changes.
  Sensible Defaults & Quick Tuning 
Start with New York timezone, 45-degree tilt, and all sessions enabled—these balance global coverage without clutter. For too-small visibility, bump clock size to 300 and resolution to 48. If labels overlap on narrow views, reduce hand lengths proportionally. To emphasize one session (e.g., London), disable others and widen its color contrast. For minimalism, set digital size to small and offset to -100.
  What this indicator is—and isn’t 
This is a visual time and session overlay to contextualize trading windows, not a signal generator or predictive tool. It complements price analysis and risk rules but requires manual interpretation. Use alongside order flow or momentum indicators for decisions.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.  
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.  
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.  
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.  
 Best regards and happy trading  
Chervolino 
  Acknowledgments 
This indicator draws inspiration from the open-source contributions of the TradingView community, whose advanced programming techniques have greatly influenced its development. Special thanks to LonesomeTheBlue for the innovative polyline handling and midpoint centering techniques in RSI Radar Multi Time Frame: 
Gratitude also extends to LuxAlgo for the precise timezone calculations in Sessions: 
Finally, appreciation to TradingView for their comprehensive documentation on polyline features, including the support article at www.tradingview.com and the blog post at www.tradingview.com These resources were instrumental in implementing smooth, dynamic drawings.
Smart MACD Volume Trader# Smart MACD Volume Trader
## Overview
Smart MACD Volume Trader is an enhanced momentum indicator that combines the classic MACD (Moving Average Convergence Divergence) oscillator with an intelligent high-volume filter. This combination significantly reduces false signals by ensuring that trading signals are only generated when price momentum is confirmed by substantial volume activity.
The indicator supports over 24 different instruments including major and exotic forex pairs, precious metals (gold and silver), energy commodities (crude oil, natural gas), and industrial metals (copper). For forex and commodity traders, the indicator automatically maps to CME and COMEX futures contracts to provide accurate institutional-grade volume data.
## Originality and Core Concept
Traditional MACD indicators generate signals based solely on price momentum, which can result in numerous false signals during low-activity periods or ranging markets. This indicator addresses this critical weakness by introducing a volume confirmation layer with automatic institutional volume integration.
**What makes this approach original:**
- Signals are triggered only when MACD crossovers coincide with elevated volume activity
- Implements a lookback mechanism to detect volume spikes within recent bars
- Automatically detects and maps 24+ forex pairs and commodities to their corresponding CME and COMEX futures contracts
- Provides real institutional volume data for forex pairs where spot volume is unreliable
- Combines two independent market dimensions (price momentum and volume) into a single, actionable signal
- Includes intelligent asset detection that works across multiple exchanges and ticker formats
**The underlying principle:** Volume validates price movement. When institutional money enters the market, it creates volume signatures. By requiring high volume confirmation and using actual institutional volume data from futures markets, this indicator filters out weak price movements and focuses on trades backed by genuine market participation. The automatic futures mapping ensures that forex and commodity traders always have access to the most accurate volume data available, without manual configuration.
## How It Works
### MACD Component
The indicator calculates MACD using standard methodology:
1. **Fast EMA (default: 12 periods)** - Tracks short-term price momentum
2. **Slow EMA (default: 26 periods)** - Tracks longer-term price momentum  
3. **MACD Line** - Difference between Fast EMA and Slow EMA
4. **Signal Line (default: 9-period SMA)** - Smoothed average of MACD line
**Crossover signals:**
- **Bullish:** MACD line crosses above Signal line (momentum turning positive)
- **Bearish:** MACD line crosses below Signal line (momentum turning negative)
### Volume Filter Component
The volume filter adds an essential confirmation layer:
1. **Volume Moving Average** - Calculates exponential MA of volume (default: 20 periods)
2. **High Volume Threshold** - Multiplies MA by ratio (default: 2.0x or 200%)
3. **Volume Detection** - Identifies bars where current volume exceeds threshold
4. **Lookback Period** - Checks if high volume occurred in recent bars (default: 5 bars)
**Signal logic:**
- Buy/Sell signals only trigger when BOTH conditions are met:
  - MACD crossover/crossunder occurs
  - High volume detected within lookback period
### Automatic CME Futures Integration
For forex traders, spot FX volume data can be unreliable or non-existent. This indicator solves this problem by automatically detecting forex pairs and mapping them to corresponding CME futures contracts with real institutional volume data.
**Supported Major Forex Pairs (7):**
- EURUSD → CME:6E1! (Euro FX Futures)
- GBPUSD → CME:6B1! (British Pound Futures)
- AUDUSD → CME:6A1! (Australian Dollar Futures)
- USDJPY → CME:6J1! (Japanese Yen Futures)
- USDCAD → CME:6C1! (Canadian Dollar Futures)
- USDCHF → CME:6S1! (Swiss Franc Futures)
- NZDUSD → CME:6N1! (New Zealand Dollar Futures)
**Supported Exotic Forex Pairs (4):**
- USDMXN → CME:6M1! (Mexican Peso Futures)
- USDRUB → CME:6R1! (Russian Ruble Futures)
- USDBRL → CME:6L1! (Brazilian Real Futures)
- USDZAR → CME:6Z1! (South African Rand Futures)
**Supported Cross Pairs (6):**
- EURJPY → CME:6E1! (Uses Euro Futures)
- GBPJPY → CME:6B1! (Uses British Pound Futures)
- EURGBP → CME:6E1! (Uses Euro Futures)
- AUDJPY → CME:6A1! (Uses Australian Dollar Futures)
- EURAUD → CME:6E1! (Uses Euro Futures)
- GBPAUD → CME:6B1! (Uses British Pound Futures)
**Supported Precious Metals (2):**
- Gold (XAUUSD, GOLD) → COMEX:GC1! (Gold Futures)
- Silver (XAGUSD, SILVER) → COMEX:SI1! (Silver Futures)
**Supported Energy Commodities (3):**
- WTI Crude Oil (USOIL, WTIUSD) → NYMEX:CL1! (Crude Oil Futures)
- Brent Oil (UKOIL) → NYMEX:BZ1! (Brent Crude Futures)
- Natural Gas (NATGAS) → NYMEX:NG1! (Natural Gas Futures)
**Supported Industrial Metals (1):**
- Copper (COPPER) → COMEX:HG1! (Copper Futures)
**How the automatic detection works:**
The indicator intelligently identifies the asset type by analyzing:
1. Exchange name (FX, OANDA, TVC, COMEX, NYMEX, etc.)
2. Currency pair pattern (6-letter codes like EURUSD, GBPUSD)
3. Commodity identifiers (XAU for gold, XAG for silver, OIL for crude)
When a supported instrument is detected, the indicator automatically switches to the corresponding futures contract for volume analysis. For stocks, cryptocurrencies, and other assets, the indicator uses the native volume data from the current chart.
**Visual feedback:**
An information table appears in the top-right corner of the MACD pane showing:
- Current chart symbol
- Exchange name
- Currency pair or asset name
- Volume source being used (highlighted in orange for futures, yellow for native volume)
- Current high volume status
This provides complete transparency about which data source the indicator is using for its volume analysis.
## How to Use
### Basic Setup
1. Add the indicator to your chart
2. The indicator displays in a separate pane (MACD) and overlay (signals/volume bars)
3. Default settings work well for most assets, but can be customized
### Signal Interpretation
### Visual Signals
**Visual Signals:**
- **Green "BUY" label** - Bullish MACD crossover confirmed by high volume
- **Red "SELL" label** - Bearish MACD crossunder confirmed by high volume
- **Green/Red candles** - Highlight bars with volume exceeding the threshold
- **Light green/red background** - Emphasizes signal bars on the chart
**Information Table:**
A detailed information table appears in the top-right corner of the MACD pane, providing real-time transparency about the indicator's operation:
- **Chart:** Current symbol being analyzed
- **Exchange:** The exchange or data feed being used
- **Pair:** The currency pair or asset name extracted from the ticker
- **Volume From:** The actual symbol used for volume analysis
  - Orange color indicates CME or COMEX futures are being used (automatic institutional volume)
  - Yellow color indicates native volume from the chart symbol is being used
  - Hover tooltip shows whether automatic futures mapping is active
- **High Volume:** Current status showing YES (green) when volume exceeds threshold, NO (gray) otherwise
This table ensures complete transparency and allows you to verify that the correct volume source is being used for your analysis.
**Volume Analysis:**
- Gray histogram bars = Normal volume
- Red histogram bars = High volume (exceeds threshold)
- Green line = Volume moving average baseline
**MACD Analysis:**
- Blue line = MACD line (momentum indicator)
- Orange line = Signal line (trend confirmation)
- Gray dotted line = Zero line (bullish above, bearish below)
### Parameter Customization
**MACD Parameters:**
- Adjust Fast/Slow EMA lengths for different sensitivities
- Shorter periods = More signals, faster response
- Longer periods = Fewer signals, less noise
**Volume Parameters:**
- **Volume MA Period:** Higher values smooth volume analysis
- **High Volume Ratio:** Lower values (1.5x) = More signals; Higher values (3.0x) = Fewer, stronger signals
- **Volume Lookback Bars:** Controls how recent the volume spike must be
**Direction Filters:**
- **Only Buy Signals:** Enables long-only strategy mode
- **Only Sell Signals:** Enables short-only strategy mode
### Alert Configuration
The indicator includes three alert types:
1. **Buy Signal Alert** - Triggers when bullish signal appears
2. **Sell Signal Alert** - Triggers when bearish signal appears  
3. **High Volume Alert** - Triggers when volume exceeds threshold
To set up alerts:
1. Click the indicator name → "Add alert on Smart MACD Volume Trader"
2. Select desired alert condition
3. Configure notification method (popup, email, webhook, etc.)
## Trading Strategy Guidelines
### Best Practices
**Recommended markets:**
- Liquid stocks (large-cap, high daily volume)
- Major forex pairs (EURUSD, GBPUSD, USDJPY, AUDUSD, USDCAD, USDCHF, NZDUSD)
- Exotic forex pairs (USDMXN, USDRUB, USDBRL, USDZAR)
- Cross pairs (EURJPY, GBPJPY, EURGBP, AUDJPY, EURAUD, GBPAUD)
- Precious metals (Gold, Silver with automatic COMEX futures mapping)
- Energy commodities (Crude Oil, Natural Gas with automatic NYMEX futures mapping)
- Industrial metals (Copper with automatic COMEX futures mapping)
- Major cryptocurrency pairs
- Index futures and ETFs
**Timeframe recommendations:**
- **Day trading:** 5-minute to 15-minute charts
- **Swing trading:** 1-hour to 4-hour charts  
- **Position trading:** Daily charts
**Risk management:**
- Use signals as entry confirmation, not standalone strategy
- Combine with support/resistance levels
- Consider overall market trend direction
- Always use stop-loss orders
### Strategy Examples
**Trend Following Strategy:**
1. Identify overall trend using higher timeframe (e.g., daily chart)
2. Trade only in trend direction
3. Use "Only Buy" filter in uptrends, "Only Sell" in downtrends
4. Enter on signal, exit on opposite signal or at resistance/support
**Volume Breakout Strategy:**
1. Wait for consolidation period (low volume, tight MACD range)
2. Enter when signal appears with high volume (confirms breakout)
3. Target previous swing highs/lows
4. Stop loss below/above recent consolidation
**Forex Scalping Strategy (with automatic CME futures):**
1. The indicator automatically detects forex pairs and uses CME futures volume
2. Trade during active sessions only (use session filter)
3. Focus on quick profits (10-20 pips)
4. Exit at opposite signal or profit target
**Commodities Trading Strategy (Gold, Silver, Oil):**
1. The indicator automatically maps to COMEX and NYMEX futures contracts
2. Trade during high-liquidity sessions (overlap of major markets)
3. Use the high volume confirmation to identify institutional entry points
4. Combine with key support and resistance levels for entries
5. Monitor the information table to confirm futures volume is being used (orange color)
6. Exit on opposite MACD signal or at predefined profit targets
## Why This Combination Works
### The Volume Advantage
Studies consistently show that price movements accompanied by high volume are more likely to continue, while low-volume movements often reverse. This indicator leverages this principle by requiring volume confirmation.
**Key benefits:**
1. **Reduced False Signals:** Eliminates MACD whipsaws during low-volume consolidation
2. **Confirmation Bias:** Two independent indicators (price momentum + volume) agreeing
3. **Institutional Alignment:** High volume often indicates institutional participation
4. **Trend Validation:** Volume confirms that price momentum has "conviction"
### Statistical Edge
By combining two uncorrelated signals (MACD crossovers and volume spikes), the indicator creates a higher-probability setup than either signal alone. The lookback mechanism ensures signals aren't missed if volume spike slightly precedes the MACD cross.
## Supported Exchanges and Automatic Detection
The indicator includes intelligent asset detection that works across multiple exchanges and ticker formats:
**Forex Exchanges (Automatic CME Mapping):**
- FX (TradingView forex feed)
- OANDA
- FXCM
- SAXO
- FOREXCOM
- PEPPERSTONE
- EASYMARKETS
- FX_IDC
**Commodity Exchanges (Automatic COMEX/NYMEX Mapping):**
- TVC (TradingView commodity feed)
- COMEX (directly)
- NYMEX (directly)
- ICEUS
**Other Asset Classes (Native Volume):**
- Stock exchanges (NASDAQ, NYSE, AMEX, etc.)
- Cryptocurrency exchanges (BINANCE, COINBASE, KRAKEN, etc.)
- Index providers (SP, DJ, etc.)
The detection algorithm analyzes three factors:
1. Exchange prefix in the ticker symbol
2. Pattern matching for currency pairs (6-letter codes)
3. Commodity identifiers in the symbol name
This ensures accurate automatic detection regardless of which data feed or exchange you use for charting. The information table in the top-right corner always displays which volume source is being used, providing complete transparency.
## Technical Details
**Calculations:**
- MACD Fast MA: EMA(close, fastLength)
- MACD Slow MA: EMA(close, slowLength)
- MACD Line: Fast MA - Slow MA
- Signal Line: SMA(MACD Line, signalLength)
- Volume MA: Exponential MA of volume
- High Volume: Current volume >= Volume MA × Ratio
**Signal logic:**
```
Buy Signal = (MACD crosses above Signal) AND (High volume in last N bars)
Sell Signal = (MACD crosses below Signal) AND (High volume in last N bars)
```
## Parameters Reference
| Parameter | Default | Description |
|-----------|---------|-------------|
| Volume Symbol | Blank | Manual override for volume source (leave blank for automatic detection) |
| Use CME Futures | False | Legacy option (automatic detection is now built-in) |
| Alert Session | 1530-2200 | Active session time range for alerts |
| Timezone | UTC+1 | Timezone for alert sessions |
| Volume MA Period | 20 | Number of periods for volume moving average |
| High Volume Ratio | 2.0 | Volume threshold multiplier (2.0 = 200% of average) |
| Volume Lookback | 5 | Number of bars to check for high volume confirmation |
| MACD Fast Length | 12 | Fast EMA period for MACD calculation |
| MACD Slow Length | 26 | Slow EMA period for MACD calculation |
| MACD Signal Length | 9 | Signal line SMA period |
| Only Buy | False | Filter to show only bullish signals |
| Only Sell | False | Filter to show only bearish signals |
| Show Signals | True | Display buy and sell labels on chart |
## Optimization Tips
**For volatile markets (crypto, small caps):**
- Increase High Volume Ratio to 2.5-3.0
- Reduce Volume Lookback to 3-4 bars
- Consider faster MACD settings (8, 17, 9)
**For stable markets (large-cap stocks, bonds):**
- Decrease High Volume Ratio to 1.5-1.8
- Increase Volume MA Period to 30-50
- Use standard MACD settings
**For forex (with automatic CME futures):**
- The indicator automatically uses CME futures when forex pairs are detected
- Set appropriate trading session based on your timezone
- Use Volume Lookback of 5-7 bars
- Consider session-based alerts only
- Monitor the information table to verify correct futures mapping
**For commodities (Gold, Silver, Oil, Copper):**
- The indicator automatically maps to COMEX and NYMEX futures
- Increase High Volume Ratio to 2.0-2.5 for metals
- Use slightly higher Volume MA Period (25-30) for smoother analysis
- Trade during active market hours for best volume data
- The information table will show the futures contract being used (orange highlight)
## Limitations and Considerations
**What this indicator does NOT do:**
- Does not predict future price direction
- Does not guarantee profitable trades
- Does not replace proper risk management
- Does not work well in extremely low-volume conditions
**Market conditions to avoid:**
- Pre-market and after-hours sessions (low volume)
- Major news events (volatile, unpredictable volume)
- Holidays and low-liquidity periods
- Extremely low float stocks
## Conclusion
Smart MACD Volume Trader represents a significant evolution of the traditional MACD indicator by combining volume confirmation with automatic institutional volume integration. This dual-confirmation approach significantly improves signal quality by filtering out low-conviction price movements and ensuring traders work with accurate volume data.
The indicator's automatic detection and mapping system supports over 24 instruments across forex, commodities, and metals markets. By intelligently switching to CME and COMEX futures contracts when appropriate, the indicator provides forex and commodity traders with the same quality of volume data that stock traders naturally have access to.
This indicator is particularly valuable for traders who want to:
- Align their entries with institutional money flow
- Avoid getting trapped in false breakouts
- Trade forex pairs with reliable volume data
- Access accurate volume information for gold, silver, and energy commodities
- Combine momentum and volume analysis in a single, streamlined tool
Whether you are day trading stocks, swing trading forex pairs, or positioning in commodities markets, this indicator provides a robust framework for identifying high-probability momentum trades backed by genuine institutional participation. The automatic futures mapping works seamlessly across all supported instruments, requiring no manual configuration or expertise in futures markets.
---
## Support and Updates
This indicator is actively maintained and updated based on user feedback and market conditions. For questions about implementation or custom modifications, please use the comments section below.
**Disclaimer:** This indicator is for educational and informational purposes only. Past performance does not guarantee future results. Always conduct your own analysis and risk management before trading.
ICT Killzones & MacrosICT Killzones & Macros (v1.1.5)  — configurable ICT session windows + refined “macro” windows with live High/Low levels, optional extensions, next-window previews, and lightweight opening-price lines. Built to be clock-robust, timezone-aware, and performant on intraday charts.
 Tip:  All times are interpreted in your chosen IANA timezone (default: America/New_York) and auto-handle DST. You can rename, recolor, enable/disable, and retime every window. 
 What it plots 
-  Killzones (5) : Asia (19:00–02:00), London (02:00–05:00), NY AM (07:00–09:30), London Close (10:00–12:00), NY PM (13:30–16:00) — full-height boxes with optional header.
-  Macros (8)  (defaults tailored for common ICT “refined” windows): Asia-1 (18:00–21:00), Asia-2 (21:00–00:00), London-1 (01:00–04:00), AM-1 (09:45–10:15), AM-2 (10:45–11:15), Lunch (12:00–13:00), PM-1 (13:30–14:30), Power Hour (15:10–16:00).
-  Live High/Low lines  for the current Macro/Killzone window.
-  Optional HL extension  to the right until price crosses or the trading day rolls (style selectable).
-  “Next” previews : earliest upcoming Macro and Killzone header; optional next-window background band.
-  Opening Prices (3 lightweight time lines) : defaults 00:00, 08:30, 09:30 with right-edge labels, scoped to a session you choose (auto-cleans at session end).
-  Key inputs & styling 
-  General : Timezone (IANA), “Sessions to show” (per window) to keep only the last N completed windows.
-  Header : height (ticks), gap (ticks), fill opacity, border width/style, text size/color, toggle “Next Macro/Killzone” headers.
-  Boxes : global fill opacity, global border width/style (used by both Macros & Killzones).
-  High/Low : show HL, HL line style, extend on/off + extension style, optional extension labels.
-  Opening Prices : enable Time 1/2/3, set HH:MM for each, session window, per-line colors, style (dotted/dashed/solid), width.
-  Per-window controls : each Macro/Killzone has Enable, Session (HHMM-HHMM), Label, Fill color.
 How to use (quick start) 
- Set  Timezone  to your preference (default America/New_York).
- Toggle on the  Macros  and  Killzones  you trade. Adjust session times if needed.
- (Optional) Turn on  Extend High/Low  to project levels until crossed/day-roll.
- (Optional) Enable  Next… headers  to see the next upcoming window at a glance.
- (Optional) Configure  Opening Prices  (00:00 / 08:30 / 09:30 by default) and the session over which they appear.
 Behavior & notes 
- Time windows are computed by clock, not by guessing bar timestamps, making them robust across brokers and timeframes.
- With HL extension on, the current window’s levels extend until crossed or the end of the trading day (in your timezone). With it off, completed windows keep static HL markers (limited by “Sessions to show”).
- “Sessions to show” applies per Macro/Killzone to automatically prune older windows and keep charts snappy.
- Opening-price lines exist only within the chosen “Opening Prices Session” and are removed when it ends (keeps charts clean).
 Defaults (color cues) 
Killzones: Asia (blue), London (purple), NY AM (green), London Close (yellow), NY PM (orange).
Macros: neutral greys with Lunch and PM accents out of the box (all customizable).
 Performance tips 
- Reduce “Sessions to show” if you scroll far back in history.
- Disable “Next…” previews and/or extension labels on very slow machines.
- Narrow the “Opening Prices Session” window to exactly when you need those lines.
 Changelog highlights 
-  v1.1.5 : Internal refinements and stability.
-  v1.1.3 : Live High/Low lines for current windows + optional extension.
-  v1.1.2 : Added “next Killzone” preview (to match “next Macro”).
-  v1.1.0 : Defaults updated (5 KZ, 8 Macros). Removed “snap-to-killzone” behavior.
-  v1.0.0 : Independent Macro vs. Killzone rendering; cleaner header logic.
-  Known limitations 
If your chart warns about drawings, trim “Sessions to show”.
If your broker session times differ from NY hours, adjust the sessions or change the indicator timezone.
 Credits & intent 
Inspired by ICT timing concepts; provided for education/mark-up, not financial advice.
Built to be flexible so you can mirror your personal playbook and journaling workflow.
Larry Williams Oops StrategyThis strategy is a modern take on Larry Williams’ classic Oops setup. It trades intraday while referencing daily bars to detect opening gaps and align entries with the prior day’s direction. Risk is managed with day-based stops, and—unlike the original—all positions are closed at the end of the session (or at the last bar’s close), not at a fixed profit target or the first profitable open.
 Entry Rules 
 
 Long setup (bullish reversion): Today opens below yesterday’s low (down gap) and yesterday’s candle was bearish. Place a buy stop at yesterday’s low + Filter (ticks).
 Short setup (bearish reversion): Today opens above yesterday’s high (up gap) and yesterday’s candle was bullish. Place a sell stop at yesterday’s high − Filter (ticks).
 Longs are only taken on down-gap days; shorts only on up-gap days.
 
 Protective Stop
 
 
 If long, stop loss trails the current day’s low.
 If short, stop loss trails the current day’s high.
 
 Exit Logic 
Positions are force-closed at the end of the session (in the last bar), ensuring no overnight exposure. There is no take-profit; only stop loss or end-of-day flat.
 Notes 
This strategy is designed for intraday charts (minutes/seconds) using daily data for gaps and prior-day direction.
Longs/shorts can be enabled or disabled independently.
Tchwella Stocks Custom WatermarkThis Pine Script v5 indicator adds a customizable watermark to TradingView charts, displaying key stock information while allowing for flexible positioning and formatting.
📌 Features & Functionality:
✅ Custom Positioning:
• Fixed to the top-left corner.
• Adjustable spacing ensures the text is properly aligned.
✅ Displayed Information (Configurable):
• Company Name & Market Cap (Optional: Shows dynamically calculated market cap)
• Stock Ticker & Timeframe
• Industry & Sector
✅ Customization Options:
• Font Size: Huge, Large, Normal, Small
• Text Color & Transparency: Adjustable
• Proper Left Alignment for a clean, structured display
• Vertical Offset Tweaks to move text down for better visibility
✅ Optimized Table Layout:
• Uses table.new() for persistent placement.
• Added an empty row to fine-tune positioning, ensuring the watermark doesn’t overlap key chart areas.
🔧 Use Case:
Designed for traders who want a clear, customizable stock watermark to enhance their charting experience without obstructing price action.
Feb 1
Release Notes
Updated version: now you can decide your location for the watermark
Micha Stocks Custom Watermark (MSWM) – TradingView Script
This Pine Script v5 indicator adds a customizable watermark to TradingView charts, displaying key stock information while allowing for flexible positioning and formatting.
📌 Features & Functionality:
✅ Custom Positioning:
• Fixed to the top-left corner.
• Adjustable spacing ensures the text is properly aligned.
✅ Displayed Information (Configurable):
• Company Name & Market Cap (Optional: Shows dynamically calculated market cap)
• Stock Ticker & Timeframe
• Industry & Sector
✅ Customization Options:
• Font Size: Huge, Large, Normal, Small
• Text Color & Transparency: Adjustable
• Proper Left Alignment for a clean, structured display
• Vertical Offset Tweaks to move text down for better visibility
✅ Optimized Table Layout:
• Uses table.new() for persistent placement.
• Added an empty row to fine-tune positioning, ensuring the watermark doesn’t overlap key chart areas.
🔧 Use Case:
Designed for traders who want a clear, customizable stock watermark to enhance their charting experience without obstructing price action.
Feb 7
Release Notes
Micha Stocks Custom Watermark – Updated Version 🚀
This updated Micha Stocks Custom Watermark script enhances your TradingView experience by adding an ATR-based volatility signal alongside the existing customizable stock watermark.
🆕 New Features & Improvements:
✅ ATR (14-Day) with Dynamic Volatility Indicator
• Displays the ATR value and its percentage relative to price.
• Includes a color-coded volatility signal:
• 🔴 High Volatility (Above user-defined Red Threshold)
• 🟡 Moderate Volatility (Between Red & Yellow Thresholds)
• 🟢 Low Volatility (Below user-defined Yellow Threshold)
✅ Fully Customizable ATR Thresholds
• Users can set their own ATR % levels for Red, Yellow, and Green signals.
✅ Improved Watermark Customization
• Users can still adjust the position, size, and color of the watermark.
• Includes Company Name, Ticker, Market Cap, Industry, and Sector.
• ATR can be turned on/off in settings for flexibility.
🔧 How to Use:
1️⃣ Go to Indicator Settings → Enable or Disable ATR Display
2️⃣ Adjust ATR % Thresholds to fit your volatility preference
3️⃣ Customize Text Position, Color, and Size to match your chart setup
This update makes it easier to quickly assess market volatility while keeping a clean and professional chart layout.
💡 Why Use This Indicator?
• Effortlessly track key stock info without cluttering your chart.
• Quickly identify volatile conditions using ATR percentage signals.
• Adjust settings on the fly to match your trading strategy.
📢 Update Now & Enjoy a Smarter Charting Experience!
SMT (DXY) DIVERGENCESThis indicator detects Smart Money Technique (SMT) Divergences between the chart symbol and up to two comparison symbols defined in the settings.
It identifies swing highs and swing lows on correlated/uncorrelated instruments, compares their highs and lows, and determines possible divergences.
 🔷 What It Detects 
-Bullish SMT Divergence: When the lows of the chart symbol slope in the opposite direction of the comparison symbol’s lows.
-Bearish SMT Divergence: When the highs of the chart symbol slope in the opposite direction of the comparison symbol’s highs.
-Multi-Symbol Compatibility: Ability to compare the main symbol with one or two external tickers (default: DXY and GBPUSD).
-Negative Divergence Option: The inversion feature allows comparison with opposite-moving charts.
 
 🔷 Calculation Logic 
-Swing Detection: Swing highs and lows are confirmed using pivot-based logic.
-Comparison: Slopes of highs and lows are calculated for both the chart symbol and the comparison symbols.
-Divergence Identification: If slopes point in opposite directions, an SMT divergence (bullish or bearish) is marked.
-Visualization: Lines and labels (“+ SMT” or “– SMT”) are drawn on the chart. Historical lines can be kept or cleared depending on user settings.
 🔷 Visual  
Bearish SMT: Downward line with “– SMT” label.
Bullish SMT: Upward line with “+ SMT” label.
Style Options: Predefined color schemes (TLAB, standard, monochrome) or fully customizable colors.
Line Style: Solid, dashed, or dotted.
 
 
🔷 Customization Options 
-Show Historical: Decide whether past divergences remain visible on the chart.
-Comparison Symbols: Define up to two external tickers, with optional inversion.
-Swing Lengths: Preconfigured pivot lengths automatically adapt to the selected timeframe (Daily, 4H, 1H, 5m/15m).
-Lines & Labels: Enable or disable bullish/bearish SMT divergences and their annotations.
 
🔷 Indicator Usage 
Select the comparison symbol with positive or negative correlation.
Wait for the “+ SMT” or “– SMT” marker to appear on the chart.
Divergences can be used as contextual confluence when studying potential market shifts:
A + SMT marker may suggest bullish divergence.
A – SMT marker may suggest bearish divergence.
    
   
Prev Day Volume ProfileWhat the script does
Calculates yesterday’s Volume Profile from the bars on your chart (not tick data) and derives:
POC (Point of Control)
VAL (Value Area Low)
VAH (Value Area High)
Draws three horizontal lines for today:
POC in orange
VAL and VAH in purple
Adds labels on the right edge that show the level name and the exact price (e.g., POC 1.2345).
Why it’s bar-based (not tick-based)
Pine Script can’t fetch external tick/aggTrades data. The script approximates a volume profile by distributing each bar’s volume across the price bins that the bar’s high–low range covers. For “yesterday”, this produces a stable, TV-native approximation that’s usually sufficient for intraday trading.
Key inputs
Value Area %: Defaults to 0.70 (70%)—the typical value area range.
TZ Offset vs Exchange (hours): Shifts the day boundary to match your desired session (e.g., Europe/Berlin: +1 winter / +2 summer). This ensures “yesterday” means 00:00–24:00 in your target timezone.
Row Size: Manual? / Manual Row Size: If enabled, you can set the price bin size yourself. Otherwise, the script chooses a TV-like step from syminfo.mintick.
Colors & Line width: POC orange; VAL/VAH purple; configurable width.
Benchmark Relative Performance BRPBenchmark Relative Performance (BRP) is a comprehensive technical analysis tool that compares any stock's performance against a chosen benchmark (QQQ, SPY, IWM, etc.) to identify outperformance and underperformance patterns.
Key Features:
Dual-line visualization: Shows both ticker and relative strength performance
Dynamic color coding: 5-level color system indicating performance strength
Customizable benchmark: Choose from any ticker via TradingView's symbol picker
Volume weighting: Optional volume analysis for stronger signal confirmation
Performance zones: Visual thresholds for strong/moderate performance levels
Compact info table: Real-time performance status and values
What It Shows:
Benchmark Performance Line (Blue): Shows your chosen benchmark's percentage performance
Relative Strength Line (Color-coded): Shows how much the ticker outperforms/underperforms
Fill Area: Visual gap between ticker and benchmark performance
Performance Zones: Dotted lines marking significant performance thresholds
Color System:
Green: Strong outperformance (above custom threshold)
Lime: Standard outperformance
Yellow: Neutral/Equal performance
Orange: Standard underperformance
Red: Strong underperformance (below custom threshold)
Best Used For:
Stock selection and rotation strategies
Sector/ETF relative strength analysis
Identifying momentum shifts vs benchmarks
Portfolio performance evaluation
Market timing based on relative performance
Settings:
Customizable lookback period (default: 20)
Adjustable strong performance threshold (default: 5%)
Optional volume weighting factor
Full table customization (position, colors, fonts)
Performance display (percentage or decimal)
Perfect for traders and investors who want to identify stocks showing relative strength or weakness compared to major market benchmarks.






















