Weird Renko StratThis strategy uses Renko, it generates a signal when there is a reversal in Renko. When using historical data, it provides a good entry and an okay exit. However, in a real-time environment, this strategy is subject to repaint and may produce a false signal.
As a result, the backtesting result should not be used as a metric to predict future results. It is highly recommended to forward-test the strategy before using it in real trading. I forward test it from 12/18/2022 to 12/21/2022 in paper trading, using the alert feature in Tradingview. I made 60 trades trading the BTCUSDT BINANCE 3 min with 26 as the param and under the condition that I use 20x margin, compounding my yield, and having 0 trading fee, a steady loss is generated: from $10 to $3.02.
This is quite interesting. As if I flip the signal from "Long" to "Short" and another way too, it will be a steady profit from $10 to $21.85. Hence, if I'm trying to anti-trade the real-time alert signal, the current "4 Days Result" will be good. Nevertheless, I still have to forward-test it for longer to see if it will fail eventually.
Dive into the setting of the strategy
- Margin is the leverage you use. 1 means 1x, 10 means 10x. It affects the backtest yield when you backtest
- Compound Yield button is for compound calculation, disable it to go back to normal backtesting
- Anti Strategy button is to do the opposite direction trade, when the original strat told you to "Long", you "Short" instead. Enable it to use the feature
- Param is the block size for the Renko chart
- Drawdown is just a visual tool for you in case you want to place a stop loss (represent by the semitransparent red area in the chart)
- From date Thru Date is to specify the backtest range of the strategy, This feature is turned off by default. It is controlled by the Max Backtest Timeframe which will be explain below
- Max Backtest Timeframe control the From date Thru Date function, disable it to enable the From Date Thru Date function
Param is the most important input in this strategy as it directly affects performance. It is highly recommended to backtest nearly all the possible parameters before deploying it in real trading. Some factors should be considered:
- Price of the asset (like an asset of 1 USD vs an asset of 10000 USD required different param)
- Timeframe (1-minute param is different than 1-month param)
I believe this is caused by the volatility of the selected timeframe since different timeframe has different volatility. Param should be fine-tuned before usage.
Here is the param I'm using:
BTCUSDT BINANCE 3min: 26
BTCUSDT BINANCE 5min: 28
BTCUSDT BINANCE 1day: 15
Background of the strategy:
- The strategy starts with $10 at the start of backtesting (customizable in setting)
- The trading fee is set to 0.00% which is not common for most of the popular exchanges (customizable in setting)
- The contract size is not a fixed amount, but it uses your balance to buy it at the open price. If you are using the compound mode, your balance will be your current total balance. If you are using the non-compound mode, it will just use the $10 you start with unless you change the amount you start with. If you are using a margin higher than 1, it will calculate the corresponding contract size properly based on your margin. (Only these options are allowed, you are not able to change them without changing the code)
Cari skrip untuk "backtesting"
Grid Strategy Back Tester (Long/Short/Neutral)Preface   
I'd like to send a thank you to @xxattaxx-DisDev.
The 'Line' Code, which was the most difficult to plan the Grid Indicator, was solved through the  'Grid Bot Simulator' script of @xxattaxx-DisDev.
 A brief description of the indicators 
These indicators are designed for backtesting of grid trading that can be opened on various exchanges.
Grid trading is a method of selling at particular intervals as prices rise and fall for gird interval price range. 
This indicator is actually designed to see what the Long / Short / Neutral grid has achieved and how much it has achieved over a given period of time.
 How to use 
1. Lower Limit and Upper Limit are required when putting indicators on the chart.
After that, choose the 'Time' when to open the grid.
Also, select Long / Short / Neutral direction if necessary.
2. Statistics Table
  
 Matched Grid  shows how many grid pairs were engaged during the backtesting period.
 The Daily Average Matching Profit  is calculated based on the number of these closed grids.
 Total Matching Profit  is calculated as Matching Grid * Per Matching Profit.
 Position Profit/Loss  shows the benefits and losses from your current position.
 Total Profit/Loss  is sum of Total Matching Profit and Position Profit/Loss.
 The Expanded APY  shows the benefits of running the strategy on these terms for a year.
 Max Loss of Upper   is the maximum loss assumed to be directly at the top of the grid range.
 BEP days (Upper)  show how many days of maintenance relative to Average Matching Profit can result in greater profit than maximum loss if the grid continues to move within range.
(In the case of Long Strategy, it appears to be 'Min Profit', which shows minimal benefit if it reaches the top.)
 Max Loss of Lower  and  BEP days (Lower)  shows the opposite.
(In the case of Short Strategy, it is also referred to as 'Min Profit', which shows minimal benefit if it reaches the bottom.)
3. Grid Info
  
Total Grid Number, Upper Limit, and Lower Limit show the values you set in INPUT.
 Grid Open Price  shows the price for the period you decide to open.
 Starting Position  shows the number of positions that were initially held in the case of a Long / Short Strategy.
(0 for Neutral Strategy)
 Per Grid qty  shows how many positions are allocated to one grid
 Grid Interval  shows the spacing of each grid.
 Per Matched Profit  shows how much profit is generated when a single grid is matched.
 Caution 
Backtesting results for these indicators may vary depending on the time frame. 
Therefore, I recommend that you use it only to compare Profit/Loss over time.
*In addition, there is a problem that all lines in the grid are not implemented, but it is independent of the backtest results.
--------------------------------------
 서문 
지표를 기획함에 있어서 가장 어려웠던 line 코드를 @xxattaxx-DisDev의 'Grid Bot Simulator' 스크립트를 통해 해결할 수 있었습니다.
이에 감사의 말씀을 드립니다.
 해당 지표에 대한 간단한 설명 
해당 지표는 다양한 거래소에서 오픈할 수 있는 그리드 매매에 대한 백테스팅을 위해 만들어졌습니다.
그리드매매는, 특정 가격 구간에 대해 가격이 오르고 내림에 따라 일정 간격에 맞춰 매매를 하는 방식입니다. 
이 지표는 실질적으로 롱/숏/중립 그리드가 어떠한 성과를, 특정 기간동안 얼마나 냈는지를 확인하고자 만들어졌습니다.
 사용방법 
 1. 인풋 
지표를 차트위에 넣을 때, Lower Limit과 Upper Limit이 필요합니다.
그 후 그리드를 언제부터 오픈할 것인지를 선택하세요.
또, 필요하다면 Long / Short / Neutral의 방향을 선택하세요.
 2. 그리드 통계  
Matched Grid는, 백테스팅 기간동안 체결된 그리드 쌍이 몇개인지를 보여줍니다.
이 체결된 그리드의 갯수를 바탕으로 Daily Average Matched Profit이 계산됩니다.
Total Matched Profit은, Matched Grid * Per Matched Profit으로 계산됩니다.
Position Profit/Loss는, 현재 갖고 있는 포지션으로 인한 이익과 손실을 보여줍니다.
Total Matched Profit과 Position Profit/Loss를 합친 금액이 Total Profit/Loss가 됩니다.
Expcted APY는, 이러한 조건으로 전략을 1년동안 운영했을 때의 이익을 보여줍니다.
Max Loss of Upper는, 그리드 범위의 최상단에 바로 도달했을 경우를 가정한 최대 손실입니다.
BEP days(Upper)는, 그리드가 범위 내에서 계속 움직일 경우, Average Matched Profit을 기준으로 며칠동안 유지되어야 최대손실보다 더 큰 이익이 발생할 수 있는지를 보여줍니다.
(Long Strategy의 경우, ‘Min Profit’이라고 나타나는데, 최상단에 도달했을 경우 최소한의 이익을 보여줍니다)
Max Loss of Lower는 그 반대의 경우를 보여줍니다.
(Short Strategy의 경우,  역시 ‘Min Profit’이라고 나타나는데, 최하단에 도착했을 경우 최소한의 이익을 보여줍니다)
 3. 그리드 정보  
그리드 갯수, Upper Limt, Lower Limt은 자신이 설정한 값을 보여줍니다.
Grid Open Price는, 자신이 오픈하기로 정했던 기간의 가격을 보여줍니다.
Starting Position은, 롱/숏 그리드의 경우에 처음에 들고 시작했던 포지션의 갯수를 보여줍니다.
Neutral Strategy의 경우 0입니다.
Per Grid qty는, 하나의 그리드에 얼마만큼의 포지션이 배분되었는지를 보여주며
Grid Interval은 각 그리드의 간격을 보여줍니다.
또, Per Matched Profit은 하나의 그리드가 체결될 때 얼마만큼의 이익이 발생하는 지를 보여줍니다.
 
이러한 지표에 대한 역테스트 결과는 시간 프레임에 따라 달라질 수 있습니다. 
따라서 시간 경과에 따른 손익을 비교할 때만 사용하는 것이 좋습니다.
*추가로, 그리드의 라인이 모두 구현되지 않는 문제가 있지만, 백테스팅 결과와는 무관합니다.
Hammer & Shooting Star [C] - KaspricciHammer and Shooting Star  
This indicator identifies Hammer and Shooting Star candles and marks them with a respective label. It uses a set of predefined fibonacci levels to measure the size of the body in comparison to the overall size of the candle. You can change the fibonacci level according to your preferences.
You can enable a confirmation of the Hammer or Shooting Star candle by a following green or red candle.
 Settings 
 
   Fibonacci Level  - Select on of the predefined fibonacci levels as a threshold for the maximum size of the body compared to the overall size of the candle.
   Confirm by next candle  - by default turned off. If turned on, this will check the subsequent candle and only mark a Hammer followed by a green candle or a Shooting Star followed by a red candle.
   Show labels on chart  - by default turned on. If turned off, the indicator will hide the labels on the chart.
 
 Alerts 
You can create alerts for Hammer and Shooting Star candles. The indicator provides the respective conditions.
 Linking with Backtesting Strategy 
I also added a feature to combine this indicator with a backtesting strategy.  It provides a plot  Connector   which can be selected in a backtesting strategy supporting this linking feature. 
Signals:
 
  Signal:  2 - Hammer candle (long entry) 
  Signal: -2 - Shooting Start candle (short entry)
 
You can see the signal values in the status line of the indicator. This is based on the  External Signal Protocol  defined by  PineCoders .
RSI SMA Crossover StrategyOverview 
RSI SMA Crossover Strategy works the same way as traditional MA crossover strategies, but using RSI instead of price. When RSI crosses over the SMA, a long position is opened (buy). When RSI crosses under the SMA, the long position is closed (sell). 
This strategy can be very effective when the right inputs are used (see below). Be sure to use the backtesting tool to determine the optimal parameters for a given asset/timeframe. 
 Inputs/Parameters 
RSI Length: length for RSI calculation (default = 50)
SMA Length: length for SMA calculation (default = 25)
 Strategy Properties 
Initial Capital = $1000
No default properties are defined for Slippage, Commission, etc, so be sure to set these values to get accurate backtesting results. This script is being published open-source for a reason - save yourself a copy and adjust the settings as you like!
 Backtesting Results 
Testing on Bitcoin (all time index) 1D chart, with all default parameters. 
$1,000 initial investment on 10/07/2010 turns into almost $2.5 billion as of 08/30/2022 (compared to $334 million if the initial investment was held over the same period)
  
Remember, results can vary greatly based on the variables mentioned above, so always be sure to backtest. 
Short Selling EMA Cross (By Coinrule)BINANCE:AVAXUSDT
This short selling script works best in periods of downtrends and general bearish market conditions, with the ultimate goal to sell as the the price decreases further and buy back before a rebound.
This script can work well on coins you are planning to hodl for long-term and works especially well whilst using an automated bot that can execute your trades for you. It allows you to hedge your investment by allocating a % of your coins to trade with, whilst not risking your entire holding. This mitigates unrealised losses from hodling as it provides additional cash from the profits made. You can then choose to to hodl this cash, or use it to reinvest when the market reaches attractive buying levels.
Entry
The exponential moving average ( EMA ) 20 and EMA 50 have been used for the variables determining the entry to the short. EMAs can operate better than simple moving averages due to the additional weighting placed on the most recent data points, whereas simple moving averages weight all the data the same. This means that price is tracked more closely and the most recent volatile moves can be captured and exploited more efficiently using EMAs.
Our backtesting data revealed that the most profitable timeframe was the 30-minute timeframe, this also enabled a good frequency of trades and high profitability.
A fast (shorter term) exponential moving average , in this strategy the EMA 20, crossing under a slow (longer term) moving average, in this example the EMA 50, signals the price of an asset has started to trend to the downside, as the most recent data signals price is declining compared to earlier data. The entry acts on this principle and executes when the EMA 20 crosses under the EMA 50.
Enter Short: EMA 20 crosses under EMA 50.
Exit
This script utilises a take profit and stop loss for the exit. The take profit is set at -8% and the stop loss is set at +16% from the entry price. This would normally be a poor trade due to the risk:reward equalling 0.5. However, when looking at the backtesting data, the high profitability of the strategy (93.33%) leads to increased confidence and showcases the high probability of success according to historical data.
The take profit (-8%) and the stop loss (+16%) of the strategy are widely placed to ensure the move is captured without being stopped out due to relief rallies. The stop loss also plays a role of mitigating losses and minimising risk of being stuck in a short position once there has been a fundamental trend reversal and the market has become bullish .
Exit Short: -8% price decrease from entry price.
OR
Exit Short: +16% price increase from entry price.
Tip: Research what coins have consistent and large token unlocks / highly inflationary tokenomics, and target these during bear markets to short as they will most likely have substantial selling pressure that outweighs demand - leading to declining prices.
The strategy assumes each order is using 30% of the available coins to make the results more realistic and to simulate you only ran this strategy on 30% of your holdings. A trading fee of 0.1% is also taken into account and is aligned to the base fee applied on Binance.
The backtesting data was recorded from December 1st 2021, just as the market was beginning its downtrend. We therefore recommend analysing the market conditions prior to utilising this strategy as it operates best on weak coins during downtrends and bearish conditions.
Last Available Bar InfoLibrary   "Last_Available_Bar_Info" 
 getLastBarTimeStamp()  
 getAvailableBars()  
 This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change.
 For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart). 
 Methods 
     getLastBarTimeStamp()
     : Returns Timestamp of the last available bar (Constant)
     
      getAvailableBars()
      :Returns Number of Available Bars on the chart (Constant)
  Example    
import paragjyoti2012/Last_Available_Bar_Info/v1 as LastBarInfo
last_bar_timestamp=LastBarInfo.getLastBarTimeStamp()
no_of_bars=LastBarInfo.getAvailableBars()
If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe. 
In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted, 
previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results. 
To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available.
    
    tf=timeframe.period
    real_available_bars   = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() ,  lookahead = barmerge.lookahead_off)
    last_available_bar_timestamp   = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() ,  lookahead = barmerge.lookahead_off)
Financial Astrology Crypto ML Daily TrendThis daily trend indicator is based on financial astrology cycles detected with advanced machine learning techniques for the crypto-currencies research portfolio: ADA, BAT, BNB, BTC, DASH, EOS, ETC, ETH, LINK, LTC, XLM, XMR, XRP, ZEC and ZRX. The daily price trend is forecasted through this planets cycles (angular aspects, speed, declination), fast ones are based on Moon, Mercury, Venus and Sun and Mid term cycles are based on Mars, Vesta and Ceres. The combination of all this cycles produce a daily price trend prediction that is encoded into a PineScript array using binary format "0 or 1" that represent sell and buy signals respectively. The indicator provides signals since 2021-01-01 to 2022-12-31, the past months signals purpose is to support backtesting of the indicator combined with other technical indicator entries like MAs, RSI or Stochastic. For future predictions besides 2022 a machine learning models re-train phase will be required.
The resolution of this indicator is 1D, you can tune a parameter where you can determine how many future bars of daily trend are plotted and  adjust an hours shift to anticipate future signals into current bar in order to produce a leading indicator effect to anticipate the trend changes with some hours of anticipation. Combined with technical analysis indicators this daily trend is very powerful because can help to produce approximately 60% of profitable signals based on the backtesting results. You can look at our open source Github repositories to validate accuracy using the backtesting strategies we have implemented in Jesse Crypto Trading Framework as proof of concept of the predictive potential of this indicator. Alternatively, we have implemented a PineScript strategy that use this indicator, just consider that we are pending to do signals update to the period July 2021 to December 2022:  This strategy have accumulated more than 110 likes and many traders have validated the predictive power of Financial Astrology.
DISCLAIMER: This indicator is experimental and don’t provide financial or investment advice, the main purpose is to demonstrate the predictive power of financial astrology. Any allocation of funds following the documented machine learning model prediction is a high-risk endeavour and it’s the users responsibility to practice healthy risk management according to your situation.
[laoowai]BNB_USDT_3m_3Commas_Bollinger_MACD_RSI_StrategyBNB_USDT  _3m
 Release Notes: 
 Time:  3min
 Pair:  BNB_USDT
 Use:  {{strategy.order.alert_message}}
 What's the difference with 3Commas Bollinger Strategy by tedwardd: 
1. Initial capital: 1210 USDT (10$ Base order / 400$*3 Safety order), if you will change, please change JUST  safety order volume or number of safety orders  2-3
2. Using just 2(3) safety order (original script 4)
3. More high-performance strategy for BNB_USDT
4. Using MACD to sell order (original script take profit by scale), thanks  Drun30 .
5. Using RSI to analyze the market conditions.
Need to change:
bot_id = input(title="3Commas Bot ID", defval=" YOUR DATA ")
email_token = input(title="Bot Email Token", defval=" YOUR DATA ")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 FAQ copy from tedwardd 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
This strategy is intended for use as a way of backtesting various parameters available on 3commas.
The primary inputs for the strategy are:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// USER INPUTS
Short MA Window - The length of the Short moving average
Long MA Window - The length of the Long moving average
Upper Band Offset - The offset to use for the upper bollinger offset
Lower Band Offset - The offset to use for the lower bollinger offset
Long Stop Loss % - The stop loss percentage to test
Long Take Profit % - The Take profit percentage to test
Initial SO Deviation % - The price deviation percentage required to place to first safety order
Safety Order Vol Step % - The volume scale to test
3Commas Bot ID - (self-explanatory)
Bot Email Token - Found in the deal start message for your bot (see link in the previous section for details)
3Commas Bot Trading Pair - The pair to include for composite bot start deals (should match the format of 3commas, not TradingView IE. USDT_BTC not BTCUSDT )
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Start Date, Month, Year and End Date, Month, and Year all apply to the backtesting window. By default, it will use as much data as it can give the current period select (there is less historical data available for periods below 1H) back as far as 2016 (there appears to be no historical data on Trading view much before this). If you would like to test a different period of time, just change these values accordingly.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Composite bot using a Bollinger band type trading strategy. While its primary intention is to provide users a way of backtesting bot parameters, it can also be used to trigger a deal start by either using the  {{strategy.order.alert_message}}  field in your alert and providing the bot details in the configuration screen for the strategy or by including the usual deal start message provided by 3commas.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Original script:
1. 3Commas Bollinger Strategy by tedwardd
2. Momentum Strategy ( BTC /USDT; 1h) - MACD (with source code) by Drun30
3Commas Bollinger StrategyThis strategy is intended for use as a way of backtesting various parameters available on 3commas.io composite bot using a bollinger band type trading strategy. While it's primary intention is to provide users a way of backtesting bot parameters, it can also be used to trigger a deal start by either using the {{strategy.open.alert_message}} field in your alert and providing the bot details in the configuration screen for the strategy or by including the usual deal start message provided by 3commas. You can find more information about how to do this from help.3commas.io
  
The primary inputs for the strategy are:
// USER INPUTS
Short MA Window - The length of the Short moving average
Long MA Window  - The length of the Long moving average
Upper Band Offset - The offset to use for the upper bollinger offset
Lower Band Offset - The offset to use for the lower bollinger offset
Long Stop Loss % - The stop loss percentage to test
Long Take Profit % - The Take profit percentage to test
Initial SO Deviation % - The price deviation percentage required to place to first safety order
Safety Order Vol Step % - The volume scale to test
3Commas Bot ID - (self explanatory)
Bot Email Token - Found in the deal start message for your bot (see link in previous section for details)
3Commas Bot Trading Pair - The pair to include for composite bot start deals (should match format of 3commas, not TradingView IE. USDT_BTC not BTCUSDT)
Start Date, Month, Year and End Date, Month and Year all apply to the backtesting window. By default it will use as much data as it can given the current period select (there is less historical data available for periods below 1H) back as far as 2016 (there appears to be no historical data on Trading view much before this). If you would like to test a different period of time, just change these values accordingly.
 Known Issues 
Currently there are a couple of issues with this strategy that you should be aware of. I may fix them at some point in the future but they don't really bug me so this is more for informational purposes than a promise that they may one day be fixed.
 
  Does not test trailing take profit
  Number of safety orders and Safety Order Step Scale are currently not user configurable (must edit source code)
  Using the user configuration to generate deal start message assumes you are triggering a composite bot, not a simple bot. 
 
Efficient Work [LucF]█  OVERVIEW 
Efficient Work measures the ratio of price movement from close to close ( resulting work ) over the distance traveled to the high and low before settling down at the close ( total work ). The closer the two values are, the more Efficient Work approaches its maximum value of +1 for an up move or -1 for a down move. When price does not change, Efficient Work is zero.
Higher values of Efficient Work indicate more efficient price travel between the close of two successive bars, which I interpret to be more significant, regardless of the move's amplitude. Because it measures the direction and strength of price changes rather than their amplitude, Efficient Work may be thought of as a sentiment indicator.
█  CONCEPTS 
This oscillator's design stems from a few key concepts.
 Relative Levels 
Other than the centerline, relative rather than absolute levels are used to identify levels of interest. Accordingly, no fixed levels correspond to overbought/oversold conditions. Relative levels of interest are identified using:
 • A Donchian channel (historical highs/lows).
 • The oscillator's position relative to higher timeframe values.
 • Oscillator levels following points in time where a divergence is identified.
 Higher timeframes 
Two progressively higher timeframes are used to calculate larger-context values for the oscillator. The rationale underlying the use of timeframes higher than the chart's is that, while they change less frequently than the values calculated at the chart's resolution, they are more meaningful because more work (trader activity) is required to calculate them. Combining the immediacy of values calculated at the chart's resolution to higher timeframe values achieves a compromise between responsiveness and reliability.
 Divergences as points of interest rather than directional clues 
A very simple interpretation of what constitutes a divergence is used. A divergence is defined as a discrepancy between any bar's direction and the direction of the signal line on that same bar. No attempt is made to attribute a directional bias to divergences when they occur. Instead, the oscillator's level is saved and subsequent movement of the oscillator relative to the saved level is what determines the bullish/bearish state of the oscillator.
 Conservative coloring scheme 
Several additive coloring conditions allow the bull/bear coloring of the oscillator's main line to be restricted to specific areas meeting all the selected conditions. The concept is built on the premise that most of the time, an oscillator's value should be viewed as mere noise, and that somewhat like price, it only occasionally conveys actionable information.
█  FEATURES 
 Plots 
 • Three lines can be plotted. They are named  Main line ,  Line 2  and  Line 3 . You decide which calculation to use for each line:
   • The oscillator's value at the chart's resolution.
   • The oscillator's value at a medium timeframe higher than the chart's resolution.
   • The oscillator's value at the highest timeframe.
   • An aggregate line calculated using a weighed average of the three previous lines (see the  Aggregate Weights  section of Inputs to configure the weights).
 • The coloring conditions, divergence levels and the Hi/Lo channel always apply to the Main line, whichever calculation you decide to use for it.
 • The color of lines 2 and 3 are fixed but can be set in the "Colors" section of Inputs.
 • You can change the thickness of each line.
 • When the aggregate line is displayed, higher timeframe values are only used in its calculation when they become available in the chart's history,
  otherwise the aggregate line would appear much later on the chart. To indicate when each higher timeframe value becomes available,
  a small label appears near the centerline.
 • Divergences can be shown as small dots on the centerline.
 • Divergence levels can be shown. The level and fill are determined by the oscillator's position relative to the last saved divergence level.
 • Bull/bear markers can be displayed. They occur whenever a new bull/bear state is determined by the "Main Line Coloring Conditions".
 • The Hi/Lo (Donchian) channel can be displayed, and its period defined.
 • The background can display the state of any one of 11 different conditions.
 • The resolutions used for the higher timeframes can be displayed to the right of the last bar's value.
 • Four key values are always displayed in the Data Window (fourth icon down to the right of your chart):
  oscillator values for the chart, medium and highest timeframes, and the oscillator's instant value before it is averaged.
 Main Line Coloring Conditions 
 • Nine different conditions can be selected to determine the bull/bear coloring of the main line. All conditions set to "ON" must be met to determine the bull/bear state.
 • A volatility state can also be used to filter the conditions.
 • When the coloring conditions and the filter do not allow for a bull/bear state to be determined, the neutral color is used.
 Signal 
 • Seven different averages can be used to calculate the average of the oscillator's value.
 • The average's period can be set. A period of one will show the instant value of the oscillator,
  provided you don't use linear regression or the Hull MA as they do not work with a period of one.
 • An external signal can be used as the oscillator's instant value. If an already averaged external value is used, set the period to one in this indicator.
 • For the cases where an external signal is used, a centerline value can be set.
 Higher Timeframes 
 • The two higher timeframes are named  Medium timeframe  and  Highest timeframe . They can be determined using one of three methods:
  • Auto-steps: the higher timeframes are determined using the chart's resolution. If the chart uses a seconds resolution, for example,
   the medium and highest resolutions will be 15 and 60 minutes.
  • Multiples: the timeframes are calculated using a multiple of the chart's resolution, which you can set.
  • Fixed: the set timeframes do not change with the chart's resolution.
 Repainting 
 • Repainting can be controlled separately for the chart's value and the higher timeframe values.
 • The default is a repainting chart value and non-repainting higher timeframe values. The Aggregate line will thus repaint by default,
  as it uses the chart's value along with the higher timeframes values.
 Aggregate Weights 
 • The weight of each component of the Aggregate line can be set.
 • The default is equal weights for the three components, meaning that the chart's value accounts for one third of the weight in the Aggregate.
 High Volatility 
 • This provides control over the volatility filter used in the Main line's coloring conditions and the background display.
 • Volatility is determined to be high when the short-term ATR is greater than the long-term ATR.
 Colors 
 • You can define your own colors for all of the oscillator's plots.
 • The default colors will perform well on both white and black chart backgrounds.
 Alerts 
 • An alert can be defined for the script. The alert will trigger whenever a bull/bear marker appears in the indicator's display.
  The particular combination of coloring conditions and the display of bull/bear markers when you create the alert will thus determine when the alert triggers.
  Once the alerts are created, subsequent changes to the conditions controlling the display of markers will not affect the existing alert(s).
 • You can create multiple alerts from this script, each triggering on different conditions.
 Backtesting & Trading Engine Signal Line 
 • An invisible plot named "BTE Signal" is provided. It can be used as an entry signal when connected to the  PineCoders Backtesting & Trading Engine  as an external input.
  It will generate an entry whenever a marker is displayed.
█  NOTES 
• I do not know for sure if the calculations in Efficient Work are original. I apologize if they are not.
• Because this version of Efficient Work only has access to OHLC information, it cannot measure the total distance traveled through all of a bar's ticks, but the indicator nonetheless behaves in a manner consistent with the intentions underlying its design.
 For Pine coders 
This code was written using the following standards:
 • The PineCoders  Coding Conventions for Pine .
 • A modified version of the PineCoders  MTF Oscillator Framework  and  MTF Selection Framework .
MTF Oscillator Framework [PineCoders]This framework allows Pine coders to quickly build a complete multi-timeframe oscillator from any calculation producing values around a centerline, whether the values are bounded or not. Insert your calculation in the script and you have a ready-to-publish MTF Oscillator offering a plethora of presentation options and features.
█  HOW TO USE THE FRAMEWORK 
1 — Insert your calculation in the `f_signal()` function at the top of the "Helper Functions" section of the script.
2 — Change the script's name in the `study()` declaration statement and the `alertcondition()` text in the last part of the "Plots" section.
3 — Adapt the default value used to initialize the CENTERLINE constant in the script's "Constants" section.
4 — If you want to publish the script, copy/paste the following description in your new publication's description and replace the "OVERVIEW" section with a description of your calculations.
5 — Voilà!
═════════════════════════════════════════════════════════════════════════
█  OVERVIEW 
This oscillator calculates a directional value of True Range. When a bar is up, the positive value of True Range is used. A negative value is used when the bar is down. When there is no movement during the bar, a zero value is generated, even if True Range is different than zero. Because the unit of measure of True Range is price, the oscillator is unbounded (it does not have fixed upper/lower bounds).
True Range can be used as a metric for volatility, but by using a signed value, this oscillator will show the directional bias of progressively increasing/decreasing volatility, which can make it more useful than an always positive value of True Range.
The True Range calculation appeared for the first time in J. Welles Wilder's  New Concepts in Technical Trading Systems  book published in 1978. Wilder's objective was to provide a reliable measure of the effective movement—or range—between two bars, to measure volatility. True Range is also the building block used to calculate ATR (Average True Range), which calculates the average of True Range values over a given period using the `rma` averaging method—the same used in the calculation of another of Wilder's remarkable creations: RSI.
█  CONCEPTS 
This oscillator's design stems from a few key concepts.
 Relative Levels 
Other than the centerline, relative rather than absolute levels are used to identify levels of interest. Accordingly, no fixed levels correspond to overbought/oversold conditions. Relative levels of interest are identified using:
 • A Donchian channel (historical highs/lows).
 • The oscillator's position relative to higher timeframe values.
 • Oscillator levels following points in time where a divergence is identified.
 Higher timeframes 
Two progressively higher timeframes are used to calculate larger-context values for the oscillator. The rationale underlying the use of timeframes higher than the chart's is that, while they change less frequently than the values calculated at the chart's resolution, they are more meaningful because more work (trader activity) is required to calculate them. Combining the immediacy of values calculated at the chart's resolution to higher timeframe values achieves a compromise between responsiveness and reliability.
 Divergences as points of interest rather than directional clues 
A very simple interpretation of what constitutes a divergence is used. A divergence is defined as a discrepancy between any bar's direction and the direction of the signal line on that same bar. No attempt is made to attribute a directional bias to divergences when they occur. Instead, the oscillator's level is saved and subsequent movement of the oscillator relative to the saved level is what determines the bullish/bearish state of the oscillator.
 Conservative coloring scheme 
Several additive coloring conditions allow the bull/bear coloring of the oscillator's main line to be restricted to specific areas meeting all the selected conditions. The concept is built on the premise that most of the time, an oscillator's value should be viewed as mere noise, and that somewhat like price, it only occasionally conveys actionable information.
█  FEATURES 
 Plots 
 • Three lines can be plotted. They are named  Main line ,  Line 2  and  Line 3 . You decide which calculation to use for each line:
   • The oscillator's value at the chart's resolution.
   • The oscillator's value at a medium timeframe higher than the chart's resolution.
   • The oscillator's value at the highest timeframe.
   • An aggregate line calculated using a weighed average of the three previous lines (see the  Aggregate Weights  section of Inputs to configure the weights).
 • The coloring conditions, divergence levels and the Hi/Lo channel always apply to the Main line, whichever calculation you decide to use for it.
 • The color of lines 2 and 3 are fixed but can be set in the "Colors" section of Inputs.
 • You can change the thickness of each line.
 • When the aggregate line is displayed, higher timeframe values are only used in its calculation when they become available in the chart's history,
  otherwise the aggregate line would appear much later on the chart. To indicate when each higher timeframe value becomes available,
  a small label appears near the centerline.
 • Divergences can be shown as small dots on the centerline.
 • Divergence levels can be shown. The level and fill are determined by the oscillator's position relative to the last saved divergence level.
 • Bull/bear markers can be displayed. They occur whenever a new bull/bear state is determined by the "Main Line Coloring Conditions".
 • The Hi/Lo (Donchian) channel can be displayed, and its period defined.
 • The background can display the state of any one of 11 different conditions.
 • The resolutions used for the higher timeframes can be displayed to the right of the last bar's value.
 • Four key values are always displayed in the Data Window (fourth icon down to the right of your chart):
  oscillator values for the chart, medium and highest timeframes, and the oscillator's instant value before it is averaged.
 Main Line Coloring Conditions 
 • Nine different conditions can be selected to determine the bull/bear coloring of the main line. All conditions set to "ON" must be met to determine the bull/bear state.
 • A volatility state can also be used to filter the conditions.
 • When the coloring conditions and the filter do not allow for a bull/bear state to be determined, the neutral color is used.
 Signal 
 • Seven different averages can be used to calculate the average of the oscillator's value.
 • The average's period can be set. A period of one will show the instant value of the oscillator,
  provided you don't use linear regression or the Hull MA as they do not work with a period of one.
 • An external signal can be used as the oscillator's instant value. If an already averaged external value is used, set the period to one in this indicator.
 • For the cases where an external signal is used, a centerline value can be set.
 Higher Timeframes 
 • The two higher timeframes are named  Medium timeframe  and  Highest timeframe . They can be determined using one of three methods:
  • Auto-steps: the higher timeframes are determined using the chart's resolution. If the chart uses a seconds resolution, for example,
   the medium and highest resolutions will be 15 and 60 minutes.
  • Multiples: the timeframes are calculated using a multiple of the chart's resolution, which you can set.
  • Fixed: the set timeframes do not change with the chart's resolution.
 Repainting 
 • Repainting can be controlled separately for the chart's value and the higher timeframe values.
 • The default is a repainting chart value and non-repainting higher timeframe values. The Aggregate line will thus repaint by default,
  as it uses the chart's value along with the higher timeframes values.
 Aggregate Weights 
 • The weight of each component of the Aggregate line can be set.
 • The default is equal weights for the three components, meaning that the chart's value accounts for one third of the weight in the Aggregate.
 High Volatility 
 • This provides control over the volatility filter used in the Main line's coloring conditions and the background display.
 • Volatility is determined to be high when the short-term ATR is greater than the long-term ATR.
 Colors 
 • You can define your own colors for all of the oscillator's plots.
 • The default colors will perform well on both white and black chart backgrounds.
 Alerts 
 • An alert can be defined for the script. The alert will trigger whenever a bull/bear marker appears in the indicator's display.
  The particular combination of coloring conditions and the display of bull/bear markers when you create the alert will thus determine when the alert triggers.
  Once the alerts are created, subsequent changes to the conditions controlling the display of markers will not affect the existing alert(s).
 • You can create multiple alerts from this script, each triggering on different conditions.
 Backtesting & Trading Engine Signal Line 
 • An invisible plot named "BTE Signal" is provided. It can be used as an entry signal when connected to the  PineCoders Backtesting & Trading Engine  as an external input.
  It will generate an entry whenever a marker is displayed.
 Look first. Then leap.  
Dual Harmonic-based AHR DCA (Default :BTC-ETH)A panel indicator designed for dual-asset BTC/ETH DCA (Dollar Cost Averaging) decisions.  
It is inspired by the Chinese community indicator  "AHR999"   proposed by “Jiushen”.
 How to use:   
 
 Lower HM-based AHR → cheaper (potential buy zone).  
 Higher HM-based AHR → more expensive (potential risk zone).  
 Higher than Risk Threshold → consider to sell, but not suitable for DCA.  
 When both AHR lines are below the Risk threshold → buy the cheaper one (or split if similar).  
 If one AHR is above Risk → buy the other asset.  
 If both are above Risk → simulation shows “STOP (both risk)”.  
 Not limited to BTC/ETH — you can freely change symbols in the input panel  
   to build any dual-asset DCA pair you want (e.g., BTC/BNB, ETH/SOL, etc.).
 
 What you’ll see: 
 
 Two lines: AHR BTC (HM) and AHR ETH (HM)  
 Two dashed lines: OppThreshold (green) and RiskThreshold (red)  
 Colored fill showing which asset is cheaper (BTC or ETH)  
 Buy markers:  
   -  B  = Buy BTC  
   -  E  = Buy ETH  
   -  D  = Dual (split budget)  
 Top-right table: prices, AHRs, thresholds, qOpp/qRisk%, simulation, P&L  
 Labels showing last-bar AHR values
 
 Core idea:   
Use an AHR based on Harmonic Moving Average (HM) — a ratio that measures how “cheap or expensive” price is relative to both its short-term mean and long-term trend.  
The original AHR999 used SMA and was designed for BTC only.  
This indicator extends it with cross-exchange percentile mapping, allowing the empirical “opportunity/risk” zones of the AHR999 (on Bitstamp) to adapt automatically to the current market pair.
The indicator derives two adaptive thresholds:
 
 OppThreshold  – opportunity zone  
 RiskThreshold  – risk zone
 
These thresholds are compared with the current HM-based AHR of BTC and ETH to decide which asset is cheaper, and whether it is good to DCA or not, or considering to sell(When it in risk area). 
 This version uses 
 
 Display base:  Binance (default: perpetual) with HM-based AHR  
 Percentile base:  Bitstamp spot SMA-AHR (complete, stable history)  
 Rolling window:  2920 daily bars (~8 years) for percentile tracking  
 
 Concept summary 
 
 AHR measures the ratio of price to its long-term regression and short-term mean.  
 HM replaces SMA to better reflect equal-fiat-cost DCA behavior.  
 Cross-exchange percentile mapping (Bitstamp → Binance) keeps thresholds consistent with the original AHR999 interpretation.
 
 Recommended settings (1D):   
 
 DCA length (harmonic):  200  
 Log-regression lookback:  1825 (≈5 years)  
 Rolling window:  2920 (≈8 years)  
 Reference thresholds:  0.45 / 1.20 (AHR999 empirical priors)  
 Tie split tolerance (ΔAHR):  0.05  
 Daily budget:  15 USDT (simulation)  
 All display options can be toggled: table, markers, labels, etc.  
 
 Notes:   
When the rolling window is filled (2920 bars by default), thresholds are first calculated and then visually backfilled as left-extended lines.  
The “buy markers” and “decision table” are  light simulations  without fees or funding costs — for rhythm and relative analysis, not backtesting.
Crypto Futures Basis Tracker (Annualized)🧩 What is Basis Arbitrage 
 Basis arbitrage  is a market-neutral trading strategy that exploits the price difference between a cryptocurrency’s spot and its futures markets.
 
 When futures trade above spot (called contango), traders can buy spot and short futures, locking in a potential yield.
 When futures trade below spot (backwardation), the reverse applies — short spot and go long futures.
 
The yield earned (or cost paid) by holding this position until expiry is called the basis. Expressing it as an annualized percentage allows comparison across different contract maturities.
 ⚙️ How the Indicator Works 
This tool calculates the annualized basis for up to 10 cryptocurrency futures against a chosen spot price.
 
  You select one  spot symbol  (e.g., BITSTAMP:BTCUSD) and up to  10 futures symbols  (e.g., DERIBIT:BTCUSD07X2025, DERIBIT:BTCUSD14X2025, etc.).
  The script automatically computes the days-to-expiry (DTE) and the annualized basis for each future.
  A table displays for each contract: symbol, expiry date, DTE, last price, and annualized basis (%) — making it easy to compare the forward curve across maturities.
 
 ⚠️ Risks and Limitations 
While basis arbitrage is often considered low-risk, it’s not risk-free:
 
 Funding and financing costs  can erode returns, especially when borrowing or using leverage.
 Exchange or counterparty risk  — if one leg of the trade fails (e.g., exchange default, margin liquidation), the hedge breaks.
 Execution and timing risk  — the basis can tighten or invert before both legs are opened.
 Liquidity differences   — thin futures may have large bid-ask spreads or slippage.
 
Use this indicator for analysis and monitoring, not as an automated trading signal.
 Disclaimer:   Please remember that past performance may not be indicative of future results. Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting. This post and the script don't provide any financial advice.
Pivots High Low Live DetectionPivots High Low Live Detection 
 
Identifies and visualizes swing highs and lows on the chart in real time.
Helps to observe evolving market structure by connecting confirmed or developing pivot points with lines and labels.
Using a configurable lookback, minimum deviation, and confirmation bar system, the indicator highlights new Higher Highs (HH), Higher Lows (HL), Lower Highs (LH), and Lower Lows (LL) as they form.
When “Live (repainting)” mode is enabled, the current swing leg updates dynamically with each candle, giving immediate feedback as price develops.
When disabled, only confirmed pivots are plotted, ideal for historical validation and backtesting.
 + Key Features 
Detects and labels major swing points (HH, HL, LH, LL).
Works in live or confirmed (non-repainting) mode.
Adjustable parameters for lookback, deviation (in ticks), and confirmation bars.
Lightweight and compatible with any timeframe or symbol.
Includes runtime alerts for new structural pivots and direction shifts.
 + How to Use 
Adjust the inputs under the “Pivots” group to control sensitivity.
Enable “Live (repainting)” to see developing swing legs, or disable it for confirmed structure only.
Use alerts to track structural changes or potential trend reversals.
No-Trade Zones UTC+7This indicator helps you visualize and backtest your preferred trading hours. For example, if you have a 9-to-5 job, you obviously can’t trade during that time — and when backtesting, you should avoid those hours too. It also marks weekends if you prefer not to trade on those days.
By highlighting no-trade periods directly on the chart, you can easily see when you shouldn’t be taking trades, without constantly checking the time or date by hovering over the chart. It makes backtesting smoother and more realistic for your personal schedule.
Gap & Crap Detector V1Gap & Crap Detector (5% Gap Detector + % Labels)
This indicator automatically detects stocks that gap up ≥ 5% (adjustable) from the previous day’s close and tracks whether the move holds or fails over the next three candles.
🔍 How It Works
Yellow % Label → Appears on every candle that gaps up ≥ 5%, showing the exact percentage gap.
Gap & Go (Green Label) → Triggers when the next 3 candles close above the gap-day low, signaling momentum continuation.
Gap & Crap (Red Label) → Triggers immediately if any of the next 3 candles close below the gap-day low, signaling momentum failure.
⚙️ Inputs & Customization
Gap % Threshold – Default 5% (adjustable)
Label Size – Tiny / Small / Normal / Large / Huge
Opacity Controls – Independently set transparency for yellow, red, and green labels
Gap & Go Offset – Adjust how high above the candle the green label appears
🧠 Usage
Use this tool to identify breakout gaps and verify whether price action confirms (Gap & Go) or fails (Gap & Crap).
Ideal for momentum traders, swing traders, Ovtlyr Plan M, and gap strategy backtesting.
Luxy BIG beautiful Dynamic ORBThis is an advanced Opening Range Breakout (ORB) indicator that tracks price breakouts from the first 5, 15, 30, and 60 minutes of the trading session. It provides complete trade management including entry signals, stop-loss placement, take-profit targets, and position sizing calculations.
The ORB strategy is based on the concept that the opening range of a trading session often acts as support/resistance, and breakouts from this range tend to lead to significant moves.
  
 What Makes This Different? 
Most ORB indicators simply draw horizontal lines and leave you to figure out the rest. This indicator goes several steps further:
 Multi-Stage Tracking 
Instead of just one ORB timeframe, this tracks FOUR simultaneously (5min, 15min, 30min, 60min). Each stage builds on the previous one, giving you multiple trading opportunities throughout the session.
 Active Trade Management 
When a breakout occurs, the indicator automatically calculates and displays entry price, stop-loss, and multiple take-profit targets. These lines extend forward and update in real-time until the trade completes.
 Cycle Detection 
Unlike indicators that only show the first breakout, this tracks the complete cycle: Breakout → Retest → Re-breakout. You can see when price returns to test the ORB level after breaking out (potential re-entry).
 Failed Breakout Warning 
If price breaks out but quickly returns inside the range (within a few bars), the label changes to "FAILED BREAK" - warning you to exit or avoid the trade.
 Position Sizing Calculator 
Built-in risk management that tells you exactly how many shares to buy based on your account size and risk tolerance. No more guessing or manual calculations.
 Advanced Filtering 
Optional filters for volume confirmation, trend alignment, and Fair Value Gaps (FVG) to reduce false signals and improve win rate.
  
 Core Features Explained
 
### 1. Multi-Stage ORB Levels
The indicator builds four separate Opening Range levels:
 
 ORB 5  - First 5 minutes (fastest signals, most volatile)
 ORB 15  - First 15 minutes (balanced, most popular)
 ORB 30  - First 30 minutes (slower, more reliable)
 ORB 60  - First 60 minutes (slowest, most confirmed)
 
Each level is drawn as a horizontal range on your chart. As time progresses, the ranges expand to include more price action. You can enable or disable any stage and assign custom colors to each.
 How it works:  During the opening minutes, the indicator tracks the highest high and lowest low. Once the time period completes, those levels become your ORB high and low for that stage.
### 2. Breakout Detection
When price closes outside the ORB range, a label appears:
 
 BREAK UP  (green label above price) - Price closed above ORB High
 BREAK DOWN  (red label below price) - Price closed below ORB Low
 
The label shows which ORB stage triggered (ORB5, ORB15, etc.) and the cycle number if tracking multiple breakouts.
 Important:  Signals appear on bar close only - no repainting. What you see is what you get.
### 3. Retest Detection
After price breaks out and moves away, if it returns to test the ORB level, a "RETEST" label appears (orange). This indicates:
 
 The original breakout level is now acting as support/resistance
 Potential re-entry opportunity if you missed the first breakout
 Confirmation that the level is significant
 
The indicator requires price to move a minimum distance away before considering it a valid retest (configurable in settings).
### 4. Failed Breakout Detection
If price breaks out but returns inside the ORB range within a few bars (before the breakout is "committed"), the original label changes to "FAILED BREAK" in orange.
This warns you:
 
 The breakout lacked conviction
 Consider exiting if already in the trade
 Wait for better setup
 
 Committed Breakout:  The indicator tracks how many bars price stays outside the range. Only after staying outside for the minimum number of bars does it become a committed breakout that can be retested.
  
### 5. TP/SL Lines (Trade Management)
When a breakout occurs, colored horizontal lines appear showing:
 
 Entry Line  (cyan for long, orange for short) - Your entry price (the ORB level)
 Stop Loss Line  (red) - Where to exit if trade goes against you
 TP1, TP2, TP3 Lines  (same color as entry) - Profit targets at 1R, 2R, 3R
 
These lines extend forward as new bars form, making it easy to track your trade. When a target is hit, the line turns green and the label shows a checkmark.
 Lines freeze (stop updating) when: 
 
 Stop loss is hit
 The final enabled take-profit is hit
 End of trading session (optional setting)
 
### 6. Position Sizing Dashboard
The dashboard (bottom-left corner by default) shows real-time information:
 
 Current ORB stage and range size
 Breakout status (Inside Range / Break Up / Break Down)
 Volume confirmation (if filter enabled)
 Trend alignment (if filter enabled)
 Entry and Stop Loss prices
 All enabled Take Profit levels with percentages
 Risk/Reward ratio
 Position sizing: Max shares to buy and total risk amount
 
 Position Sizing Example: 
If your account is $25,000 and you risk 1% per trade ($250), and the distance from entry to stop loss is $0.50, the calculator shows you can buy 500 shares (250 / 0.50 = 500).
  
### 7. FVG Filter (Fair Value Gap)
Fair Value Gaps are price inefficiencies - gaps left by strong momentum where one candle's high doesn't overlap with a previous candle's low (or vice versa).
When enabled, this filter:
 
 Detects bullish and bearish FVGs
 Draws semi-transparent boxes around these gaps
 Only allows breakout signals if there's an FVG near the breakout level
 
 Why this helps:  FVGs indicate institutional activity. Breakouts through FVGs tend to be stronger and more reliable.
 Proximity setting:  Controls how close the FVG must be to the ORB level. 2.0x means the breakout can be within 2 times the FVG size - a reasonable default.
### 8. Volume & Trend Filters
 Volume Filter: 
Requires current volume to be above average (customizable multiplier). High volume breakouts are more likely to sustain.
 
 Set minimum multiplier (e.g., 1.5x = 50% above average)
 Set "strong volume" multiplier (e.g., 2.5x) that bypasses other filters
 Dashboard shows current volume ratio
 
 Trend Filter: 
Only shows breakouts aligned with a higher timeframe trend. Choose from:
 
 VWAP - Price above/below volume-weighted average
 EMA - Price above/below exponential moving average
 SuperTrend - ATR-based trend indicator
 Combined modes (VWAP+EMA, VWAP+SuperTrend) for stricter filtering
 
### 9. Pullback Filter (Advanced)
 Purpose: 
Waits for price to pull back slightly after initial breakout before confirming the signal. 
This reduces false breakouts from immediate reversals.
 How it works: 
- After breakout is detected, indicator waits for a small pullback (default 2%)
- Once pullback occurs AND price breaks out again, signal is confirmed
- If no pullback within timeout period (5 bars), signal is issued anyway
 Settings: 
 
 Enable Pullback Filter:  Turn this filter on/off
 Pullback %:  How much price must pull back (2% is balanced)
 Timeout (bars):  Max bars to wait for pullback (5 is standard)
 
 When to use: 
- Choppy markets with many fake breakouts
- When you want higher quality signals
- Combine with Volume filter for maximum confirmation
 Trade-off: 
- Better signal quality
- May miss some valid fast moves
- Slight entry delay
  
 How to Use This Indicator 
### For Beginners - Simple Setup
 
 Add the indicator to your chart (5-minute or 15-minute timeframe recommended)
 Leave all default settings - they work well for most stocks
 Watch for BREAK UP or BREAK DOWN labels to appear
 Check the dashboard for entry, stop loss, and targets
 Use the position sizing to determine how many shares to buy
 
 Basic Trading Plan: 
 
 Wait for a clear breakout label
 Enter at the ORB level (or next candle open if you're late)
 Place stop loss where the red line indicates
 Take profit at TP1 (50% of position) and TP2 (remaining 50%)
 
### For Advanced Traders - Customized Setup
 
 Choose which ORB stages to track (you might only want ORB15 and ORB30)
 Enable filters: Volume (stocks) or Trend (trending markets)
 Enable FVG filter for institutional confirmation
 Set "Track Cycles" mode to catch retests and re-breakouts
 Customize stop loss method (ATR for volatile stocks, ORB% for stable ones)
 Adjust risk per trade and account size for accurate position sizing
 
 Advanced Strategy Example: 
 
 Enable ORB15 only (disable others for cleaner chart)
 Turn on Volume filter at 1.5x with Strong at 2.5x
 Enable Trend filter using VWAP
 Set Signal Mode to "Track Cycles" with Max 3 cycles
 Wait for aligned breakouts (Volume + Trend + Direction)
 Enter on retest if you missed the initial break
 
### Timeframe Recommendations
 
 5-minute chart:  Scalping, very active trading, crypto
 15-minute chart:  Day trading, balanced approach (most popular)
 30-minute chart:  Swing entries, less screen time
 60-minute chart:  Position trading, longer holds
 
The indicator works on any intraday timeframe, but ORB is fundamentally a day trading strategy. Daily charts don't make sense for ORB.
 
 DEFAULT CONFIGURATION  
ON by Default:
• All 4 ORB stages (5/15/30/60)
• Breakout Detection
• Retest Labels
• All TP levels (1/1.5/2/3)
• TP/SL Lines (Detailed mode)
• Dashboard (Bottom Left, Dark theme)
• Position Size Calculator
OFF by Default (Optional Filters):
• FVG Filter
• Pullback Filter
• Volume Filter
• Trend Filter
• HTF Bias Check
• Alerts
Recommended for Beginners:
• Leave all defaults
• Session Mode: Auto-Detect
• Signal Mode: Track Cycles
• Stop Method: ATR
• Add Volume Filter if trading stocks
 Recommended for Advanced: 
• Enable ORB15 + ORB30 only (disable 5 & 60)
• Enable: Volume + Trend + FVG 
• Signal Mode: Track Cycles, Max 3 
• Stop Method: ATR or Safer 
• Enable HTF Daily bias check 
 
## Settings Guide
The settings are organized into logical groups. Here's what each section controls:
### ORB COLORS Section
 
 Show Edge Labels:  Display "ORB 5", "ORB 15" labels at the right edge of the levels
 Background:  Fill the area between ORB high/low with color
 Transparency:  How see-through the background is (95% is nearly invisible)
 Enable ORB 5/15/30/60:  Turn each stage on or off individually
 Colors:  Assign colors to each ORB stage for easy identification
 
### SESSION SETTINGS Section
 
 Session Mode:  Choose trading session (Auto-Detect works for most instruments)
 Custom Session Hours:  Define your own hours if needed (format: HHMM-HHMM)
 
Auto-Detect uses the instrument's natural hours (stocks use exchange hours, crypto uses 24/7).
### BREAKOUT DETECTION Section
 
 Enable Breakout Detection:  Master switch for signals
 Show Retest Labels:  Display retest signals
 Label Size:  Visual size for all labels (Small recommended)
 Enable FVG Filter:  Require Fair Value Gap confirmation
 Show FVG Boxes:  Display the gap boxes on chart
 Signal Mode:  "First Only" = one signal per direction per day, "Track Cycles" = multiple signals
 Max Cycles:  How many breakout-retest cycles to track (6 is balanced)
 Breakout Buffer:  Extra distance required beyond ORB level (0.1-0.2% recommended)
 Min Distance for Retest:  How far price must move away before retest is valid (2% recommended)
 Min Bars Outside ORB:  Bars price must stay outside for committed breakout (2 is balanced)
 
### TARGETS & RISK Section
 
 Enable Targets & Stop-Loss:  Calculate and show trade management
 TP1/TP2/TP3 checkboxes:  Select which profit targets to display
 Stop Method:  How to calculate stop loss placement
  - ATR: Based on volatility (best for most cases)
  - ORB %: Fixed % of ORB range
  - Swing: Recent swing high/low
  - Safer: Widest of all methods
 ATR Length & Multiplier:  Controls ATR stop distance (14 period, 1.5x is standard)
 ORB Stop %:  Percentage beyond ORB for stop (20% is balanced)
 Swing Bars:  Lookback period for swing high/low (3 is recent)
 
### TP/SL LINES Section
 
 Show TP/SL Lines:  Display horizontal lines on chart
 Label Format:  "Short" = minimal text, "Detailed" = shows prices
 Freeze Lines at EOD:  Stop extending lines at session close
 
### DASHBOARD Section
 
 Show Info Panel:  Display the metrics dashboard
 Theme:  Dark or Light colors
 Position:  Where to place dashboard on chart
 Toggle rows:  Show/hide specific information rows
 Calculate Position Size:  Enable the position sizing calculator
 Risk Mode:  Risk fixed $ amount or % of account
 Account Size:  Your total trading capital
 Risk %:  Percentage to risk per trade (0.5-1% recommended)
 
### VOLUME FILTER Section
 
 Enable Volume Filter:  Require volume confirmation
 MA Length:  Average period (20 is standard)
 Min Volume:  Required multiplier (1.5x = 50% above average)
 Strong Volume:  Multiplier that bypasses other filters (2.5x)
 
### TREND FILTER Section
 
 Enable Trend Filter:  Require trend alignment
 Trend Mode:  Method to determine trend (VWAP is simple and effective)
 Custom EMA Length:  If using EMA mode (50 for swing, 20 for day trading)
 SuperTrend settings:  Period and Multiplier if using SuperTrend mode
 
### HIGHER TIMEFRAME Section
 
 Check Daily Trend:  Display higher timeframe bias in dashboard
 Timeframe:  What TF to check (D = daily, recommended)
 Method:  Price vs MA (stable) or Candle Direction (reactive)
 MA Period:  EMA length for Price vs MA method (20 is balanced)
 Min Strength %:  Minimum strength threshold for HTF bias to be considered
  - For "Price vs MA": Minimum distance (%) from moving average
  - For "Candle Direction": Minimum candle body size (%)
  - 0.5% is balanced - increase for stricter filtering
  - Lower values = more signals, higher values = only strong trends
 
### ALERTS Section
 
 Enable Alerts:  Master switch (must be ON to use any alerts)
 Breakout Alerts:  Notify on ORB breakouts
 Retest Alerts:  Notify when price retests after breakout
 Failed Break Alerts:  Notify on failed breakouts
 Stage Complete Alerts:  Notify when each ORB stage finishes forming
 
After enabling desired alert types, click "Create Alert" button, select this indicator, choose "Any alert() function call".
## Tips & Best Practices
### General Trading Tips
 
 ORB works best on liquid instruments (stocks with good volume, major crypto pairs)
 First hour of the session is most important - that's when ORB is forming
 Breakouts WITH the trend have higher success rates - use the trend filter
 Failed breakouts are common - use the "Min Bars Outside" setting to filter weak moves
 Not every day produces good ORB setups - be patient and selective
 
### Position Sizing Best Practices
 
 Never risk more than 1-2% of your account on a single trade
 Use the built-in calculator - don't guess your position size
 Update your account size monthly as it grows
 Smaller accounts: use $ Amount mode for simplicity
 Larger accounts: use % of Account mode for scaling
 
### Take Profit Strategy
 
 Most traders use: 50% at TP1, 50% at TP2
 Aggressive: Hold through TP1 for TP2 or TP3
 Conservative: Full exit at TP1 (1:1 risk/reward)
 After TP1 hits, consider moving stop to breakeven
 TP3 rarely hits - only on strong trending days
 
### Filter Combinations
 
 Maximum Quality:  Volume + Trend + FVG (fewest signals, highest quality)
 Balanced:  Volume + Trend (good quality, reasonable frequency)
 Active Trading:  No filters or Volume only (many signals, lower quality)
 Trending Markets:  Trend filter essential (indices, crypto)
 Range-Bound:  Volume + FVG (avoid trend filter)
 
### Common Mistakes to Avoid
 
 Chasing breakouts - wait for the bar to close, don't FOMO into wicks
 Ignoring the stop loss - always use it, move it manually if needed
 Over-leveraging - the calculator shows MAX shares, you can buy less
 Trading every signal - quality > quantity, use filters
 Not tracking results - keep a journal to see what works for YOU
 
## Pros and Cons
### Advantages
 
 Complete all-in-one solution - from signal to position sizing
 Multiple timeframes tracked simultaneously
 Visual clarity - easy to see what's happening
 Cycle tracking catches opportunities others miss
 Built-in risk management eliminates guesswork
 Customizable filters for different trading styles
 No repainting - what you see is locked in
 Works across multiple markets (stocks, forex, crypto)
 
### Limitations
 
 Intraday strategy only - doesn't work on daily charts
 Requires active monitoring during first 1-2 hours of session
 Not suitable for after-hours or extended sessions by default
 Can produce many signals in choppy markets (use filters)
 Dashboard can be overwhelming for complete beginners
 Performance depends on market conditions (trends vs ranges)
 Requires understanding of risk management concepts
 
### Best For
 
 Day traders who can watch the first 1-2 hours of market open
 Traders who want systematic entry/exit rules
 Those learning proper position sizing and risk management
 Active traders comfortable with multiple signals per day
 Anyone trading liquid instruments with clear sessions
 
### Not Ideal For
 
 Swing traders holding multi-day positions
 Set-and-forget / passive investors
 Traders who can't watch market open
 Complete beginners unfamiliar with trading concepts
 Low volume / illiquid instruments
 
## Frequently Asked Questions
 Q: Why are no signals appearing? 
A: Check that you're on an intraday timeframe (5min, 15min, etc.) and that the current time is within your session hours. Also verify that "Enable Breakout Detection" is ON and at least one ORB stage is enabled. If using filters, they might be blocking signals - try disabling them temporarily.
 Q: What's the best ORB stage to use? 
A: ORB15 (15 minutes) is most popular and balanced. ORB5 gives faster signals but more noise. ORB30 and ORB60 are slower but more reliable. Many traders use ORB15 + ORB30 together.
 Q: Should I enable all the filters? 
A: Start with no filters to see all signals. If too many false signals, add Volume filter first (stocks) or Trend filter (trending markets). FVG filter is most restrictive - use for maximum quality but fewer signals.
 Q: How do I know which stop loss method to use? 
A: ATR works for most cases - it adapts to volatility. Use ORB% if you want predictable stop placement. Swing is for respecting chart structure. Safer gives you the most room but largest risk.
 Q: Can I use this for swing trading? 
A: Not really - ORB is fundamentally an intraday strategy. The ranges reset each day. For swing trading, look at weekly support/resistance or moving averages instead.
 Q: Why do TP/SL lines disappear sometimes? 
A: Lines freeze (stop extending) when: stop loss is hit, the last enabled take-profit is hit, or end of session arrives (if "Freeze at EOD" is enabled). This is intentional - the trade is complete.
 Q: What's the difference between "First Only" and "Track Cycles"? 
A: "First Only" shows one breakout UP and one DOWN per day maximum - clean but might miss opportunities. "Track Cycles" shows breakout-retest-rebreak sequences - more signals but busier chart.
 Q: Is position sizing accurate for options/forex? 
A: The calculator is designed for shares (stocks). For options, ignore the share count and use the risk amount. For forex, you'll need to adapt the lot size calculation manually.
 Q: How much capital do I need to use this? 
A: The indicator works for any account size, but practical day trading typically requires $25,000 in the US due to Pattern Day Trader rules. Adjust the "Account Size" setting to match your capital.
 Q: Can I backtest this strategy? 
A: This is an indicator, not a strategy script, so it doesn't have built-in backtesting. You can visually review historical signals or code a strategy script using similar logic.
 Q: Why does the dashboard show different entry price than the breakout label? 
A: If you're looking at an old breakout, the ORB levels may have changed when the next stage completed. The dashboard always shows the CURRENT active range and trade setup.
 Q: What's a good win rate to expect? 
A: ORB strategies typically see 40-60% win rate depending on market conditions and filters used. The strategy relies on positive risk/reward ratios (2:1 or better) to be profitable even with moderate win rates.
 Q: Does this work on crypto? 
A: Yes, but crypto trades 24/7 so you need to define what "session start" means. Use Session Mode = Custom and set your preferred daily reset time (e.g., 0000-2359 UTC).
## Credits & Transparency
### Development
This indicator was developed with the assistance of AI technology to implement complex ORB trading logic.
The strategy concept, feature specifications, and trading logic were designed by the publisher. The implementation leverages modern development tools to ensure:
 
 Clean, efficient, and maintainable code
 Comprehensive error handling and input validation
 Detailed documentation and user guidance
 Performance optimization
 
### Trading Concepts
This indicator implements several public domain trading concepts:
 
 Opening Range Breakout (ORB):  Trading strategy popularized by Toby Crabel, Mark Fisher and many more talanted traders.
 Fair Value Gap (FVG):  Price imbalance concept from ICT methodology
 SuperTrend:  ATR-based trend indicator using public formula
 Risk/Reward Ratio:  Standard risk management principle
 
All mathematical formulas and technical concepts used are in the public domain.
### Pine Script
Uses standard TradingView built-in functions:
 ta.ema(), ta.atr(), ta.vwap(), ta.highest(), ta.lowest(), request.security() 
No external libraries or proprietary code from other authors.
## Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice.
Trading involves substantial risk of loss and is not suitable for every investor. Past performance shown in examples is not indicative of future results.
The indicator provides signals and calculations, but trading decisions are solely your responsibility. Always:
 
 Test strategies on paper before using real money
 Never risk more than you can afford to lose
 Understand that all trading involves risk
 Consider seeking advice from a licensed financial advisor
 
The publisher makes no guarantees regarding accuracy, profitability, or performance. Use at your own risk.
---
 Version:  3.0
 Pine Script Version:  v6
 Last Updated:  October 2024
For support, questions, or suggestions, please comment below or send a private message.
---
 Happy trading, and remember: consistent risk management beats perfect entry timing every time.
Volume + MA5 & MA10This Volume + MA5 & MA10 (Technical Volume Trend Analysis)
The Volume + MA5 & MA10 indicator provides a precise view of market participation and volume momentum by combining raw volume data with two moving averages (MA5 and MA10). It’s designed for traders who rely on volume-based confirmation to validate price movements, breakouts, and trend reversals.
🔍 Overview
This indicator displays volume bars alongside two smooth volume averages — MA5 (short-term) and MA10 (medium-term) — making it easier to detect shifts in market activity.
When the short-term average crosses above or below the long-term average, it signals a potential change in trading intensity or market sentiment.
⚙️ Key Features
Dual Volume Moving Averages (MA5 & MA10) for short- and medium-term analysis.
Dynamic Bar Coloring based on whether current volume exceeds MA5 or MA10.
Crossover Detection with visual markers for MA5/MA10 intersections.
Alert Conditions to notify you of significant volume trend shifts.
Fully customizable appearance and smoothing options.
📊 How to Interpret
MA5 > MA10 → Increasing short-term volume activity (strengthening momentum).
MA5 < MA10 → Decreasing short-term volume (weakening participation).
Rising volume with price → Confirms trend strength.
Falling volume with rising/falling price → Suggests potential reversal or reduced conviction.
💡 Applications
Confirm breakouts and trend continuations.
Identify momentum divergences between price and volume.
Filter out low-volume or weak-trend setups.
Combine with RSI, MACD, or moving averages for enhanced signal validation.
✅ Advantages
Simple yet powerful structure for clean visual analysis.
Works across all timeframes and markets (crypto, stocks, forex, indices).
No repainting — reliable for both live and historical backtesting.
Use Volume + MA5 & MA10 to strengthen your technical analysis and gain a deeper understanding of how market participation drives price trends.
4-Hour Range Scalping [v6.3]User Guide: 4-Hour Range Scalping Strategy 
Hello! Here is the guide for the Pine Script strategy. Please read it carefully to get the best results.
📈 This script automates the "4-Hour Range Scalping Strategy" from the video.
The main idea is that the first four hours of a major trading day (like New York) set up a "trap zone." The strategy waits for the price to break out of this zone and then fail, giving us a signal that the breakout was false and the price is likely to reverse.
Here’s the simple logic:
 
 Define the Range: It precisely calculates the highest high and lowest low during the first four hours of the selected trading session (e.g., 00:00 to 04:00 New York Time).
 Wait for a Breakout: It then monitors the 5-minute chart for a price breakout where a candle fully closes outside of this established range.
 Identify the Reversal: The trade trigger occurs when the price fails to continue its breakout and a subsequent 5-minute candle closes back inside the range. This signals a potential reversal or "failed breakout."
 Execute the Trade:
]A Short (Sell) trade is triggered after a failed breakout above the range high.
A Long (Buy) trade is triggered after a failed breakout below the range low.
 Manage the Risk: The Stop Loss is automatically placed at the peak (for shorts) or trough (for longs) of the breakout move, and the Take Profit is set to a default 2:1 Risk/Reward Ratio.
 
 How to Use the Script (Step-by-Step) ⚙️ 
Follow these instructions to get it running perfectly.
1. Set Your Chart Timeframe This is the most important step. The strategy is designed to run on a 5-minute (5m) chart. Open your TradingView chart and make sure the timeframe is set to "5m".
2. Add the Script to Your Chart Open the Pine Editor tab at the bottom of TradingView, paste the entire script, and click the "Add to chart" button.
3. Configure the Settings On your chart, find the strategy's name (e.g., "4-Hour Range Scalping  ") and click the gear icon ⚙️ to open its settings.
Trading Session: Choose the session for the range. New York is the default and the one from the video.
Risk/Reward Ratio: The default is 2.0, meaning your potential profit is twice your potential loss. You can adjust this to test other targets.
Backtesting Period: To see how the strategy performed on all historical data, go to the "Strategy Tester" panel, click its own gear icon ⚙️, and uncheck the boxes for "Start Date" and "End Date."
4. Understand the Visuals on Your Chart
Blue Background Area: This is the 4-hour calculation window. The script is identifying the day's high and low during this time. No trades will ever happen here.
Red Line (Range High): The highest price of the 4-hour window. This is the upper boundary of the "trap zone."
Green Line (Range Low): The lowest price of the 4-hour window. This is the lower boundary.
Green Triangle (▲): Shows where a Long (Buy) trade was entered.
Red Triangle (▼): Shows where a Short (Sell) trade was entered.
A Very Important Note on Timezones 🕒
This is critical for you in the Philippines (PHT).
The script is based on the New York session, which is 12 hours behind you. Your TradingView chart will still show your local time, but the script works on NY time in the background.
The New York "day" begins at 12:00 PM (Noon) your time.
The script's blue calculation window will be from 12:00 PM to 4:00 PM your local time.
The red and green range lines will appear on your chart only after 4:00 PM your time.
So, if you look at your chart in the morning or early afternoon, you will not see today's range yet. This is normal! The script is just waiting for the New York session to start.
How to Set Up Trade Alerts 🔔
You can have TradingView send you a notification whenever the script enters a trade.
Click the "Alert" button (looks like a clock) in the right-hand toolbar of TradingView.
In the "Condition" dropdown, select the name of the script (e.g., "4-Hour Range Scalping...").
You will then see two options: "Long Signal" and "Short Signal".
Select one (e.g., "Long Signal") and configure how you want to be notified (e.g., "Notify on app").
Click "Create". Repeat the process to create an alert for the other signal.
⚠️ Important Disclosure
For Educational and Research Purposes Only.
This script and all accompanying information are provided for educational and research purposes only. The strategy demonstrated is a technical concept and should not be misconstrued as financial, investment, legal, or tax advice.
Trading financial markets involves substantial risk and is not suitable for every investor. There is a possibility that you could sustain a loss of some or all of your initial investment. Therefore, you should not invest money that you cannot afford to lose.
Past performance is not indicative of future results. The backtesting results shown by this script are historical and do not guarantee future performance. Market conditions are constantly changing.
By using this script, you acknowledge that you are solely responsible for any and all trading decisions you make. You should conduct your own thorough research and, if necessary, seek advice from an independent financial advisor before making any investment decisions. The creators of this script assume no liability for any of your trading results.
Portfolio Strategy TesterThe Portfolio Strategy Tester is an institutional-grade backtesting framework that evaluates the performance of trend-following strategies on multi-asset portfolios. It enables users to construct custom portfolios of up to 30 assets and apply moving average crossover strategies across individual holdings. The model features a clear, color-coded table that provides a side-by-side comparison between the buy-and-hold portfolio and the portfolio using the risk management strategy, offering a comprehensive assessment of both approaches relative to the benchmark.
Portfolios are constructed by entering each ticker symbol in the menu, assigning its respective weight, and reviewing the total sum of individual weights displayed at the top left of the table. For strategy selection, users can choose between Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), Weighted Moving Average (WMA), Moving Average Convergence Divergence (MACD), and Volume-Weighted Moving Average (VWMA). Moving average lengths are defined in the menu and apply only to strategy-enabled assets.
To accurately replicate real-world portfolio conditions, users can choose between daily, weekly, monthly, or quarterly rebalancing frequencies and decide whether cash is held or redistributed. Daily rebalancing maintains constant portfolio weights, while longer intervals allow natural drift. When cash positions are not allowed, capital from bearish assets is automatically redistributed proportionally among bullish assets, ensuring the portfolio remains fully invested at all times. The table displays a comprehensive set of widely used institutional-grade performance metrics:
 
 CAGR = Compounded annual growth rate of returns.
 Volatility = Annualized standard deviation of returns.
 Sharpe = CAGR per unit of annualized standard deviation.
 Sortino = CAGR per unit of annualized downside deviation.
 Calmar = CAGR relative to maximum drawdown.
 Max DD = Largest peak-to-trough decline in value.
 Beta (β) = Sensitivity of returns relative to benchmark returns.
 Alpha (α) = Excess annualized risk-adjusted returns relative to benchmark.
 Upside = Ratio of average return to benchmark return on up days.
 Downside = Ratio of average return to benchmark return on down days.
 Tracking = Annualized standard deviation of returns versus benchmark.
 Turnover = Average sum of absolute changes in weights per year.
 
Cumulative returns are displayed on each label as the total percentage gain from the selected start date, with green indicating positive returns and red indicating negative returns. In the table, baseline metrics serve as the benchmark reference and are always gray. For portfolio metrics, green indicates outperformance relative to the baseline, while red indicates underperformance relative to the baseline. For strategy metrics, green indicates outperformance relative to both the baseline and the portfolio, red indicates underperformance relative to both, and gray indicates underperformance relative to either the baseline or portfolio. Metrics such as Volatility, Tracking Error, and Turnover ratio are always displayed in gray as they serve as descriptive measures.
In summary, the Portfolio Strategy Tester is a comprehensive backtesting tool designed to help investors evaluate different trend-following strategies on custom portfolios. It enables real-world simulation of both active and passive investment approaches and provides a full set of standard institutional-grade performance metrics to support data-driven comparisons. While results are based on historical performance, the model serves as a powerful portfolio management and research framework for developing, validating, and refining systematic investment strategies.
Curved Radius Supertrend [BOSWaves]Curved Radius Supertrend — Adaptive Parabolic Trend Framework with Dynamic Acceleration Geometry 
 Overview 
The Curved Radius Supertrend   introduces an evolution of the classic Supertrend indicator - engineered with a dynamic curvature engine that replaces rigid ATR bands with parabolic, radius-based motion. Traditional Supertrend systems rely on static band displacement, reacting linearly to volatility and often lagging behind emerging price acceleration. The Curved Radius Supertend   model redefines this by integrating controlled acceleration and curvature geometry, allowing the trend bands to adapt fluidly to both velocity and duration of price movement.
  
The result is a smoother, more organic trend flow that visually captures the momentum curve of price action - not just its direction. Instead of sharp pivots or whipsaws, traders experience a structurally curved trajectory that mirrors real market inertia. This makes it particularly effective for identifying sustained directional phases, detecting early trend rotations, and filtering out noise that plagues standard Supertrend methodologies.
Unlike conventional band-following systems, the Curved Radius framework is time-reactive and velocity-aware, providing a nuanced signal structure that blends geometric precision with volatility sensitivity.
 Theoretical Foundation 
The Curved Radius Supertrend   draws from the intersection of mathematical curvature dynamics and adaptive volatility processing. Standard Supertrend algorithms extend from Average True Range (ATR) envelopes - a linear measure of volatility that moves proportionally with price deviation. However, markets do not expand or contract linearly. Trend velocity typically accelerates and decelerates in nonlinear arcs, forming natural parabolas across price phases.
By embedding a radius-based acceleration function, the indicator models this natural behavior. The core variable, radiusStrength, controls how aggressively curvature accelerates over time. Instead of simply following price distance, the band now evolves according to temporal acceleration - each bar contributes incremental velocity, bending the trend line into a radius-like curve.
This structural design allows the indicator to anticipate rather than just respond to price action, capturing momentum transitions as curved accelerations rather than binary flips. In practice, this eliminates the stutter effect typical of standard Supertrends and replaces it with fluid directional motion that better reflects actual trend geometry.
 How It Works 
The Curved Radius Supertrend is constructed through a multi-stage process designed to balance price responsiveness with geometric stability:
 1. Baseline Supertrend Core 
The framework begins with a standard ATR-derived upper and lower band calculation. These define the volatility envelope that constrains potential price zones. Directional bias is determined through crossover logic - prices above the lower band confirm an uptrend, while prices below the upper band confirm a downtrend.
 2. Curvature Acceleration Engine 
Once a trend direction is established, a curvature engine is activated. This system uses radiusStrength as a coefficient to simulate acceleration per bar, incrementally increasing velocity over time. The result is a parabolic displacement from the anchor price (the price level at trend change), creating a curved motion path that dynamically widens or tightens as the trend matures.
Mathematically, this acceleration behaves quadratically - each new bar compounds the previous velocity, forming an exponential rate of displacement that resembles curved inertia.
 3. Adaptive Smoothing Layer 
After the radius curve is applied, a smoothing stage (defined by the smoothness parameter) uses a simple moving average to regulate curve noise. This ensures visual coherence without sacrificing responsiveness, producing flowing arcs rather than jagged band steps.
 4. Directional Visualization and Outer Envelope 
Directional state (bullish or bearish) dictates both the color gradient and band displacement. An outer envelope is plotted one ATR beyond the curved band, creating a layered trend visualization that shows the extent of volatility expansion.
 5. Signal Events and Alerts 
Each directional transition triggers a 'BUY' or 'SELL' signal, clearly labeling phase shifts in market structure. Alerts are built in for automation and backtesting.
 Interpretation 
The Curved Radius Supertrend reframes how traders visualize and confirm trends. Instead of simply plotting a trailing stop, it maps the dynamic curvature of trend development.
 
 Uptrend Phases : The band curves upward with increasing acceleration, reflecting the market’s growing directional velocity. As curvature steepens, conviction strengthens.
 Downtrend Phases : The band bends downward in a mirrored acceleration pattern, indicating sustained bearish momentum.
 Trend Change Points : When the direction flips and a new anchor point forms, the curve resets - providing a clean, early visual confirmation of structural reversal.
 Smoothing and Radius Interplay : A lower radius strength produces a tighter, more reactive curve ideal for scalping or short timeframes. Higher values generate broad, sweeping arcs optimized for swing or positional analysis.
 
Visually, this curvature system translates market inertia into shape - revealing how trends bend, accelerate, and ultimately exhaust.
 Strategy Integration 
The Curved Radius Supertrend is versatile enough to integrate seamlessly into multiple trading frameworks:
 
 Trend Following : Use BUY/SELL flips to identify emerging directional bias. Strong curvature continuation confirms sustained momentum.
 Momentum Entry Filtering : Combine with oscillators or volume tools to filter entries only when the curve slope accelerates (high momentum conditions).
 Pullback and Re-entry Timing : The smooth curvature of the radius band allows traders to identify shallow retracements without premature exits. The band acts as a dynamic, self-adjusting support/resistance arc.
 Volatility Compression and Expansion : Flattening curvature indicates volatility compression - a potential pre-breakout zone. Rapid re-steepening signals expansion and directional conviction.
 Stop Placement Framework : The curved band can serve as a volatility-adjusted trailing stop. Because the curve reflects acceleration, it adapts naturally to market rhythm - widening during momentum surges and tightening during stagnation.
 
 Technical Implementation Details 
 
 Curved Radius Engine : Parabolic acceleration algorithm that applies quadratic velocity based on bar count and radiusStrength.
 Anchor Logic : Resets curvature at each trend change, establishing a new reference base for directional acceleration.
 Smoothing Layer : SMA-based curve smoothing for noise reduction.
 Outer Envelope : ATR-derived band offset visualizing volatility extension.
 Directional Coloring : Candle and band coloration tied to current trend state.
 Signal Engine : Built-in BUY/SELL markers and alert conditions for automation or script integration.
 
 Optimal Application Parameters 
 Timeframe Guidance :
 
 1-5 min (Scalping) : 0.08–0.12 radius strength, minimal smoothing for rapid responsiveness.
 15 min : 0.12–0.15 radius strength for intraday trends.
 1H : 0.15–0.18 radius strength for structured short-term swing setups.
 4H : 0.18–0.22 radius strength for macro-trend shaping.
 Daily : 0.20–0.25 radius strength for broad directional curves.
 Weekly : 0.25–0.30 radius strength for smooth macro-level cycles.
 
The suggested radius strength ranges provide general structural guidance. Optimal values may vary across assets and volatility regimes, and should be refined through empirical testing to account for instrument-specific behavior and prevailing market conditions.
 Asset Guidance :
 
 Cryptocurrency : Higher radius and multiplier values to stabilize high-volatility environments.
 Forex : Midrange settings (0.12-0.18) for clean curvature transitions.
 Equities : Balanced curvature for trending sectors or momentum rotation setups.
 Indices/Futures : Moderate radius values (0.15-0.22) to capture cyclical macro swings.
 
 Performance Characteristics 
 High Effectiveness :
 
 Trending environments with directional expansion.
 Markets exhibiting clean momentum arcs and low structural noise.
 
 Reduced Effectiveness :
 
 Range-bound or low-volatility conditions with repeated false flips.
 Ultra-short-term timeframes (<1m) where curvature acceleration overshoots.
 
 Integration Guidelines 
 
 Confluence Framework : Combine with structure tools (order blocks, BOS, liquidity zones) for entry validation.
 Risk Management : Trail stops along the curved band rather than fixed points to align with adaptive market geometry.
 Multi-Timeframe Confirmation : Use higher timeframe curvature as a trend filter and lower timeframe curvature for execution timing.
 Curve Compression Awareness : Treat flattening arcs as potential exhaustion zones - ideal for scaling out or reducing exposure.
 
 Disclaimer 
The Curved Radius Supertrend   is a geometric trend model designed for professional traders and analysts. It is not a predictive system or a guaranteed profit method. Its performance depends on correct parameter calibration and sound risk management. BOSWaves recommends using it as part of a comprehensive analytical framework, incorporating volume, liquidity, and structural context to validate directional signals.
Moving Average Trend Strategy V2.1 — With Stop Loss and Add Posi**Strategy Feature Description:**
---
### **Entry Logic:**
* When **MA7** crosses **MA15**, and the distance between **MA15** and **MA99** is less than **0.5%**
* When **MA15** crosses **MA99**, and the distance between **MA7** and **MA15** is less than **0.5%**
* When the distance among all three MAs (**MA7**, **MA15**, **MA99**) is less than **0.5%** (adjustable via parameters)
---
### **Capital Management:**
* Initial capital: **$100**
* Each position uses **15%** of total capital
* Opens **both long and short positions simultaneously** (dual-direction mode)
---
### **Risk Control:**
* **Long position stop-loss:** Entry price − 2%
* **Short position stop-loss:** Entry price + 2%
* Uses a **five-level take-profit grid**:
  * Every 5% profit → close 20% of position
* Any pending take-profit orders are automatically canceled when stop-loss triggers
---
### **Visualization Features:**
* Real-time display of the three moving averages
* Chart annotations for entry signal points
* All trade signals and performance can be viewed through **TradingView backtest reports**
---
### **Notes:**
* Parameters can be adjusted based on the volatility of the instrument (historical backtesting is recommended first)
* Dual-direction positions may generate **hedging costs** — recommended for low-fee markets
* Real trading must consider **exchange minimum order size limits**
* Suggest enabling a **volume filter mechanism** (extension interface already reserved)
* Always perform **historical backtesting and parameter optimization** in TradingView before connecting to live trading systems
Swing AURORA v4.0 — Refined Trend Signals### Swing Algo v4.0 — Refined Trend Signals
#### Overview
Swing Algo v4.0 is an advanced technical indicator designed for TradingView, built to detect trend changes and provide actionable buy/sell signals in various market conditions. It combines multiple technical elements like moving averages, ADX for trend strength, Stochastic RSI for timing, and RSI divergence for confirmation, all while adapting to different timeframes through auto-tuning. This indicator overlays on your chart, highlighting trend regimes with background colors, displaying buy/sell labels (including "strong" variants), and offering early "potential" signals for proactive trading decisions. It's suitable for swing trading, trend following, or as a filter for other strategies across forex, stocks, crypto, and other assets.
#### Purpose
The primary goal of Swing Algo v4.0 is to help traders identify high-probability trend reversals and continuations early, reducing noise and false signals. It aims to provide clear, non-repainting signals that align with market structure, volatility, and momentum. By incorporating filters like higher timeframe (HTF) alignment, bias EMAs, and divergence, it refines entries for better accuracy. The indicator emphasizes balanced performance across aggressive, balanced, and conservative modes, making it versatile for both novice and experienced traders seeking to optimize their decision-making process.
#### What It Indicates
- **Trend Regimes (Background Coloring)**: The chart background changes color to reflect the current market regime:
  - **Green (Intense for strong uptrends, faded when cooling)**: Indicates bullish trends where price is above the baseline and EMAs are aligned upward.
  - **Red/Maroon (Intense maroon for strong downtrends, faded red when cooling)**: Signals bearish trends with price below the baseline and downward EMA alignment.
  - **Faded Yellow**: Marks "no-trade" zones or potential trend changes, where conditions are choppy, weak, or neutral (e.g., low ADX, near baseline, or low volatility).
- **Buy/Sell Signals**: Labels appear on the chart for confirmed entries:
  - "BUY" or "STRONG BUY" for bullish signals (strong variants require higher scores and optional divergence).
  - "SELL" or "STRONG SELL" for bearish signals.
- **Potential Signals**: Early warnings like "Potential BUY" or "Potential SELL" appear before full confirmation, allowing traders to anticipate moves (confirmed after a few bars based on the trigger window).
- **Divergence Marks**: Small "DIV↑" (bullish) or "DIV↓" (bearish) labels highlight RSI divergences on pivots, adding confluence for strong signals.
- **Lines**: Optional plots for baseline (teal), EMA13/21 (lime/red based on crossover), providing visual trend context.
Signals are anchored either to the current bar or confirmed pivots, ensuring alignment with price action. The indicator avoids repainting by confirming on close if enabled.
#### Key Parameters and Customization
Swing Algo v4.0 offers minimal yet efficient parameters for fine-tuning, with defaults optimized for common use cases. Most can be auto-tuned based on timeframe for simplicity:
- **Confirm on Close (no repaint)**: Boolean (default: true) – Ensures signals don't repaint by waiting for bar confirmation.
- **Auto-tune by Timeframe**: Boolean (default: true) – Automatically adjusts lengths and sensitivity for 5-15m, 30-60m, 2-4h, or higher frames.
- **Mode**: String (options: Aggressive, Balanced  , Conservative) – Controls signal thresholds; Aggressive for more signals, Conservative for fewer but higher-quality ones.
- **Signal Anchor**: String (options: Pivot (divLB)  , Current bar) – Places labels on confirmed pivots or the current bar.
- **Trigger Window (bars)**: Integer (default: 3) – Window for signal timing; auto-tuned if enabled.
- **Baseline Type**: String (options: HMA  , EMA, ALMA) – Core trend line; lengths auto-tune (e.g., 55 for short frames).
- **Use Bias EMA Filter**: Boolean (default: false) – Adds a long-term EMA for trend bias.
- **Use HTF Filter**: Boolean (default: false) – Aligns with higher timeframe (auto or manual like 60m, 240m, D); override for stricter scoring.
- **Sensitivity (10–90)**: Integer (default: 55) – Adjusts ADX threshold for trend detection; higher = more sensitive.
- **Use RSI-Stoch Trigger**: Boolean (default: true) – Enables Stochastic RSI for entry timing; customizable lengths, smooths, and levels.
- **Use RSI Divergence for STRONG**: Boolean (default: true) – Requires divergence for strong signals; pivot lookback (default: 5).
- **Visual Options**: Booleans for background regime, labels, divergence marks, and lines (all default: true).
These parameters are grouped for ease, with tooltips in TradingView for quick reference. Start with defaults and tweak based on backtesting.
#### How It Works
At its core, Swing Algo v4.0 calculates a baseline (e.g., HMA) to define the trend direction. It then scores potential buys/sells using factors like:
- **Trend Strength**: ADX above a dynamic threshold, combined with EMA crossovers (13/21) and slope analysis.
- **Volatility/Volume**: Bollinger/Keltner squeeze exits, volume z-score, and ATR filters to avoid choppy markets.
- **Timing**: Stochastic RSI crossovers or micro-timing via DEMA/TEMA for precise entries.
- **Filters**: Bias EMA, HTF alignment, gap from baseline, and no-trade zones (weak ADX, near baseline, low vol).
- **Divergence**: RSI pivots confirm strong signals.
- **Scoring**: Buy/sell scores (min 3-5 based on mode) trigger labels only when all gates pass, with early "potential" detection for foresight.
The algorithm processes these in real-time, auto-adapting to timeframe for efficiency. Signals flip only on direction changes to prevent over-trading. For best results, use on liquid assets and combine with risk management.
#### Disclaimer
This indicator is for educational and informational purposes only and does not constitute financial advice, investment recommendations, or trading signals. Trading involves significant risk of loss and is not suitable for all investors. Past performance is not indicative of future results. Always backtest the indicator on your preferred assets and timeframes, and consult a qualified financial advisor before making any trading decisions. The author assumes no liability for any losses incurred from using this script. Use at your own risk.






















