*Auto Backtest & Optimize EngineFull-featured Engine for Automatic Backtesting and parameter optimization. Allows you to test millions of different combinations of stop-loss and take profit parameters, including on any connected indicators.
⭕️ Key Futures
Quickly identify the optimal parameters for your strategy.
Automatically generate and test thousands of parameter combinations.
A simple Genetic Algorithm for result selection.
Saves time on manual testing of multiple parameters.
Detailed analysis, sorting, filtering and statistics of results.
Detailed control panel with many tooltips.
Display of key metrics: Profit, Win Rate, etc..
Comprehensive Strategy Score calculation.
In-depth analysis of the performance of different types of stop-losses.
Possibility to use to calculate the best Stop-Take parameters for your position.
Ability to test your own functions and signals.
Customizable visualization of results.
Flexible Stop-Loss Settings:
• Auto ━ Allows you to test all types of Stop Losses at once(listed below).
• S.VOLATY ━ Static stop based on volatility (Fixed, ATR, STDEV).
• Trailing ━ Classic trailing stop following the price.
• Fast Trail ━ Accelerated trailing stop that reacts faster to price movements.
• Volatility ━ Dynamic stop based on volatility indicators.
• Chandelier ━ Stop based on price extremes.
• Activator ━ Dynamic stop based on SAR.
• MA ━ Stop based on moving averages (9 different types).
• SAR ━ Parabolic SAR (Stop and Reverse).
Advanced Take-Profit Options:
• R:R: Risk/Reward ━ sets TP based on SL size.
• T.VOLATY ━ Calculation based on volatility indicators (Fixed, ATR, STDEV).
Testing Modes:
• Stops ━ Cyclical stop-loss testing
• Pivot Point Example ━ Example of using pivot points
• External Example ━ Built-in example how test functions with different parameters
• External Signal ━ Using external signals
⭕️ Usage
━ First Steps:
When opening, select any point on the chart. It will not affect anything until you turn on Manual Start mode (more on this below).
The chart will immediately show the best results of the default Auto mode. You can switch Part's to try to find even better results in the table.
Now you can display any result from the table on the chart by entering its ID in the settings.
Repeat steps 3-4 until you determine which type of Stop Loss you like best. Then set it in the settings instead of Auto mode.
* Example: I flipped through 14 parts before I liked the first result and entered its ID so I could visually evaluate it on the chart.
Then select the stop loss type, choose it in place of Auto mode and repeat steps 3-4 or immediately follow the recommendations of the algorithm.
Now the Genetic Algorithm at the bottom right will prompt you to enter the Parameters you need to search for and select even better results.
Parameters must be entered All at once before they are updated. Enter recommendations strictly in fields with the same names.
Repeat steps 5-6 until there are approximately 10 Part's left or as you like. And after that, easily pour through the remaining Parts and select the best parameters.
━ Example of the finished result.
━ Example of use with Takes
You can also test at the same time along with Take Profit. In this example, I simply enabled Risk/Reward mode and immediately specified in the TP field Maximum RR, Minimum RR and Step. So in this example I can test (3-1) / 0.1 = 20 Takes of different sizes. There are additional tips in the settings.
━
* Soon you will start to understand how the system works and things will become much easier.
* If something doesn't work, just reset the engine settings and start over again.
* Use the tips I have left in the settings and on the Panel.
━ Details:
Sort ━ Sorting results by Score, Profit, Trades, etc..
Filter ━ Filtring results by Score, Profit, Trades, etc..
Trade Type ━ Ability to disable Long\Short but only from statistics.
BackWin ━ Backtest Window Number of Candle the script can test.
Manual Start ━ Enabling it will allow you to call a Stop from a selected point. which you selected when you started the engine.
* If you have a real open position then this mode can help to save good Stop\Take for it.
1 - 9 Сheckboxs ━ Allow you to disable any stop from Auto mode.
Ex Source - Allow you to test Stops/Takes from connected indicators.
Connection guide:
//@version=6
indicator("My script")
rsi = ta.rsi(close, 14)
buy = not na(rsi) and ta.crossover (rsi, 40) // OS = 40
sell = not na(rsi) and ta.crossunder(rsi, 60) // OB = 60
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, "🔌Connector🔌", display = display.none)
* Format the signal for your indicator in a similar style and then select it in Ex Source.
⭕️ How it Works
Hypothesis of Uniform Distribution of Rare Elements After Mixing.
'This hypothesis states that if an array of N elements contains K valid elements, then after mixing, these valid elements will be approximately uniformly distributed.'
'This means that in a random sample of k elements, the proportion of valid elements should closely match their proportion in the original array, with some random variation.'
'According to the central limit theorem, repeated sampling will result in an average count of valid elements following a normal distribution.'
'This supports the assumption that the valid elements are evenly spread across the array.'
'To test this hypothesis, we can conduct an experiment:'
'Create an array of 1,000,000 elements.'
'Select 1,000 random elements (1%) for validation.'
'Shuffle the array and divide it into groups of 1,000 elements.'
'If the hypothesis holds, each group should contain, on average, 1~ valid element, with minor variations.'
* I'd like to attach more details to My hypothesis but it won't be very relevant here. Since this is a whole separate topic, I will leave the minimum part for understanding the engine.
Practical Application
To apply this hypothesis, I needed a way to generate and thoroughly mix numerous possible combinations. Within Pine, generating over 100,000 combinations presents significant challenges, and storing millions of combinations requires excessive resources.
I developed an efficient mechanism that generates combinations in random order to address these limitations. While conventional methods often produce duplicates or require generating a complete list first, my approach guarantees that the first 10% of possible combinations are both unique and well-distributed. Based on my hypothesis, this sampling is sufficient to determine optimal testing parameters.
Most generators and randomizers fail to accommodate both my hypothesis and Pine's constraints. My solution utilizes a simple Linear Congruential Generator (LCG) for pseudo-randomization, enhanced with prime numbers to increase entropy during generation. I pre-generate the entire parameter range and then apply systematic mixing. This approach, combined with a hybrid combinatorial array-filling technique with linear distribution, delivers excellent generation quality.
My engine can efficiently generate and verify 300 unique combinations per batch. Based on the above, to determine optimal values, only 10-20 Parts need to be manually scrolled through to find the appropriate value or range, eliminating the need for exhaustive testing of millions of parameter combinations.
For the Score statistic I applied all the same, generated a range of Weights, distributed them randomly for each type of statistic to avoid manual distribution.
Score ━ based on Trade, Profit, WinRate, Profit Factor, Drawdown, Sharpe & Sortino & Omega & Calmar Ratio.
⭕️ Notes
For attentive users, a little tricks :)
To save time, switch parts every 3 seconds without waiting for it to load. After 10-20 parts, stop and wait for loading. If the pause is correct, you can switch between the rest of the parts without loading, as they will be cached. This used to work without having to wait for a pause, but now it does slower. This will save a lot of time if you are going to do a deeper backtest.
Sometimes you'll get the error “The scripts take too long to execute.”
For a quick fix you just need to switch the TF or Ticker back and forth and most likely everything will load.
The error appears because of problems on the side of the site because the engine is very heavy. It can also appear if you set too long a period for testing in BackWin or use a heavy indicator for testing.
Manual Start - Allow you to Start you Result from any point. Which in turn can help you choose a good stop-stick for your real position.
* It took me half a year from idea to current realization. This seems to be one of the few ways to build something automatic in backtest format and in this particular Pine environment. There are already better projects in other languages, and they are created much easier and faster because there are no limitations except for personal PC. If you see solutions to improve this system I would be glad if you share the code. At the moment I am tired and will continue him not soon.
Also You can use my previosly big Backtest project with more manual settings(updated soon)
Su Pine
Pure Price Action StrategyTest Price Action Strategy from Lux Pure Price Action Indicator
How This Strategy Works:
Recognizing Trends & Reversals:
Break of Structure (BOS): A bullish signal indicating a trend continuation.
Market Structure Shift (MSS): A bearish signal indicating a potential reversal.
Analyzing Market Momentum:
It uses recent highs and lows to confirm whether the price is making higher highs (bullish) or lower lows (bearish).
Customizing Visualization Styles:
Buy signals (BUY Signal) are plotted as green upward arrows.
Sell signals (SELL Signal) are plotted as red downward arrows.
Stop-Loss (SL) & Take-Profit (TP): Configurable via percentage input.
B.T 트레이딩1️⃣ 추세 추종 전략 (Trend Following)
📌 개요
추세 추종 전략은 시장이 상승 또는 하락하는 흐름을 따라 매매하는 방식입니다. EMA, Supertrend, Range Filter 등을 활용하여 추세를 식별하고, 해당 방향으로 매매를 진행합니다.
💡 설정 방법
✅ 기본 조건
EMA(200) 필터: 가격이 200 EMA 위에 있으면 롱(매수) 진입, 아래에 있으면 숏(매도) 진입
Supertrend 필터: Supertrend가 상승 신호를 나타내면 롱, 하락 신호를 나타내면 숏
2 EMA 크로스(50 EMA vs 200 EMA): 단기 EMA(50)가 장기 EMA(200)를 상향 돌파하면 롱, 하향 돌파하면 숏
✅ 매매 진입 예시
롱(매수) 조건
가격이 200 EMA 위에 있음
Supertrend가 상승 트렌드 신호
50 EMA가 200 EMA를 상향 돌파
숏(매도) 조건
가격이 200 EMA 아래에 있음
Supertrend가 하락 트렌드 신호
50 EMA가 200 EMA를 하향 돌파
✅ 손절(SL) 및 익절(TP) 설정
손절: 직전 저점(롱) 또는 직전 고점(숏)
익절: ATR의 2~3배 또는 이전 주요 지지/저항 레벨
🛠 활용 팁
✔ 볼린저 밴드(BB) 추가 → 가격이 BB 중심선을 따라 움직이면 추세 지속 가능성 높음
✔ ADX 추가(기본값 20~25 이상) → 추세 강도를 확인하여 거짓 신호 필터링
2️⃣ 반전 전략 (Mean Reversion)
📌 개요
반전 전략은 가격이 과도하게 상승하거나 하락했을 때 평균 회귀(Mean Reversion) 를 이용해 진입하는 전략입니다. RSI, Bollinger Bands, Pivot Points 등을 활용합니다.
💡 설정 방법
✅ 기본 조건
RSI(14): 70 이상이면 과매수(매도 기회), 30 이하면 과매도(매수 기회)
볼린저 밴드(BB) 활용: 가격이 상한선 도달 후 되돌아오면 숏, 하한선 도달 후 반등하면 롱
피보나치 & 피벗 포인트: 주요 저항(매도) 또는 지지(매수)에서 반전 신호 확인
✅ 매매 진입 예시
롱(매수) 조건
RSI 30 이하에서 반등
볼린저 밴드 하단선 도달 후 캔들이 상승 전환
피보나치 0.618 지지 레벨에서 반등
숏(매도) 조건
RSI 70 이상에서 하락
볼린저 밴드 상단선 도달 후 캔들이 하락 전환
피보나치 1.618 저항 레벨에서 되돌림 발생
✅ 손절(SL) 및 익절(TP) 설정
손절: 변동성이 높은 시장에서는 1%~2% 이내 설정
익절: RSI가 중립 구간(40~60)으로 돌아오면 청산
🛠 활용 팁
✔ MACD 크로스오버 추가 → MACD가 시그널선 아래에서 골든 크로스하면 롱 신호 강화
✔ 볼륨 확인(VWAP, OBV 등) → 거래량이 급증하면서 반전하면 신뢰도 상승
3️⃣ 스캘핑 전략 (Scalping)
📌 개요
스캘핑 전략은 초단기 매매 방식으로, 작은 가격 변동을 이용해 빠르게 수익을 실현하는 전략입니다. VWAP, 3 EMA Cross, Stochastic RSI 등을 활용합니다.
💡 설정 방법
✅ 기본 조건
VWAP(Volume Weighted Average Price): 가격이 VWAP 위에 있을 때만 롱, 아래 있을 때만 숏
3 EMA 크로스(9 EMA / 21 EMA / 55 EMA): 단기 EMA(9)가 중기 EMA(21)를 돌파하면 진입
Stochastic RSI: %K가 %D를 상향 돌파하면 매수, 하향 돌파하면 매도
✅ 매매 진입 예시
롱(매수) 조건
가격이 VWAP 위에 있음
9 EMA > 21 EMA > 55 EMA 정렬
Stochastic RSI %K가 %D를 상향 돌파
숏(매도) 조건
가격이 VWAP 아래에 있음
9 EMA < 21 EMA < 55 EMA 정렬
Stochastic RSI %K가 %D를 하향 돌파
✅ 손절(SL) 및 익절(TP) 설정
손절: 최근 5캔들 저점(롱) 또는 고점(숏)
익절: 1:2 이상 리스크-리워드 비율 유지
🛠 활용 팁
✔ 거래량 증가 구간에서만 매매 → 거래량이 적으면 변동성이 부족하여 진입 신뢰도 낮음
✔ 피보나치 확장(1.618, 2.618) 구간에서 청산 목표 설정
🔎 결론 및 최적 활용법
이 스크립트는 추세, 반전, 스캘핑 등 다양한 매매 스타일을 지원하므로, 개인의 투자 성향과 시장 상황에 맞춰 활용하는 것이 중요합니다.
🛠 최적 조합 예시
전략 유형 주요 지표 조합 추천 시간 프레임
추세 추종 EMA(50/200), Supertrend, ADX 1시간, 4시간, 일봉
반전 전략 RSI(14), MACD, 볼린저 밴드 15분, 1시간
스캘핑 VWAP, 3 EMA Cross, Stochastic RSI 1분, 5분
각 전략을 실전 적용할 때는 백테스트(Backtest) 및 데모 트레이딩을 통해 검증한 후 사용하길 추천합니다. 🚀
1 Min Gold Heikin Ashi StrategyThis mash up of previously published indicators now turned into a Strategy reflects a very effective Gold 1 min Scalping Strategy. When utilised with two other Indicators that I cannot combine. These two other indicators are
- Future Trend Channel by Chart Prime
- Machine Learning: Lorentzian Classification: JDEHorty
The imbedded scripts within this indicator are
- Chandelier Exit by Everget
- STK a better MACD by Shayankm
- Supertrend by Everget
- EMA is the stock indicator provided by TradingView.
The settings should be a followed
Chandelier Exit
ATR Length: 1
ATR Multiplier: 1
Extremums: on
EMA: 150
STC
Length: 5
FastLength: 30
Slow: Length: 50
EMA and STC should be applied as filters.
Lorentzian the settings should be as standard. Confirmation of a Buy/Sell signal should be by the Future Trend Channel by ChartPrime if Bullish Market is being shown on the chart by Future Trend Channel then only Buys should be placed. The reverse should be applied for Sells. Final Confirmation should be from the Lorentzian Classification. Both in candle colour and the candle classification number. If the classification for Buys should be equal or greater than 6 and the candle colour is green then the trade can be placed. For Sells if the classification should be equal of less than -6 and the candle colour should be red then the Sell trade can be placed.
This Strategy has been implemented to use SL and TP in the number of pips required for XAUUSD. I am using a target of TP 8-9 pis and SL at 25 pips.
1 Min Gold Indicator Heikin AshiThis mash up of previously published indicators reflects a very effective Gold 1 min Scalping Strategy. When utilised with two other Indicators that I cannot combine. These two other indicators are
- Future Trend Channel by Chart Prime
- Machine Learning: Lorentzian Classification: JDEHorty
The imbedded scripts within this indicator are
- Chandelier Exit by Everget
- STK a better MACD by Shayankm
- Supertrend by Everget
- EMA is the stock indicator provided by TradingView.
The settings should be a followed
Chandelier Exit
ATR Length: 1
ATR Multiplier: 1
Extremums: on
EMA: 150
STC
Length: 5
FastLength: 30
Slow: Length: 50
EMA and STC should be applied as filters.
Lorentzian the settings should be as standard. Confirmation of a Buy/Sell signal should be by the Future Trend Channel by ChartPrime if Bullish Market is being shown on the chart by Future Trend Channel then only Buys should be placed. The reverse should be applied for Sells. Final Confirmation should be from the Lorentzian Classification. Both in candle colour and the candle classification number. If the classification for Buys should be equal or greater than 6 and the candle colour is green then the trade can be placed. For Sells if the classification should be equal of less than -6 and the candle colour should be red then the Sell trade can be placed.
Oh the strategy also uses Heikin Ashi Candles to reduce ghost entry signals.
I have created a Strategy that can be backtested called 1 Gold Heikin Ashi Strategy.
High and Low with Horizontal TableHigh and Low with Horizontal Table Indicator
Overview
The "High and Low with Horizontal Table" indicator is designed for traders who wish to monitor key levels based on specific candle times, along with dynamic risk-to-reward ratios and ATR-based values. This indicator features real-time calculations, visual cues, and a table for quick reference of the calculated values.
Key Features
Custom Time Inputs:
Users can define two specific time inputs to select the candles for the High and Low prices. These times can target the same or separate candles.
ATR-based Calculation:
The indicator allows users to apply an ATR Multiplier to adjust the calculation of key levels. By default, the ATR multiplier is set to 1.2, but users can adjust it to their preferred value (e.g., 1.5 or 2).
Risk-to-Reward (R:R) Calculation:
The Risk-to-Reward Ratio (R:R) is used to calculate potential Take Profit (TP) levels based on the high and low of the selected candle(s).
The default R:R ratio is 2.0, but it can be customized to suit the trader’s strategy.
Visual Markings:
The High and Low values are plotted with subtle markers on the chart (cross style) for easy identification. The display of these markers is subdued for minimal visual distraction.
Horizontal Table Display:
A horizontal table is generated in the top-right corner of the chart, providing a quick reference for the following values:
High and Low of the selected candle(s)
High + ATR Multiplier and Low - ATR Multiplier
R:R ratio
Buy TP and Sell TP levels
Each value is displayed with a reasonable number of decimal places (4 decimals) for major forex pairs, XAUUSD, and BTCUSD.
Input Parameters
Hour and Minute for High Candle: Select the time for the candle that will determine the High.
Hour and Minute for Low Candle: Select the time for the candle that will determine the Low.
ATR Multiplier: A customizable input for adjusting the ATR-based calculations (default is 1.2).
Risk-to-Reward (R:R): Set the ratio to determine the TP levels (default is 2.0).
How It Works
The user defines two distinct time inputs (one for the High and one for the Low).
At the specified times, the indicator captures the High and Low prices of the candles.
The ATR is calculated and adjusted by the user-defined ATR Multiplier to determine buffers above the High and below the Low.
The Risk-to-Reward ratio is applied to calculate the Take Profit levels.
All of these values are displayed on the chart and updated in real time. The horizontal table ensures quick reference to all the key levels without cluttering the main chart.
Use Cases
Trend Trading: Identify potential support and resistance levels based on specific timeframes and adjust TP targets using ATR.
Scalping: Use the ATR and R:R calculations to target precise entry and exit points.
Market Opens: Track key market opens (such as New York and London) with candle times that reflect your trading strategy.
Conclusion
The High and Low with Horizontal Table indicator is a powerful tool for traders looking to combine precise candle-based level tracking with ATR-based risk management. By displaying key levels and TP targets in a clear, tabular format, traders can quickly assess and act on key price levels throughout their trading sessions.
ADX + RSI with Buy/Sell SignalsADX Calculation:
Measures trend strength.
If ADX > 25, it indicates a strong trend.
RSI Calculation:
Determines overbought/oversold conditions.
Buy signal: RSI crosses above 30 (exiting oversold) & ADX > 25.
Sell signal: RSI crosses below 70 (exiting overbought) & ADX > 25.
Visualization:
ADX (red line) and RSI (blue line) are plotted.
Thresholds at 25 (ADX), 30 (RSI oversold), and 70 (RSI overbought).
Background colors indicate overbought (red) and oversold (green) RSI zones.
Alerts & Buy/Sell Markers:
"B" appears when a buy condition is met.
"S" appears when a sell condition is met.
Alerts notify users of potential trade opportunities.
Market Cipher BThe script combines multiple indicators (EMA, Fisher Transform, TSI, and Vortex Indicator) to give traders a comprehensive view of market conditions. The buy and sell signals are based on crossovers of the Fisher Transform, the TSI, and momentum indicators, helping traders make informed decisions about market entry and exit points.
Order Block Detector [LuxAlgo] - 15minCe code est un indicateur personnalisé pour TradingView, conçu pour détecter et afficher les Order Blocks (blocs d'ordre) sur un graphique de trading. Les Order Blocks sont des zones de prix où les institutions ou les gros acteurs du marché ont placé des ordres importants, ce qui peut influencer le mouvement futur des prix. Voici une courte description des fonctionnalités principales :
1. Objectif principal
- Détecter les Order Blocks : Identifier les zones de prix où des blocs d'ordre (bullish ou bearish) se forment.
- Afficher visuellement : Représenter ces zones sur le graphique à l'aide de boîtes colorées et de lignes.
- Gérer les Order Blocks mitigés : Supprimer les blocs d'ordre qui ont été "mitigés" (c'est-à-dire que le prix a traversé la zone, invalidant son importance).
2. Fonctionnalités clés
- Détection des Order Blocks :
- Bullish Order Blocks : Zones où les acheteurs ont pris le contrôle (représentées en vert).
- Bearish Order Blocks : Zones où les vendeurs ont pris le contrôle (représentées en rouge).
- Paramètres personnalisables :
- Longueur des pivots de volume (`Volume Pivot Length`).
- Nombre de blocs à afficher (`Bullish OB` et `Bearish OB`).
- Style et couleur des blocs et des lignes moyennes.
- Méthode de mitigation (`Wick` ou `Close`).
- Affichage visuel :
- Boîtes colorées pour représenter les zones d'Order Blocks.
- Lignes pour indiquer le niveau moyen de chaque bloc.
- Alertes :
- Alertes pour la formation de nouveaux blocs (bullish ou bearish).
- Alertes pour la mitigation des blocs existants.
3. Logique de fonctionnement
- Volume Pivot : Utilise les pivots de volume pour identifier les zones où l'activité de trading est significative.
- Mitigation : Vérifie si le prix a traversé une zone d'Order Block (en utilisant soit les ombres des bougies, soit les clôtures).
- Affichage dynamique : Les blocs sont affichés en temps réel et mis à jour à chaque nouvelle bougie.
4. Utilisation pratique:
- Trading sur 15 minutes : Le code est optimisé pour un intervalle de temps de 15 minutes, ce qui le rend adapté aux traders intraday.
- Support et résistance : Les Order Blocks peuvent servir de niveaux de support ou de résistance dynamiques.
- Confirmation de trading : Les traders peuvent utiliser ces zones pour prendre des décisions d'entrée ou de sortie, en combinaison avec d'autres indicateurs ou analyses.
5. Exemple visuel
- Bullish Order Block : Une boîte verte apparaît lorsque les conditions d'un bloc haussier sont remplies.
- Bearish Order Block : Une boîte rouge apparaît lorsque les conditions d'un bloc baissier sont remplies.
- Ligne moyenne : Une ligne horizontale indique le niveau moyen du bloc, aidant à identifier le point d'équilibre.
En résumé, ce code est un outil puissant pour identifier les zones clés où le marché pourrait réagir, en se basant sur l'activité des gros acteurs. Il est particulièrement utile pour les traders qui cherchent à anticiper les mouvements de prix à court terme.
RSI XIONG50倍空单指标。
例子:500刀投资额,1秒投资额的5%加仓,5秒投资额的8%加仓。保证金不计入加仓,1秒单止盈设置6%,5秒单止盈设置18%,保证金10000刀。
一天收益500刀,20天回本1万刀,回本后可继续利滚利开仓。
Chart Box Session Indicator [The Quant Science]This indicator allows highlighting specific time sessions within a chart by creating colored boxes to represent the price range of the selected session. Is an advanced and flexible tool for chart segmenting trading sessions. Thanks to its extensive customization options and advanced visualization features, it allows traders to gain a clear representation of key market areas based on chosen time intervals.
The indicator offers two range calculation modes:
Body to Body: considers the range between the opening and closing price.
Wick to Wick: considers the range between the session's low and high.
Body To Body
Wick to Wick
Key Features
1. Session Configuration
- Users can select the time range of the session of interest.
- Option to choose the day of the week for the calculation.
- Supports UTC timezone selection to correctly align data.
2. Customizable Visualization
- Option to display session price lines.
- Ability to show a central price line.
- Extension of session lines beyond the specified duration.
3. Design Display Configuration
- Three different background configurations to suit light and dark themes.
- Two gradient modes for session coloring:
- Centered: the color is evenly distributed.
- Off-Centered: the gradient is asymmetrical.
How It Works
The indicator determines whether the current time falls within the selected session, creating a colored box that highlights the corresponding price range. Depending on user preferences, the indicator draws horizontal lines at the minimum and maximum price levels and, optionally, a central line.
During the session:
- The lowest and highest session prices are dynamically updated.
- The range is divided into 10 bands to create a gradient effect.
- A colored box is generated to visually highlight the chosen session.
If the Extend Lines option is enabled, price lines continue even after the session ends, keeping the range visible for further analysis.
This indicator is useful for traders who want to analyze price behavior in specific timeframes. It is particularly beneficial for strategies based on market sessions (e.g., London or New York open) or for identifying accumulation and distribution zones.
is_strategyCorrection-Adaptive Trend Strategy (Open-Source)
Core Advantage: Designed specifically for the is_correction indicator, with full transparency and customization options.
Key Features:
Open-Source Code:
✅ Full access to the strategy logic – study how every trade signal is generated.
✅ Freedom to customize – modify entry/exit rules, risk parameters, or add new indicators.
✅ No black boxes – understand and trust every decision the strategy makes.
Built for is_correction:
Filters out false signals during market noise.
Works only in confirmed trends (is_correction = false).
Adaptable for Your Needs:
Change Take Profit/Stop Loss ratios directly in the code.
Add alerts, notifications, or integrate with other tools (e.g., Volume Profile).
For Developers/Traders:
Use the code as a template for your own strategies.
Test modifications risk-free on historical data.
How the Strategy Works:
Main Goal:
Automatically buys when the price starts rising and sells when it starts falling, but only during confirmed trends (ignoring temporary pullbacks).
What You See on the Chart:
📈 Up arrows ▼ (below the candle) = Buy signal.
📉 Down arrows ▲ (above the candle) = Sell signal.
Gray background = Market is in a correction (no trades).
Key Mechanics:
Buy Condition:
Price closes higher than the previous candle + is_correction confirms the main trend (not a pullback).
Example: Red candle → green candle → ▼ arrow → buy.
Sell Condition:
Price closes lower than the previous candle + is_correction confirms the trend (optional: turn off short-selling in settings).
Exit Rules:
Closes trades automatically at:
+0.5% profit (adjustable in settings).
-0.5% loss (adjustable).
Or if a reverse signal appears (e.g., sell signal after a buy).
User-Friendly Settings:
Sell – On (default: ON):
ON → Allows short-selling (selling when price falls).
OFF → Strategy only buys and closes positions.
Revers (default: OFF):
ON → Inverts signals (▼ = sell, ▲ = buy).
%Profit & %Loss:
Adjust these values (0-30%) to increase/decrease profit targets and risk.
Example Scenario:
Buy Signal:
Price rises for 3 days → green ▼ arrow → strategy buys.
Stop loss set 0.5% below entry price.
If price keeps rising → trade closes at +0.5% profit.
Correction Phase:
After a rally, price drops for 1 day → gray background → strategy ignores the drop (no action).
Stop Loss Trigger:
If price drops 0.5% from entry → trade closes automatically.
Key Features:
Correction Filter (is_correction):
Acts as a “noise filter” → avoids trades during temporary pullbacks.
Flexibility:
Disable short-selling, flip signals, or tweak profit/loss levels in seconds.
Transparency:
Open-source code → see exactly how every signal is generated (click “Source” in TradingView).
Tips for Beginners:
Test First:
Run the strategy on historical data (click the “Chart” icon in TradingView).
See how it performed in the past.
Customize It:
Increase %Profit to 2-3% for volatile assets like crypto.
Turn off Sell – On if short-selling confuses you.
Trust the Stop Loss:
Even if you think the price will rebound, the strategy will close at -0.5% to protect your capital.
Where to Find Settings:
Click the strategy name on the top-left of your chart → adjust sliders/toggles in the menu.
Русская Версия
Трендовая стратегия с открытым кодом
Главное преимущество: Полная прозрачность логики и адаптация под ваши нужды.
Особенности:
Открытый исходный код:
✅ Видите всю «кухню» стратегии – как формируются сигналы, когда открываются сделки.
✅ Меняйте правила – корректируйте тейк-профит, стоп-лосс или добавляйте новые условия.
✅ Никаких секретов – вы контролируете каждое правило.
Заточка под is_correction:
Игнорирует ложные сигналы в коррекциях.
Работает только в сильных трендах (is_correction = false).
Гибкая настройка:
Подстройте параметры под свой риск-менеджмент.
Добавьте свои индикаторы или условия для входа.
Для трейдеров и разработчиков:
Используйте код как основу для своих стратегий.
Тестируйте изменения на истории перед реальной торговлей.
Простыми словами:
Почему это удобно:
Открытый код = полный контроль. Вы можете:
Увидеть, как именно стратегия решает купить или продать.
Изменить правила закрытия сделок (например, поставить TP=2% вместо 1.5%).
Добавить новые условия (например, торговать только при высоком объёме).
Примеры кастомизации:
Новички: Меняйте только TP/SL в настройках (без кодинга).
Продвинутые: Добавьте RSI-фильтр, чтобы избегать перекупленности.
Разработчики: Встройте стратегию в свою торговую систему.
Как начать:
Скачайте код из TradingView.
Изучите логику в разделе strategy.entry/exit.
Меняйте параметры в блоке input.* (безопасно!).
Тестируйте изменения и оптимизируйте под свои цели.
Как работает стратегия:
Главная задача:
Автоматически покупает, когда цена начинает расти, и продаёт, когда падает. Но делает это «умно» — только когда рынок в основном тренде, а не во временном откате (коррекции).
Что видно на графике:
📈 Стрелки вверх ▼ (под свечой) — сигнал на покупку.
📉 Стрелки вниз ▲ (над свечой) — сигнал на продажу.
Серый фон — рынок в коррекции (не торгуем).
Как это работает:
Когда покупаем:
Если цена закрылась выше предыдущей и индикатор is_correction показывает «основной тренд» (не коррекция).
Пример: Была красная свеча → стала зелёная → появилась стрелка ▼ → покупаем.
Когда продаём:
Если цена закрылась ниже предыдущей и is_correction подтверждает тренд (опционально, можно отключить в настройках).
Когда закрываем сделку:
Автоматически при достижении:
+0.5% прибыли (можно изменить в настройках).
-0.5% убытка (можно изменить).
Или если появился противоположный сигнал (например, после покупки пришла стрелка продажи).
Настройки для чайников:
«Sell – On» (включено по умолчанию):
Если включено → стратегия будет продавать в шорт.
Если выключено → только покупки и закрытие позиций.
«Revers» (выключено по умолчанию):
Если включить → стратегия будет работать наоборот (стрелки ▼ = продажа, ▲ = покупка).
«%Profit» и «%Loss»:
Меняйте эти цифры (от 0 до 30), чтобы увеличить/уменьшить прибыль и риски.
Пример работы:
Сигнал на покупку:
Цена 3 дня растет → появляется зелёная стрелка ▼ → стратегия покупает.
Стоп-лосс ставится на 0.5% ниже цены входа.
Если цена продолжает расти → сделка закрывается при +0.5% прибыли.
Коррекция:
После роста цена падает на 1 день → фон становится серым → стратегия игнорирует это падение (не закрывает сделку).
Стоп-лосс:
Если цена упала на 0.5% от точки входа → сделка закрывается автоматически.
Важные особенности:
Фильтр коррекций (is_correction):
Это «защита от шума» — стратегия не реагирует на мелкие откаты, работая только в сильных трендах.
Гибкие настройки:
Можно запретить шорты, перевернуть сигналы или изменить уровни прибыли/убытка за 2 клика.
Прозрачность:
Весь код открыт → вы можете увидеть, как формируется каждый сигнал (меню «Исходник» в TradingView).
Советы для новичков:
Начните с теста:
Запустите стратегию на исторических данных (кнопка «Свеча» в окне TradingView).
Посмотрите, как она работала в прошлом.
Настройте под себя:
Увеличьте %Profit до 2-3%, если торгуете валюты.
Отключите «Sell – On», если не понимаете шорты.
Доверяйте стоп-лоссу:
Даже если кажется, что цена развернётся — стратегия закроет сделку при -0.5%, защитив ваш депозит.
Где найти настройки:
Кликните на название стратегии в верхнем левом углу графика → откроется меню с ползунками и переключателями.
Важно: Стратегия предоставляет «рыбу» – чтобы она стала «уловистой», адаптируйте её под свой стиль торговли!
200 EMA AlertHow It Works:
The 200 EMA calculates the average price over the last 200 periods, giving more weight to recent price movements for a smoother and more responsive trend line.
It helps traders determine whether the market is in a bullish (above 200 EMA) or bearish (below 200 EMA) phase.
Why Traders Use the 200 EMA:
✅ Trend Confirmation – If the price is above the 200 EMA, the trend is bullish; if below, the trend is bearish.
✅ Dynamic Support & Resistance – Price often reacts around the 200 EMA, making it a key level for entries and exits.
✅ Works on All Timeframes – Whether on the 1-minute chart or the daily timeframe, the 200 EMA is effective for scalping, swing trading, and long-term investing.
✅ Easy to Combine with Other Indicators – Traders pair it with RSI, MACD, or price action for stronger confirmation.
How to Use It in Trading:
📌 Trend Trading – Buy when price pulls back to the 200 EMA in an uptrend; sell when price retests it in a downtrend.
📌 Breakout Strategy – A strong candle breaking above/below the 200 EMA signals a possible trend reversal.
📌 Filtering Trades – Many traders only take long trades above and short trades below the 200 EMA to align with the overall market trend.
Conclusion:
The 200 EMA is an essential indicator for traders of all levels, offering clear trend direction, strong support/resistance zones, and trade filtering for better decision-making. Whether you're trading forex, stocks, or crypto, mastering the 200 EMA can give you a significant edge in the markets. 🚀📈
Consecutive Bullish/Bearish Candles🔍 Overview:
This indicator detects market manipulation and deception by identifying sequences of consecutive bullish or bearish candles. It highlights potential reversal zones where trends may exhaust or trap traders before reversing.
📌 How It Works:
The user can set a custom number of consecutive bullish or bearish candles (default: 5).
If the set number of consecutive green (bullish) or red (bearish) candles appears, the indicator plots a signal on the chart.
This pattern often signals exhaustion, stop hunts, or market traps, making it useful for traders looking for reversal opportunities.
📊 Features:
✅ Customizable candle count for detection
✅ Visual signals (✅ for bullish, ❌ for bearish)
✅ Alerts support for automated notifications
✅ Works on all timeframes and all markets (crypto, stocks, forex)
⚠️ Note:
This indicator does not guarantee reversals but helps identify areas where traders may be trapped and a trend shift is likely. Always use it with other confluence factors like volume, support/resistance, and market sentiment.
🚀 Use this tool to spot market deception and trade smart!
Wave Modulation Demo█ OVERVIEW
This script demonstrates Stacked Wave Modulation by visualizing four interconnected waves. Wave 1 is the base wave, influencing Wave 2's frequency, which in turn modulates Wave 3's amplitude, and finally, Wave 3 modulates Wave 4's phase. Explore the fascinating effects of wave modulation by adjusting the inputs for each wave and their modulation scales.
══════════════════════════════════════════════════
█ CONCEPTS
This script visualizes a cascade of wave modulations:
1 — Base Wave (Wave 1): This is the foundational wave. Its parameters (type, frequency, amplitude, phase, vertical shift) are directly controlled and serve as the basis for subsequent modulations.
2 — Frequency Modulation (Wave 2): Wave 2's frequency is modulated by Wave 1 . As Wave 1 oscillates, it dynamically changes the frequency of Wave 2 , creating interesting frequency variations. The Frequency Mod Scale input controls the intensity of this modulation.
3 — Amplitude Modulation (Wave 3): Building upon the cascade, Wave 3 's amplitude is modulated by Wave 2 . The peaks and troughs of Wave 2 influence the amplitude of Wave 3 , resulting in amplitude variations. The Amplitude Mod Scale input adjusts the strength of this amplitude modulation.
4 — Phase Modulation (Wave 4): Finally, Wave 4 's phase is modulated by Wave 3 . Wave 3 's oscillations shift the phase of Wave 4 , leading to phase-related distortions and dynamic wave patterns. The Phase Mod Scale input determines the extent of phase modulation.
5 — Stacked Wave (Average): The script calculates and plots the average of all four waves, providing a composite view of the combined modulation effects.
══════════════════════════════════════════════════
█ FEATURES
The script is organized into input groups for each wave, allowing for detailed customization:
1 — Wave 1: Base Wave
• Type : Select the waveform type for Wave 1 (Sine, Cosine, Triangle, Square).
• Frequency (Hz) : Sets the base frequency of Wave 1 in Hertz (cycles per second).
• Amplitude : Controls the vertical amplitude or height of Wave 1.
• Phase Shift (deg) : Adjusts the phase shift of Wave 1 in degrees, shifting the wave horizontally.
• Vertical Shift : Sets the vertical position of Wave 1 on the chart.
2 — Wave 2: Frequency Modulation
• Type : Select the waveform type for Wave 2.
• Base Frequency (Hz) : Sets the base frequency of Wave 2, before modulation.
• Amplitude : Controls the amplitude of Wave 2.
• Phase Shift (deg) : Adjusts the phase shift of Wave 2.
• Vertical Shift : Sets the vertical position of Wave 2.
• Frequency Mod Scale : Determines the degree to which Wave 1 modulates Wave 2's frequency. Higher values increase the modulation effect.
3 — Wave 3: Amplitude Modulation
• Type : Select the waveform type for Wave 3.
• Base Frequency (Hz) : Sets the base frequency of Wave 3.
• Amplitude : Controls the base amplitude of Wave 3, before modulation.
• Phase Shift (deg) : Adjusts the phase shift of Wave 3.
• Vertical Shift : Sets the vertical position of Wave 3.
• Amplitude Mod Scale : Determines the degree to which Wave 2 modulates Wave 3's amplitude. Higher values increase the modulation effect.
4 — Wave 4: Phase Modulation
• Type : Select the waveform type for Wave 4.
• Base Frequency (Hz) : Sets the base frequency of Wave 4.
• Amplitude : Controls the amplitude of Wave 4.
• Phase Shift (deg) : Sets the base phase shift of Wave 4, before modulation.
• Vertical Shift : Sets the vertical position of Wave 4.
• Phase Mod Scale : Determines the degree to which Wave 3 modulates Wave 4's phase. Higher values increase the modulation effect.
══════════════════════════════════════════════════
█ HOW TO USE
1. Add the "Stacked Wave Modulation Demo" script to your TradingView chart.
2. Explore the input settings. Each wave has its own group of customizable parameters.
3. Adjust the Type , Frequency , Amplitude , Phase Shift , and Vertical Shift for each wave to define their base characteristics.
4. Experiment with the modulation scales ( Frequency Mod Scale , Amplitude Mod Scale , Phase Mod Scale ) to control the intensity of the modulation effects between the waves.
5. Observe how the waves interact and how the modulations shape their forms and the final stacked wave (average).
══════════════════════════════════════════════════
█ NOTES
* This script utilizes the `waves` and `hsvColor` libraries. Look for other scripts on my profile.
* The frequencies are set in Hertz (cycles per second), which relate to bars on the chart. A frequency of 0.5 Hz means 0.5 cycles per bar, or 1 cycle every 2 bars.
* Adjusting the modulation scales allows you to fine-tune the visual impact of the modulation effects.
* The color of each wave plot is dynamically generated based on its value using the HSV color model for visual distinction.
* Feel free to modify and experiment with the script to create different modulation schemes or stacking methods.
Let me know if you have any other questions or would like further refinements!
Volume Flow Indicator Signals | iSolani
Volume Flow Indicator Signals | iSolani: Decoding Trend Momentum with Volume Precision
In markets where trends are fueled by institutional participation, discerning genuine momentum from false moves is critical. The Volume Flow Indicator Signals | iSolani cuts through this noise by synthesizing price action with volume dynamics, generating high-confidence signals when capital flows align with directional bias. This tool reimagines traditional volume analysis by incorporating volatility-adjusted thresholds and dual-layer smoothing, offering traders a laser-focused approach to trend identification.
Core Methodology
The indicator employs a multi-stage calculation to quantify volume-driven momentum:
Volatility-Adjusted Filter: Measures price changes via log returns, scaling significance using a 30-bar standard deviation multiplied by user-defined sensitivity (default: 2x).
Volume Normalization: Caps extreme volume spikes at 3x the 50-bar moving average, preventing distortion from anomalous trades.
Directional Volume Flow: Assigns positive/negative values to volume based on whether price movement exceeds volatility-derived thresholds.
Dual Smoothing: Applies consecutive SMA (3-bar) and EMA (14-bar) to create the Volume Flow Indicator (VFI) and its signal line, filtering out transient fluctuations.
Breaking New Ground
This implementation introduces three key innovations:
Adaptive Noise Gates: Unlike static volume oscillators, the sensitivity coefficient dynamically adjusts to market volatility, reducing false signals during choppy conditions.
Institutional Volume Capping: The vcoef parameter limits the influence of outlier volume spikes, focusing on sustained institutional activity rather than one-off trades.
Non-Repainting Signals: Generates single-per-trend labels (buy below bars, sell above) to avoid chart clutter while maintaining visual clarity.
Engine Under the Hood
The script executes through five systematic stages:
Data Preparation: Computes HLC3 typical price and its logarithmic rate of change.
Threshold Calculation: Derives dynamic cutoff levels using 30-period volatility scaled by user sensitivity.
Volume Processing: Filters raw volume through a 50-bar SMA, capping extremes at 3x average.
VFI Construction: Sums directional volume flow over 50 bars, smoothed with a 3-bar SMA.
Signal Generation: Triggers alerts when VFI crosses zero, confirmed by a 14-bar EMA crossover.
Standard Configuration
Optimized defaults balance responsiveness and reliability:
Volume MA: 50-bar smoothing window
Sensitivity: 2.0 (doubles volatility threshold)
Signal Smoothing: 14-bar EMA
Volume Cap: 3x average (hidden parameter)
VFI Smoothing: Enabled (3-bar SMA)
By fusing adaptive volume filtering with price confirmation logic, the Volume Flow Indicator Signals | iSolani transforms raw market data into institutional-grade trend signals. Its ability to mute choppy price action while amplifying high-conviction volume moves makes it particularly effective for spotting early trend reversals in equities, forex, and futures markets.
SMA Strategy Builder: Create & Prove Profitability📄 Pine Script Strategy Description (For Publishing on TradingView)
🎯 Strategy Title:
SMA Strategy Builder: Create & Prove Profitability
✨ Description:
This tool is designed for traders who want to build, customize, and prove their own SMA-based trading strategies. The strategy tracks capital growth in real-time, providing clear evidence of profitability after each trade. Users can adjust key parameters such as SMA period, take profit levels, and initial capital, making it a flexible solution for backtesting and strategy validation.
🔍 Key Features:
✅ SMA-Based Logic:
Core trading logic revolves around the Simple Moving Average (SMA).
SMA period is fully adjustable to suit various trading styles.
🎯 Customizable Take Profit (TP):
User-defined TP percentages per position.
TP line displayed as a Step Line with Breaks for clear segmentation.
Visual 🎯TP label for quick identification of profit targets.
💵 Capital Tracking (Proof of Profitability):
Initial capital is user-defined.
Capital balance updates after each closed trade.
Shows both absolute profit/loss and percentage changes for every position.
Darker green profit labels for better readability and dark red for losses.
📈 Capital Curve (Performance Visualization):
Capital growth curve available (hidden by default, can be enabled via settings).
📏 Dynamic Label Positioning:
Label positions adjust dynamically based on the price range.
Ensures consistent visibility across low and high-priced assets.
⚡ How It Works:
Long Entry:
Triggered when the price crosses above the SMA.
TP level is calculated as a user-defined percentage above the entry price.
Short Entry:
Triggered when the price crosses below the SMA.
TP level is calculated as a user-defined percentage below the entry price.
TP Execution:
Positions close immediately once the TP level is reached (no candle close confirmation needed).
🔔 Alerts:
🟩 Long Signal Alert: When the price crosses above the SMA.
🟥 Short Signal Alert: When the price crosses below the SMA.
🎯 TP Alert: When the TP target is reached.
⚙️ Customization Options:
📅 SMA Period: Choose the moving average period that best fits your strategy.
🎯 Take Profit (%): Adjust TP percentages for flexible risk management.
💵 Initial Capital: Set the starting capital for realistic backtesting.
📈 Capital Curve Toggle: Enable or disable the capital curve to track overall performance.
🌟 Why Use This Tool?
🔧 Flexible Strategy Creation: Adjust core parameters and create tailored SMA-based strategies.
📈 Performance Proof: Capital tracking acts as real proof of profitability after each trade.
🎯 Immediate TP Execution: No waiting for candle closures; profits lock in as soon as targets are hit.
💹 Comprehensive Performance Insights: Percentage-based and absolute capital tracking with dynamic visualization.
🏦 Clean Visual Indicators: Strategy insights made clear with dynamic labeling and adjustable visuals.
⚠️ Disclaimer:
This script is provided for educational and informational purposes only. Trading financial instruments carries risk, and past performance does not guarantee future results. Always perform your own due diligence before making any trading decisions.
Stock Earnings Viewer for Pine ScreenerThe script, titled "Stock Earnings Viewer with Surprise", fetches actual and estimated earnings, calculates absolute and percent surprise values, and presents them for analysis. It is intended to use in Pine Screener, as on chart it is redundant.
How to Apply to Pine Screener
Favorite this script
Open pine screener www.tradingview.com
Select "Stock Earnings Viewer with Surprise" in "Choose indicator"
Click "Scan"
Data
Actual Earnings: The reported earnings per share (EPS) for the stock, sourced via request.earnings().
Estimated Earnings: Analyst-predicted EPS, accessed with field=earnings.estimate.
Absolute Surprise: The difference between actual and estimated earnings (e.g., actual 1.2 - estimated 1.0 = 0.2).
Percent Surprise (%): The absolute surprise as a percentage of estimated earnings (e.g., (0.2 / 1.0) * 100 = 20%). Note: This may return NaN or infinity if estimated earnings are zero, due to division by zero.
Practical Use
This screener script allows users to filter stocks based on earnings metrics. For example, you could screen for stocks where Percent Surprise > 15 to find companies exceeding analyst expectations significantly, or use Absolute Surprise < -0.5 to identify underperformers.
Astro R4.0Regarding the code that has a significant impact on Pine Community and many feel helped by it, this is the code that I ported from VBA to PineScript which comes from simontelescopium owner of astroexcel dot wordpress dot com and "astrofnc" by Keith Burnett, previously I used it personally but I forgot to give a citation to those who are entitled to them both so that when I shared it for community use and it has been shared by brother @BarefootJoey with the additions made by him personally, there was no citation for them.
Apologies for my negligence because I am only human.
Hopefully with this script it can help the community to see the potential for implementation in the trading world as a significant variable.
Finally, I publish this script as a reference to find out astronomical charts presented in table form to make it easier to visualize and debug as long as the input.timestamp() allow it.
Future updates for optimization using library of brother @BarefootJoey
Thank you.
Mon to Fri + LSE and NYSE📌 Highlight Custom Days & Market Hours Indicator 📌
🔹 Overview:
This script allows traders to visually highlight specific weekdays and market sessions directly on their TradingView charts. With customizable checkboxes, you can choose which days of the week to highlight, along with session times for the New York Stock Exchange (NYSE) and London Stock Exchange (LSE).
🔹 Features:
✅ Select individual weekdays (Monday–Friday) to highlight in blue
✅ Highlight NYSE open hours (2:30 PM – 9:30 PM UK time) in green
✅ Highlight LSE open hours (8:00 AM – 4:30 PM UK time) in orange
✅ Ensures NYSE & LSE sessions are only highlighted on weekdays (no weekends)
✅ Clean and simple visualization for enhanced market awareness
🔹 How to Use:
1️⃣ Add the indicator to your TradingView chart
2️⃣ Use the settings panel to enable/disable specific weekdays
3️⃣ Toggle NYSE or LSE session highlights based on your trading preference
🚀 Perfect for traders who follow institutional sessions and want better time-based confluence in their strategies!