HTF Liquidity Levels█ OVERVIEW 
The indicator introduces a new representation of the previous days, weeks, and months highs & lows ( DWM HL ) with a focus on untapped levels.
 █ CONCEPTS 
 Untapped Levels 
It is popularly known that the liquidity is located  behind swing points  or  beyond higher time frames highs/lows  (in a sense, an intraday swing point is a day high/low). These key areas are said "liquid" because of the accumulation of resting orders, mainly in the form of stop-loss orders. And this more significantly on higher time frames which have more time for stacking orders. As the result, the indicator aims to keep track of untapped levels that have their liquidity states intact.
  
 Liquidity Pools 
Once a liquidity level identified, or better, a cluster of liquidity levels work as magnets for the market. The price is more likely to make its way towards heavier pockets of liquidity, by proximity (the closest liquidity pool), and by difficulty (path with less obstacles). This phenomenon is referred as liquidity run, raid, purge, grab, hunt, sweep, you name it. Consequently, the indicator can help you frame a directional bias during your trading session.
  
 █ NOTES 
 Drawings 
Once a level is tapped, it is highlighted. At the end of each day, all tapped levels are cleared.
 
Cari dalam skrip untuk "order"
Strategy█   OVERVIEW 
This library is a Pine Script™ programmer’s tool containing a variety of strategy-related functions to assist in calculations like profit and loss, stop losses and limits. It also includes several useful functions one can use to convert between units in ticks, price, currency or a percentage of the position's size.
█  CONCEPTS  
The library contains three types of functions:
1 — Functions beginning with `percent` take either a portion of a price, or the current position's entry price and convert it to the value outlined in the function's documentation.
  Example: Converting a percent of the current position entry price to ticks, or calculating a percent profit at a given level for the position. 
2 — Functions beginning with `tick` convert a tick value to another form.
  These are useful for calculating a price or currency value from a specified number of ticks. 
3 — Functions containing `Level` are used to calculate a stop or take profit level using an offset in ticks from the current entry price. 
  These functions can be used to plot stop or take profit levels on the chart, or as arguments to the `limit` and `stop` parameters in  strategy.exit()  function calls.
  Note that these calculated levels flip automatically with the position's bias.
  For example, using `ticksToStopLevel()` will calculate a stop level under the entry price for a long position, and above the entry price for a short position. 
There are also two functions to assist in calculating a position size using the entry's stop and a fixed risk expressed as a percentage of the current account's equity. By varying the position size this way, you ensure that entries with different stop levels risk the same proportion of equity.
█  NOTES  
Example code using some of the library's functions is included at the end of the library. To see it in action, copy the library's code to a new script in the Pine Editor, and “Add to chart”. 
For each trade, the code displays:
 • The entry level in orange.
 • The stop level in fuchsia.
 • The take profit level in green.
The stop and take profit levels automatically flip sides based on whether the current position is long or short. 
Labels near the last trade's levels display the percentages used to calculate them, which can be changed in the script's inputs.
We plot markers for entries and exits because strategy code in libraries does not display the usual markers for them.
  
 Look first. Then leap.  
█  FUNCTIONS  
 percentToTicks(percent)  Converts a percentage of the average entry price to ticks.
  Parameters:
     percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to ticks. 50 is 50% of the entry price.
  Returns: (float) A value in ticks.
 percentToPrice(percent)  Converts a percentage of the average entry price to a price.
  Parameters:
     percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to price. 50 is 50% of the entry price.
  Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).
 percentToCurrency(price, percent)  Converts the percentage of a price to money.
  Parameters:
     price : (series int/float) The symbol's price.
     percent : (series int/float) The percentage of `price` to calculate.
  Returns: (float) A value in the symbol's currency.
 percentProfit(exitPrice)  Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
  Parameters:
     exitPrice : (series int/float) The potential price to close the position. 
  Returns: (float) Percentage profit for the current position if closed at the `exitPrice`.
 priceToTicks(price)  Converts a price to ticks.
  Parameters:
     price : (series int/float) Price to convert to ticks.
  Returns: (float) A quantity of ticks.
 ticksToPrice(price)  Converts ticks to a price offset from the average entry price.
  Parameters:
     price : (series int/float) Ticks to convert to a price.
  Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
 ticksToCurrency(ticks)  Converts ticks to money.
  Parameters:
     ticks : (series int/float) Number of ticks.
  Returns: (float) Money amount in the symbol's currency.
 ticksToStopLevel(ticks)  Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
  Parameters:
     ticks : (series int/float) The distance in ticks from the entry price to the stop loss level.
  Returns: (float) A stop loss level for the current position.
 ticksToTpLevel(ticks)  Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price.  This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
  Parameters:
     ticks : (series int/float) The distance in ticks from the entry price to the take profit level.
  Returns: (float) A take profit level for the current position.
 calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)  Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
  Parameters:
     stopLossTicks : (series int) The stop loss (in ticks) that will be used to protect the position.
     riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
  Returns: (int) A quantity of contracts.
 calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)  Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
  Parameters:
     stopLossPercent : (series int/float) The stop loss in percent that will be used to protect the position.
     riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
     entryPrice : (series int/float) The entry price of the position. 
  Returns: (int) A quantity of contracts.
 exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, when, alertMessage)  A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit in as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
  Parameters:
     id : (series string)    The order identifier of the `strategy.exit()` call. 
     lossPercent : (series int/float) Stop loss as a percent of the entry price. 
     profitPercent : (series int/float) Take profit as a percent of the entry price. 
     qty : (series int/float) Number of contracts/shares/lots/units to exit a trade with. The default value is `na`. 
     qtyPercent : (series int/float) The percent of the position's size to exit a trade with.  If `qty` is `na`, the default value of `qty_percent` is 100.
     comment : (series string)    Optional. Additional notes on the order.
     when : (series bool)      Condition of the order. The order is placed if it is true. 
     alertMessage : (series string)    An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
PointsLibrary   "Points" 
Provides functions for simplifying operations with collections of x+y coordinates.  Where x is typically a bar index or time (millisecond) value.
 new(size)  Creates two arrays. One for X (int ) and another for Y (float ).
  Parameters:
     size : The initial size of the arrays.
 size(xA, yA)  Checks the size of the arrays and if they're equal returns the size.
  Parameters:
     xA : The X array.
     yA : The Y array.
 get(xA, yA, index)  Gets the X and Y values of the arrays at the index.
  Parameters:
     xA : The X array.
     yA : The Y array.
     index : The index.
  Returns:  
 set(xA, yA, index, x, y)  Sets the X and Y values of the arrays at the index.
  Parameters:
     xA : The X array.
     yA : The Y array.
     index : The index.
     x : The x value.
     y : The y value.
  Returns:  
 push(xA, yA, x, y)  Adds X and Y values to the end of the arrays (as the last element).
  Parameters:
     xA : The X array.
     yA : The Y array.
     x : The x value.
     y : The y value.
  Returns:  
 unshift(xA, yA, x, y)  Adds X and Y values to the beginning of the arrays (as the first element).
  Parameters:
     xA : The X array.
     yA : The Y array.
     x : The x value.
     y : The y value.
  Returns:  
 insert(xA, yA, index, x, y)  Inserts X and Y values to the arrays at the index.
  Parameters:
     xA : The X array.
     yA : The Y array.
     index : The index to insert at.
     x : The x value.
     y : The y value.
  Returns:  
 pop(xA, yA)  Removes the last element from the arrays and returns their value.
  Parameters:
     xA : The X array.
     yA : The Y array.
  Returns:  
 shift(xA, yA)  Removes the first element from the arrays and returns their value.
  Parameters:
     xA : The X array.
     yA : The Y array.
  Returns:  
 remove(xA, yA)  Removes the element from the arrays at the index and returns their value.
  Parameters:
     xA : The X array.
     yA : The Y array.
  Returns:  
 first(xA, yA)  Gets the X and Y values of the first element.
  Parameters:
     xA : The X array.
     yA : The Y array.
  Returns:  
 last(xA, yA)  Gets the X and Y values of the last element.
  Parameters:
     xA : The X array.
     yA : The Y array.
  Returns:  
 allIndexesBetween(xA, lo, hi, start, ordered)  Gets the indexes that have values at or above the low value and below the high value.
  Parameters:
     xA : The X array.
     lo : The inclusive low value.
     hi : The excluded hi value.
     start : The optional index to start the backwards search.
     ordered : If true, the search ends when the first value is found that is less than the low.
 lastIndexBetween(xA, lo, hi, start, ordered)  Gets the first found from the end that has a value at or above the low value and below the high value.
  Parameters:
     xA : The X array.
     lo : The inclusive low value.
     hi : The excluded hi value.
     start : The optional index to start the backwards search.
     ordered : If true, the search ends when the first value is found that is less than the low.
 lastIndexBelow(xA, hi, start)  Gets the first found from the end that has a value below the high value.
  Parameters:
     xA : The X array.
     hi : The excluded hi value.
     start : The optional index to start the backwards search.
Currency Strength Meter [HeWhoMustNotBeNamed]⬜  Note: This is not the strength of currency pairs. But, in this script we are trying to derive strength of individual currencies by matching against single base currency.
⬜  Process
This is based on similar concept as that of Magic Numbers for stocks. Idea is simple.
▶ Calculate strength of each currency against USD. Derive the strength for both price movement and volume movement.
▶ Similarly calculate momentum of price and volume change.
▶ If USD is base currency, inverse momentum and strength index for the given symbol.
▶ Once these calculations are done, rank each currencies based on individual score on given things.
▶ Add up all the ranks to derive combined rank
▶ sort the currencies in the ascending order of overall rank.
⬜  USAGE
▶ Identify a base currency. In our case, we have used USD as base currency as it is easy to get pairs of all currencies with USD.
▶ Identify most used combos for all other currencies which are paired with USD. Fx pair can either have USD as base currency or quote currency. It is desirable to use the pair which is most traded. For example, USDJPY is more traded pair than JPYUSD - hence it is advisable to use USDJPY instead of JPYUSD. Similarly AUDUSD is more traded than USDAUD - hence choosing AUDUSD for the purpose of this exercise is better approach. Notice that USDJPY has USD as base currency whereas AUDUSD has USD as quote currency. These calculations are handled internally to derive the right outcome irrespective of position of USD in the pair.
▶ Identify the forex broker which has all the selected forex tickers. All comparison is done against a single broker. Hence, choosing broker which does not wide range of forex pairs will show NAN for many rows.
▶ Once we set these, we get tabular output containing strength and oscillator based trend indexes for both price and volume indicator. Currencies are ordered in descending order of strength. Hence, top of the list can be considered as currency having highest strength and bottom of the table can be considered as currency having lowest strength. Please note that the calculation is valid only for selected timeframe and users can set other parameters such as moving average type, oscillator type, length etc which can alter the outcome.
▶ Use multiple timeframes to find out stronger and weaker currencies. Use directional indicators to understand where they are heading. Combine all these info to come up with currency pair you would like to trade :)
⬜  Settings
▶ Main settings and Currencies
  
 
   Base Currency  : This is set to USD by default as rest of the tickers used are paired with USD. Whatever the base currency is selected, rest of the tickers should follow the same combination.
   Timeframe  : Timeframe for which rankings need to be calculated.
   Currencies  : These should be the currency pair which involve base currency defined in the setting on either side.
 
▶ Display
 
   Table  : Allows users to set table location and size of the table. By default this is set to middle center and default size is normal. If user want to use multiple timeframes side by side, they can do so by changing these display settings.
   Stat Type  : To show either comparative ranking or actual indicator values
 
  
Strategy Template - V2This is an educational script created to demonstrate few basic building blocks of a trend based strategy and how to achieve different entry and exit types. My initial intention was to create a comprehensive strategy template which covers all the aspects of strategy. But, ended up creating fully fledged strategy based on trend following.
This is an enhancement on  Strategy-Template  But this script is comparitively more complex. Hence I decided to create new version instead of updating the existing one.
Lets dive deep.
 SIMPLE COMPONENTS OF TREND FOLLOWING STRATEGY 
 TREND BIAS  - This defines the direction of trend. Idea is not to trade against the trend direction. If the bias is bullish, look for long opportunities and if bias is bearish, look for short opportunities. Stay out of the market when the bias is neutral.
Often, trend bias is determined based on longer timeframe conditions. Example - 200 Moving Average, Higher timeframe moving averages, Higher timeframe high-lows etc. can be used for determining the trend bias.
In this script, I am using Weekly donchian channels combined with daily donchian channels to define trend bias.
 Long Bias  - 40 Day donchian channel sits completely in upper portion of 40 Week dochnial channel.
 Short Bias  - 40 Day donchian channel sits completely in lower portion of 40 Week donchian channel.
 ENTRY CONDITION  - Entry signals are generated only in the direction of bias. Hence, when in LongBias, we only get Long signals and when in short bias, we only get short signals.
In our case, when in  Long Bias  - if price hits 40 day high for the first time, this creates our long entry signal. Similarly when in  Short Bias , price hitting 40 day low will create signal for going short. Since we do not take trades opposite to trend, no entry conditions are formed when price hits 40 day high in Short Bias or 40 day low in Long Bias.
 EXIT CONDITION  - Exit conditions are formed when we get signals of trend failure.
In our case, when in long trade, price hitting 40 day low creates exit signal. Similarly when in short trade price hitting 40 day high creates exit signal for short trade.
 DIFFERENT TYPES OF ENTRY AND EXIT 
In this script, I have tried to demonstrate different entry and exit types.
 Entry types 
 
  Market - Enter immediately when entry signal is received. That is, in this case when price crossover over high in long bias and crosses under low in short bias
  Stop - This method includes estimating at what level new highs are made and creating a stop buy order at that level. This way, we do not miss if the break out is stronger. But, susciptible to fail during fakeouts.
  Limit - This method includes executing a limit order to buy at lower price or sell at higher price. In trend following methods, downside of limit order is when there is genuine breakout, these limit orders may not hit and during trend failures the limit orders are likely to hit and go straight to stop.
  Stop-Limit - this is same as stop order but will also place a limit condition to avoid buying on overextended breakout or with lots of slippage.
 
 Exit types 
 
  Market - whether to keep the existing trade running or whether to close it is determined after close of each bar and exit orders are executed manually upon receiving exit signal.
  Stop - We place stop loss orders beforehand when there is a trade in place. This can help in avoiding big movements against trade within bar. But, this may also stop on false signals or fakeouts.
 
 Take profit 
 
  Stop - No take profits are configured.
  Target - 30% of the positions are closed when take profit levels are hit. Take profit levels are defined by risk reward.
 
 USING THE CODE AS TEMPLATE 
As mentioned earlier, I intended to create a fully fledged strategy template. But, ended up creating a fully fledged stratgy. However, you can take some part of this code and use it to start your own strategy. Will explain what all things can be adopted without worrying about the strategy implementation within
 
   Strategy definition  : This can be copied as is and just change the title of strategy. This defines some of the commonly used parameters of strategy which can help with close to realistic backtesting results for your coded strategy and comparison with buy and hold.
   Generic Strategy Parameters : The parameter which defines controlling alllowed trade direction and trading window are present here. This again can be copied as is and variable inDateRange can be directly used in entry conditions.
   Generic Methods : f_getMovingAverage and f_secureSecurity are handy and can be used as is. atr method provideded by pine gives you ATR based on RMA. If you want SMA or any other moving average based ATR, you can use the method f_getCustomAtr
   Trade Statements : This section has all types of trading instructions which includes market/stop/limit/stop-limit type of entries and exits and take profit statements. You can adopt the type of entry you are interested in and change when condition to suit your strategy.
   Trade conditions and levels : This section is required. But, cannot be copied. All the trade logic goes here which also sets parameters which are used in when of Trade Statements.
 
Hope this helps. 
(IK) Base Break BuyThis strategy first calculates areas of support (bases), and then enters trades if that support is broken. The idea is to profit off of retracement. Dollar-cost-averaging safety orders are key here. This strategy takes into account a .1% commission, and tests are done with an initial capital of 100.00 USD. This only goes long.
The strategy is highly customizable. I've set the default values to suit ETH/USD 15m. If you're trading this on another ticker or timeframe, make sure to play around with the settings. There is an explanation of each input in the script comments. I found this to be profitable across most 'common sense' values for settings, but tweaking led to some pretty promising results. I leaned more towards high risk/high trade volume. 
Always remember though:  historical performance is no guarantee of future behavior . Keep settings within your personal risk tolerance, even if it promises better profit. Anyone can write a 100% profitable script if they assume price always eventually goes up. 
Check the script comments for more details, but, briefly, you can customize:
	-How many bases to keep track of at once
	-How those bases are calculated
	-What defines a 'base break'
	-Order amounts
	-Safety order count
	-Stop loss
Here's the basic algorithm:
	-Identify support.
		--Have previous candles found bottoms in the same area of the current candle bottom?
		--Is this support unique enough from other areas of support?
	-Determine if support is broken.
		--Has the price crossed under support quickly and with certainty? 
	-Enter trade with a percentage of initial capital.
	-Execute safety orders if price continues to drop.
	-Exit trade at profit target or stop loss. 
Take profit is dynamic and calculated on order entry. The bigger the 'break', the higher your take profit percentage. This target percentage is based on average position size, so as safety orders are filled, and average position size comes down, the target profit becomes easier to reach.
Stop loss can be calculated one of two ways, either a static level based on initial entry, or a  dynamic level based on average position size.  If you use the latter (default), be aware, your real losses will be greater than your stated stop loss percentage . For example:
	-stop loss = 15%, capital = 100.00, safety order threshold = 10%
	-you buy $50 worth of shares at $1         - price average is $1
	-you safety $25 worth of shares at $0.9  - price average is $0.966
	-you safety $25 worth of shares at $0.8. - price average is $0.925
	-you get stopped out at 0.925 * (1-.15) = $0.78625, and you're left with $78.62. 
This is a realized loss of ~21.4% with a stop loss set to 15%. The larger your safety order threshold, the larger your real loss in comparison to your stop loss percentage, and vice versa. 
Indicator plots show the calculated bases in white. The closest base below price is yellow. If that base is broken, it turns purple. Once a trade is entered, profit target is shown in silver and stop loss in red. 
Short In Downtrend Below MA100 (Coinrule)This is a simple strategy to take advantage of downtrends. It's useful to run such a strategy as a hedge in times of market uncertainty.
 The Sell Condition - Entry 
The sell signal triggers when:
 
 the coin has MA (100) greater than the price in a timeframe of 15 minutes, meaning that the coin is in a short-term downtrend.
 the coin has an RSI greater than 30 in a timeframe of 15 minutes, indicating that it didn't reach oversold conditions yet, so there is still room for a further price drop.
 
On Coinrule, you can launch the strategy on real market conditions, setting up multiple sequential sell orders. The strategy would keep selling while the price stays below the MA(100). In that case, it's advisable to set low amounts for the sell orders. the position will grow gradually while the downtrend intensifies. Set a minimum time interval between the sell orders will also help to have control over the overall position size.
 The Buy Condition - Exit 
The bot connects to each trade a stop loss and a take profit. The percentages are optimized for short term trades on mid-cap coins. You can adjust the percentages depending on the specific coin you are trading. A ratio of 1:1.5 between the stop loss and the take profit could work as the strategy trades in the same direction of the trend. 
Stop loss at 3% from the entry price
Take profit at 2% from the entry price
A slightly larger stop loss allows tolerating more volatility to reduce the case of stops triggering when it shouldn't.
Percentile Nearest Rank Using Arrays [LuxAlgo]The new array feature is extremely powerful, as it will allow pinescript users to do more complex things, or compute existing calculations more efficiently, it will also be possible to shine some light to some already existing functions, one of them being  percentile_nearest_rank .
We have been working on this new feature with our pal alexgrover, and made this script which computes a rolling percentile using the nearest rank method.
 Settings  
 
 Length: Window of the rolling percentile, determine the number of past data to be used.
 Percentage: Return the current value if  Percentage % of the data fall below that value, the setting is in a range (0,100).
 Src: Input source of the indicator.
 
 Usage 
A rolling percentile can have many usages when it comes to technical analysis, this is due to its ability to return the value of three common rolling statistics, the rolling median, which can be obtained using a percentage equal to 50, the rolling maximum, obtained with a percentage equal to 100, and the rolling minimum, obtained with a percentage equal to 0. 
When we use our rolling percentile as a rolling median, we can obtain a robust estimation of the underlying trend in the price, while using it as a rolling maximum/minimum can allow us to determine if the market is trending, and at which direction. The rolling maximum/minimum is a rolling statistic used to calculate the well known stochastic oscillator and Donchian channel indicator.
We can also compute rolling quartiles, which can be obtained using a percentage of 25 or 75, with one of 25 returning the lower quartile and 75 the upper quartile.
  
In blue the upper rolling quartile (%75), in orange the lower rolling quartile (%25), both using a window size of 100.
 Details 
In order to compute a rolling percentile nearest rank, we must first take the most recent  length  closing prices, then order them in ascending order, we then return the value of the ordered observations at index  (percentage/100*length) - 1  (we use - 1 because our array index starts at 0).
Complete Trend Trading System [Fhenry0331]This system was designed for the beginner trader to make money swing trading. Your losses will be small and your gains will be mostly large. You will show consistent profit. Period.
The system works on any security you like to trade. I used GBPUSD as an example because of the up swing and down swing it had recently. I tried to put as much information of how the system works in the chart. Hope it helps and is not to cluttered.
I will reiterate how the system works here: Everything is based off of closed price.
 Legend 
 Uptrend: Buy 
Green bar: initial start of an uptrend or uptrend continuing. Place order above that bar. If the initial bar does not stray too far from the MVWAP , I will place orders above subsequent bars if no filled occurred.
If initial start of the trend is missed, I will wait for the pullback. A pullback is a close below the MVWAP, and a close above the EMA (Low), RSI is above 50. Orders are placed above the pullback bars with plotted char "B" and also plotted green triangle up. Again orders are placed above those bars. the bars do not notate automatic buys. Don't chase anything. You will miss the initial bar on something because of news or earnings and it rocket up. Just wait, it will pullback. If it doesn't, to hell with it, on to the next.
Take profits: In the indicator you will see "T." That notates to take some profits. It is a suggestion. I was always told to take profits into spikes, as well as you can never lose money if you take profits. Up to you if you want to scale out and take the suggested profits or not.
Exit Completely: In an uptrend, close your entire position on bars colored yellow or red. (Again, closed bars)
In uptrend bars colored orange and black, do nothing, they are just pullback bars. Look for the buy pullback signal, then follow pullback buy rules for an uptrend. 
 Downtrend: Short 
Red bar: initial start of a downtrend or downtrend continuing. Place order below the bar. If the initial bar does not stray too far fro the MVWAP, place orders below subsequent bars.
If initial start on the downtrend is missed, wait for the pullback. A pullback is a close above the MVWAP, and close below the EMA(Low). RSI is below 50. Orders are placed below the pullback bars with the plotted char "S" and also plotted red triangle. Again those bars are not automatic shorts, orders are placed below them. Don't chase anything. Wait for price to come into your plan. The idea FOMO is the stupidest thing ever, how can you miss out on something when it is always there. The market is always there and something will come into your zone. Chill. 
"T": same as in uptrend, suggestion to take some profits.
Exit Completely: In a downtrend, close your entire position on bars colored orange or green.
In downtrend you will see bars colored yellow and black, do nothing, they are pullback bars. Look for the pullback short signal and follow pullback short rules. 
If you have any questions get at me. Take a look at it on what you trade. Flip it through different securities. 
Best of luck in all you do. 
P.S. You should not take a trade right before earnings. You should also exit a trade right before earnings. 
Forex Master v4.0 (EUR/USD Mean-Reversion Algorithm)DESCRIPTION  
Forex Master v4.0 is a mean-reversion algorithm currently optimized for trading the EUR/USD pair on the 5M chart interval. All indicator inputs use the period's closing price and all trades are executed at the open of the period following the period where the trade signal was generated. 
There are 3 main components that make up Forex Master v4.0: 
 
I. Trend Filter 
 
The algorithm uses a version of the ADX indicator as a trend filter to trade only in certain time periods where price is more likely to be range-bound (i.e., mean-reverting). This indicator is composed of a Fast ADX and a Slow ADX, both using the same look-back period of 50. However, the Fast ADX is smoothed with a 6-period EMA and the Slow ADX is smoothed with a 12-period EMA. When the Fast ADX is above the Slow ADX, the algorithm does not trade because this indicates that price is likelier to trend, which is bad for a mean-reversion system. Conversely, when the Fast ADX is below the Slow ADX, price is likelier to be ranging so this is the only time when the algorithm is allowed to trade. 
 
II. Bollinger Bands  
When allowed to trade by the Trend Filter, the algorithm uses the Bollinger Bands indicator to enter long and short positions. The Bolliger Bands indicator has a look-back period of 20 and a standard deviation of 1.5 for both upper and lower bands. When price crosses over the lower band, a Long Signal is generated and a long position is entered. When price crosses under the upper band, a Short Signal is generated and a short position is entered. 
 III. Money Management  
Rule 1 - Each trade will use a limit order for a fixed quantity of 50,000 contracts (0.50 lot). The only exception is Rule 
Rule 2 - Order pyramiding is enabled and up to 10 consecutive orders of the same signal can be executed (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts). 
Rule 3 - Every order will include a bracket with both TP and SL set at 50 pips (note: the algorithm only closes the current open position and does not enter the opposite trade once a TP or SL has been hit). 
Rule 4 - When a new opposite trade signal is generated, the algorithm sends in a larger order to close the current open position as well as open a new one (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts. A Short Signal is generated shortly after the 14th Long Signal. The algorithm then sends in a sell order for 400,000 contracts to close the 350,000 contracts long position and open a new short position of 50,000 contracts). 
FU Candle Detector (Smart Money Concept)  En Anglais🧠 Overall concept: “FU Candle” in Smart Money logic
In the context of Smart Money Concepts (SMC) or ICT (Inner Circle Trader), an FU Candle (also known as a “Fakeout Candle” or “Manipulation Candle”) is a candle that:
Creates an imbalance or a break (often above a swing high or below a swing low),
Attracts liquidity by trapping retail traders (liquidity grab),
Then abruptly reverses direction, revealing the hand of “Smart Money” (large institutions).
It therefore often marks:
The point of manipulation before an impulsive movement (reversal),
An area of interest for entering in the institutional direction (after the liquidity grab).
---
⚙️ How the “FU Candle Detector” script works
The script identifies these candlesticks by observing several typical criteria:
1. Detection of the manipulative candle (FU Candle)
Search for a candlestick that breaks a previous swing (significant high or low),
But closes in the opposite direction, often below/above the broken zone,
Thus indicating a fakeout.
Examples:
Bullish FU Candle: breaks a previous low, but closes bullish.
Bearish FU Candle: breaks a previous high, but closes bearish.
---
2. Visualization on the chart
The script generally displays:
🔴 Red markers for bearish FUs (Fake Breakout upwards),
🟢 Green markers for bullish FUs (Fake Breakout downwards),
🟦 Rectangles of areas of interest (often around the FU Candle Open),
📏 Horizontal lines on areas of imbalance (OB/FVG if integrated).
---
3. Possible additions depending on the version
Depending on the version you have received, the script can also:
Detect Fair Value Gaps (FVG) around FU Candles,
Mark Order Blocks (OB) associated with manipulation,
Add alerts when new FU Candles are detected,
Calculate the distance between the manipulation point and the price return,
Filter according to candle size, volume, or market structure (MSB/CHoCH).
---
🎯 Practical use
FU Candles are often used:
As confirmation of an imminent reversal,
To identify institutional entry zones (hidden Order Block),
To anticipate the direction of the next impulse after the liquidity hunt.
Typical entry example:
> Wait for the formation of an FU Candle + price return within the candle body = entry in the opposite direction to the false breakout.
📈 Recommended combinations
This detector is often combined with:
Structure Break Indicator (CHoCH / BOS)
Liquidity Pool Zones
Fair Value Gap Finder
Order Block Detector
This gives you a complete Smart Money Concept system, capable of mapping:
1. Where liquidity has been taken,
2. Where the price is rebalancing,
3. Where Smart Money is repositioning its orders.
FluxVector Liquidity Universal Trendline FluxVector Liquidity Trendline FFTL
 Summary in one paragraph 
FFTL is a single adaptive trendline for stocks ETFs FX crypto and indices on one minute to daily. It fires only when price action pressure and volatility curvature align. It is original because it fuses a directional liquidity pulse from candle geometry and normalized volume with realized volatility curvature and an impact efficiency term to modulate a Kalman like state without ATR VWAP or moving averages. Add it to a clean chart and use the colored line plus alerts. Shapes can move while a bar is open and settle on close. For conservative alerts select on bar close.
 Scope and intent 
• Markets. Major FX pairs index futures large cap equities liquid crypto top ETFs
• Timeframes. One minute to daily
• Default demo used in the publication. SPY on 30min
• Purpose. Reduce false flips and chop by gating the line reaction to noise and by using a one bar projection
• Limits. This is a strategy. Orders are simulated on standard candles only
 Originality and usefulness 
• Unique fusion. Directional Liquidity Pulse plus Volatility Curvature plus Impact Efficiency drives an adaptive gain for a one dimensional state
• Failure mode addressed. One or two shock candles that break ordinary trendlines and saw chop in flat regimes
• Testability. All windows and gains are inputs
• Portable yardstick. Returns use natural log units and range is bar high minus low
• Protected scripts. Not used. Method disclosed plainly here
 Method overview in plain language 
Base measures
• Return basis. Natural log of close over prior close. Average absolute return over a window is a unit of motion
 Components 
• Directional Liquidity Pulse DLP. Measures signed participation from body and wick imbalance scaled by normalized volume and variance stabilized
• Volatility Curvature. Second difference of realized volatility from returns highlights expansion or compression
• Impact Efficiency. Price change per unit range and volume boosts gain during efficient moves
• Energy score. Z scores of the above form a single energy that controls the state gain
• One bar projection. Current slope extended by one bar for anticipatory checks
 Fusion rule 
Weighted sum inside the energy score then logistic mapping to a gain between k min and k max. The state updates toward price plus a small flow push.
 Signal rule 
• Long suggestion and order when close is below trend and the one bar projection is above the trend
• Short suggestion and flip when close is above trend and the one bar projection is below the trend
• WAIT is implicit when neither condition holds
• In position states end on the opposite condition
 What you will see on the chart 
• Colored trendline teal for rising red for falling gray for flat
• Optional projection line one bar ahead
• Optional background can be enabled in code
• Alerts on price cross and on slope flips
 
Inputs with guidance 
Setup
• Price source. Close by default
Logic
• Flow window. Typical range 20 to 80. Higher smooths the pulse and reduces flips
• Vol window. Typical range 30 to 120. Higher calms curvature
• Energy window. Typical range 20 to 80. Higher slows regime changes
• Min gain and Max gain. Raise max to react faster. Raise min to keep momentum in chop
UI
• Show 1 bar projection. Colors for up down flat
 Properties visible in this publication 
• Initial capital 25000
• Base currency USD
• Commission percent 0.03
• Slippage 5
• Default order size method percent of equity value 3%
• Pyramiding 0
• Process orders on close off
• Calc on every tick off
• Recalculate after order is filled off
 Realism and responsible publication 
• No performance claims
• Intrabar reminder. Shapes can move while a bar forms and settle on close
• Strategy uses standard candles only
 Honest limitations and failure modes 
• Sudden gaps and thin liquidity can still produce fast flips
• Very quiet regimes reduce contrast. Use larger windows and lower max gain
• Session time uses the exchange time of the chart if you enable any windows later
• Past results never guarantee future outcomes
 Open source reuse and credits
 • None
Hyper SAR Reactor Trend StrategyHyperSAR Reactor Adaptive PSAR Strategy
 Summary 
Adaptive Parabolic SAR strategy for liquid stocks, ETFs, futures, and crypto across intraday to daily timeframes. It acts only when an adaptive trail flips and confirmation gates agree. Originality comes from a logistic boost of the SAR acceleration using drift versus ATR, plus ATR hysteresis, inertia on the trail, and a bear-only gate for shorts. Add to a clean chart and run on bar close for conservative alerts.
 Scope and intent 
• Markets: large cap equities and ETFs, index futures, major FX, liquid crypto
• Timeframes: one minute to daily
• Default demo: BTC on 60 minute
• Purpose: faster yet calmer PSAR that resists chop and improves short discipline
• Limits: this is a strategy that places simulated orders on standard candles
 Originality and usefulness 
• Novel fusion: PSAR AF is boosted by a logistic function of normalized drift, trail is monotone with inertia, entries use ATR buffers and optional cooldown, shorts are allowed only in a bear bias
• Addresses false flips in low volatility and weak downtrends
• All controls are exposed in Inputs for testability
• Yardstick: ATR normalizes drift so settings port across symbols
• Open source. No links. No solicitation
 Method overview 
Components
• Adaptive AF: base step plus boost factor times logistic strength
• Trail inertia: one sided blend that keeps the SAR monotone
• Flip hysteresis: price must clear SAR by a buffer times ATR
• Volatility gate: ATR over its mean must exceed a ratio
• Bear bias for shorts: price below EMA of length 91 with negative slope window 54
• Cooldown bars optional after any entry
• Visual SAR smoothing is cosmetic and does not drive orders
 Fusion rule 
Entry requires the internal flip plus all enabled gates. No weighted scores.
 Signal rule 
• Long when trend flips up and close is above SAR plus buffer times ATR and gates pass
• Short when trend flips down and close is below SAR minus buffer times ATR and gates pass
• Exit uses SAR as stop and optional ATR take profit per side
 Inputs with guidance 
Reactor Engine
• Start AF 0.02. Lower slows new trends. Higher reacts quicker
• Max AF 1. Typical 0.2 to 1. Caps acceleration
• Base step 0.04. Typical 0.01 to 0.08. Raises speed in trends
• Strength window 18. Typical 10 to 40. Drift estimation window
• ATR length 16. Typical 10 to 30. Volatility unit
• Strength gain 4.5. Typical 2 to 6. Steepness of logistic
• Strength center 0.45. Typical 0.3 to 0.8. Midpoint of logistic
• Boost factor 0.03. Typical 0.01 to 0.08. Adds to step when strength rises
• AF smoothing 0.50. Typical 0.2 to 0.7. Adds inertia to AF growth
• Trail smoothing 0.35. Typical 0.15 to 0.45. Adds inertia to the trail
• Allow Long, Allow Short toggles
 Trade Filters 
• Flip confirm buffer ATR 0.50. Typical 0.2 to 0.8. Raise to cut flips
• Cooldown bars after entry 0. Typical 0 to 8. Blocks re entry for N bars
• Vol gate length 30 and Vol gate ratio 1. Raise ratio to trade only in active regimes
• Gate shorts by bear regime ON. Bear bias window 54 and Bias MA length 91 tune strictness
 Risk 
• TP long ATR 1.0. Set to zero to disable
• TP short ATR 0.0. Set to 0.8 to 1.2 for quicker shorts
 Usage recipes 
Intraday trend focus
Confirm buffer 0.35 to 0.5. Cooldown 2 to 4. Vol gate ratio 1.1. Shorts gated by bear regime.
Intraday mean reversion focus
Confirm buffer 0.6 to 0.8. Cooldown 4 to 6. Lower boost factor. Leave shorts gated.
Swing continuation
Strength window 24 to 34. ATR length 20 to 30. Confirm buffer 0.4 to 0.6. Use daily or four hour charts.
 
Properties visible in this publication 
Initial capital 10000. Base currency USD. Order size Percent of equity 3. Pyramiding 0. Commission 0.05 percent. Slippage 5 ticks. Process orders on close OFF. Bar magnifier OFF. Recalculate after order filled OFF. Calc on every tick OFF. No security calls.
 
Realism and responsible publication 
No performance claims. Past results never guarantee future outcomes. Shapes can move while a bar forms and settle on close. Strategies execute only on standard candles.
 Honest limitations and failure modes 
High impact events and thin books can void assumptions. Gap heavy symbols may prefer longer ATR. Very quiet regimes can reduce contrast and invite false flips.
 Open source reuse and credits
 
Public domain building blocks used: PSAR concept and ATR. Implementation and fusion are original. No borrowed code from other authors.
 Strategy notice 
Orders are simulated on standard candles. No lookahead.
 Entries and exits 
Long: flip up plus ATR buffer and all gates true
Short: flip down plus ATR buffer and gates true with bear bias when enabled
Exit: SAR stop per side, optional ATR take profit, optional cooldown after entry
Tie handling: stop first if both stop and target could fill in one bar
TriAnchor Elastic Reversion US Market SPY and QQQ adaptedSummary in one paragraph
Mean-reversion strategy for liquid ETFs, index futures, large-cap equities, and major crypto on intraday to daily timeframes. It waits for three anchored VWAP stretches to become statistically extreme, aligns with bar-shape and breadth, and fades the move. Originality comes from fusing daily, weekly, and monthly AVWAP distances into a single ATR-normalized energy percentile, then gating with a robust Z-score and a session-safe gap filter.
Scope and intent
• Markets: SPY QQQ IWM NDX large caps liquid futures liquid crypto
• Timeframes: 5 min to 1 day
• Default demo: SPY on 60 min
• Purpose: fade stretched moves only when multi-anchor context and breadth agree
• Limits: strategy uses standard candles for signals and orders only
Originality and usefulness
• Unique fusion: tri-anchor AVWAP energy percentile plus robust Z of close plus shape-in-range gate plus breadth Z of SPY QQQ IWM
• Failure mode addressed: chasing extended moves and fading during index-wide thrusts
• Testability: each component is an input and visible in orders list via L and S tags
• Portable yardstick: distances are ATR-normalized so thresholds transfer across symbols
• Open source: method and implementation are disclosed for community review
Method overview in plain language
Base measures
• Range basis: ATR(length = atr_len) as the normalization unit
• Return basis: not used directly; we use rank statistics for stability
Components
• Tri-Anchor Energy: squared distances of price from daily, weekly, monthly AVWAPs, each divided by ATR, then summed and ranked to a percentile over base_len
• Robust Z of Close: median and MAD based Z to avoid outliers
• Shape Gate: position of close inside bar range to require capitulation for longs and exhaustion for shorts
• Breadth Gate: average robust Z of SPY QQQ IWM to avoid fading when the tape is one-sided
• Gap Shock: skip signals after large session gaps
Fusion rule
• All required gates must be true: Energy ≥ energy_trig_prc, |Robust Z| ≥ z_trig, Shape satisfied, Breadth confirmed, Gap filter clear
Signal rule
• Long: energy extreme, Z negative beyond threshold, close near bar low, breadth Z ≤ −breadth_z_ok
• Short: energy extreme, Z positive beyond threshold, close near bar high, breadth Z ≥ +breadth_z_ok
What you will see on the chart
• Standard strategy arrows for entries and exits
• Optional short-side brackets: ATR stop and ATR take profit if enabled
Inputs with guidance
Setup
• Base length: window for percentile ranks and medians. Typical 40 to 80. Longer smooths, shorter reacts.
• ATR length: normalization unit. Typical 10 to 20. Higher reduces noise.
• VWAP band stdev: volatility bands for anchors. Typical 2.0 to 4.0.
• Robust Z window: 40 to 100. Larger for stability.
• Robust Z entry magnitude: 1.2 to 2.2. Higher means stronger extremes only.
• Energy percentile trigger: 90 to 99.5. Higher limits signals to rare stretches.
• Bar close in range gate long: 0.05 to 0.25. Larger requires deeper capitulation for longs.
Regime and Breadth
• Use breadth gate: on when trading indices or broad ETFs.
• Breadth Z confirm magnitude: 0.8 to 1.8. Higher avoids fighting thrusts.
• Gap shock percent: 1.0 to 5.0. Larger allows more gaps to trade.
Risk — Short only
• Enable short SL TP: on to bracket shorts.
• Short ATR stop mult: 1.0 to 3.0.
• Short ATR take profit mult: 1.0 to 6.0.
Properties visible in this publication
• Initial capital: 25000USD
• Default order size: Percent of total equity 3%
• Pyramiding: 0
• Commission: 0.03 percent
• Slippage: 5 ticks
• Process orders on close: OFF
• Bar magnifier: OFF
• Recalculate after order is filled: OFF
• Calc on every tick: OFF
• request.security lookahead off where used
Realism and responsible publication
• No performance claims. Past results never guarantee future outcomes
• Fills and slippage vary by venue
• Shapes can move during bar formation and settle on close
• Standard candles only for strategies
Honest limitations and failure modes
• Economic releases or very thin liquidity can overwhelm mean-reversion logic
• Heavy gap regimes may require larger gap filter or TR-based tuning
• Very quiet regimes reduce signal contrast; extend windows or raise thresholds
Open source reuse and credits
• None
Strategy notice
Orders are simulated by TradingView on standard candles. request.security uses lookahead off where applicable. Non-standard charts are not supported for execution.
Entries and exits
• Entry logic: as in Signal rule above
• Exit logic: short side optional ATR stop and ATR take profit via brackets; long side closes on opposite setup
• Risk model: ATR-based brackets on shorts when enabled
• Tie handling: stop first when both could be touched inside one bar
Dataset and sample size
• Test across your visible history. For robust inference prefer 100 plus trades.
Aurum DCX AVE Gold and Silver StrategySummary in one paragraph
Aurum DCX AVE is a volatility break strategy for gold and silver on intraday and swing timeframes. It aligns a new Directional Convexity Index with an Adaptive Volatility Envelope and an optional USD/DXY bias so trades appear only when direction quality and expansion agree. It is original because it fuses three pieces rarely combined in one model for metals: a convexity aware trend strength score, a percentile based envelope that widens with regime heat, and an intermarket DXY filter.
Scope and intent
• Markets. Gold and silver futures or spot, other liquid commodities, major indices
• Timeframes. Five minutes to one day. Defaults to 30min for swing pace
• Default demo used in this publication. TVC:GOLD on 30m
• Purpose. Enter confirmed volatility breaks while muting chop using regime heat and USD bias
• Limits. This is a strategy. Orders are simulated on standard candles only
Originality and usefulness
• Unique fusion. DCX combines DI strength with path efficiency and curvature. AVE blends ATR with a high TR percentile and widens with DCX heat. DXY adds an intermarket bias
• Failure mode addressed. False starts inside compression and unconfirmed breakouts during USD swings
• Testability. Each component has a named input. Entry names L and S are visible in the list of trades
• Portable yardstick. Weekly ATR for stops and R multiples for targets
• Open source. Method and implementation are disclosed for community review
Method overview in plain language
You score direction quality with DCX, size an adaptive envelope with a blend of ATR and a high TR percentile, and only allow breaks that clear the band while DCX is above a heat threshold in the same direction. An optional DXY filter favors long when USD weakens and short when USD strengthens. Orders are bracketed with a Weekly ATR stop and an R multiple target, with optional trailing to the envelope.
Base measures
• Range basis. True Range and ATR over user windows. A high TR percentile captures expansion tails used by AVE
• Return basis. Not required
Components
• Directional Convexity Index DCX. Measures directional strength with DX, multiplies by path efficiency, blends a curvature term from acceleration, scales to 0 to 100, and uses a rise window
• Adaptive Volatility Envelope AVE. Midline ALMA or HMA or EMA plus bands sized by a blend of ATR and a high TR percentile. The blend weight follows volatility of volatility. Band width widens with DCX heat
• DXY Bias optional. Daily EMA trend of DXY. Long bias when USD weakens. Short bias when USD strengthens
• Risk block. Initial stop equals Weekly ATR times a multiplier. Target equals an R multiple of the initial risk. Optional trailing to AVE band
Fusion rule
• All gates must pass. DCX above threshold and rising. Directional lead agrees. Price breaks the AVE band in the same direction. DXY bias agrees when enabled
Signal rule
• Long. Close above AVE upper and DCX above threshold and DCX rising and plus DI leads and DXY bias is bearish
• Short. Close below AVE lower and DCX above threshold and DCX falling and minus DI leads and DXY bias is bullish
• Exit and flip. Bracket exit at stop or target. Optional trailing to AVE band
Inputs with guidance
Setup
• Symbol. Default TVC:GOLD (Correlation Asset for internal logic)
• Signal timeframe. Blank follows the chart
• Confirm timeframe. Default 1 day used by the bias block
Directional Convexity Index
• DCX window. Typical 10 to 21. Higher filters more. Lower reacts earlier
• DCX rise bars. Typical 3 to 6. Higher demands continuation
• DCX entry threshold. Typical 15 to 35. Higher avoids soft moves
• Efficiency floor. Typical 0.02 to 0.06. Stability in quiet tape
• Convexity weight 0..1. Typical 0.25 to 0.50. Higher gives curvature more influence
Adaptive Volatility Envelope
• AVE window. Typical 24 to 48. Higher smooths more
• Midline type. ALMA or HMA or EMA per preference
• TR percentile 0..100. Typical 75 to 90. Higher favors only strong expansions
• Vol of vol reference. Typical 0.05 to 0.30. Controls how much the percentile term weighs against ATR
• Base envelope mult. Typical 1.4 to 2.2. Width of bands
• Regime adapt 0..1. Typical 0.6 to 0.95. How much DCX heat widens or narrows the bands
Intermarket Bias
• Use DXY bias. Default ON
• DXY timeframe. Default 1 day
• DXY trend window. Typical 10 to 50
Risk
• Risk percent per trade. Reporting field. Keep live risk near one to two percent
• Weekly ATR. Default 14. Basis for stops
• Stop ATR weekly mult. Typical 1.5 to 3.0
• Take profit R multiple. Typical 1.5 to 3.0
• Trail with AVE band. Optional. OFF by default
Properties visible in this publication
• Initial capital. 20000
• Base currency. USD
• request.security lookahead off everywhere
• Commission. 0.03 percent
• Slippage. 5 ticks
• Default order size method percent of equity with value 3% of the total capital available
• Pyramiding 0
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
Realism and responsible publication
• No performance claims. Past results never guarantee future outcomes
• Shapes can move while a bar forms and settle on close
• Strategies use standard candles for signals and orders only
Honest limitations and failure modes
• Economic releases and thin liquidity can break assumptions behind the expansion logic
• Gap heavy symbols may prefer a longer ATR window
• Very quiet regimes can reduce signal contrast. Consider higher DCX thresholds or wider bands
• Session time follows the exchange of the chart and can change symbol to symbol
• Symbol sensitivity is expected. Use the gates and length inputs to find stable settings
Open source reuse and credits
• None
Mode
Public open source. Source is visible and free to reuse within TradingView House Rules
Legal
Education and research only. Not investment advice. You are responsible for your decisions. Test on historical data and in simulation before any live use. Use realistic costs.
USDJPY Fair Value Gap + Session Strategy🎯 Overview 
This strategy combines Fair Value Gaps (FVGs) with session-based order flow analysis, specifically optimized for USDJPY. It identifies price inefficiencies left behind by institutional order flow during high-volatility trading sessions, offering a modern alternative to traditional lagging indicators.
 🔬 What Are Fair Value Gaps? 
Fair Value Gaps represent areas where aggressive institutional buying or selling created "gaps" in the market structure:
Bullish FVG: Price moves up so aggressively that it leaves unfilled buy orders behind
Bearish FVG: Price moves down so quickly that it leaves unfilled sell orders behind
Research shows approximately 80% of FVGs get "filled" (price returns to the gap) within 20-60 bars, making them highly predictable trading zones.
(see the generated image above)
(see the generated image above)
FVG Detection Logic:
text
// Bullish FVG: Gap between high  and current low
bullishFVG = low > high  and high  > high 
// Bearish FVG: Gap between low  and current high
bearishFVG = high < low  and low  < low 
 🌏 Session-Based Trading 
Why Sessions Matter for USDJPY
(see the generated image above)
Tokyo Session (00:00-09:00 UTC)
Highest volatility during first hour (00:00-01:00 UTC)
Average movement: 51-60 pips
Best for breakout strategies
London/NY Overlap (13:00-16:00 UTC)
Maximum liquidity and institutional participation
Tightest spreads and most reliable FVG formations
Optimal for continuation trades
Monday Premium Effect
USDJPY moves 120+ pips on Mondays due to weekend positioning
Enhanced FVG formation during session opens
 📊 Strategy Components 
(see the generated image above)
1. Fair Value Gap Detection
Identifies bullish and bearish FVGs automatically
Age limit: FVGs expire after 20 bars to avoid stale setups
Size filter: Minimum gap size to filter out noise
2. Session Filtering
Tokyo Open focus: Trades during first hour of Asian session
London/NY Overlap: Captures high-liquidity institutional flows
Weekend gap strategy: Enhanced signals on Monday opens
3. Volume Confirmation
Requires 1.5x average volume spike
Confirms institutional participation
Reduces false signals
4. Trend Alignment
50 EMA filter ensures trades align with higher timeframe trend
Long trades above EMA, short trades below
Prevents costly counter-trend trades
5. Risk Management
2:1 Risk/Reward minimum ensures profitability with 40%+ win rate
Percentage-based stops adapt to USDJPY volatility (0.3% default)
Configurable position sizing
 🎯 Entry Conditions 
(see the generated image above)
Long Entry (BUY)
✅ Bullish FVG detected in previous bars
✅ Price returns to FVG zone during active trading session
✅ Volume spike above 1.5x average
✅ Price above 50 EMA (trend confirmation)
✅ Bullish candle closes within FVG zone
✅ Trading during Tokyo open OR London/NY overlap
Short Entry (SELL)
✅ Bearish FVG detected in previous bars
✅ Price returns to FVG zone during active trading session
✅ Volume spike above 1.5x average
✅ Price below 50 EMA (trend confirmation)
✅ Bearish candle closes within FVG zone
✅ Trading during Tokyo open OR London/NY overlap
 📈 Expected Performance 
 
 Backtesting Results (Based on Similar Strategies):
 Win Rate: 44-59% (profitable due to high R:R ratio)
 Average Winner: 60-90 pips during London/NY sessions
 Average Loser: 30-40 pips (tight stops at FVG boundaries)
 Risk/Reward: 2:1 minimum, often 3:1 during strong trends
 Best Performance: Monday Tokyo opens and Wednesday London/NY overlaps
 Why This Works for USDJPY:
 90% correlation with US-Japan bond yield spreads
 High volatility provides sufficient pip movement
 Heavy institutional/central bank participation creates clear FVGs
 Consistent volatility patterns across trading sessions
 
⚙️ Configurable Parameters
Session Settings:
Trade Tokyo Session (Enable/Disable)
Trade London/NY Overlap (Enable/Disable)
FVG Settings:
FVG Minimum Size (Filter small gaps)
Maximum FVG Age (20 bars default)
Show FVG Markers (Visual display)
Volume Settings:
Use Volume Filter (Enable/Disable)
Volume Multiplier (1.5x default)
Volume Average Period (20 bars)
Trend Settings:
Use Trend Filter (Enable/Disable)
Trend EMA Period (50 default)
Risk Management:
Risk/Reward Ratio (2.0 default)
Stop Loss Percentage (0.3% default)
🎨 Visual Indicators
🟡 Yellow Line: 50 EMA trend filter
🟢 Green Triangles: Long entry signals
🔴 Red Triangles: Short entry signals
🟢 Green Dots: Bullish FVG zones
🔴 Red Dots: Bearish FVG zones
🟦 Blue Background: Tokyo open session
🟧 Orange Background: London/NY overlap
📊 Recommended Settings
Optimal Timeframes:
Primary: 5-minute charts (scalping)
Secondary: 15-minute charts (swing trading)
Parameter Optimization:
Conservative: Stop Loss 0.2%, R:R 2:1, Volume 2.0x
Balanced: Stop Loss 0.3%, R:R 2:1, Volume 1.5x (default)
Aggressive: Stop Loss 0.4%, R:R 1.5:1, Volume 1.2x
Risk Management:
Maximum 1-2% of account per trade
Daily loss limit: Stop after 3-5 consecutive losses
Use fixed percentage position sizing
⚠️ Important Considerations
Avoid Trading During:
Major news events (BOJ interventions, NFP, FOMC)
Holiday periods with reduced liquidity
Low volatility Asian afternoon sessions
When US-Japan yield differential narrows sharply
Best Practices:
Limit to 2-3 trades per session maximum
Always respect the 50 EMA trend filter
Never risk more than planned per trade
Paper trade for 2-4 weeks before live implementation
Track performance by session and day of week
🚀 How to Use
 
 Add the script to your USDJPY chart
 Set timeframe to 5-minute or 15-minute
 Adjust parameters based on your risk tolerance
 Enable strategy alerts for automated notifications
 Wait for visual signals (triangles) to appear
 Enter trades according to your risk management rules
 
📚 Strategy Foundation
This strategy is based on:
Smart Money Concepts (SMC): Institutional order flow tracking
Market Microstructure: Understanding how FVGs form in electronic trading
Quantified Risk Management: Statistical edge through proper R:R ratios
Session Liquidity Patterns: Exploiting predictable volatility cycles
US Opening 5-Minute Candle HighlighterUS Opening 5-Minute Candle Highlighter — True RVOL (Two-Tier + Label) 
What it does (in plain English)
This indicator finds the first 5-minute bar of the US cash session (09:30–09:35 ET) and highlights it when the candle has the specific “strong open” look you want:
Opens near the low of its own range, and
Closes near the high of its own range, and
Has a decisive real body (not a wick-y doji), and
(Optionally) is a green candle, and
Meets a TRUE opening-bar RVOL filter (compares today’s 09:30–09:35 volume only to prior sessions’ 09:30–09:35 volumes).
You get two visual intensities based on opening RVOL:
Tier-1 (≥ threshold 1, default 1.0×) → light green highlight + lime arrow
Tier-2 (≥ threshold 2, default 1.5×) → darker green highlight + green arrow
An RVOL label (e.g., RVOL 1.84x) can be shown above or below the opening bar.
Designed for 5-minute charts. On other timeframes the “opening bar” will be the bar that starts at 09:30 on that timeframe (e.g., 15-minute 09:30–09:45). For best results keep the chart on 5m.
 How the pattern is defined 
For the opening 5-minute bar, we compute:
Range = high − low
Body = |close − open|
Then we measure where the open and close sit within the bar’s own range on a 0→1 scale:
0 means exactly at the low
1 means exactly at the high
Using two quantiles:
Open ≤ position in range (0–1) (default 0.20)
Example: 0.20 means “open must be in the lowest 20% of the bar’s range.”
Close ≥ position in range (0–1) (default 0.80)
Example: 0.80 means “close must be in the top 20% of the bar’s range.”
This keeps the logic range-normalized so it adapts across different tickers and vol regimes (you’re not using fixed cents or % of price).
Body ≥ fraction of range (0–1) (default 0.55)
Requires the real body to be at least that fraction of the total range.
0.55 = body fills ≥ 55% of the candle.
Purpose: filter out indecisive, wick-heavy bars.
Raise to 0.7–0.8 for only the fattest thrusts; lower to 0.3–0.4 to admit more bars.
Require green candle? (default ON)
If ON, close > open must be true. Turn OFF if you also want to catch strong red opens for shorts.
Minimum range (ticks)
Ignore tiny, illiquid opens: e.g., set to 2–5 ticks to suppress micro bars.
 TRUE Opening-Bar RVOL (why it’s “true”) 
Most “RVOL” compares against any recent bars, which isn’t fair at the open.
This indicator calculates only against prior opening bars:
At 09:30–09:35 ET, take today’s opening 5-minute volume.
Compare it to the average of the last N sessions’ opening 5-minute volumes.
RVOL = today_open_volume / average_prior_open_volumes.
So:
1.0× = equal to average prior opens.
1.5× = 150% of average prior opens.
2.0× = double the typical opening participation.
A minimum prior samples guard (default 10) ensures you don’t judge with too little history. Until enough samples exist, the RVOL gate won’t pass (you can disable RVOL temporarily if needed).
 Visuals & tiers 
Light green highlight + lime arrow → price filters pass and RVOL ≥ Tier-1 (default 1.0×)
Dark green highlight + green arrow → price filters pass and RVOL ≥ Tier-2 (default 1.5×)
Optional bar paint in matching green tones for extra visibility.
Optional RVOL label (e.g., RVOL 1.84x) above or below the opening bar.
You can show the label only when the candle qualifies, or on every open.
 Inputs (step-by-step) 
Price-action filters
Open ≤ position in range (0–1): default 0.20. Smaller = stricter (must open nearer the low).
Close ≥ position in range (0–1): default 0.80. Larger = stricter (must close nearer the high).
Body ≥ fraction of range (0–1): default 0.55. Raise to demand a “fatter” body.
Require green candle?: default ON. Turn OFF to also mark bearish thrusts.
Minimum range (ticks): default 0. Set to 2–5 for liquid mid/large caps.
 Time settings 
Timezone: default America/New_York. Leave as is for US equities.
Start hour / minute: defaults 09:30. The bar that starts at this time is evaluated.
 TRUE Opening-Bar RVOL (two-tier) 
Require TRUE opening-bar RVOL?: ON = must pass Tier-1 to highlight; OFF = price filters alone can highlight (still shows Tier-2 when hit).
RVOL lookback (prior opens count): default 20. How many prior openings to average.
Min prior opens required: default 10. Warm-up guard.
Tier-1 RVOL threshold (× avg): default 1.00× (light green).
Tier-2 RVOL threshold (× avg): default 1.50× (dark green).
 Display 
Also paint candle body?: OFF by default. Turn ON for instant visibility on a chart wall.
Arrow size: tiny/small/normal/large.
Light/Dark opacity: tune highlight strength.
Show RVOL label?: ON/OFF.
Show label only when candle qualifies?: ON by default; OFF to see RVOL every open.
Label position: Above candle or Below candle.
Label size: tiny/small/normal/large.
 How to use (quick start) 
Apply to a 5-minute chart.
Keep defaults: Open ≤ 0.20, Close ≥ 0.80, Body ≥ 0.55, Require green ON.
Turn RVOL required ON, with Tier-1 = 1.0×, Tier-2 = 1.5×, Lookback = 20, Min prior = 10.
Optional: enable Paint bar and set Arrow size = large for monitor-wall visibility.
Optional: show RVOL label below the bar to keep wicks clean.
 Interpretation: 
Dark green = A+ opening thrust with strong participation (≥ Tier-2).
Light green = Valid opening thrust with at least average participation (≥ Tier-1).
No highlight = one or more filters failed (quantiles, body, green, range, or RVOL if required).
 Alerts 
Two alert conditions are included:
Opening 5m Match — Tier-2 RVOL → fires when the opening candle passes price filters and RVOL ≥ Tier-2.
Opening 5m Match — Tier-1 RVOL → fires when the opening candle passes price filters and RVOL ≥ Tier-1 (but < Tier-2).
 Recommended alert settings 
Condition: choose the script + desired tier.
Options: Once Per Bar Close (you want the confirmed 09:30–09:35 bar).
Set your watchlist to symbols of interest (themes/sectors) and let the alerts pull you to the right charts.
 Recommended starting values 
Quantiles: Open ≤ 0.20, Close ≥ 0.80
Body fraction: 0.55
Require green: ON
RVOL: Required ON, Tier-1 = 1.0×, Tier-2 = 1.5×, Lookback 20, Min prior 10
Display: Paint bar ON, Arrow large, Label ON, Below candle
Tune tighter for A-plus selectivity:
Open ≤ 0.15, Close ≥ 0.85, Body ≥ 0.65, Tier-2 2.0×.
 Notes, tips & limitations 
5-minute timeframe is the intended use. On higher TFs, the 09:30 bar spans more than 5 minutes; geometry may not reflect the first 5 minutes alone.
RTH only: The opening detection looks at the clock (09:30 ET). Pre-market bars are ignored for the signal and for RVOL history.
Warm-up period: Until you have Min prior opens required samples, the RVOL gate won’t pass. You can temporarily toggle RVOL off.
DST & timezone: Leave timezone on America/New_York for US equities. If you trade non-US exchanges, set the appropriate TZ and opening time.
Illiquid tickers: Use Minimum range (ticks) and require RVOL to reduce noise.
No strategy orders: This is a visual/alert tool. Combine with your execution and risk plan.
Why this is useful on multi-monitor setups
Instant pattern recognition: the two-shade green makes A vs A+ opens pop at a glance.
Adaptive thresholds: quantiles & body are within-bar, so it works across $5 and $500 names.
Fair volume test: TRUE opening RVOL avoids comparing to pre-market or midday bars.
Optional labels: glanceable RVOL x-value helps triage the strongest themes quickly.
Dynamic Swing Anchored VWAP STRAT (Zeiierman/PineIndicators)Dynamic Swing Anchored VWAP STRATEGY — Zeiierman × PineIndicators (Pine Script v6) 
 A pivot-to-pivot Anchored VWAP strategy that adapts to volatility, enters long on bullish structure, and closes on bearish structure. Built for TradingView in Pine Script v6. 
Full credits to zeiierman.
 Repainting notice:  The original indicator logic is repainting. Swing labels (HH/HL/LH/LL) are finalized after enough bars have printed, so labels do  not  occur in real time. It is not possible to execute at historical label points. Treat results as educational and validate with Bar Replay and paper trading before considering any discretionary use. 
 Concept 
 
 The script identifies swing highs/lows over a user-defined lookback ( Swing Period ). When structure flips (most recent swing low is newer than the most recent swing high, or vice versa), a new regime begins.
 At each confirmed pivot, a fresh  Anchored VWAP  segment is started and updated bar-by-bar using an EWMA-style decay on price×volume and volume.
 Responsiveness is controlled by  Adaptive Price Tracking (APT) . Optionally, APT auto-adjusts with an ATR ratio so that high volatility accelerates responsiveness and low volatility smooths it.
 Longs are opened/held in bullish regimes and closed when the regime turns bearish. No short positions are taken by design.
 
 How it works (under the hood) 
 
 Swing detection:  Uses  ta.highestbars / ta.lowestbars  over  prd  to update swing highs (ph) and lows (pl), plus their bar indices (phL, plL).
 Regime logic:  If  phL > plL  → bullish regime; else → bearish regime. A change in this condition triggers a re-anchor of the VWAP at the newest pivot.
 Adaptive VWAP math:  APT is converted to an exponential decay factor ( alphaFromAPT ), then applied to running sums of price×volume and volume, producing the current VWAP estimate.
 Rendering:  Each pivot-anchored VWAP segment is drawn as a polyline and color-coded by regime. Optional structure labels (HH/HL/LH/LL) annotate the swing character.
 Orders:  On bullish flips,  strategy.entry("L")  opens/maintains a long; on bearish flips,  strategy.close("L")  exits.
 
 Inputs & controls 
 
 Swing Period (prd)  — Higher values identify larger, slower swings; lower values catch more frequent pivots but add noise.
 Adaptive Price Tracking (APT)  — Governs the VWAP’s “half-life.” Smaller APT → faster/closer to price; larger APT → smoother/stabler.
 Adapt APT by ATR ratio  — When enabled, APT scales with volatility so the VWAP speeds up in turbulent markets and slows down in quiet markets.
 Volatility Bias  — Tunes the strength of APT’s response to volatility (above 1 = stronger effect; below 1 = milder).
 Style settings  — Colors for swing labels and VWAP segments, plus line width for visibility.
 
 Trade logic summary 
 
 Entry:  Long when the swing structure turns bullish (latest swing low is more recent than the last swing high).
 Exit:  Close the long when structure turns bearish.
 Position size:   qty = strategy.equity / close × 5  (dynamic sizing; scales with account equity and instrument price). Consider reducing the multiplier for a more conservative profile.
 
 Recommended workflow 
 
 Apply to instruments with reliable volume (equities, futures, crypto; FX tick volume can work but varies by broker).
 Start on your preferred timeframe. Intraday often benefits from smaller APT (more reactive); higher timeframes may prefer larger APT (smoother).
 Begin with defaults ( prd=50, APT=20 ); then toggle “Adapt by ATR” and vary  Volatility Bias  to observe how segments tighten/loosen.
 Use Bar Replay to watch how pivots confirm and how the strategy re-anchors VWAP at those confirmations.
 Layer your own risk rules (stops/targets, max position cap, session filters) before any discretionary use.
 
 Practical tips 
 
 Context filter:  Consider combining with a higher-timeframe bias (e.g., daily trend) and using this strategy as an entry timing layer.
 First pivot preference:  Some traders prefer only the first bullish pivot after a bearish regime (and vice versa) to reduce whipsaw in choppy ranges.
 Deviations:  You can add VWAP deviation bands to pre-plan partial exits or re-entries on mean-reversion pulls.
 Sessions:  Session-based filters (RTH vs. ETH) can materially change behavior on futures and equities.
 
 Extending the script (ideas) 
 
 Add stops/targets (e.g., ATR stop below last swing low; partial profits at k×VWAP deviation).
 Introduce mirrored short logic for two-sided testing.
 Include alert conditions for regime flips or for price-VWAP interactions.
 Incorporate HTF confirmation (e.g., only long when daily VWAP slope ≥ 0).
 Throttle entries (e.g., once per regime flip) to avoid over-trading in ranges.
 
 Known limitations 
 
 Repainting:  Swing labels and pivot confirmations depend on future bars; historical labels can look “perfect.” Treat them as annotations, not executable signals.
 Execution realism:  Strategy includes commission and slippage fields, yet actual fills differ by venue/liquidity.
 No guarantees:  Past behavior does not imply future results. This publication is for research/education only and not financial advice.
 
 Defaults (backtest environment) 
 
 Initial capital: 10,000
 Commission value: 0.01
 Slippage: 1
 Overlay: true
 Max bars back: 5000; Max labels/polylines set for deep swing histories
 
 Quick checklist 
 
 Add to chart and verify that the instrument has volume.
 Use defaults, then tune  APT  and  Volatility Bias  with/without ATR adaptation.
 Observe how each pivot re-anchors VWAP and how regime flips drive entries/exits.
 Paper trade across several symbols/timeframes before any discretionary decisions.
 
 Attribution & license 
 
 Original indicator concept and logic:  Zeiierman  — please credit the author.
 Strategy wrapper and publication:  PineIndicators .
 License:  CC BY-NC-SA 4.0  (Attribution-NonCommercial-ShareAlike). Respect the license when forking or publishing derivatives.
PumpC PAC & MAsPumpC – PAC & MAs (Open Source) 
A complete Price Action Candles (PAC) toolkit combining classical price action patterns (Fair Value Gaps, Inside Bars, Hammers, Inverted Hammers, and Volume Imbalances) with a flexible Moving Averages (MAs) module and an advanced bar-coloring system.
This script highlights supply/demand inefficiencies and micro-patterns with forward-extending boxes, recolors zones when mitigated, qualifies patterns with a global High-Volume filter, and ships with ready-to-use alerts. It works across intraday through swing trading on any market (e.g.,  NASDAQ:QQQ , $CME:ES1!,  FX:EURUSD ,  BITSTAMP:BTCUSD ).
This is an open-source script. The description is detailed so users understand what the script does, how it works, and how to use it. It makes no performance claims and does not provide trade advice.
 Acknowledgment & Credits 
This script originates from the structural and box-handling logic found in the  Super OrderBlock / FVG / BoS Tools  by makuchaku & eFe. Their pioneering framework provided the base methods for managing arrays of boxes, extending zones forward, and recoloring once mitigated.
Building on that foundation, I have substantially expanded and adapted the code to create a  unified Price Action Candles toolkit . This includes Al Brooks–inspired PAC logic, additional patterns like Inside Bars, Hammers, Inverted Hammers, and the new Volume Imbalance module, along with strong-bar coloring, close-threshold detection, a flexible global High-Volume filter, and a multi-timeframe Moving Averages system.
 What it does 
 
   Fair Value Gaps (FVG) : Detects 3-bar displacement gaps, plots forward-extending boxes, and optionally recolors them once mitigated.
   Inside Bars (IB) : Highlights bars fully contained within the prior candle’s range, with optional high-volume filter.
   Hammers (H) & Inverted Hammers (IH) : Identifies rejection candles using configurable body/upper/lower wick thresholds. High-volume qualification optional.
   Volume Imbalances (VI) : Detects inter-body gaps where one candle’s body does not overlap the prior candle’s body. Boxes extend forward until wick-based mitigation occurs (only after the two-bar formation completes). Alerts available for creation and mitigation.
   Mitigation Recolor : Each pattern can flip to a mitigated color once price trades back through its vertical zone.
   Moving Averages (MAs) : Four configurable EMAs/SMAs, with per-MA timeframe, length, color, and clutter-free plotting rules.
   Strong Bar Coloring : Highlights bullish/bearish engulfing reversals with different colors for high-volume vs low-volume cases.
   Close Threshold Bars : Marks candles that close in the top or bottom portion of their range, even if the body is small. Helps spot continuation pressure before a full trend bar forms.
   Alerts : Notifications available for FVG+, FVG−, IB, H, IH, VI creation, and VI mitigation.
 
 Connection to Al Brooks’ PAC teachings 
This script reflects Al Brooks’ Price Action Candle methodology. PAC patterns like Inside Bars, Hammers, and Inverted Hammers are not trade signals on their own—they gain meaning in context of trend, failed breakouts, and effort vs. result.
By layering in volume imbalances, strong-bar reversals, and volume filters, this script focuses attention on the PACs that show true participation and conviction, aligning with Brooks’ emphasis on reading crowd psychology through price action.
 Why the High-Volume filter matters 
Volume is a key proxy for conviction. A PAC or VI formed on light volume can be misleading noise; one formed on above-average volume carries more weight.
 
  Elevates Inside Bars that show absorption/compression with heavy activity.
  Distinguishes Hammers that reject price aggressively vs. weak drifts.
  Filters Inverted Hammers to emphasize true supply pressure.
  Highlights VI zones where institutional order flow left inefficiencies.
  Differentiates strong engulfing reversals from weaker, low-participation moves.
 
 Inputs & Customization 
Inputs are grouped logically for fast configuration:
 
   High-Volume Filter : Global lookback & multiple, per-pattern toggles.
   FVG : Visibility, mitigated recolor, box style/transparency, label controls.
   IB : Visibility, require high volume, mitigated recolor, colors, label settings.
   Hammer / IH : Visibility, require high volume, mitigated recolor, wick/body thresholds.
   VI : Visibility, require high volume, mitigated recolor, box style, labels, mitigation alerts.
   Strong Bars : Enable/disable, separate colors for high-volume and low-volume outcomes.
   Close Threshold Bars : Customizable close thresholds, labels, optional count markers.
   MAs : EMA/SMA type, per-MA toggle, length, timeframe, color.
 
 Alerts 
 
  New Bullish FVG (+)
  New Bearish FVG (−)
  New Inside Bar (IB)
  New Hammer (H)
  New Inverted Hammer (IH)
  New Volume Imbalance (VI)
  VI Mitigated
  Strong Bullish Engulfing / Bearish Engulfing (high- and low-volume variants)
 
 Suggested workflow 
 
  Choose your market & timeframe (script works across equities, futures, FX, crypto).
  Toggle only the PACs you actually trade. Assign distinct colors for clarity.
  Use MAs for directional bias and higher timeframe structure.
  Enable High-Volume filters when you want to emphasize conviction.
  Watch mitigation recolors to see which levels/zones have been interacted with.
  Use alerts selectively for setups aligned with your plan.
 
 Originality 
 
  Builds upon Super OrderBlock / FVG / BoS Tools (makuchaku & eFe) for FVG/box framework.
  Expanded into a unified PAC toolkit including IB, H, IH, and VI patterns.
  Brooks-inspired design: Patterns contextualized with volume and trend, not isolated.
  Flexible high-volume gating with per-pattern toggles.
  New VI integration with wick-based mitigation.
  Strong Bar Coloring differentiates conviction vs weak reversals.
  MTF-aware MAs prevent clutter while providing structure.
  Open-source: Transparent for learning, editing, and extension.
 
 Disclaimer 
For educational and informational purposes only. This script is not financial advice. Trading carries risk—always test thoroughly before live use.
Prime NumbersPrime Numbers  highlights prime numbers (no surprise there 😅), tokens and the recent "active" feature in "input".
  
🔸  CONCEPTS 
🔹  What are Prime Numbers? 
 A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. 
 Wikipedia: Prime number 
🔹  Prime Factorization 
 The fundamental theorem of arithmetic states that every integer larger than 1 can be written as a product of one or more primes. More strongly, this product is unique in the sense that any two prime factorizations of the same number will have the same number of copies of the same primes, although their ordering may differ. So, although there are many different ways of finding a factorization using an integer factorization algorithm, they all must produce the same result. Primes can thus be considered the "basic building blocks" of the natural numbers.
 Wikipedia: Fundamental theorem of arithmetic 
 Math Is Fun: Prime Factorization 
 
We divide a given number by Prime Numbers until only Primes remain.
Example:
 
24 / 2 = 12                 | 24 / 3 = 8
         12 / 3 = 4         |          8 / 2 = 4 
                  4 / 2 = 2 |                  4 / 2 = 2
                            |
24 = 2 x 3 x 2              | 24 = 3 x 2 x 2 
or                          | or
24 = 2² x 3                 | 24 = 2² x 3
 
In other words, every natural/integer number above 1 has a unique representation as a product of prime numbers, no matter how the number is divided. Only the order can change, but the factors (the basic elements) are always the same.
🔸  USAGE 
The  Prime Numbers  publication contains two use cases:
 
 Prime Factorization: performed on "close" prices, or a manual chosen number.                                     
 List Prime Numbers: shows a list of Prime Numbers.                                  
 
The other two options are discussed in the DETAILS chapter:
 
 Prime Factorization Without Arrays                               
 Find Prime Numbers
 
🔹  Prime Factorization 
Users can choose to perform Prime Factorization on close prices or a manually given number.
 ❗️ Note that this option only applies to close prices above 1, which are also rounded since Prime Factorization can only be performed on natural (integer) numbers above 1.
 
In the image below, the left example shows Prime Factorization performed on each close price for the latest 50 bars (which is set with "Run script only on 'Last x Bars'" -> 50).
The right example shows Prime Factorization performed on a manually given number, in this case "1,340,011". This is done only on the last bar. 
  
When the "Source" option "close price" is chosen, one can toggle "Also current price", where both the historical and the latest current price are factored. If disabled, only historical prices are factored.
Note that, depending on the chosen options, only applicable settings are available, due to a recent feature, namely the  parameter "active"  in settings.
Setting the "Source" option to "Manual - Limited" will factorize any given number between 1 and 1,340,011, the latter being the highest value in the available arrays with primes.
Setting to "Manual - Not Limited" enables the user to enter a higher number. If all factors of the manual entered number are in the 1 - 1,340,011 range, these factors will be shown; however, if a factor is higher than 1,340,011, the calculation will stop, after which a warning is shown:
  
The calculated factors are displayed as a label where identical factors are simplified with an exponent notation in superscript.
For example 2 x 2 x 2 x 5 x 7 x 7  will be noted as 2³ x 5 x 7²
  
🔹  List Prime Numbers 
  
The "List Prime Numbers" option enables users to enter a number, where the first found Prime Number is shown, together with the next x Prime Numbers ("Amount", max. 200)
The highest shown Prime Number is 1,340,011.
One can set the number of shown columns to customize the displayed numbers ("Max. columns", max. 20).
🔸  DETAILS 
The  Prime Numbers  publication consists out of 4 parts:
 
 Prime Factorization Without Arrays                               
 Prime Factorization                                       
 List Prime Numbers                                             
 Find Prime Numbers
 
The usage of "Prime Factorization" and "List Prime Numbers" is explained above.
🔹  Prime Factorization Without Arrays 
This option is only there to highlight a hurdle while performing Prime Factorization.
The basic method of Prime Factorization is to divide the base number by 2, 3, ... until the result is an integer number. Continue until the remaining number and its factors are all primes.
The division should be done by primes, but then you need to know which one is a prime.
In practice, one performs a loop from 2 to the base number.
Example:
 Base_number = input.int(24) 
arr = array.new() 
n = Base_number 
go = true 
while go
    for i = 2 to n 
        if n % i == 0
            if n / i == 1
                go := false                
                arr.push(i)
                label.new(bar_index, high, str.tostring(arr))
            else     
                arr.push(i)
                n /= i  
            break  
Small numbers won't cause issues, but when performing the calculations on, for example, 124,001 and a timeframe of, for example, 1 hour, the script will struggle and finally give a runtime error.
 How to solve this?
 
If we use an array with only primes, we need fewer calculations since if we divide by a non-prime number, we have to divide further until all factors are primes.
I've filled arrays with prime numbers and made libraries of them. (see chapter "Find Prime Numbers" to know how these primes were found).
🔹  Tokens 
A hurdle was to fill the libraries with as many prime numbers as possible.
Initially, the maximum token limit of a library was 80K. 
Very recently, that limit was lifted to 100K. Kudos to the TradingView developers! 
 What are tokens? 
Tokens are the smallest elements of a program that are meaningful to the compiler. They are also known as the fundamental building blocks of the program.
I have included a code block below the publication code (// - - - Educational (2) - - - ) which, if copied and made to a library, will contain exactly 100K tokens.
Adding more exported functions will throw a "too many tokens" error when saving the library. Subtracting 100K from the shown amount of tokens gives you the amount of used tokens for that particular function.
In that way, one can experiment with the impact of each code addition in terms of tokens.
For example adding the following code in the library:
 export a() => a = array.from(1)  will result in a 100,041 tokens error, in other words (100,041 - 100,000) that functions contains 41 tokens.
Some more examples, some are straightforward, others are not )
 
// adding these lines in one of the arrays results in x tokens
, 1 					   //  2 tokens 
, 111, 111, 111		    // 12 tokens 
 
, 1111 			        //  5 tokens 
, 111111111  			  // 10 tokens
, 1111111111111111111      // 20 tokens
, 1234567890123456789 	 // 20 tokens
, 1111111111111111111 + 1  // 20 tokens
, 1111111111111111111 + 8  // 20 tokens
, 1111111111111111111 + 9  // 20 tokens
, 1111111111111111111 * 1  // 20 tokens
 
, 1111111111111111111 * 9  // 21 tokens
, 9999999999999999999      // 21 tokens
 
, 1111111111111111111 * 10 // 21 tokens
, 11111111111111111110     // 21 tokens 
 
//adding these functions to the library results in x tokens
export f() => 1	   	  // 4 tokens 
export f() => v = 1	     // 4 tokens
export f() => var v = 1	 // 4 tokens
export f() => var v = 1, v  // 4 tokens 
 
//adding these functions to the library results in x tokens
export a() => const arraya = array.from(1)		         // 42 tokens
export a() =>       arraya = array.from(1)				 // 42 tokens
export a() =>                 a = array.from(1)			     // 41 tokens
export a() => 			        array.from(1)		         // 32 tokens
export a() =>                 a = array.new()              // 44 tokens
export a() =>                 a = array.new(), a.push(1)   // 56 tokens 
 What if we could lower the amount of tokens, so we can export more Prime Numbers?
 
Look at this example:
 829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193 
Eight numbers contain the same number 8291.
If we make a function that removes recurrent values, we get fewer tokens!
 
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193  
//is transformed to:
829111,     21,     23,     51,     59,     77,     87,     93  
The code block below the publication code (// - - - Educational (1) - - - ) shows how these values were reduced. With each step of 100, only the first Prime Number is shown fully. 
This function could be enhanced even more to reduce recurrent thousands, tens of thousands, etc.
Using this technique enables us to export more Prime Numbers. The number of necessary libraries was reduced to half or less.
The reduced Prime Numbers are restored using the restoreValues() function, found in the library fikira/Primes_4.
🔹  Find Prime Numbers 
This function is merely added to show how I filled arrays with Prime Numbers, which were, in turn, added to libraries (after reduction of recurrent values).
To know whether a number is a Prime Number, we divide the given number by values of the Primes array (Primes 2 -> max. 1,340,011). Once the division results in an integer, where the divisor is smaller than the dividend, the calculation stops since the given number is not a Prime.
When we perform these calculations in a loop, we can check whether a series of numbers is a Prime or not. Each time a number is proven not to be a Prime, the loop starts again with a higher number. Once all Primes of the array are used without the result being an integer, we have found a new Prime Number, which is added to the array.
Doing such calculations on one bar will result in a runtime error.
To solve this, the findPrimeNumbers() function remembers the index of the array. Once a limit has been reached on 1 bar (for example, the number of iterations), calculations will stop on that bar and restart on the next bar. 
This spreads the workload over several bars, making it possible to continue these calculations without a runtime error.
The result is placed in  log.info() , which can be copied and pasted into a hardcoded array of Prime Number values.
These settings adjust the amount of workload per bar:
 
 Max Size: maximum size of Primes array.
 Max Bars Runtime: maximum amount of bars where the function is called.
 Max Numbers To Process Per Bar: maximum numbers to check on each bar, whether they are Prime Numbers.
 Max Iterations Per Bar: maximum loop calculations per bar.
 
  
🔹  The End 
 ❗️ The code and description is written without the help of an LLM, I've only used Grammarly to improve my description (without AI :) )
Advanced ICT Theory - A-ICT📊 Advanced ICT Theory (A-ICT): The Institutional Manipulation Detector 
 Are you tired of being the liquidity? Stop chasing shadows and start tracking the architects of price movement. 
 This is not another lagging indicator. This is a complete framework for viewing the market through the lens of institutional traders. Advanced ICT Theory (A-ICT) is an all-in-one, military-grade analysis engine designed to decode the complex language of "Smart Money." It automates the core tenets of Inner Circle Trader (ICT) methodology, moving beyond simple patterns to build a dynamic, real-time narrative of market manipulation, liquidity engineering, and institutional order flow. 
 AIT provides a living blueprint of the market, identifying high-probability zones, tracking structural shifts, and scoring the quality of setups with a sophisticated, multi-factor algorithm. This is your X-ray into the market's true intentions. 
 🔬 THE CORE ENGINE: DECODING THE THEORY & FORMULAS 
 A-ICT is built upon a sophisticated, multi-layered logic system that interprets price action as a story of cause and effect. It does not guess; it confirms. Here is the foundational theory that drives the engine: 
 1. Market Structure: The Blueprint of Trend 
 The script first establishes a deep understanding of the market's skeleton through multi-level pivot analysis. It uses ta.pivothigh and ta.pivotlow to identify significant swing points. 
 Internal Structure (iBOS):   Minor swings that show the short-term order flow. A break of internal structure is the first whisper of a potential shift. 
 External Structure (eBOS):   Major swing points that define the primary trend. A confirmed break of external structure is a powerful statement of trend continuation. AIT validates this with optional  Volume Confirmation  (volume > volumeSMA * 1.2) and  Candle Confirmation  to ensure the break is driven by institutional force, not just a random spike. 
 Change of Character (CHoCH):   This is the earthquake. A CHoCH occurs when a confirmed eBOS happens against the prevailing trend (e.g., a bearish eBOS in a clear uptrend). A-ICT flags this immediately, as it is the strongest signal that the primary trend is under threat of reversal. 
 2. Liquidity Engineering: The Fuel of the Market 
 Institutions don't buy into strength; they buy into weakness. They need liquidity. A-ICT maps these liquidity pools with forensic precision: 
 Buyside & Sellside Liquidity (BSL/SSL):   Using ta.highest and ta.lowest, AIT identifies recent highs and lows where clusters of stop-loss orders (liquidity) are resting. These are institutional targets. 
 Liquidity Sweeps:   This is the "manipulation" part of the detector. AIT has a specific formula to detect a sweep: high > bsl  and close < bsl . This signifies that institutions pushed price just high enough to trigger buy-stops before aggressively selling—a classic "stop hunt." This event dramatically increases the quality score of subsequent patterns. 
 3. The Element Lifecycle: From Potential to Power 
 This is the revolutionary heart of A-ICT. Zones are not static; they have a lifecycle. AIT tracks this with its dynamic classification engine. 
 Phase 1: PENDING (Yellow):   The script identifies a potential zone of interest based on a specific candle formation (a "displacement"). It is marked as "Pending" because its true nature is unknown. It is a question. 
 Phase 2: CLASSIFICATION:   After the zone is created, AIT watches what happens next. The zone's identity is defined by its actions: 
 ORDER BLOCK (Blue):   The highest-grade element. A zone is classified as an Order Block if it directly  causes a Break of Structure (BOS) . This is the footprint of institutions entering the market with enough force to validate the new trend direction. 
 TRAP ZONE (Orange):   A zone is classified as a Trap Zone if it is directly involved in a  Liquidity Sweep . This indicates the zone was used to engineer liquidity, setting a "trap" for retail traders before a reversal. 
 REVERSAL / S&R ZONE (Green):   If a zone is not powerful enough to cause a BOS or a major sweep, but still serves as a pivot point, it's classified as a general support/resistance or reversal zone. 
 4. Market Inefficiencies: Gaps in the Matrix 
 Fair Value Gaps (FVG):   AIT detects FVGs—a 3-bar pattern indicating an imbalance—with a strict formula: low > high  (for a bullish FVG) and gapSize > atr14 * 0.5. This ensures only significant, volatile gaps are shown. An FVG co-located with an Order Block is a high-confluence setup. 
 5. Premium & Discount: The Law of Value 
 Institutions buy at wholesale (Discount) and sell at retail (Premium). AIT uses a pdLookback to define the current dealing range and divides it into three zones: Premium (sell zone), Discount (buy zone), and Equilibrium. An element's quality score is massively boosted if it aligns with this principle (e.g., a bullish Order Block in a Discount zone). 
 ⚙️ THE CONTROL PANEL: A COMPLETE GUIDE TO THE INPUTS MENU 
 Every setting is a lever, allowing you to tune the AIT engine to your exact specifications. Master these to unlock the script's full potential. 
 🎯 A-ICT Detection Engine 
 Min Displacement Candles:   Controls the sensitivity of element detection.  How it works:  It defines the number of subsequent candles that must be "inside" a large parent candle.  Best practice:  Use 2-3 for a balanced view on most timeframes. A higher number (4-5) will find only major, more significant zones, ideal for swing trading. A lower number (1) is highly sensitive, suitable for scalping. 
 Mitigation Method:   Defines when a zone is considered "used up" or mitigated.  How it works:  Cross triggers as soon as price touches the zone's boundary. Close requires a candle to fully close beyond it.  Best practice:  Cross is more responsive for fast-moving markets. Close is more conservative and helps filter out fake-outs caused by wicks, making it safer for confirmations. 
 Min Element Size (ATR):   A crucial noise filter.  How it works:  It requires a detected zone to be at least this multiple of the Average True Range (ATR).  Best practice:  Keep this around 0.5. If you see too many tiny, irrelevant zones, increase this value to 0.8 or 1.0. If you feel the script is missing smaller but valid zones, decrease it to 0.3. 
 Age Threshold & Pending Timeout:   These manage visual clutter.  How they work:  Age Threshold removes old, mitigated elements after a set number of bars. Pending Timeout removes a "Pending" element if it isn't classified within a certain window.  Best practice:  The default settings are optimized. If your chart feels cluttered, reduce the Age Threshold. If pending zones disappear too quickly, increase the Pending Timeout. 
 Min Quality Threshold:   Your primary visual filter.  How it works:  It hides all elements (boxes, lines, labels) that do not meet this minimum quality score (0-100).  Best practice:  Start with the default 30. To see only A- or B-grade setups, increase this to 60 or 70 for an exceptionally clean, high-probability view. 
 🏗️ Market Structure 
 Lookbacks (Internal, External, Major):   These define the sensitivity of the trend analysis.  How they work:  They set the number of bars to the left and right for pivot detection.  Best practice:  Use smaller values for Internal (e.g., 3) to see minor structure and larger values for External (e.g., 10-15) to map the main trend. For a macro, long-term view, increase the Major Swing Lookback. 
 Require Volume/Candle Confirmation:   Toggles for quality control on BOS/CHoCH signals.  Best practice:  It is  highly recommended  to keep these enabled. Disabling them will result in more structure signals, but many will be false alarms. They are your filter against market noise. 
 ... (Continue this detailed breakdown for every single input group: Display Configuration, Zones Style, Levels Appearance, Colors, Dashboards, MTF, Liquidity, Premium/Discount, Sessions, and IPDA). 
 📊 THE INTELLIGENCE DASHBOARDS: YOUR COMMAND CENTER 
 The dashboards synthesize all the complex analysis into a simple, actionable intelligence briefing. 
 Main Dashboard (Bottom Right) 
 ICT Metrics & Breakdown:   This is your statistical overview. Total Elements shows how much structure the script is tracking. High Quality instantly tells you if there are any A/B grade setups nearby. Unmitigated vs. Mitigated shows the balance of fresh opportunities versus resolved price action. The breakdown by Order Blocks, Trap Zones, etc., gives you a quick read on the market's recent character. 
 Structure & Market Context:   This is your core bias. Order Flow tells you the current script-determined trend. Last BOS shows you the most recent structural event. CHoCH Active is a critical warning. HTF Bias shows if you are aligned with the higher timeframe—the checkmark (✓) for alignment is one of the most important confluence factors. 
 Smart Money Flow:   A volume-based sentiment gauge. Net Flow shows the raw buying vs. selling pressure, while the Bias provides an interpretation (e.g., "STRONG BULLISH FLOW"). 
 Key Guide (Large Dashboard only):   A built-in legend so you never have to guess. It defines every pattern, structure type, and special level visually. 
 📖 Narrative Dashboard (Bottom Left) 
 This is the "story" of the market, updated in real-time. It's designed to build your trading thesis. 
 Recent Elements Table:   A live list of the most recent, high-quality setups. It displays the  Type , its  Narrative Role  (e.g., "Bullish OB caused BOS"), its raw  Quality  percentage, and its final  Trade Score  grade. This is your at-a-glance opportunity scanner. 
 Market Narrative Section:   This is the soul of A-ICT. It combines all data points into a human-readable story: 
 📍 Current Phase:   Tells you if you are in a high-volatility Killzone or a consolidation phase like the Asian Range. 
 🎯 Bias & Alignment:   Your primary direction, with a clear indicator of HTF alignment or conflict. 
 🔗 Events:   A causal sequence of recent events, like "💧 Sell-side liquidity swept → 
📊 Bullish BOS → 🎯 Active Order Block". 
 🎯 Next Expectation:   The script's logical conclusion. It provides a specific, forward-looking hypothesis, such as "📉 Pullback expected to bullish OB at 1.2345 before continuation up." 
 🎨 READING THE BATTLEFIELD: A VISUAL INTERPRETATION GUIDE 
 Every color and line is a piece of information. Learn to read them together to see the full picture. 
 The Core Zones (Boxes): 
 Blue Box (Order Block):   Highest probability zone for trend continuation. Look for entries here. 
 Orange Box (Trap Zone):   A manipulation footprint. Expect a potential reversal after price interacts with this zone. 
 Green Box (Reversal/S&R):   A standard pivot area. A good reference point but requires more confluence. 
 Purple Box (FVG):   A market imbalance. Acts as a magnet for price. An FVG inside an Order Block is an A+ confluence. 
 The Structural Lines: 
 Green/Red Line (eBOS):   Confirms the trend direction. A break above the green line is bullish; a break below the red line is bearish. 
 Thick Orange Line (CHoCH):   WARNING. The previous trend is now in question. The market character has changed. 
 Blue/Red Lines (BSL/SSL):   Liquidity targets. Expect price to gravitate towards these lines. A dotted line with a checkmark (✓) means the liquidity has been "swept" or "purged." 
 How to Synthesize:   The magic is in the confluence. A perfect setup might look like this: Price sweeps below a  red SSL line , enters a  green Discount Zone  during the  NY Killzone , and forms a  blue Order Block  which then causes a  green eBOS . This sequence, visible at a glance, is the story of a high-probability long setup. 
 🔧 THE ARCHITECT'S VISION: THE DEVELOPMENT JOURNEY 
 A-ICT was forged from the frustration of using lagging indicators in a market that is forward-looking. Traditional tools are reactive; they tell you what happened. The vision for A-ICT was to create a proactive engine that could anticipate institutional behavior by understanding their objectives: liquidity and efficiency. The development process was centered on creating a "lifecycle" for price patterns—the idea that a zone's true meaning is only revealed by its consequence. This led to the post-breakout classification system and the narrative-building engine. It's designed not just to show you patterns, but to tell you their story. 
 ⚠️ RISK DISCLAIMER & BEST PRACTICES 
 Advanced ICT Theory (A-ICT) is a professional-grade analytical tool and does not provide financial advice or direct buy/sell signals. Its analysis is based on historical price action and probabilities. All forms of trading involve substantial risk. Past performance is not indicative of future results. Always use this tool as part of a comprehensive trading plan that includes your own analysis and a robust risk management strategy. Do not trade based on this indicator alone. 
 観の目つよく、見の目よわく 
 "Kan no me tsuyoku, ken no me yowaku" 
— Miyamoto Musashi, The Book of Five Rings
 English:   "Perceive that which cannot be seen with the eye." 
— Dskyz, Trade with insight. Trade with anticipation.
MA Crossover Strategy with TP/SL (5 EMA Filter)How the Strategy Works on a 5-Minute Chart:
Data Input (5-Minute Candles):
Every single data point (candle) on your chart will represent 5 minutes of price action (Open, High, Low, Close for that 5-minute period).
All calculations (MAs, EMA, signals) will be based on these 5-minute price data points.
Moving Average Calculations:
Fast MA (10-period SMA): This will be the Simple Moving Average of the closing prices of the last 10 five-minute candles. It reacts relatively quickly to recent price changes.
Slow MA (30-period SMA): This will be the Simple Moving Average of the closing prices of the last 30 five-minute candles. It represents a slightly longer-term trend compared to the Fast MA.
5 EMA (5-period EMA): This is the Exponential Moving Average of the closing prices of the last 5 five-minute candles. Being an EMA, it gives more weight to the most recent 5-minute prices, making it very responsive to immediate price action.
Signal Generation (Entry Conditions):
Long Entry Signal:
The 10-period SMA crosses above the 30-period SMA (indicating a potential bullish shift in the short-to-medium term trend).
AND the current 5-minute candle's closing price is above the 5-period EMA (confirming that the immediate price momentum is also bullish and supporting the crossover).
If both conditions are met at the close of a 5-minute candle, a "Buy" signal is generated.
Short Entry Signal:
The 10-period SMA crosses below the 30-period SMA (indicating a potential bearish shift).
AND the current 5-minute candle's closing price is below the 5-period EMA (confirming immediate bearish momentum).
If both conditions are met at the close of a 5-minute candle, a "Sell" signal is generated.
Trade Execution:
When a signal is triggered, the strategy enters a trade (long or short) at the closing price of that 5-minute candle.
Immediately upon entry, it places two contingent orders:
Take Profit (Target): Set at 2% (by default) away from your entry price. For a long trade, it's 2% above; for a short trade, 2% below.
Stop Loss: Set at 1% (by default) away from your entry price. For a long trade, it's 1% below; for a short trade, 1% above.
The trade will remain open until either the Take Profit or Stop Loss price is hit by subsequent 5-minute candles.
Implications for Trading on a 5-Minute Chart:
Increased Trade Frequency: You will likely see many more signals and trades compared to higher timeframes (like 1-hour or daily charts). This means more potential opportunities but also more transaction costs (commissions, slippage).
Sensitivity to Noise: Lower timeframes are more prone to "market noise" – small, random price fluctuations that don't indicate a true trend. While the 5 EMA filter helps, some false signals might still occur.
Faster Price Action: Price movements can be very rapid on a 5-minute chart. Your take profit or stop loss levels might be hit very quickly, sometimes within the same or next few candles.
Parameter Optimization is Crucial: The default MA lengths (10, 30) and EMA (5) might not be optimal for every asset or market condition on a 5-minute chart. You'll need to backtest extensively and potentially adjust these lengths, as well as the targetPerc and stopPerc, to find what works best for the specific instrument you're trading.
Risk Management: The fixed percentage stop loss is vital on a 5-minute chart due to its volatility. Without it, a few unfavorable moves could lead to significant losses.
System 0530 - Stoch RSI Strategy with ATR filterStrategy Description: System 0530 - Multi-Timeframe Stochastic RSI with ATR Filter
Overview:
This strategy, "System 0530," is designed to identify trading opportunities by leveraging the Stochastic RSI indicator across two different timeframes: a shorter timeframe for initial signal triggers (assumed to be the chart's current timeframe, e.g., 5-minute) and a longer timeframe (15-minute) for signal confirmation. It incorporates an ATR (Average True Range) filter to help ensure trades are taken during periods of adequate market volatility and includes a cooldown mechanism to prevent rapid, successive signals in the same direction. Trade exits are primarily handled by reversing signals.
How It Works:
1. Signal Initiation (e.g., 5-Minute Timeframe):
Long Signal Wait: A potential long entry is considered when the 5-minute Stochastic RSI %K line crosses above its %D line, AND the %K value at the time of the cross is at or below a user-defined oversold level (default: 30).
Short Signal Wait: A potential short entry is considered when the 5-minute Stochastic RSI %K line crosses below its %D line, AND the %K value at the time of the cross is at or above a user-defined overbought level (default: 70). When these conditions are met, the strategy enters a "waiting state" for confirmation from the 15-minute timeframe.
2. Signal Confirmation (15-Minute Timeframe):
Once in a waiting state, the strategy looks for confirmation on the 15-minute Stochastic RSI within a user-defined number of 5-minute bars (wait_window_5min_bars, default: 5 bars).
Long Confirmation:
The 15-minute Stochastic RSI %K must be greater than or equal to its %D line.
The 15-minute Stochastic RSI %K value must be below a user-defined threshold (stoch_15min_long_entry_level, default: 40).
Short Confirmation:
The 15-minute Stochastic RSI %K must be less than or equal to its %D line.
The 15-minute Stochastic RSI %K value must be above a user-defined threshold (stoch_15min_short_entry_level, default: 60).
3. Filters:
ATR Volatility Filter: If enabled, trades are only confirmed if the current ATR value (converted to ticks) is above a user-defined minimum threshold (min_atr_value_ticks). This helps to avoid taking signals during periods of very low market volatility. If the ATR condition is not met, the strategy continues to wait for the condition to be met within the confirmation window, provided other conditions still hold.
Signal Cooldown Filter: If enabled, after a signal is generated, the strategy will wait for a minimum number of bars (min_bars_between_signals) before allowing another signal in the same direction. This aims to reduce overtrading.
4. Entry and Exit Logic:
Entry: A strategy.entry() order is placed when all trigger, confirmation, and filter conditions are met.
Exit: This strategy primarily uses reversing signals for exits. For example, if a long position is open, a confirmed short signal will close the long position and open a new short position. There are no explicit take profit or stop loss orders programmed into this version of the script.
Key User-Adjustable Parameters:
Stochastic RSI Parameters: RSI Length, Stochastic RSI Length, %K Smoothing, %D Smoothing.
Signal Trigger & Confirmation:
5-minute %K trigger levels for long and short.
15-minute %K confirmation thresholds for long and short.
Wait window (in 5-minute bars) for 15-minute confirmation.
Filters:
Enable/disable and configure the Signal Cooldown filter (minimum bars between signals).
Enable/disable and configure the ATR Volatility filter (ATR period, minimum ATR value in ticks).
Strategy Parameters:
Leverage Multiplier (Note: This primarily affects theoretical position sizing for backtesting calculations in TradingView and does not simulate actual leveraged trading risks).
Recommendations for Users:
Thorough Backtesting: Test this strategy extensively on historical data for the instruments and timeframes you intend to trade.
Parameter Optimization: Experiment with different parameter settings to find what works best for your trading style and chosen markets. The default values are starting points and may not be optimal for all conditions.
Understand the Logic: Ensure you understand how each component (Stochastic RSI on different timeframes, ATR filter, cooldown) interacts to generate signals.
Risk Management: Since this version does not include explicit stop-loss orders, ensure you have a clear risk management plan in place if trading this strategy live. You might consider manually adding stop-loss orders through your broker or using TradingView's separate strategy order settings for stop-loss if applicable.
Disclaimer:
This strategy description is for informational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Trading involves significant risk of loss. Always do your own research and understand the risks before trading.






















