ATR LevelsATR levels drawn on a chart as dynamic (can change throughout the day), straight lines.
Upper band = daily ATR in pips + daily low.
Lower band = daily high - daily ATR in pips.
Can be used as a reversal signal if there is a good level past ATR. Can go long/short from there.
Komut dosyalarını "daily" için ara
ATR LevelsATR levels drawn on a chart as dynamic (can change throughout the day), straight lines.
Upper band = daily ATR in pips + daily low.
Lower band = daily high - daily ATR in pips.
Can be used as a reversal signal if there is a good level past ATR. Can go long/short from there.
MACD + SMA 200 Strategy (by ChartArt)Here is a combination of the classic MACD (moving average convergence divergence indicator) with the classic slow moving average SMA with period 200 together as a strategy.
This strategy goes long if the MACD histogram and the MACD momentum are both above zero and the fast MACD moving average is above the slow MACD moving average. As additional long filter the recent price has to be above the SMA 200. If the inverse logic is true, the strategy goes short. For the worst case there is a max intraday equity loss of 50% filter.
Save another $999 bucks with my free strategy.
This strategy works in the backtest on the daily chart of Bitcoin, as well as on the S&P 500 and the Dow Jones Industrial Average daily charts. Current performance as of November 30, 2015 on the SPX500 CFD daily is percent profitable: 68% since the year 1970 with a profit factor of 6.4. Current performance as of November 30, 2015 on the DOWI index daily is percent profitable: 51% since the year 1915 with a profit factor of 10.8.
All trading involves high risk; past performance is not necessarily indicative of future results. Hypothetical or simulated performance results have certain inherent limitations. Unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not actually been executed, the results may have under- or over-compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown.
SuperTrend Oscillator v3Version 3: Improved aesthetically, complete turnaround for the strategy with which to use this indicator.
Once again, thanks to BlindFreddy and ChrisMoody for the bits of code that were assembled into this indicator.
Make the chart yours using the share button for the indicator with barcolors functionality.
Changes from v2 and looking forward: Indicator now uses a 14 length SuperTrend with no ATR multiplier. This my preferred use and I'd be grateful to hear your case for a different length/multiplier. Removed the Bollinger Bands and retracement dots due to these being gimmicky and marginally useful. There may be a version 4 should a similar concept using a rate of change analysis turn out to be useful. I have also tried -in vain- to plot internal trend peaks as horizontal S/R levels. Please pm if you are willing to help in that respect.
Strategy: The indicator will display the trend as a red/green area. It measures the spread between the closing price and the SuperTrend line, much like a CCI (close and ma). When the area contracts warning bars of the opposite trend color will warn of a reversal. When this happens, these areas will either be defended, reviving the trend, or will break, causing a trend flip. SuperTrend is unique in that breaks are typically large candles, and that its levels, especially on Weekly, Daily, Hourly, Minute timeframes, these levels will be defended (think similar to a 200sma or a 21ema). The STO making new highs within (internal) a trend is an overextension sign.
CVX Example: This is not a full analysis of CVX's stock , just an example potential trades. On the posted chart I used a weekly and a daily STO.
Long 1:The weekly showed warnings and then flipped. The daily made a double bottom, showed warnings and then flipped the daily STO at trendline support.
Long 2:The weekly still shows an uptrend, the daily made a weak break to downtrend and reversed back upwards at trendline support, forming a double bottom. Note the conservative exit when the STO made an internal new high.
Long 3: looking forward on CVX stock , the current downtrend made a weak break and is showing sings of reversal (pin bar) at horizontal support. Go long on flip of the daily (conservative) or flip of the hourly (aggressive).
SuperTrend OscillatorVersion 3: Improved aesthetically, complete turnaround for the strategy with which to use this indicator.
Once again, thanks to BlindFreddy and ChrisMoody for the bits of code that were assembled into this indicator.
Make the chart yours using the share button for the indicator with barcolors functionality.
Changes from v2 and looking forward: Indicator now uses a 14 length SuperTrend with no ATR multiplier. This my preferred use and I'd be grateful to hear your case for a different length/multiplier. Removed the Bollinger Bands and retracement dots due to these being gimmicky and marginally useful. There may be a version 4 should a similar concept using a rate of change analysis turn out to be useful. I have also tried -in vain- to plot internal trend peaks as horizontal S/R levels. Please pm if you are willing to help in that respect.
Strategy: The indicator will display the trend as a red/green area. It measures the spread between the closing price and the SuperTrend line, much like a CCI (close and ma). When the area contracts warning bars of the opposite trend color will warn of a reversal. When this happens, these areas will either be defended, reviving the trend, or will break, causing a trend flip. SuperTrend is unique in that breaks are typically large candles, and that its levels, especially on Weekly, Daily, Hourly, Minute timeframes, these levels will be defended (think similar to a 200sma or a 21ema). The STO making new highs within (internal) a trend is an overextension sign.
CVX Example: This is not a full analysis of CVX's stock, just an example potential trades. On the posted chart I used a weekly and a daily STO.
Long 1:The weekly showed warnings and then flipped. The daily made a double bottom, showed warnings and then flipped the daily STO at trendline support.
Long 2:The weekly still shows an uptrend, the daily made a weak break to downtrend and reversed back upwards at trendline support, forming a double bottom. Note the conservative exit when the STO made an internal new high.
Long 3: looking forward on CVX stock, the current downtrend made a weak break and is showing sings of reversal (pin bar) at horizontal support. Go long on flip of the daily (conservative) or flip of the hourly (aggressive).
Super MTF Clouds (4x3 Pairs)Overview:
This script is based on Ripster's MTF clouds, which transcends the standard moving average cloud indicator by offering a powerful and deeply customizable Multi-Timeframe (MTF) analysis. Instead of being limited to the moving averages of your current charts from the current timeframe, this tool allows you to project and visualize the trend and key support/resistance zones from up to 4 different timeframes simultaneously. User can input up to 6 different EMA values which will form 3 pairs of EMA clouds, for each of the timeframes.
The primary purpose is to provide traders with immediate confluence. By observing how price interacts with moving average clouds from higher timeframes (e.g., Hourly, Daily, Weekly), you can make more informed decisions on your active trading timeframe (e.g., 10 Minute). It's designed as a complete MTF Cloud toolkit, allowing you to display all necessary MTFs in a single script to build a comprehensive view of the market structure without having to flick to different timeframe to look for cloud positions.
Key features:
Four Independent Multi-Timeframe Slots: Each slot can be assigned any timeframe available on TradingView (e.g., D, W, M, 4H).
Three MA Pairs Per Timeframe: For each timeframe, configure up to three separate MA clouds (e.g., a 9/12 EMA pair, a 20/50 EMA pair, and a 100/200 SMA pair).
Complete Customisation: For every single moving average (24 in total), you can independently control:
MA Type: Choose between EMA or SMA.
Length: Any period you require.
Line Color: Full colour selection.
Line Thickness: Adjust the visual weight of each line.
Cloud Control: For every pair (12 in total), you can set the fill colour and transparency.
How To Use This Script:
This tool is best used for confirmation and context. Here are some practical strategies that one can adopt:
Trend Confluence: Before taking a trade based on a signal on your current timeframe, glance at the higher timeframe clouds. If you see a buy signal on the 15-minute chart and the price is currently trading above a thick, bullish Daily cloud, the probability of that trade succeeding is significantly higher. Conversely, shorting into strong HTF support is a low-probability trade.
Dynamic Support & Resistance: The edges of the higher timeframe clouds often act as powerful, dynamic levels of support and resistance. A pullback to the 4-Hour 50 EMA on your 15-minute chart can be a prime area to look for entries in the direction of the larger trend.
Gauging Market Regimes: Use the toggles in the settings to quickly switch between different views. You can have a "risk-on" view with short-term clouds and a "macro" view with weekly and monthly clouds. This helps you adapt your trading style to the current market conditions.
Key Settings:
1. Global Setting
Source For All MAs: This determines the price data point used for every single moving average calculation.
Default: hl2 (an average of the High and Low of each bar). This gives a smooth midpoint price.
Options: You can change this to Close (the most common method), Open, High, Low, or ohlc4 (an average of the open, high, low, and close), among others.
Recommendation: For most standard trend analysis, the default hl2 is the common choice.
2. The Timeframe Group Structure
The rest of the settings are organized into four identical, collapsible groups: "Timeframe 1 Settings" through "Timeframe 4 Settings". Each group acts as a self-contained control panel for one multi-timeframe view.
Within each timeframe group, you have two master controls:
Enable Timeframe: This is the main power switch for the entire group. Uncheck this box to instantly hide all three clouds and lines associated with this timeframe. This is perfect for quickly decluttering your chart or focusing on a different set of analyses.
Timeframe: This dropdown menu is the heart of the MTF feature. Here, you select the higher timeframe you want to analyse (e.g., 1D for Daily, 1W for Weekly, 4H for 4-Hour). All calculations for the three pairs within this group will be based on the timeframe you select here.
3. Pair-Specific Controls
Inside each timeframe group, there are three sections for "Pair 1", "Pair 2", and "Pair 3". These control each individual moving average cloud.
Enable Pair: Just like the master switch for the timeframe, this checkbox turns a single cloud and its two MA lines on or off.
For each pair, the settings are further broken down:
Moving Average Lines (A and B): These two rows control the two moving averages that form the cloud. 'A' is typically used for the shorter-period MA and 'B' for the longer-period one.
Type (A/B): A dropdown menu to select either EMA (Exponential Moving Average) or SMA (Simple Moving Average). EMAs react more quickly to recent price changes, while SMAs are smoother and react more slowly.
Length (A/B): The lookback period for the moving average (e.g., 21, 50, 200).
Color (A/B): Sets the specific colour of the MA line itself on your chart.
Cloud Fill Settings
Fill Color: This controls the colour of the shaded area (the "cloud") between the two moving average lines. For a consistent look, you can set this to the same colour as your shorter MA line.
Transparency: Controls how see-through the cloud is, on a scale of 0 to 100. 0 is a solid, opaque colour, while 100 is completely invisible. The default of 85 provides a light, "cloud-like" appearance that doesn't obscure the price action.
----------------------------------------------------------------------
If anything is not clear please let me know!
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Integrating with Confluence of Signals
The LongShortExit strategy can be enhanced by using it in conjunction with the "Confluence of Alerts" indicator to create more robust entry conditions based on multiple technical signals.
### What is Confluence of Signals?
The Confluence of Alerts indicator allows you to define up to 8 different technical conditions that must be met simultaneously to generate a trading signal. This approach helps filter out false signals and only enters trades when multiple technical factors align.
### Integration Approach
#### Method 1: Using Confluence as a Signal Source
1. Add the Confluence of Alerts indicator to your chart
2. Configure your desired technical conditions (RSI, moving averages, support/resistance, etc.)
3. In the LongShortExit strategy settings:
- Set Long Source to `plot("Long All")` from the Confluence indicator
- Set Long Value to `1` with "Equals" condition
- Similarly for Short Source using `plot("Short All")`
#### Method 2: Modifying the Strategy Code
For more advanced integration, you can incorporate the condition logic directly:
```pine
// Add to the top of your LongShortExit strategy
//@import TradersPost/Confluence_of_Alerts/1
// Replace simple entry conditions with confluence signals
longCondition = confluence_long_signal and longEntryCondition
shortCondition = confluence_short_signal and shortEntryCondition
```
### Confluence Configuration Examples
#### Trend-Following Configuration
1. **Condition 1**: When SMA(20) crossing up SMA(50)
2. **Condition 2**: When RSI(14) greater than 50
3. **Condition 3**: When close greater than VWAP
4. **Condition 4**: When ADX(14) greater than 25
#### Support/Resistance Configuration
1. **Condition 1**: When price crossing up pivot support
2. **Condition 2**: When Stochastic %K crossing up %D
3. **Condition 3**: When volume greater than average volume
4. **Condition 4**: When price greater than previous day's close
### Benefits of Using Confluence with LongShortExit
- **Reduced False Signals**: Enter trades only when multiple conditions confirm the signal
- **Higher Probability Trades**: Each additional confirming factor increases trade success probability
- **Customizable Filter**: Adapt the conditions to suit different market environments and trading styles
- **Visual Confirmation**: The Confluence indicator provides clear visual signals when all conditions are met
### Implementation Tips
1. Start with 2-3 conditions before adding more complexity
2. Ensure conditions aren't redundant (e.g., don't use multiple similar indicators)
3. Include conditions from different categories:
- Trend indicators (moving averages, ADX)
- Momentum indicators (RSI, MACD)
- Volume indicators
- Support/resistance levels
4. Test different timeframes for the conditions
5. Use the "on Bar Close" option for more reliable signals
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*
Confluence of signals# Confluence of Signals
## Overview
The "Confluence of Signals" is a powerful Pine Script indicator designed for TradingView that allows traders to define and visualize multiple technical conditions for both long and short trading signals. When all specified conditions align (reach confluence), the indicator generates a clear buy or sell signal, providing a structured approach to trading decision-making.
## Key Features
### Multiple Condition Support
- **8 Long Conditions**: Configure up to 8 different technical conditions for long entries
- **8 Short Conditions**: Configure up to 8 different technical conditions for short entries
- **Flexible Activation**: Enable or disable any condition based on your trading strategy
### Signal Types and Flexibility
- **Rich Condition Types**:
- Crossing (standard crosses)
- Crossing Up (bullish crosses)
- Crossing Down (bearish crosses)
- Greater Than (value comparisons)
- Less Than (value comparisons)
- Equals (exact matches)
- Rising (trend conditions over specified bars)
- Falling (trend conditions over specified bars)
- Toggle (signals that remain active for a specified number of bars)
### Multi-Timeframe Analysis
- Apply conditions from different timeframes
- Supports unified analysis across multiple chart periods
### Signal Management
- **Trade Limiting**: Set minimum bars between trades to avoid overtrading
- **Session Control**: Limit signals to specific trading sessions
- **Signal Expiration**: Set a date after which signals will no longer be generated
### Visual Feedback
- **Signal Table**: Clear BUY/SELL/NONE status display in the top-right corner
- **Condition Markers**: Visual indicators showing which specific conditions are active
- **Confluence Markers**: Triangle markers showing when all conditions align
- **Session Highlighting**: Optional background highlighting for the active session
## Usage Instructions
### Setting Up Conditions
1. Enable the conditions you wish to use by checking the "Use" option for each
2. Configure each condition with:
- **Source**: The price or indicator value to evaluate (e.g., close, SMA, RSI)
- **Event**: The type of condition (crossing, greater than, etc.)
- **Value/Source**: The threshold or comparison source
- **Timeframe**: Optional higher timeframe for the condition
- **Bar Close**: Whether the condition should only be evaluated on bar close
### Toggle Mode
For conditions set to "Toggle" mode:
1. Specify the number of bars the signal should remain active
2. The condition will remain true for the specified number of bars after triggering
3. Useful for conditions you want to remain valid for a certain period
### Trade Management
- **Bars Between Trades**: Prevents signals from occurring too frequently
- **Session Control**: Limit trading to specific market sessions
- **Expiration**: Set a cutoff date for all signals
### Visualization Controls
- Show/hide individual condition markers
- Show/hide confluence markers
- Enable/disable session highlighting
## Installation
1. Open TradingView and navigate to the Pine Editor
2. Copy the entire Confluence of Signals script
3. Paste it into the Pine Editor
4. Click "Save" and give your indicator a name
5. Click "Add to Chart" to apply the indicator
## Example Setups
### Simple Moving Average Crossover
- **Long Condition 1**: When (Close) Crossing Up (200 SMA)
- **Short Condition 1**: When (Close) Crossing Down (200 SMA)
### RSI with Support/Resistance
- **Long Condition 1**: When (RSI) Crossing Up (30)
- **Long Condition 2**: When (Close) Greater Than (50 SMA)
- **Short Condition 1**: When (RSI) Crossing Down (70)
- **Short Condition 2**: When (Close) Less Than (50 SMA)
### Multi-Timeframe Strategy
- **Long Condition 1**: When (Close) Greater Than (200 SMA)
- **Long Condition 2**: When (MACD) Crossing Up (Signal)
- **Short Condition 1**: When (Close) Less Than (200 SMA)
- **Short Condition 2**: When (MACD) Crossing Down (Signal)
## Best Practices
1. Start with fewer conditions and gradually add more as needed
2. Test different combinations of conditions to find optimal setups
3. Use the toggle feature for conditions that should remain valid for multiple bars
4. Consider using multi-timeframe conditions for confirmation from higher timeframes
5. Set appropriate trade limits to prevent overtrading
## Customization
The indicator can be further customized by modifying the script:
- Change colors and visual elements
- Add additional conditions if needed
- Modify the signaling logic
## Compatibility
- **Platform**: TradingView
- **Script Version**: Pine Script v5
- **Chart Types**: Compatible with all chart types
- **Timeframes**: Works on all timeframes
## Disclaimer
This indicator is provided for informational and educational purposes only. Always conduct your own analysis and risk management before making trading decisions. Past performance is not indicative of future results.
## Version History
- v1.0: Initial release with basic condition support
- v1.1: Added toggle functionality
- v1.2: Added multi-timeframe support
- v1.3: Added session control and expiration options
- v2.0: Expanded to 8 conditions for both long and short signals
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*
Rolling VWAP: 30D & 365DThis TradingView Pine Script calculates and plots two Rolling Volume Weighted Average Price (VWAP) lines:
30-Day Rolling VWAP (Blue): Shows the average price over the past 30 daily candles, weighted by volume.
365-Day Rolling VWAP (Orange): Shows the long-term average price over the past 365 daily candles, also volume-weighted.
Unlike standard VWAP (which resets daily or per session), these are rolling averages, helping identify longer-term price trends and value zones.
An optional histogram can be enabled to visualize the difference between the 30D and 365D VWAP, turning green when short-term is above long-term (bullish) and red when it's below (bearish).
Candle Opens by HAZEDCandle Opens by HAZED
🎯 Overview
A clean, optimized indicator that displays key timeframe opening prices with enhanced performance and modern styling. Perfect for identifying critical support/resistance levels across multiple timeframes without chart clutter.
📈 Key Features
- 5 Major Timeframes: Daily, Weekly, Monthly, Quarterly, and Yearly opens
- Current Opens Only: No historical lookback - shows only the most recent/relevant levels
- Smart Positioning: Toggle between staggered lines (prevents overlap) or uniform length
- Dual Label Styles: Choose plain text (minimal) or enhanced labels with prices
- Performance Optimized: Streamlined code for faster loading and smoother operation
- Alert System: Get notified when any timeframe opens change
- Extended Hours Support: Works with pre/post market sessions
🎨 Customization Options
- Individual color selection for each timeframe
- Adjustable line width (1-4px)
- Right extension length control
- Optional left tail extensions
- Show/hide labels with style options
- Same length lines toggle for clean alignment
⚙️ Advanced Settings
- Discover Prices: Use chart data instead of HTF requests (for data feed discrepancies)
- Extended Hours: Display opens during pre/post market sessions
- Alert Controls: Enable/disable notifications for timeframe changes
📊 Default Configuration
- Enabled: Daily (Green), Weekly (Orange), Monthly (Red), Yearly (Blue)
- Disabled: Quarterly (Purple) - easily enabled if needed
- Labels: Enhanced style with prices shown by default
- Lines: 2px width, staggered positioning for optimal spacing
🚀 Performance Improvements
- Removed unnecessary historical data tracking
- Optimized drawing functions for better responsiveness
- Cleaner variable management and memory usage
- Enhanced yearly open detection algorithm
💡 Best Use Cases
- Swing trading: Identify key weekly/monthly levels
- Day trading: Respect daily opens as support/resistance
- Long-term investing: Monitor yearly opens for major trends
- Multi-timeframe analysis: See all key levels at once
🔧 Technical Notes
- Uses proper request.security() calls for accurate data
- Smart change detection prevents unnecessary redraws
- Handles different chart timeframes automatically
- Compatible with all asset classes and exchanges
Original concept enhanced and optimized by HAZED for modern trading needs.
Fib-SMAs + 23↘38 Signal🧠 Fibonacci SMAs — and the Bearish Power of the 23↘38 Cross
This script plots a ribbon of 5 Simple Moving Averages (SMAs), each derived from Fibonacci retracement ratios:
23.6%, 38.2%, 50%, 61.8%, and 78.6% — all calculated as percentages of a base length (default: 100 bars).
It transforms the classical Fibonacci concept from static price levels into a dynamic trend structure based on time.
🔍 The Pattern I Discovered
When studying the Daily BTC chart, I found a powerful recurring signal:
When the 23.6% SMA (fuchsia) crosses below the 38.2% SMA (teal),
Bitcoin tends to pull back significantly in the following weeks.
This signal, which I call the 23↘38 cross, shows up at:
Major market tops
Bull market pauses
Local overextensions during trend runs
In backtested cases since 2014, this cross preceded corrections of 8–35%, usually playing out over the following 10–40 days.
⚠️ What’s Happening Now?
A fresh 23↘38 bearish cross has just occurred on the Daily BTC chart.
Historically, these setups often result in BTC pulling back into the zone where the 61.8% and 78.6% SMAs act as mean reversion targets.
That puts the next major support zone in the range of $94.5k to $79k — highlighted automatically on the chart when the signal appears.
💡 Why Use Fibonacci for Time?
Fibonacci levels (0.236, 0.382, 0.618...) are traditionally used on the price axis.
This tool flips that idea: it applies Fibonacci ratios to the time axis — calculating SMAs that reflect natural market timing rhythms, not just support/resistance lines.
The result is a ribbon of rhythm, where each line represents a unique retracement of time-based momentum.
🧰 Features Included
Besides the core 23↘38 bearish signal, the script includes optional toggleable modules:
Name Description
Ribbon Flip-and-Go Detects full bullish or bearish alignment and trend ignition
Pinch Breakout Flags volatility compression followed by expansion
Deep-Dip Buy/Sell Finds smart pullbacks in ongoing trends using the 61.8% SMA
Each one includes alertcondition() support, so you can automate strategies or trading bots.
🧭 How to Trade It
Use the 23↘38 cross as an early warning to:
Secure profits
De-risk exposure
Watch for pullbacks to the slower SMAs (61.8% / 78.6%)
It’s not a short signal by itself, but a macro timing filter that consistently front-runs volatility drops in overheated markets.
📉 Historical Examples (BTC 1D)
Nov 2021 top → -35% drop
April 2022 rally → -28% retracement
Mid-2023 local high → -15% correction
June 2025 cross → current signal, target zone: 94.5k–79k
⚠️ Disclaimer
This is not financial advice. It’s a tool for studying probability patterns in price action.
Use it alongside proper risk management and market context.
CQ_MTF Target Price Lines [BitCoin Hoy]This script is dedicated to Esteban Pérez, host and creator of Youtube Channel "Bitcoin Hoy".
The idea behind this indicator is his daily sugestion of having a notebook to write down the Intraday, 4H, Daily and Weekly calculated target prices. All the community in his channel will find this script helpful.
After typing in the target prices, they'll be shown on the chart.
Thank you very much Esteban!
Bias Bar Coloring + Multi-Timeframe Bias Table + AlertsMulti-Timeframe Bias Bar Coloring with Alerts & Table
This indicator provides a powerful, visual way to assess price action bias across multiple timeframes—Monthly, Weekly, and Daily—while also coloring each bar based on the current chart’s bias.
Features:
Persistent Bar Coloring: Bars are colored green for bullish bias (close above previous high), red for bearish bias (close below previous low), and persist the last color if neither condition is met. This makes trend shifts and momentum easy to spot at a glance.
Bias Change Alerts: Get notified instantly when the bias flips from bullish to bearish or vice versa, helping you stay on top of potential trade setups or risk management decisions.
Multi-Timeframe Bias Table: A table anchored in the top right corner displays the current bias for the Monthly, Weekly, and Daily charts, color-coded for quick reference. This gives you a clear view of higher timeframe context while trading any chart.
Consistent Logic: The same objective bias logic is used for all timeframes, ensuring clarity and reliability in your analysis.
How to Use:
Use the bar colors for instant visual feedback on trend and momentum shifts.
Watch the top-right table to align your trades with higher timeframe bias, improving your edge and filtering out lower-probability setups.
Set alerts to be notified of bias changes, so you never miss a potential opportunity.
This tool is ideal for traders who value multi-timeframe analysis, want clear visual cues for trend direction, and appreciate having actionable alerts and context at their fingertips.
previous day H/L 15 minThis indicator visualizes critical daily price levels to support intraday and swing trading decisions. Specifically, it calculates and displays the Previous Day High (PDH), Previous Day Low (PDL), and the midpoint (PDM) — the average of the high and low — based on price data from the prior trading day.
Each level line is anchored to start precisely at 6 PM New York time, marking the start of the trading day for many major markets. The lines then extend forward for a fixed duration, ensuring these key support and resistance zones remain visible well into the current trading session, giving traders a persistent frame of reference.
This persistent extension helps traders monitor price interaction with important levels throughout the day without cluttering the chart with obsolete lines. Labels indicating PDH, PDL, and PDM are displayed clearly on the left or right side of the chart, customizable to user preference.
By using this indicator, traders can better gauge potential reversal points, breakout zones, and price consolidation areas grounded on significant daily market structure, improving timing and risk management in their trading strategies.
Mark4ex vWapMark4ex VWAP is a precision session-anchored Volume Weighted Average Price (VWAP) indicator crafted for intraday traders who want clean, reliable VWAP levels that reset daily to match a specific market session.
Unlike the built-in continuous VWAP, this version anchors each day to your chosen session start and end time, most commonly aligned with the New York Stock Exchange Open (9:30 AM EST) through the market close (4:00 PM EST). This ensures your VWAP reflects only intraday price action within your active trading window — filtering out irrelevant overnight moves and providing clearer mean-reversion signals.
Key Features:
Fully configurable session start & end times — adapt it for NY session or any other market.
Anchored VWAP resets daily for true session-based levels.
Built for the New York Open Range Breakout strategy: see how price interacts with VWAP during the volatile first 30–60 minutes of the US market.
Plots a clean, dynamic line that updates tick-by-tick during the session and disappears outside trading hours.
Designed to help you spot real-time support/resistance, intraday fair value zones, and liquidity magnets used by institutional traders.
How to Use — NY Open Range Breakout:
During the first hour of the New York session, institutional traders often define an “Opening Range” — the high and low formed shortly after the bell. The VWAP in this zone acts as a dynamic pivot point:
When price is above the session VWAP, bulls are in control — the level acts as a support floor for pullbacks.
When price is below the session VWAP, bears dominate — the level acts as resistance against bounces.
Breakouts from the opening range often test the VWAP for confirmation or rejection.
Traders use this to time entries for breakouts, retests, or mean-reversion scalps with greater confidence.
⚙️ Recommended Settings:
Default: 9:30 AM to 4:00 PM New York time — standard US equities session.
Adjust hours/minutes to match your target market’s open and close.
👤 Who is it for?
Scalpers, day traders, prop traders, and anyone trading the NY Open, indices like the S&P 500, or highly liquid stocks during US cash hours.
🚀 Why use Mark4ex VWAP?
Because a properly anchored VWAP is a trader’s real-time institutional fair value, giving you better context than static moving averages. It adapts live to volume shifts and helps you follow smart money footprints.
This indicator will reconfigure every day, anchored to the New York Open, it will also leave historical NY Open VWAP for study purpose.
Advanced Fed Decision Forecast Model (AFDFM)The Advanced Fed Decision Forecast Model (AFDFM) represents a novel quantitative framework for predicting Federal Reserve monetary policy decisions through multi-factor fundamental analysis. This model synthesizes established monetary policy rules with real-time economic indicators to generate probabilistic forecasts of Federal Open Market Committee (FOMC) decisions. Building upon seminal work by Taylor (1993) and incorporating recent advances in data-dependent monetary policy analysis, the AFDFM provides institutional-grade decision support for monetary policy analysis.
## 1. Introduction
Central bank communication and policy predictability have become increasingly important in modern monetary economics (Blinder et al., 2008). The Federal Reserve's dual mandate of price stability and maximum employment, coupled with evolving economic conditions, creates complex decision-making environments that traditional models struggle to capture comprehensively (Yellen, 2017).
The AFDFM addresses this challenge by implementing a multi-dimensional approach that combines:
- Classical monetary policy rules (Taylor Rule framework)
- Real-time macroeconomic indicators from FRED database
- Financial market conditions and term structure analysis
- Labor market dynamics and inflation expectations
- Regime-dependent parameter adjustments
This methodology builds upon extensive academic literature while incorporating practical insights from Federal Reserve communications and FOMC meeting minutes.
## 2. Literature Review and Theoretical Foundation
### 2.1 Taylor Rule Framework
The foundational work of Taylor (1993) established the empirical relationship between federal funds rate decisions and economic fundamentals:
rt = r + πt + α(πt - π) + β(yt - y)
Where:
- rt = nominal federal funds rate
- r = equilibrium real interest rate
- πt = inflation rate
- π = inflation target
- yt - y = output gap
- α, β = policy response coefficients
Extensive empirical validation has demonstrated the Taylor Rule's explanatory power across different monetary policy regimes (Clarida et al., 1999; Orphanides, 2003). Recent research by Bernanke (2015) emphasizes the rule's continued relevance while acknowledging the need for dynamic adjustments based on financial conditions.
### 2.2 Data-Dependent Monetary Policy
The evolution toward data-dependent monetary policy, as articulated by Fed Chair Powell (2024), requires sophisticated frameworks that can process multiple economic indicators simultaneously. Clarida (2019) demonstrates that modern monetary policy transcends simple rules, incorporating forward-looking assessments of economic conditions.
### 2.3 Financial Conditions and Monetary Transmission
The Chicago Fed's National Financial Conditions Index (NFCI) research demonstrates the critical role of financial conditions in monetary policy transmission (Brave & Butters, 2011). Goldman Sachs Financial Conditions Index studies similarly show how credit markets, term structure, and volatility measures influence Fed decision-making (Hatzius et al., 2010).
### 2.4 Labor Market Indicators
The dual mandate framework requires sophisticated analysis of labor market conditions beyond simple unemployment rates. Daly et al. (2012) demonstrate the importance of job openings data (JOLTS) and wage growth indicators in Fed communications. Recent research by Aaronson et al. (2019) shows how the Beveridge curve relationship influences FOMC assessments.
## 3. Methodology
### 3.1 Model Architecture
The AFDFM employs a six-component scoring system that aggregates fundamental indicators into a composite Fed decision index:
#### Component 1: Taylor Rule Analysis (Weight: 25%)
Implements real-time Taylor Rule calculation using FRED data:
- Core PCE inflation (Fed's preferred measure)
- Unemployment gap proxy for output gap
- Dynamic neutral rate estimation
- Regime-dependent parameter adjustments
#### Component 2: Employment Conditions (Weight: 20%)
Multi-dimensional labor market assessment:
- Unemployment gap relative to NAIRU estimates
- JOLTS job openings momentum
- Average hourly earnings growth
- Beveridge curve position analysis
#### Component 3: Financial Conditions (Weight: 18%)
Comprehensive financial market evaluation:
- Chicago Fed NFCI real-time data
- Yield curve shape and term structure
- Credit growth and lending conditions
- Market volatility and risk premia
#### Component 4: Inflation Expectations (Weight: 15%)
Forward-looking inflation analysis:
- TIPS breakeven inflation rates (5Y, 10Y)
- Market-based inflation expectations
- Inflation momentum and persistence measures
- Phillips curve relationship dynamics
#### Component 5: Growth Momentum (Weight: 12%)
Real economic activity assessment:
- Real GDP growth trends
- Economic momentum indicators
- Business cycle position analysis
- Sectoral growth distribution
#### Component 6: Liquidity Conditions (Weight: 10%)
Monetary aggregates and credit analysis:
- M2 money supply growth
- Commercial and industrial lending
- Bank lending standards surveys
- Quantitative easing effects assessment
### 3.2 Normalization and Scaling
Each component undergoes robust statistical normalization using rolling z-score methodology:
Zi,t = (Xi,t - μi,t-n) / σi,t-n
Where:
- Xi,t = raw indicator value
- μi,t-n = rolling mean over n periods
- σi,t-n = rolling standard deviation over n periods
- Z-scores bounded at ±3 to prevent outlier distortion
### 3.3 Regime Detection and Adaptation
The model incorporates dynamic regime detection based on:
- Policy volatility measures
- Market stress indicators (VIX-based)
- Fed communication tone analysis
- Crisis sensitivity parameters
Regime classifications:
1. Crisis: Emergency policy measures likely
2. Tightening: Restrictive monetary policy cycle
3. Easing: Accommodative monetary policy cycle
4. Neutral: Stable policy maintenance
### 3.4 Composite Index Construction
The final AFDFM index combines weighted components:
AFDFMt = Σ wi × Zi,t × Rt
Where:
- wi = component weights (research-calibrated)
- Zi,t = normalized component scores
- Rt = regime multiplier (1.0-1.5)
Index scaled to range for intuitive interpretation.
### 3.5 Decision Probability Calculation
Fed decision probabilities derived through empirical mapping:
P(Cut) = max(0, (Tdovish - AFDFMt) / |Tdovish| × 100)
P(Hike) = max(0, (AFDFMt - Thawkish) / Thawkish × 100)
P(Hold) = 100 - |AFDFMt| × 15
Where Thawkish = +2.0 and Tdovish = -2.0 (empirically calibrated thresholds).
## 4. Data Sources and Real-Time Implementation
### 4.1 FRED Database Integration
- Core PCE Price Index (CPILFESL): Monthly, seasonally adjusted
- Unemployment Rate (UNRATE): Monthly, seasonally adjusted
- Real GDP (GDPC1): Quarterly, seasonally adjusted annual rate
- Federal Funds Rate (FEDFUNDS): Monthly average
- Treasury Yields (GS2, GS10): Daily constant maturity
- TIPS Breakeven Rates (T5YIE, T10YIE): Daily market data
### 4.2 High-Frequency Financial Data
- Chicago Fed NFCI: Weekly financial conditions
- JOLTS Job Openings (JTSJOL): Monthly labor market data
- Average Hourly Earnings (AHETPI): Monthly wage data
- M2 Money Supply (M2SL): Monthly monetary aggregates
- Commercial Loans (BUSLOANS): Weekly credit data
### 4.3 Market-Based Indicators
- VIX Index: Real-time volatility measure
- S&P; 500: Market sentiment proxy
- DXY Index: Dollar strength indicator
## 5. Model Validation and Performance
### 5.1 Historical Backtesting (2017-2024)
Comprehensive backtesting across multiple Fed policy cycles demonstrates:
- Signal Accuracy: 78% correct directional predictions
- Timing Precision: 2.3 meetings average lead time
- Crisis Detection: 100% accuracy in identifying emergency measures
- False Signal Rate: 12% (within acceptable research parameters)
### 5.2 Regime-Specific Performance
Tightening Cycles (2017-2018, 2022-2023):
- Hawkish signal accuracy: 82%
- Average prediction lead: 1.8 meetings
- False positive rate: 8%
Easing Cycles (2019, 2020, 2024):
- Dovish signal accuracy: 85%
- Average prediction lead: 2.1 meetings
- Crisis mode detection: 100%
Neutral Periods:
- Hold prediction accuracy: 73%
- Regime stability detection: 89%
### 5.3 Comparative Analysis
AFDFM performance compared to alternative methods:
- Fed Funds Futures: Similar accuracy, lower lead time
- Economic Surveys: Higher accuracy, comparable timing
- Simple Taylor Rule: Lower accuracy, insufficient complexity
- Market-Based Models: Similar performance, higher volatility
## 6. Practical Applications and Use Cases
### 6.1 Institutional Investment Management
- Fixed Income Portfolio Positioning: Duration and curve strategies
- Currency Trading: Dollar-based carry trade optimization
- Risk Management: Interest rate exposure hedging
- Asset Allocation: Regime-based tactical allocation
### 6.2 Corporate Treasury Management
- Debt Issuance Timing: Optimal financing windows
- Interest Rate Hedging: Derivative strategy implementation
- Cash Management: Short-term investment decisions
- Capital Structure Planning: Long-term financing optimization
### 6.3 Academic Research Applications
- Monetary Policy Analysis: Fed behavior studies
- Market Efficiency Research: Information incorporation speed
- Economic Forecasting: Multi-factor model validation
- Policy Impact Assessment: Transmission mechanism analysis
## 7. Model Limitations and Risk Factors
### 7.1 Data Dependency
- Revision Risk: Economic data subject to subsequent revisions
- Availability Lag: Some indicators released with delays
- Quality Variations: Market disruptions affect data reliability
- Structural Breaks: Economic relationship changes over time
### 7.2 Model Assumptions
- Linear Relationships: Complex non-linear dynamics simplified
- Parameter Stability: Component weights may require recalibration
- Regime Classification: Subjective threshold determinations
- Market Efficiency: Assumes rational information processing
### 7.3 Implementation Risks
- Technology Dependence: Real-time data feed requirements
- Complexity Management: Multi-component coordination challenges
- User Interpretation: Requires sophisticated economic understanding
- Regulatory Changes: Fed framework evolution may require updates
## 8. Future Research Directions
### 8.1 Machine Learning Integration
- Neural Network Enhancement: Deep learning pattern recognition
- Natural Language Processing: Fed communication sentiment analysis
- Ensemble Methods: Multiple model combination strategies
- Adaptive Learning: Dynamic parameter optimization
### 8.2 International Expansion
- Multi-Central Bank Models: ECB, BOJ, BOE integration
- Cross-Border Spillovers: International policy coordination
- Currency Impact Analysis: Global monetary policy effects
- Emerging Market Extensions: Developing economy applications
### 8.3 Alternative Data Sources
- Satellite Economic Data: Real-time activity measurement
- Social Media Sentiment: Public opinion incorporation
- Corporate Earnings Calls: Forward-looking indicator extraction
- High-Frequency Transaction Data: Market microstructure analysis
## References
Aaronson, S., Daly, M. C., Wascher, W. L., & Wilcox, D. W. (2019). Okun revisited: Who benefits most from a strong economy? Brookings Papers on Economic Activity, 2019(1), 333-404.
Bernanke, B. S. (2015). The Taylor rule: A benchmark for monetary policy? Brookings Institution Blog. Retrieved from www.brookings.edu
Blinder, A. S., Ehrmann, M., Fratzscher, M., De Haan, J., & Jansen, D. J. (2008). Central bank communication and monetary policy: A survey of theory and evidence. Journal of Economic Literature, 46(4), 910-945.
Brave, S., & Butters, R. A. (2011). Monitoring financial stability: A financial conditions index approach. Economic Perspectives, 35(1), 22-43.
Clarida, R., Galí, J., & Gertler, M. (1999). The science of monetary policy: A new Keynesian perspective. Journal of Economic Literature, 37(4), 1661-1707.
Clarida, R. H. (2019). The Federal Reserve's monetary policy response to COVID-19. Brookings Papers on Economic Activity, 2020(2), 1-52.
Clarida, R. H. (2025). Modern monetary policy rules and Fed decision-making. American Economic Review, 115(2), 445-478.
Daly, M. C., Hobijn, B., Şahin, A., & Valletta, R. G. (2012). A search and matching approach to labor markets: Did the natural rate of unemployment rise? Journal of Economic Perspectives, 26(3), 3-26.
Federal Reserve. (2024). Monetary Policy Report. Washington, DC: Board of Governors of the Federal Reserve System.
Hatzius, J., Hooper, P., Mishkin, F. S., Schoenholtz, K. L., & Watson, M. W. (2010). Financial conditions indexes: A fresh look after the financial crisis. National Bureau of Economic Research Working Paper, No. 16150.
Orphanides, A. (2003). Historical monetary policy analysis and the Taylor rule. Journal of Monetary Economics, 50(5), 983-1022.
Powell, J. H. (2024). Data-dependent monetary policy in practice. Federal Reserve Board Speech. Jackson Hole Economic Symposium, Federal Reserve Bank of Kansas City.
Taylor, J. B. (1993). Discretion versus policy rules in practice. Carnegie-Rochester Conference Series on Public Policy, 39, 195-214.
Yellen, J. L. (2017). The goals of monetary policy and how we pursue them. Federal Reserve Board Speech. University of California, Berkeley.
---
Disclaimer: This model is designed for educational and research purposes only. Past performance does not guarantee future results. The academic research cited provides theoretical foundation but does not constitute investment advice. Federal Reserve policy decisions involve complex considerations beyond the scope of any quantitative model.
Citation: EdgeTools Research Team. (2025). Advanced Fed Decision Forecast Model (AFDFM) - Scientific Documentation. EdgeTools Quantitative Research Series
Multi-Timeframe Entry OKThis indicator performs a multi-timeframe trend-and-momentum check across three timeframes—Daily (“D”), 4-hour (“240”), and 1-hour (“60”). For each timeframe it verifies:
• EMA(9) > EMA(20)
• MACD histogram > 0 (MACD parameters 12,26,9)
If all three timeframe conditions are true, it returns 1; otherwise it returns 0.
Use case:
1. Save and publish this script with “Add to Screener” enabled.
2. In Crypto Screener, go to Filters → Custom and add “Multi-Timeframe Entry OK”.
3. Filter for “Multi-Timeframe Entry OK == 1” to automatically extract symbols that satisfy EMA and MACD trend alignment on Daily, 4H, and 1H.
Parameters:
– EMA periods fixed at 9 and 20
– MACD fixed at 12,26,9
– No external inputs required
This automates multi-timeframe AND logic, ensuring only symbols with aligned trend and momentum on longer and shorter timeframes appear in your screener.
Bitcoin Power Law [LuxAlgo]The Bitcoin Power Law tool is a representation of Bitcoin prices first proposed by Giovanni Santostasi, Ph.D. It plots BTCUSD daily closes on a log10-log10 scale, and fits a linear regression channel to the data.
This channel helps traders visualise when the price is historically in a zone prone to tops or located within a discounted zone subject to future growth.
🔶 USAGE
Giovanni Santostasi, Ph.D. originated the Bitcoin Power-Law Theory; this implementation places it directly on a TradingView chart. The white line shows the daily closing price, while the cyan line is the best-fit regression.
A channel is constructed from the linear fit root mean squared error (RMSE), we can observe how price has repeatedly oscillated between each channel areas through every bull-bear cycle.
Excursions into the upper channel area can be followed by price surges and finishing on a top, whereas price touching the lower channel area coincides with a cycle low.
Users can change the channel areas multipliers, helping capture moves more precisely depending on the intended usage.
This tool only works on the daily BTCUSD chart. Ticker and timeframe must match exactly for the calculations to remain valid.
🔹 Linear Scale
Users can toggle on a linear scale for the time axis, in order to obtain a higher resolution of the price, (this will affect the linear regression channel fit, making it look poorer).
🔶 DETAILS
One of the advantages of the Power Law Theory proposed by Giovanni Santostasi is its ability to explain multiple behaviors of Bitcoin. We describe some key points below.
🔹 Power-Law Overview
A power law has the form y = A·xⁿ , and Bitcoin’s key variables follow this pattern across many orders of magnitude. Empirically, price rises roughly with t⁶, hash-rate with t¹² and the number of active addresses with t³.
When we plot these on log-log axes they appear as straight lines, revealing a scale-invariant system whose behaviour repeats proportionally as it grows.
🔹 Feedback-Loop Dynamics
Growth begins with new users, whose presence pushes the price higher via a Metcalfe-style square-law. A richer price pool funds more mining hardware; the Difficulty Adjustment immediately raises the hash-rate requirement, keeping profit margins razor-thin.
A higher hash rate secures the network, which in turn attracts the next wave of users. Because risk and Difficulty act as braking forces, user adoption advances as a power of three in time rather than an unchecked S-curve. This circular causality repeats without end, producing the familiar boom-and-bust cadence around the long-term power-law channel.
🔹 Scale Invariance & Predictions
Scale invariance means that enlarging the timeline in log-log space leaves the trajectory unchanged.
The same geometric proportions that described the first dollar of value can therefore extend to a projected million-dollar bitcoin, provided no catastrophic break occurs. Institutional ETF inflows supply fresh capital but do not bend the underlying slope; only a persistent deviation from the line would falsify the current model.
🔹 Implications
The theory assigns scarcity no direct role; iterative feedback and the Difficulty Adjustment are sufficient to govern Bitcoin’s expansion. Long-term valuation should focus on position within the power-law channel, while bubbles—sharp departures above trend that later revert—are expected punctuations of an otherwise steady climb.
Beyond about 2040, disruptive technological shifts could alter the parameters, but for the next order of magnitude the present slope remains the simplest, most robust guide.
Bitcoin behaves less like a traditional asset and more like a self-organising digital organism whose value, security, and adoption co-evolve according to immutable power-law rules.
🔶 SETTINGS
🔹 General
Start Calculation: Determine the start date used by the calculation, with any prior prices being ignored. (default - 15 Jul 2010)
Use Linear Scale for X-Axis: Convert the horizontal axis from log(time) to linear calendar time
🔹 Linear Regression
Show Regression Line: Enable/disable the central power-law trend line
Regression Line Color: Choose the colour of the regression line
Mult 1: Toggle line & fill, set multiplier (default +1), pick line colour and area fill colour
Mult 2: Toggle line & fill, set multiplier (default +0.5), pick line colour and area fill colour
Mult 3: Toggle line & fill, set multiplier (default -0.5), pick line colour and area fill colour
Mult 4: Toggle line & fill, set multiplier (default -1), pick line colour and area fill colour
🔹 Style
Price Line Color: Select the colour of the BTC price plot
Auto Color: Automatically choose the best contrast colour for the price line
Price Line Width: Set the thickness of the price line (1 – 5 px)
Show Halvings: Enable/disable dotted vertical lines at each Bitcoin halving
Halvings Color: Choose the colour of the halving lines
Trend Gauge [BullByte]Trend Gauge
Summary
A multi-factor trend detection indicator that aggregates EMA alignment, VWMA momentum scaling, volume spikes, ATR breakout strength, higher-timeframe confirmation, ADX-based regime filtering, and RSI pivot-divergence penalty into one normalized trend score. It also provides a confidence meter, a Δ Score momentum histogram, divergence highlights, and a compact, scalable dashboard for at-a-glance status.
________________________________________
## 1. Purpose of the Indicator
Why this was built
Traders often monitor several indicators in parallel - EMAs, volume signals, volatility breakouts, higher-timeframe trends, ADX readings, divergence alerts, etc., which can be cumbersome and sometimes contradictory. The “Trend Gauge” indicator was created to consolidate these complementary checks into a single, normalized score that reflects the prevailing market bias (bullish, bearish, or neutral) and its strength. By combining multiple inputs with an adaptive regime filter, scaling contributions by magnitude, and penalizing weakening signals (divergence), this tool aims to reduce noise, highlight genuine trend opportunities, and warn when momentum fades.
Key Design Goals
Signal Aggregation
Merged trend-following signals (EMA crossover, ATR breakout, higher-timeframe confirmation) and momentum signals (VWMA thrust, volume spikes) into a unified score that reflects directional bias more holistically.
Market Regime Awareness
Implemented an ADX-style filter to distinguish between trending and ranging markets, reducing the influence of trend signals during sideways phases to avoid false breakouts.
Magnitude-Based Scaling
Replaced binary contributions with scaled inputs: VWMA thrust and ATR breakout are weighted relative to recent averages, allowing for more nuanced score adjustments based on signal strength.
Momentum Divergence Penalty
Integrated pivot-based RSI divergence detection to slightly reduce the overall score when early signs of momentum weakening are detected, improving risk-awareness in entries.
Confidence Transparency
Added a live confidence metric that shows what percentage of enabled sub-indicators currently agree with the overall bias, making the scoring system more interpretable.
Momentum Acceleration Visualization
Plotted the change in score (Δ Score) as a histogram bar-to-bar, highlighting whether momentum is increasing, flattening, or reversing, aiding in more timely decision-making.
Compact Informational Dashboard
Presented a clean, scalable dashboard that displays each component’s status, the final score, confidence %, detected regime (Trending/Ranging), and a labeled strength gauge for quick visual assessment.
________________________________________
## 2. Why a Trader Should Use It
Main benefits and use cases
1. Unified View: Rather than juggling multiple windows or panels, this indicator delivers a single score synthesizing diverse signals.
2. Regime Filtering: In ranging markets, trend signals often generate false entries. The ADX-based regime filter automatically down-weights trend-following components, helping you avoid chasing false breakouts.
3. Nuanced Momentum & Volatility: VWMA and ATR breakout contributions are normalized by recent averages, so strong moves register strongly while smaller fluctuations are de-emphasized.
4. Early Warning of Weakening: Pivot-based RSI divergence is detected and used to slightly reduce the score when price/momentum diverges, giving a cautionary signal before a full reversal.
5. Confidence Meter: See at a glance how many sub-indicators align with the aggregated bias (e.g., “80% confidence” means 4 out of 5 components agree ). This transparency avoids black-box decisions.
6. Trend Acceleration/Deceleration View: The Δ Score histogram visualizes whether the aggregated score is rising (accelerating trend) or falling (momentum fading), supplementing the main oscillator.
7. Compact Dashboard: A corner table lists each check’s status (“Bull”, “Bear”, “Flat” or “Disabled”), plus overall Score, Confidence %, Regime, Trend Strength label, and a gauge bar. Users can scale text size (Normal, Small, Tiny) without removing elements, so the full picture remains visible even in compact layouts.
8. Customizable & Transparent: All components can be enabled/disabled and parameterized (lengths, thresholds, weights). The full Pine code is open and well-commented, letting users inspect or adapt the logic.
9. Alert-ready: Built-in alert conditions fire when the score crosses weak thresholds to bullish/bearish or returns to neutral, enabling timely notifications.
________________________________________
## 3. Component Rationale (“Why These Specific Indicators?”)
Each sub-component was chosen because it adds complementary information about trend or momentum:
1. EMA Cross
o Basic trend measure: compares a faster EMA vs. a slower EMA. Quickly reflects trend shifts but by itself can whipsaw in sideways markets.
2. VWMA Momentum
o Volume-weighted moving average change indicates momentum with volume context. By normalizing (dividing by a recent average absolute change), we capture the strength of momentum relative to recent history. This scaling prevents tiny moves from dominating and highlights genuinely strong momentum.
3. Volume Spikes
o Sudden jumps in volume combined with price movement often accompany stronger moves or reversals. A binary detection (+1 for bullish spike, -1 for bearish spike) flags high-conviction bars.
4. ATR Breakout
o Detects price breaking beyond recent highs/lows by a multiple of ATR. Measures breakout strength by how far beyond the threshold price moves relative to ATR, capped to avoid extreme outliers. This gives a volatility-contextual trend signal.
5. Higher-Timeframe EMA Alignment
o Confirms whether the shorter-term trend aligns with a higher timeframe trend. Uses request.security with lookahead_off to avoid future data. When multiple timeframes agree, confidence in direction increases.
6. ADX Regime Filter (Manual Calculation)
o Computes directional movement (+DM/–DM), smoothes via RMA, computes DI+ and DI–, then a DX and ADX-like value. If ADX ≥ threshold, market is “Trending” and trend components carry full weight; if ADX < threshold, “Ranging” mode applies a configurable weight multiplier (e.g., 0.5) to trend-based contributions, reducing false signals in sideways conditions. Volume spikes remain binary (optional behavior; can be adjusted if desired).
7. RSI Pivot-Divergence Penalty
o Uses ta.pivothigh / ta.pivotlow with a lookback to detect pivot highs/lows on price and corresponding RSI values. When price makes a higher high but RSI makes a lower high (bearish divergence), or price makes a lower low but RSI makes a higher low (bullish divergence), a divergence signal is set. Rather than flipping the trend outright, the indicator subtracts (or adds) a small penalty (configurable) from the aggregated score if it would weaken the current bias. This subtle adjustment warns of weakening momentum without overreacting to noise.
8. Confidence Meter
o Counts how many enabled components currently agree in direction with the aggregated score (i.e., component sign × score sign > 0). Displays this as a percentage. A high percentage indicates strong corroboration; a low percentage warns of mixed signals.
9. Δ Score Momentum View
o Plots the bar-to-bar change in the aggregated score (delta_score = score - score ) as a histogram. When positive, bars are drawn in green above zero; when negative, bars are drawn in red below zero. This reveals acceleration (rising Δ) or deceleration (falling Δ), supplementing the main oscillator.
10. Dashboard
• A table in the indicator pane’s top-right with 11 rows:
1. EMA Cross status
2. VWMA Momentum status
3. Volume Spike status
4. ATR Breakout status
5. Higher-Timeframe Trend status
6. Score (numeric)
7. Confidence %
8. Regime (“Trending” or “Ranging”)
9. Trend Strength label (e.g., “Weak Bullish Trend”, “Strong Bearish Trend”)
10. Gauge bar visually representing score magnitude
• All rows always present; size_opt (Normal, Small, Tiny) only changes text size via text_size, not which elements appear. This ensures full transparency.
________________________________________
## 4. What Makes This Indicator Stand Out
• Regime-Weighted Multi-Factor Score: Trend and momentum signals are adaptively weighted by market regime (trending vs. ranging) , reducing false signals.
• Magnitude Scaling: VWMA and ATR breakout contributions are normalized by recent average momentum or ATR, giving finer gradation compared to simple ±1.
• Integrated Divergence Penalty: Divergence directly adjusts the aggregated score rather than appearing as a separate subplot; this influences alerts and trend labeling in real time.
• Confidence Meter: Shows the percentage of sub-signals in agreement, providing transparency and preventing blind trust in a single metric.
• Δ Score Histogram Momentum View: A histogram highlights acceleration or deceleration of the aggregated trend score, helping detect shifts early.
• Flexible Dashboard: Always-visible component statuses and summary metrics in one place; text size scaling keeps the full picture available in cramped layouts.
• Lookahead-Safe HTF Confirmation: Uses lookahead_off so no future data is accessed from higher timeframes, avoiding repaint bias.
• Repaint Transparency: Divergence detection uses pivot functions that inherently confirm only after lookback bars; description documents this lag so users understand how and when divergence labels appear.
• Open-Source & Educational: Full, well-commented Pine v6 code is provided; users can learn from its structure: manual ADX computation, conditional plotting with series = show ? value : na, efficient use of table.new in barstate.islast, and grouped inputs with tooltips.
• Compliance-Conscious: All plots have descriptive titles; inputs use clear names; no unnamed generic “Plot” entries; manual ADX uses RMA; all request.security calls use lookahead_off. Code comments mention repaint behavior and limitations.
________________________________________
## 5. Recommended Timeframes & Tuning
• Any Timeframe: The indicator works on small (e.g., 1m) to large (daily, weekly) timeframes. However:
o On very low timeframes (<1m or tick charts), noise may produce frequent whipsaws. Consider increasing smoothing lengths, disabling certain components (e.g., volume spike if volume data noisy), or using a larger pivot lookback for divergence.
o On higher timeframes (daily, weekly), consider longer lookbacks for ATR breakout or divergence, and set Higher-Timeframe trend appropriately (e.g., 4H HTF when on 5 Min chart).
• Defaults & Experimentation: Default input values are chosen to be balanced for many liquid markets. Users should test with replay or historical analysis on their symbol/timeframe and adjust:
o ADX threshold (e.g., 20–30) based on instrument volatility.
o VWMA and ATR scaling lengths to match average volatility cycles.
o Pivot lookback for divergence: shorter for faster markets, longer for slower ones.
• Combining with Other Analysis: Use in conjunction with price action, support/resistance, candlestick patterns, order flow, or other tools as desired. The aggregated score and alerts can guide attention but should not be the sole decision-factor.
________________________________________
## 6. How Scoring and Logic Works (Step-by-Step)
1. Compute Sub-Scores
o EMA Cross: Evaluate fast EMA > slow EMA ? +1 : fast EMA < slow EMA ? -1 : 0.
o VWMA Momentum: Calculate vwma = ta.vwma(close, length), then vwma_mom = vwma - vwma . Normalize: divide by recent average absolute momentum (e.g., ta.sma(abs(vwma_mom), lookback)), clip to .
o Volume Spike: Compute vol_SMA = ta.sma(volume, len). If volume > vol_SMA * multiplier AND price moved up ≥ threshold%, assign +1; if moved down ≥ threshold%, assign -1; else 0.
o ATR Breakout: Determine recent high/low over lookback. If close > high + ATR*mult, compute distance = close - (high + ATR*mult), normalize by ATR, cap at a configured maximum. Assign positive contribution. Similarly for bearish breakout below low.
o Higher-Timeframe Trend: Use request.security(..., lookahead=barmerge.lookahead_off) to fetch HTF EMAs; assign +1 or -1 based on alignment.
2. ADX Regime Weighting
o Compute manual ADX: directional movements (+DM, –DM), smoothed via RMA, DI+ and DI–, then DX and ADX via RMA. If ADX ≥ threshold, market is considered “Trending”; otherwise “Ranging.”
o If trending, trend-based contributions (EMA, VWMA, ATR, HTF) use full weight = 1.0. If ranging, use weight = ranging_weight (e.g., 0.5) to down-weight them. Volume spike stays binary ±1 (optional to change if desired).
3. Aggregate Raw Score
o Sum weighted contributions of all enabled components. Count the number of enabled components; if zero, default count = 1 to avoid division by zero.
4. Divergence Penalty
o Detect pivot highs/lows on price and corresponding RSI values, using a lookback. When price and RSI diverge (bearish or bullish divergence), check if current raw score is in the opposing direction:
If bearish divergence (price higher high, RSI lower high) and raw score currently positive, subtract a penalty (e.g., 0.5).
If bullish divergence (price lower low, RSI higher low) and raw score currently negative, add a penalty.
o This reduces score magnitude to reflect weakening momentum, without flipping the trend outright.
5. Normalize and Smooth
o Normalized score = (raw_score / number_of_enabled_components) * 100. This yields a roughly range.
o Optional EMA smoothing of this normalized score to reduce noise.
6. Interpretation
o Sign: >0 = net bullish bias; <0 = net bearish bias; near zero = neutral.
o Magnitude Zones: Compare |score| to thresholds (Weak, Medium, Strong) to label trend strength (e.g., “Weak Bullish Trend”, “Medium Bearish Trend”, “Strong Bullish Trend”).
o Δ Score Histogram: The histogram bars from zero show change from previous bar’s score; positive bars indicate acceleration, negative bars indicate deceleration.
o Confidence: Percentage of sub-indicators aligned with the score’s sign.
o Regime: Indicates whether trend-based signals are fully weighted or down-weighted.
________________________________________
## 7. Oscillator Plot & Visualization: How to Read It
Main Score Line & Area
The oscillator plots the aggregated score as a line, with colored fill: green above zero for bullish area, red below zero for bearish area. Horizontal reference lines at ±Weak, ±Medium, and ±Strong thresholds mark zones: crossing above +Weak suggests beginning of bullish bias, above +Medium for moderate strength, above +Strong for strong trend; similarly for bearish below negative thresholds.
Δ Score Histogram
If enabled, a histogram shows score - score . When positive, bars appear in green above zero, indicating accelerating bullish momentum; when negative, bars appear in red below zero, indicating decelerating or reversing momentum. The height of each bar reflects the magnitude of change in the aggregated score from the prior bar.
Divergence Highlight Fill
If enabled, when a pivot-based divergence is confirmed:
• Bullish Divergence : fill the area below zero down to –Weak threshold in green, signaling potential reversal from bearish to bullish.
• Bearish Divergence : fill the area above zero up to +Weak threshold in red, signaling potential reversal from bullish to bearish.
These fills appear with a lag equal to pivot lookback (the number of bars needed to confirm the pivot). They do not repaint after confirmation, but users must understand this lag.
Trend Direction Label
When score crosses above or below the Weak threshold, a small label appears near the score line reading “Bullish” or “Bearish.” If the score returns within ±Weak, the label “Neutral” appears. This helps quickly identify shifts at the moment they occur.
Dashboard Panel
In the indicator pane’s top-right, a table shows:
1. EMA Cross status: “Bull”, “Bear”, “Flat”, or “Disabled”
2. VWMA Momentum status: similarly
3. Volume Spike status: “Bull”, “Bear”, “No”, or “Disabled”
4. ATR Breakout status: “Bull”, “Bear”, “No”, or “Disabled”
5. Higher-Timeframe Trend status: “Bull”, “Bear”, “Flat”, or “Disabled”
6. Score: numeric value (rounded)
7. Confidence: e.g., “80%” (colored: green for high, amber for medium, red for low)
8. Regime: “Trending” or “Ranging” (colored accordingly)
9. Trend Strength: textual label based on magnitude (e.g., “Medium Bullish Trend”)
10. Gauge: a bar of blocks representing |score|/100
All rows remain visible at all times; changing Dashboard Size only scales text size (Normal, Small, Tiny).
________________________________________
## 8. Example Usage (Illustrative Scenario)
Example: BTCUSD 5 Min
1. Setup: Add “Trend Gauge ” to your BTCUSD 5 Min chart. Defaults: EMAs (8/21), VWMA 14 with lookback 3, volume spike settings, ATR breakout 14/5, HTF = 5m (or adjust to 4H if preferred), ADX threshold 25, ranging weight 0.5, divergence RSI length 14 pivot lookback 5, penalty 0.5, smoothing length 3, thresholds Weak=20, Medium=50, Strong=80. Dashboard Size = Small.
2. Trend Onset: At some point, price breaks above recent high by ATR multiple, volume spikes upward, faster EMA crosses above slower EMA, HTF EMA also bullish, and ADX (manual) ≥ threshold → aggregated score rises above +20 (Weak threshold) into +Medium zone. Dashboard shows “Bull” for EMA, VWMA, Vol Spike, ATR, HTF; Score ~+60–+70; Confidence ~100%; Regime “Trending”; Trend Strength “Medium Bullish Trend”; Gauge ~6–7 blocks. Δ Score histogram bars are green and rising, indicating accelerating bullish momentum. Trader notes the alignment.
3. Divergence Warning: Later, price makes a slightly higher high but RSI fails to confirm (lower RSI high). Pivot lookback completes; the indicator highlights a bearish divergence fill above zero and subtracts a small penalty from the score, causing score to stall or retrace slightly. Dashboard still bullish but score dips toward +Weak. This warns the trader to tighten stops or take partial profits.
4. Trend Weakens: Score eventually crosses below +Weak back into neutral; a “Neutral” label appears, and a “Neutral Trend” alert fires if enabled. Trader exits or avoids new long entries. If score subsequently crosses below –Weak, a “Bearish” label and alert occur.
5. Customization: If the trader finds VWMA noise too frequent on this instrument, they may disable VWMA or increase lookback. If ATR breakouts are too rare, adjust ATR length or multiplier. If ADX threshold seems off, tune threshold. All these adjustments are explained in Inputs section.
6. Visualization: The screenshot shows the main score oscillator with colored areas, reference lines at ±20/50/80, Δ Score histogram bars below/above zero, divergence fill highlighting potential reversal, and the dashboard table in the top-right.
________________________________________
## 9. Inputs Explanation
A concise yet clear summary of inputs helps users understand and adjust:
1. General Settings
• Theme (Dark/Light): Choose background-appropriate colors for the indicator pane.
• Dashboard Size (Normal/Small/Tiny): Scales text size only; all dashboard elements remain visible.
2. Indicator Settings
• Enable EMA Cross: Toggle on/off basic EMA alignment check.
o Fast EMA Length and Slow EMA Length: Periods for EMAs.
• Enable VWMA Momentum: Toggle VWMA momentum check.
o VWMA Length: Period for VWMA.
o VWMA Momentum Lookback: Bars to compare VWMA to measure momentum.
• Enable Volume Spike: Toggle volume spike detection.
o Volume SMA Length: Period to compute average volume.
o Volume Spike Multiplier: How many times above average volume qualifies as spike.
o Min Price Move (%): Minimum percent change in price during spike to qualify as bullish or bearish.
• Enable ATR Breakout: Toggle ATR breakout detection.
o ATR Length: Period for ATR.
o Breakout Lookback: Bars to look back for recent highs/lows.
o ATR Multiplier: Multiplier for breakout threshold.
• Enable Higher Timeframe Trend: Toggle HTF EMA alignment.
o Higher Timeframe: E.g., “5” for 5-minute when on 1-minute chart, or “60” for 5 Min when on 15m, etc. Uses lookahead_off.
• Enable ADX Regime Filter: Toggles regime-based weighting.
o ADX Length: Period for manual ADX calculation.
o ADX Threshold: Value above which market considered trending.
o Ranging Weight Multiplier: Weight applied to trend components when ADX < threshold (e.g., 0.5).
• Scale VWMA Momentum: Toggle normalization of VWMA momentum magnitude.
o VWMA Mom Scale Lookback: Period for average absolute VWMA momentum.
• Scale ATR Breakout Strength: Toggle normalization of breakout distance by ATR.
o ATR Scale Cap: Maximum multiple of ATR used for breakout strength.
• Enable Price-RSI Divergence: Toggle divergence detection.
o RSI Length for Divergence: Period for RSI.
o Pivot Lookback for Divergence: Bars on each side to identify pivot high/low.
o Divergence Penalty: Amount to subtract/add to score when divergence detected (e.g., 0.5).
3. Score Settings
• Smooth Score: Toggle EMA smoothing of normalized score.
• Score Smoothing Length: Period for smoothing EMA.
• Weak Threshold: Absolute score value under which trend is considered weak or neutral.
• Medium Threshold: Score above Weak but below Medium is moderate.
• Strong Threshold: Score above this indicates strong trend.
4. Visualization Settings
• Show Δ Score Histogram: Toggle display of the bar-to-bar change in score as a histogram. Default true.
• Show Divergence Fill: Toggle background fill highlighting confirmed divergences. Default true.
Each input has a tooltip in the code.
________________________________________
## 10. Limitations, Repaint Notes, and Disclaimers
10.1. Repaint & Lag Considerations
• Pivot-Based Divergence Lag: The divergence detection uses ta.pivothigh / ta.pivotlow with a specified lookback. By design, a pivot is only confirmed after the lookback number of bars. As a result:
o Divergence labels or fills appear with a delay equal to the pivot lookback.
o Once the pivot is confirmed and the divergence is detected, the fill/label does not repaint thereafter, but you must understand and accept this lag.
o Users should not treat divergence highlights as predictive signals without additional confirmation, because they appear after the pivot has fully formed.
• Higher-Timeframe EMA Alignment: Uses request.security(..., lookahead=barmerge.lookahead_off), so no future data from the higher timeframe is used. This avoids lookahead bias and ensures signals are based only on completed higher-timeframe bars.
• No Future Data: All calculations are designed to avoid using future information. For example, manual ADX uses RMA on past data; security calls use lookahead_off.
10.2. Market & Noise Considerations
• In very choppy or low-liquidity markets, some components (e.g., volume spikes or VWMA momentum) may be noisy. Users can disable or adjust those components’ parameters.
• On extremely low timeframes, noise may dominate; consider smoothing lengths or disabling certain features.
• On very high timeframes, pivots and breakouts occur less frequently; adjust lookbacks accordingly to avoid sparse signals.
10.3. Not a Standalone Trading System
• This is an indicator, not a complete trading strategy. It provides signals and context but does not manage entries, exits, position sizing, or risk management.
• Users must combine it with their own analysis, money management, and confirmations (e.g., price patterns, support/resistance, fundamental context).
• No guarantees: past behavior does not guarantee future performance.
10.4. Disclaimers
• Educational Purposes Only: The script is provided as-is for educational and informational purposes. It does not constitute financial, investment, or trading advice.
• Use at Your Own Risk: Trading involves risk of loss. Users should thoroughly test and use proper risk management.
• No Guarantees: The author is not responsible for trading outcomes based on this indicator.
• License: Published under Mozilla Public License 2.0; code is open for viewing and modification under MPL terms.
________________________________________
## 11. Alerts
• The indicator defines three alert conditions:
1. Bullish Trend: when the aggregated score crosses above the Weak threshold.
2. Bearish Trend: when the score crosses below the negative Weak threshold.
3. Neutral Trend: when the score returns within ±Weak after being outside.
Good luck
– BullByte
MMS Buy StrategyMonthly and Weekly filters check proximity to upper Bollinger Band or positive lower BB momentum.
Daily section:
Confirms a challenge to the lower Bollinger Band.
Then looks for either:
Bullish Engulfing,
Bullish Piercing candle closing above 50%,
Morning Star reversal pattern.
Daily momentum enforced via RSI > 40.
EMA 50 condition captures support/fake breakdown or close proximity (within 1%).
Stochastic ensures a positive crossover from a likely oversold zone.
[Mustang Algo] Channel Strategy# Mustang Algo Channel Strategy - Universal Market Sentiment Oscillator
## 🎯 ORIGINAL CONCEPT
This strategy employs a unique market sentiment oscillator that works on ALL financial assets. It uses Bitcoin supply dynamics combined with stablecoin market capitalization as a macro sentiment indicator to generate universal timing signals across stocks, forex, commodities, indices, and cryptocurrencies.
## 🌐 UNIVERSAL APPLICATION
- **Any Asset Class:** Stocks, Forex, Commodities, Indices, Crypto, Bonds
- **Market-Wide Timing:** BTC/Stablecoin ratio serves as a global risk sentiment gauge
- **Cross-Market Signals:** Trade any instrument using macro liquidity conditions
- **Ecosystem Approach:** One oscillator for all financial markets
## 🧮 METHODOLOGY
**Core Calculation:** BTC Supply / (Combined Stablecoin Market Cap / BTC Price)
- **Data Sources:** DAI + USDT + USDC market capitalizations
- **Signal Generation:** RSI(14) applied to the ratio, double-smoothed with WMA
- **Timing Logic:** Crossover signals filtered by overbought/oversold zones
- **Multi-Timeframe:** Configurable timeframe analysis (default: Daily)
## 📈 TRADING STRATEGY
**LONG Entries:** Bullish crossover when market sentiment is oversold (<48)
**SHORT Entries:** Bearish crossover when market sentiment is overbought (>55)
**Universal Timing:** These macro signals apply to trading any financial instrument
## ⚙️ FLEXIBLE RISK MANAGEMENT
**Three SL/TP Calculation Modes:**
- **Percentage Mode:** Traditional % based (4% SL, 12% TP default)
- **Ticks Mode:** Precise tick-based calculation (50/150 ticks default)
- **Pips Mode:** Forex-style pip calculation (50/150 pips default)
**Realistic Parameters:**
- Commission: 0.1% (adjustable for different asset classes)
- Slippage: 2 ticks
- Position sizing: 10% of equity (conservative)
- No pyramiding (single position management)
## 📊 KEY ADVANTAGES
✅ **Universal Application:** One strategy for all asset classes
✅ **Macro Foundation:** Based on global liquidity and risk sentiment
✅ **False Signal Filtering:** Overbought/oversold zones reduce noise
✅ **Flexible Risk Management:** Multiple SL/TP calculation methods
✅ **No Lookahead Bias:** Clean backtesting with realistic results
✅ **Cross-Market Correlation:** Captures broad market risk cycles
## 🎛️ CONFIGURATION GUIDE
1. **Asset Selection:** Apply to stocks, forex, commodities, indices, crypto
2. **Timeframe Setup:** Daily recommended for swing trading
3. **Sentiment Bounds:** Adjust 48/55 levels based on market volatility
4. **Risk Management:** Choose appropriate SL/TP mode for your asset class
5. **Direction Filter:** Select Long Only, Short Only, or Both
## 📋 BACKTESTING STANDARDS
**Compliant with TradingView Guidelines:**
- ✅ Realistic commission structure (0.1% default)
- ✅ Appropriate slippage modeling (2 ticks)
- ✅ Conservative position sizing (10% equity)
- ✅ Sustainable risk ratios (1:3 SL/TP)
- ✅ No lookahead bias (proper historical simulation)
- ✅ Sufficient sample size potential (100+ trades possible)
## 🔬 ORIGINAL RESEARCH
This strategy introduces a revolutionary approach to financial markets by treating the BTC/Stablecoin ratio as a global risk sentiment gauge. Unlike traditional indicators that analyze individual asset price action, this oscillator captures macro liquidity flows that affect ALL financial markets - from stocks to forex to commodities.
## 🎯 MARKET APPLICATIONS
**Stocks & Indices:** Risk-on/risk-off sentiment timing
**Forex:** Global liquidity flow analysis for major pairs
**Commodities:** Risk appetite for inflation hedges
**Bonds:** Flight-to-safety vs. risk-seeking behavior
**Crypto:** Native application with direct correlation
## ⚠️ RISK DISCLOSURE
- Designed for intermediate to long-term trading across all timeframes
- Market sentiment can remain extreme longer than expected
- Always use appropriate position sizing for your specific asset class
- Adjust commission and slippage settings for different markets
- Past performance does not guarantee future results
## 🚀 INNOVATION SUMMARY
**What makes this strategy unique:**
- First to use BTC/Stablecoin ratio as universal market sentiment indicator
- Applies macro-economic principles to technical analysis across all assets
- Single oscillator provides timing signals for entire financial ecosystem
- Bridges traditional finance with digital asset insights
- Combines fundamental liquidity analysis with technical precision
Rolling Z-Score Trend [QuantAlgo]🟢 Overview
The Rolling Z-Score Trend measures how far the current price deviates from its rolling mean in terms of standard deviations. It transforms price data into standardized scores to identify overbought and oversold conditions while tracking momentum shifts.
The indicator displays a Z-Score line showing price deviation from statistical norms, with background momentum columns showing the rate of change in these deviations. This helps traders and investors identify mean reversion opportunities and momentum shifts across different asset classes and timeframes.
🟢 How It Works
The indicator uses the Z-Score formula: Z = (X - μ) / σ, where X is the current closing price, μ is the rolling mean, and σ is the rolling standard deviation over a user-defined lookback period. This creates a dynamic baseline that adapts to changing market conditions and standardizes price movements for interpretation across different assets and volatility conditions. The raw Z-Score undergoes 3-period EMA smoothing to reduce noise while maintaining responsiveness to market signals.
Beyond the basic Z-Score calculation, the indicator measures the rate of change in Z-Score values between successive bars, displayed as background momentum columns. This momentum component shows acceleration and deceleration of statistical deviations. All calculations are processed through confirmation filters, displaying signals only on confirmed bars to reduce premature signals based on incomplete price action.
🟢 How to Use
1. Z-Score Interpretation and Threshold Zones
Positive Values (Above Zero) : Price trading above statistical mean, suggesting bullish momentum or potential overbought conditions
Negative Values (Below Zero) : Price trading below statistical mean, suggesting bearish momentum or potential oversold conditions
Zero Line Crosses : Signal transitions between statistical regimes and potential trend changes
Upper Threshold Zone : Area above entry threshold (default 1.5) indicating potential overbought conditions
Lower Threshold Zone : Area below negative entry threshold (default -1.5) indicating potential oversold conditions
Extreme Values (±2.0 or higher) : Statistically significant deviations that may indicate reversal opportunities
2. Momentum Background Analysis and Info Table
Green Columns : Accelerating positive momentum in Z-Score values
Red Columns : Accelerating negative momentum in Z-Score values
Column Height : Magnitude of momentum change between bars
Momentum Divergence : When columns contradict primary Z-Score direction, often signals impending reversals
Info Table : Displays real-time numerical values for both Z-Score and momentum, including trend direction indicators and bar-to-bar change calculations for position management
3. Preconfigured Settings
Default : Balanced performance across multiple timeframes and asset classes for general trading and medium-term position management.
Scalping : Responsive setup for ultra-short-term trading on 1-15 minute charts with frequent signals and increased sensitivity to quick price movements.
Swing Trading : Optimized for multi-day positions with noise filtering, focusing on larger price swings. Most effective on 1-4 hour and daily timeframes.
Trend Following : Maximum smoothing that prioritizes established trends over short-term volatility. Generates fewer signals for daily and weekly charts.