Timeshifter Triple Timeframe Strategy w/ SessionsOverview
The "Enhanced Timeshifter Triple Timeframe Strategy with Session Filtering" is a sophisticated trading strategy designed for the TradingView platform. It integrates multiple technical indicators across three different timeframes and allows traders to customize their trading Sessions. This strategy is ideal for traders who wish to leverage multi-timeframe analysis and session-based trading to enhance their trading decisions.
Features
Multi-Timeframe Analysis and direction:
Higher Timeframe: Set to a daily timeframe by default, providing a broader view of market trends.
Trading Timeframe: Automatically set to the current chart timeframe, ensuring alignment with the trader's primary analysis period.
Lower Timeframe: Set to a 15-minute timeframe by default, offering a granular view for precise entry and exit points.
Indicator Selection:
RMI (Relative Momentum Index): Combines RSI and MFI to gauge market momentum.
TWAP (Time Weighted Average Price): Provides an average price over a specified period, useful for identifying trends.
TEMA (Triple Exponential Moving Average): Reduces lag and smooths price data for trend identification.
DEMA (Double Exponential Moving Average): Similar to TEMA, it reduces lag and provides a smoother trend line.
MA (Moving Average): A simple moving average for basic trend analysis.
MFI (Money Flow Index): Measures the flow of money into and out of a security, useful for identifying overbought or oversold conditions.
VWMA (Volume Weighted Moving Average): Incorporates volume data into the moving average calculation.
PSAR (Parabolic SAR): Identifies potential reversals in price movement.
Session Filtering:
London Session: Trade during the London market hours (0800-1700 GMT+1).
New York Session: Trade during the New York market hours (0800-1700 GMT-5).
Tokyo Session: Trade during the Tokyo market hours (0900-1800 GMT+9).
Users can select one or multiple sessions to align trading with specific market hours.
Trade Direction:
Long: Only long trades are permitted.
Short: Only short trades are permitted.
Both: Both long and short trades are permitted, providing flexibility based on market conditions.
ADX Confirmation:
ADX (Average Directional Index): An optional filter to confirm the strength of a trend before entering a trade.
How to Use the Script
Setup:
Add the script to your TradingView chart.
Customize the input parameters according to your trading preferences and strategy requirements.
Indicator Selection:
Choose the primary indicator you wish to use for generating trading signals from the dropdown menu.
Enable or disable the ADX confirmation based on your preference for trend strength analysis.
Session Filtering:
Select the trading sessions you wish to trade in. You can choose one or multiple Sessions based on your trading strategy and market focus.
Trade Direction:
Set your preferred trade direction (Long, Short, or Both) to align with your market outlook and risk tolerance. You can use this feature to gauge the market and understand the possible directions.
Tips for Profitable and Safe Trading:
Recommended Timeframes Combination:
LT: 1m , CT: 5m, HT: 1H
LT: 1-5m , CT: 15m, HT: 4H
LT: 5-15m , CT: 4H, HT: 1W
Backtesting:
Always backtest the strategy on historical data to understand its performance under various market conditions.
Adjust the parameters based on backtesting results to optimize the strategy for your specific trading style.
Risk Management:
Use appropriate risk management techniques, such as setting stop-loss and take-profit levels, to protect your capital.
Avoid over-leveraging and ensure that you are trading within your risk tolerance.
Market Analysis:
Combine the script with other forms of market analysis, such as fundamental analysis or market sentiment, to make well-rounded trading decisions.
Stay informed about major economic events and news that could impact market volatility and trading sessions.
Continuous Monitoring:
Regularly monitor the strategy's performance and make adjustments as necessary.
Keep an eye on the results and settings for real-time statistics and ensure that the strategy aligns with current market conditions.
Education and Practice:
Continuously educate yourself on trading strategies and market dynamics.
Practice using the strategy in a demo account before applying it to live trading to gain confidence and understanding.
Indicadores e estratégias
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.*
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.*
Wassim's Strat v2 (Full Auto: FVG + Asia + Fibo Zones + Alerts)This strat is from wassim where we use fvg retests as an entry and the fvg we find in discount or premium prices
Strategy [High-Low Cloud Trend] (v6, perf-safe)Description
High-Low Cloud Trend Strategy (Performance-Safe Edition)
Version 6 • RezzoRedPriest (based on the original logic by @rottor29)
How it works
Dynamic range ― The script tracks the highest high / lowest low over a look-back of N bars (len). When price tags one extreme, a “pivot” flips to the opposite extreme, forming the core of the cloud.
Trend filter ― If the candle closes above the pivot, trend = bullish; below it, trend = bearish. The optional “Trade only with trend” switch forces longs in bullish mode and shorts in bearish mode.
Signals
Cloud Retest – price pulls back to the inner edge (band1) and rejects it.
Cloud Cross – price breaks through the outer edge (band).
Mean Reversion – spikes beyond the inner edge and snap back (optional).
Execution model – trades are processed once per bar (process_orders_on_close = true), capped at maxTradesPerDay.
Performance guardrails
Only the most-recent visBars bars are calculated and painted.
Object limits: max_labels_count = 400, max_lines_count = 30.
Inputs
Group Name Purpose
Display Drawings: show last N bars Hard cap for calculations & drawings (default = 500).
Display Show markers / labels Toggle all arrows / diamonds.
Display Show cloud fill & background Toggle the colored cloud & background.
Strategy Look-back period (len) Width of the cloud; larger = smoother trend.
Strategy Enable trading Completely turn trade logic on/off.
Strategy Take cloud-retest / cross / mean-reversion signals Select which setups feed the engine.
Strategy Trade only with trend Filter counter-trend signals.
Risk Max trades per day Hard daily cap.
Recommended use
Works on any timeframe; common sweet spots are 5 m & 15 m for liquid futures / FX.
Increase len for higher timeframes (e.g. 55–100 on 1 H) to avoid noise.
If your chart still lags, either:
Lower Drawings: show last N bars, or
Turn Show cloud fill off – the fill is the heaviest operation.
Disclaimer
This script is for educational purposes only and does not constitute financial advice. Always test on demo data first and use proper risk management.
Supertrend Strategy v.1.0 (Nikko)This is the well-known Supertrend indicator, adapted for use as a strategy and updated to be compatible with Pine Script v6.
While I am not the original author of this indicator, I was curious to assess its real-world performance. The Supertrend is widely promoted by trading influencers, and I assumed many traders rely on it in their decision-making.
My goal was to stress-test the Supertrend by converting it into a strategy, to evaluate whether it could be a reliable tool to follow.
After testing it across various timeframes and assets, I found that it generally delivers poor results in terms of profitable trades. It performs somewhat better when the number of trades is kept low, but once trade frequency increases, the strategy tends to lose significantly due to its low win rate. This is an important caveat for those considering its use—be cautious, especially in high-frequency setups.
The source code is open for anyone who wants to improve or investigate further. If you identify any optimizations or bugs, feel free to share them with the community so we can all benefit.
------------------------------------------------------
How the Supertrend Indicator Works
The Supertrend indicator is a trend-following tool designed to identify whether the market is in a bullish or bearish phase. It's often used to signal potential entry and exit points for trades.
It is built on the Average True Range (ATR), a measure of volatility, and a user-defined multiplier. These inputs are used to calculate dynamic support and resistance bands:
When the price is above the Supertrend line, the trend is considered bullish.
When the price is below the Supertrend line, the trend is considered bearish.
These trend shifts can offer visual cues for trade direction, but as seen in strategy testing, the effectiveness may vary widely depending on market conditions and timeframes.
Advanced Crypto Trend Line Strategysimple trend line strategy with rsi, macd, demand and supply and volume confluence.
CST WITH ATR Custom Multiplier @ DrGSthis is the revised and updated version onf contra trend in ST with ATR of 5 and 3x multiplier. it works on the principle of selling when everyone is buying and vice versa. last modified on 20 june by Dr GS
SPY DIP StrategyCatch the best dips with this simple RSI strategy! ✅
🧠 Logic:
Buy when RSI(5) drops below 30
Close when RSI(5) climbs above 30
📈 Works well on SPY 1D — perfect for dip hunters.
🎥 Full backtest & results (vs. Buy & Hold) in this video 👉
📺 youtu.be
#RSI #TradingStrategy #SPY #Backtest #PineScript #TradingView #Stocks
DJ30 Sniper (Trend + Reversal Buy + Pyramid Recovery)
4Hours chart only ,have fun people, don't forget to leave review if you like it
Bitcoin Momentum Strategy RSI(5) > 70This One Indicator Outperforms Buy & Hold on Bitcoin (Full Backtest / 2015 - Now)
Can a single indicator really outperform the classic buy & hold strategy for Bitcoin (BTC)? In this video, we backtest a simple Bitcoin trading strategy powered by just one technical indicator, and compare its performance to long-term holding.
📊 With clear results on profit factor, drawdown, and total returns, this strategy proves that sometimes less is more — and that buy & hold isn't always the best option.
✅ In this video:
www.youtube.com
Full backtest of a 1-indicator Bitcoin strategy
Strategy vs. buy & hold performance
Drawdown, profit factor, and trade results
Works on the daily (1D) timeframe
Easy to use for beginners
Strategy:
metaduro.com
COINBASE:BTCUSD
Auto Trend Entry with SL/TP, Fake Signal & Sideways Filter🐂🐻 BULL and BEAR CHRONICLES by Lucifer
Author: Lucifer
Version: 1.0
Script Type: Overlay or Strategy (Specify which)
Tags: bullish, bearish, trend trading, market structure, Lucifer, price action, breakouts, EMA, MACD, support resistance
📖 Overview
BULL and BEAR CHRONICLES by Lucifer is more than just a trading script — it’s a real-time journal of the eternal battle between market bulls and bears. Designed to track, interpret, and visualize shifts in momentum, structure, and sentiment, this tool helps traders catch major trend transitions and avoid sideways traps.
Whether you're a trend follower, breakout trader, or simply seeking clarity in noisy markets, the Chronicles reveal which side currently holds the upper hand.
⚔️ Core Features
✅ Bull vs. Bear Detection
Based on EMA trend logic, MACD momentum, and price structure filters, such as Donchian Channels or Support/Resistance zones.
📊 Dynamic Candle & Background Coloring
Visually differentiate between bullish dominance, bearish pressure, and neutral zones.
🛡️ Sideways/Fake Signal Filter (if included)
Optional logic to block signals during choppy or low-momentum zones using slope or MACD compression.
🎯 Signal Highlights & Alerts (if applicable)
Get notified when clear breakouts or reversals occur.
🧠 How It Works
Bullish Momentum: Detected when price breaks structure, EMAs align upward, and MACD confirms momentum.
Bearish Momentum: Triggers when the trend reverses under structure with MACD confirmation.
Neutral Zone: Identified by consolidation ranges or weakening slope/momentum.
🧰 Customizable Inputs (If provided):
Donchian or lookback period
Fast/slow EMAs (e.g., 8/34)
MACD parameters
Sideways filter threshold
Volume spike or ATR filters (if included)
🧪 Best Use Cases
Swing trading in trending markets
Confirming trend reversals
Avoiding entries in choppy/no-volume zones
Visual learning and live market journaling
⚠️ Disclaimer
This tool is intended for educational and analytical purposes only. No indicator guarantees results. Use with sound risk management and test in simulation or paper trading environments before going live.
Mitbai ScalperThis strategy takes a breakout depending of a candle and after a certain number of candles above or below the initial candle, open a trade in the trend direction.
XRP 16H StrongThis XRP Trading Strategy CRUSHES Buy & Hold (675 Trades Backtested!)
Unlock the power of this simple yet powerful XRP trading strategy that outperforms the classic buy & hold method. In this video, we backtest 675 XRP trades with a profit factor of 1.46, showing how this approach delivers higher returns and lower drawdowns.
Video:
www.youtube.com
metaduro.com
AWMA StrategyStrategy Overview
This AWMA (Adaptive Weighted Moving Average) strategy combines multiple short- and long-term WMAs to generate entry signals, and uses the crossover of the average of those groups for exit signals. It’s designed to capture strong trend momentum while providing clear, rule-based exits.
Inputs
Short WMA Periods: 3, 5, 8, 10, 12, 15
Long WMA Periods: 30, 35, 40, 45, 50, 60
Position Size: percentage of equity (default 100%)
Entry Rules
Bullish Entry (Long):
The maximum value among the six short-term WMAs crosses above the minimum value among the six long-term WMAs.
At bar close, the minimum short-term WMA is still above the maximum long-term WMA (i.e. all short WMAs are stacked above all long WMAs).
When both conditions are met, the strategy places a long order and triggers a JSON-formatted alert for external bots.
Bearish Entry (Short):
The maximum short-term WMA crosses below the minimum long-term WMA.
At bar close, the maximum short-term WMA remains below the minimum long-term WMA (all short WMAs stacked below long WMAs).
Executes a short order and sends a JSON alert.
Exit Rules
Exit Long: When the average of the six short-term WMAs crosses below the average of the six long-term WMAs.
Exit Short: When the average short-term WMAs cross above the average long-term WMAs.
Exits are sent with JSON alerts containing ticker, timeframe, average WMA values, and close price.
Alerts
All alerts use the following JSON payload (suitable for Telegram bots):
json
복사
편집
{"text":" Ticker: Timeframe: …additional data…"}
Replace with one of:
“매수 신호 발생” (Long entry)
“매도 신호 발생” (Short entry)
“롱 포지션 종료” (Long exit)
“숏 포지션 종료” (Short exit)
Plots
Individual short WMAs (turquoise) and long WMAs (pink) are overlaid on price.
Average short and long WMA lines are also plotted for visualizing exit crossover points.
Use this strategy on any timeframe to catch strong trend continuations and systematic exits based on grouped WMA behavior.
Pi AIPi AI 15分鐘K線圖交易
1st設定10分鐘
2st設定15分鐘
MA source設定指數移動
Use ADX and DMI 打勾取消
可以搭配布林帶使用
交易建議一定要設定
止盈設定25%
止損設定9%
Pi AI 15-minute candlestick chart trading
1st set to 10 minutes
2nd set to 15 minutes
MA source set to exponential movement
Use ADX and DMI check to cancel
Can be used with Bollinger Bands
Trading suggestions must be set
Take profit set to 25%
Stop loss set to 9%
15m Breakout w/ % SL + Min HoldThis 15-minute breakout strategy identifies the prior period’s swing high and swing low over a user-defined lookback, plotting them as entry thresholds. Trades execute only within a specified session and align with the EMA trend: longs above the EMA, shorts below. Upon entry, a fixed percentage stop-loss immediately caps risk. After holding for a minimum number of bars, the strategy replaces the hard stop with an ATR-based trailing stop—triggered once the specified hold-time elapses—to lock in profits as momentum continues. By combining breakout triggers, trend filtering, hard stops, and delayed trailing exits, it provides disciplined risk management and profit capture.
Valtoro Adaptive Momentum//@version=5
strategy("Valtoro Adaptive Momentum", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// === Inputs ===
lengthFast = input.int(14, title="Fast EMA")
lengthSlow = input.int(28, title="Slow EMA")
rsiPeriod = input.int(14, title="RSI Period")
atrPeriod = input.int(14, title="ATR Period")
riskMultiplier = input.float(1.5, title="Volatility Threshold Multiplier", step=0.1)
rsiOB = input.int(70, title="RSI Overbought")
rsiOS = input.int(30, title="RSI Oversold")
// === Indicators ===
fastEMA = ta.ema(close, lengthFast)
slowEMA = ta.ema(close, lengthSlow)
rsi = ta.rsi(close, rsiPeriod)
atr = ta.atr(atrPeriod)
avgATR = ta.sma(atr, atrPeriod)
// === Conditions ===
longCond = ta.crossover(fastEMA, slowEMA) and rsi < rsiOB and atr > avgATR * riskMultiplier
shortCond = ta.crossunder(fastEMA, slowEMA) and rsi > rsiOS and atr > avgATR * riskMultiplier
// === Risk Management ===
longSL = close * 0.98 // 2% Stop Loss
longTP = close * 1.05 // 5% Take Profit
shortSL = close * 1.02
shortTP = close * 0.95
// === Strategy Entries and Exits ===
if (longCond)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", from_entry="Long", stop=longSL, limit=longTP)
if (shortCond)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", from_entry="Short", stop=shortSL, limit=shortTP)
// === Visuals ===
plot(fastEMA, title="Fast EMA", color=color.blue)
plot(slowEMA, title="Slow EMA", color=color.red)
hline(rsiOB, "RSI Overbought", color=color.red)
hline(rsiOS, "RSI Oversold", color=color.green)
🔥 Nikko Ultra-Active Scalper (MACD + RSI)🔥 Nikko Ultra-Active Scalper (MACD + RSI)
This is a fun, high-frequency scalper with some unpredictable results in backtesting. II recommend you backtest it over a 1-year period with CRYPTOCAP:SUI to see for yourself.
While the strategy works in live conditions, there seems to be a strange issue with how TradingView calculates the backtesting (the Hold blue line behaves oddly). It might be due to certain factors in the script's execution, but I’m not entirely sure. Sor example I get a negative PNL while making profit? That is weird. I might have missed something.
I’ve not encrypted the source code, so I’m hoping someone in the community can help identify why the backtest results are behaving unexpectedly.
Enjoy experimenting with this little bot, use 1m-2n timeframe— and while it’s fun to imagine getting rich with minimal effort, remember, it’s just for entertainment and educational purposes!
----------------------------------------------
DESCRIPTION: READ FIRST
This script is a high-frequency trading strategy written in Pine Script v6 for use on TradingView, designed to open several long positions per day on fast-moving markets like crypto. Here's how it works:
📌 Strategy Overview:
It uses short-term technical indicators — MACD and RSI — to detect brief momentum bursts, enters trades quickly, and exits with a tight take-profit. It’s optimized for 1-minute timeframes.
🧠 Entry Conditions (When it Buys):
The strategy opens a long position when:
MACD > Signal Line using fast settings (6,13,5):
This shows short-term upward momentum.
RSI > 40 with a 7-period length:
This confirms bullish strength, even if modest.
Because the settings are very relaxed, this combination triggers frequently, producing multiple trades per day.
🎯 Exit Condition (When it Sells):
It closes all open positions when:
The price rises to a set profit target (takeProfitPercent, default 0.9%).
There is no stop loss or trailing stop — this means the trade will stay open until it either hits the profit or you close manually (or modify the script).
⚙️ Other Features:
pyramiding = 100
Allows up to 100 simultaneous open positions (great for scalping in volatile uptrends).
strategy.percent_of_equity = 1
Each trade uses 1% of available equity, but can be adjusted.
Visual Bar Coloring
Bars turn green when an entry condition is met (barcolor(entryCond ? color.lime : na)).
📈 Designed For:
1-2 minute(S) timeframes
Volatile assets (crypto, meme coins, high-volume stocks)
High-frequency trading where you're in/out fast with small gains
IKODO Breakout Strategy📈 IKODO Breakout Strategy – Customizable Candle-Based Breakout Detector
This indicator is designed to detect breakout opportunities based on your preferred candle range.
Whether you're a scalper looking for short-term moves or a swing trader waiting for longer consolidations, you can fully customize the number of candles used to define the breakout window.
🔧 Features:
Adjustable breakout period (define how many candles the price should consolidate before a breakout is valid)
Works on all timeframes and assets
Ideal for identifying breakout zones and potential trend initiations
🎯 How It Works: The indicator analyzes price action within the defined candle range and highlights breakout points when price exceeds the established high/low thresholds.
This gives traders clear signals when a breakout from a range is statistically significant.
💡 Tip: Combine with volume or momentum indicators for more confluence.
Not Financal advice
SniperMA Scalper (Long Only, Clean)use on 15s chart and back test from 01.01 2024 100.000k good luck and don't forget to like if you find good results
[alert-custome] direction-ema-dca-rsi-security
Below is a detailed description of the Pine Script v5 strategy titled direction-ema-dca-rsi-security. This strategy automates Long or Short trading on cryptocurrency pairs (e.g., BTCUSDT.P), leveraging technical indicators such as EMA, RSI, and ATR, combined with a Dollar Cost Averaging (DCA) approach. It integrates with OKX via alerts for automated trading execution.
Overview
Strategy Name: direction-ema-dca-rsi-security
Objective: Automate Long or Short trades using EMA, RSI, and ATR signals, with DCA to improve average position price when the market moves against the position. The strategy allows customization of trade direction (Long or Short) and integrates with OKX for automated execution.
Type: Supports both Long and Short trades, using leverage and flexible capital management.
Target Market: Designed for high-volatility cryptocurrency markets, particularly perpetual futures pairs like BTCUSDT.P.
Key Features:
Uses Fast and Slow EMAs to identify trends and entry points.
Combines RSI from the current timeframe and a user-defined timeframe (security RSI) to detect overbought/oversold conditions.
Implements DCA to add to positions when prices move unfavorably.
Integrates with OKX via JSON alerts for automated trading.
Supports Take Profit (TP) and Stop Loss (SL) based on ATR or percentage values.
Structure and Key Components
1. Strategy Configuration
Basic Settings:
Initial Capital: $1,000.
Leverage: Default 6x, adjustable from 1x to 10x.
Order Type: Cash-based, with a default quantity of 10.
Commission: 0.1% per trade.
Pyramiding: Allows up to 100 concurrent orders.
Slippage: 3 pips.
Backtest Fill Limits Assumption: 3 pips, ensuring limit orders are filled within a price range.
Calculate on Order Fills: Enabled (calc_on_order_fills = true).
Use Bar Magnifier: Enabled for detailed candle data calculations.
Fill Orders on Standard OHLC: Enabled, ensuring orders match standard open, high, low, close prices.
2. Input Parameters
The strategy offers customizable inputs, grouped as follows:
Strategy:
Fast/Slow EMA Length: Fast EMA (default 9), Slow EMA (default 21) for trend detection.
ATR Length: Default 14 for volatility measurement.
RSI Length: Default 14 for overbought/oversold detection.
RSI Security Timeframe: Default 15 minutes (options: 5m, 15m, 30m, 1h, 4h, D, W, M).
Direction Security Timeframe: Default daily (options: 4h, D, W, M).
Strategy Size:
Init Webhook Balance ($): Initial balance for webhook (default 0, uses strategy balance if unset).
Leverage: Financial leverage (default 6x).
Init Size Equity (%): Initial position size as a percentage of equity (default 2%).
Size Increase (%): Position size increase per DCA order (default 15%).
Max DCA Orders: Maximum DCA orders (default 15).
Strategy DCA:
Init Percent to DCA (%): Initial price drop/rise for DCA (default 2%).
Increase Step Percent to DCA (%): Incremental DCA price adjustment (default 1%).
Decrease DCA with ATR: ATR multiplier for DCA price (default 0, disabled).
Strategy DCA RSI:
RSI to DCA: RSI threshold for DCA (default 50, below for Long, above for Short).
Security RSI to DCA: RSI threshold for security timeframe (default 50).
Strategy Delay:
Off-Time Delays / Order (s): Delay between orders (default 1000 seconds).
Off-Time Active Stop Loss (Hour): Delay for activating Stop Loss (default 0, disabled).
Strategy TPSL (Take Profit/Stop Loss):
ATR Multiplier TP: ATR multiplier for Take Profit (default 2x).
Init TP (%): Initial Take Profit percentage (default 2%).
ATR Multiplier SL: ATR multiplier for Stop Loss (default 0, disabled).
Init SL (%): Initial Stop Loss percentage (default 0%, disabled).
Strategy Direction:
Trade Direction: Trade direction (default Long, options: Long, Short).
Strategy OKX:
OKX Signal Key: Signal key for OKX API integration.
3. Market Data
Technical Indicators:
EMA: Fast EMA (9) and Slow EMA (21) on the current timeframe for trend identification.
RSI: RSI (14) on the current timeframe and a user-defined timeframe (rsiSecurityTimeframe) for overbought/oversold signals.
ATR: ATR (14) for volatility-based calculations of TP, SL, and DCA prices.
External Library: Uses jason5480/chrono_utils/6 for time-related functions.
4. Entry Conditions
Long Position:
Condition 1: Fast EMA crosses above Slow EMA (ta.crossover(fastMA, slowMA)), or
Condition 2: RSI ≤ rsiTrigger (default 50), Fast EMA ≤ Slow EMA, and RSI security ≤ rsiSecurityTrigger (default 50).
Short Position:
Condition 1: Fast EMA crosses below Slow EMA (ta.crossunder(fastMA, slowMA)), or
Condition 2: RSI ≥ rsiTrigger, Fast EMA ≥ Slow EMA, and RSI security ≥ rsiSecurityTrigger.
Constraints:
Entries are allowed only if tradeDirection matches the signal (Long or Short).
Open trades ≤ maxDCAOrders (default 15).
Current price meets DCA conditions (if positions exist).
Time since last order ≥ offTimeMsOpen (default 1000 seconds).
5. Dollar Cost Averaging (DCA)
DCA Conditions:
Long: Current price ≤ DCA price, calculated as:
strategy.position_avg_price - (atrValue * decreaseDCAWithATR), or
strategy.position_avg_price * (1 - currentUnderPercentDCA) (default 2%, increasing by 1% per DCA).
Short: Current price ≥ DCA price, calculated similarly but for price increases.
DCA Management:
Position size increases by 15% per DCA (stepSizePercent).
DCA price distance increases by 1% per order (stepDecreasePercentDCA).
Maximum 15 DCA orders (maxDCAOrders).
6. Position Management
Position Size:
Initial size: 2% of equity (initSizeEquity).
Increases by 15% per DCA order.
Limited by leverage and current balance (currentBalance).
Current Balance:
If webhookInitBalance = 0, uses initial_capital + netprofit + openprofit.
If webhookInitBalance > 0, uses this value plus net and open profits.
Order Delay: Ensures a minimum gap of 1000 seconds between orders (offTimeMsOpen).
7. Exit Conditions
Take Profit (TP):
Long: strategy.position_avg_price + (atrValue * atrMultiplierTP) (default 2x ATR), or strategy.position_avg_price * (1 + initTP) (default 2%).
Short: strategy.position_avg_price - (atrValue * atrMultiplierTP), or strategy.position_avg_price * (1 - initTP).
Stop Loss (SL):
Long: strategy.position_avg_price - (atrValue * atrMultiplierSL), or strategy.position_avg_price * (1 - initSL).
Short: strategy.position_avg_price + (atrValue * atrMultiplierSL), or strategy.position_avg_price * (1 + initSL).
Currently, atrMultiplierSL and initSL = 0, meaning Stop Loss is disabled.
Exit Execution:
Uses strategy.order for Long TP and strategy.exit for Short TP, closing the entire position when TP is reached.
Sends OKX alerts for exits (EXIT_LONG or EXIT_SHORT).
8. Visualization
Plots:
Fast EMA: Red.
Slow EMA: Aqua.
Take Profit Price: Lime.
Position Average Price: Gray.
Background Color: Commented out, but can display green for Long or red for Short.
9. OKX Integration
Alerts:
Sends JSON alerts for entries (ENTER_LONG, ENTER_SHORT) and exits (EXIT_LONG, EXIT_SHORT), including:
Market position, size, order type (market), and investment percentage.
OKX signal key (okxSignalKeyInput) for API integration.
How the Strategy Works
Market Analysis:
Uses EMA (9, 21) for trend detection (crossover/crossunder).
Combines RSI from the current and security timeframes to confirm overbought/oversold conditions.
ATR measures volatility for TP, SL, and DCA price calculations.
Entry:
Long: Triggers on EMA crossover or RSI in oversold territory with a bearish trend.
Short: Triggers on EMA crossunder or RSI in overbought territory with a bullish trend.
Entries are restricted by tradeDirection setting.
DCA:
Adds positions when price moves against the trade (down for Long, up for Short) based on RSI or ATR conditions.
Increases position size and DCA price distance per order.
Exit:
Closes positions when price hits TP (ATR or percentage-based).
Stop Loss is currently disabled, posing a risk.
Risk Management:
Limits DCA orders to 15.
Enforces time delays between orders.
Caps leverage at 10x.
Strengths
Flexible Direction: Supports both Long and Short trades.
Effective DCA: Improves average position price in volatile markets.
OKX Integration: Automates trading via OKX API.
Multi-Timeframe Analysis: Uses RSI from a secondary timeframe for confirmation.
Customizable Capital Management: Adjustable position sizes and leverage.
Weaknesses
No Stop Loss: Disabled SL increases risk of large losses.
OKX Dependency: Requires accurate API configuration.
Simple Conditions: Relies primarily on EMA and RSI, potentially lacking depth.
Fixed Timeframes: Commented-out EMA security logic limits trend analysis flexibility.
Practical Applications
Target Market: High-volatility crypto markets, especially perpetual futures like BTCUSDT.P.
Trading Style: Suitable for short- to medium-term traders using DCA for risk management.
Optimization: Adjust fastMALen, slowMALen, rsiTrigger, or maxDCAOrders for specific markets.
Improvement Suggestions
Enable Stop Loss: Set atrMultiplierSL or initSL > 0 to protect capital.
Use EMA Security: Uncomment fastDirectionEMA and slowDirectionEMA code to enhance trend accuracy.
Optimize Parameters: Use TradingView’s optimization tool to fine-tune rsiTrigger, atrMultiplierTP, or maxDCAOrders.
Add Indicators: Incorporate Volume, ADX, or other indicators for robust entry signals.
Leverage Alerts: Add warnings for high-leverage risks in volatile conditions.
If you need further analysis, code optimization, or additional strategy development, let me know!
NA GPT - TTM Squeeze Strategy**NA GPT - TTM Squeeze Strategy**” transforms the well-known TTM Squeeze indicator into a back-testable, long-only strategy.
It combines **volatility compression** (Bollinger Bands inside Keltner Channels) with **momentum confirmation** to catch powerful bullish breakouts and then trails positions with a simple 21-period moving-average stop.
---
## 1. Core Concepts & Calculations
| Component | What it measures | How it works |
| ---------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Squeeze State** | Volatility contraction vs. expansion | • Calculate a 20-period Bollinger Band (BB). • Calculate a 20-period Keltner Channel (KC). • **Squeeze ON** when the entire BB is *inside* the KC (narrow volatility). |
| **Momentum Histogram** | Direction & strength of pressure building inside the squeeze | • Compute the midpoint of the recent high/low range and the 20-period SMA of close. • Take the price’s deviation from that blended average. • Fit a **20-period linear regression** to that deviation to produce the histogram. • Color logic: ↗ increasing green/lime for strengthening bulls, ↘ red/maroon for bears. |
| **Blue-Dot Theme** | Visual cue of squeeze state | • **Navy-blue dot** = Squeeze ON (ready to pop). • **Steel-blue dot** = Squeeze just released. • **Sky-blue dot** = Neutral (no squeeze). |
---
## 2. Trade Logic
| Step | Condition | Rationale |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **Entry (Long)** | Three consecutive navy-blue dots (i.e., **3 bars with Squeeze ON in a row**) *inside the user-defined date window*. | Requires sustained volatility compression before committing capital, filtering out one-bar “fake” squeezes. |
| **Exit (Flat)** | Close price **crosses below** the 21-period Simple Moving Average. | A classic trailing stop that lets profits run while cutting momentum failures. |
| **Positioning** | Long-only, one trade at a time. No short sales. | Focuses on bullish breakouts, keeps strategy simple and margin-friendly. |
---
## 3. Inputs & Customisation
| Input | Default | Purpose |
| -------------------------- | ------------------------ | ---------------------------------------------- |
| **BB Length / Multiplier** | 20 / 2.0 | Adjust sensitivity of Bollinger Bands. |
| **KC Length / Multiplier** | 20 / 1.5 | Adjust Keltner Channel width. |
| **Use True Range (KC)** | ✔ | Pick *True Range* vs. *High-Low* for KC width. |
| **Trade Window** | 1 Jan 2022 → 31 Dec 2069 | Back-test only the period you care about. |
| **Commission** | 0.01 % | Embedded in `strategy()` header. |
| **Slippage (Ticks)** | 3 | Models real-world order fill uncertainty. |
---
## 4. Visual Outputs
* **Momentum Histogram** (green / lime / red / maroon).
* **Zero Line** colored by squeeze state (blue / dark navy / grey).
* **Blue-Dot Row** at the chart bottom showing squeeze timing.
The visuals are **identical** to the original indicator, letting you correlate back-test trades with familiar chart cues.
---
## 5. How to Use
1. **Add to chart**, choose your symbol & timeframe (works on anything from 1-minute to weekly).
2. **Tune the BB/KC/ATR settings** to match instrument volatility.
3. **Adjust the date window** for focused walk-forward testing.
4. Run the “**Strategy Tester**” to inspect historical performance, P\&L; curves, drawdowns, and trade list.
5. Use the plotted dots & histogram to visually validate why each trade fired.
6. Combine with your own risk-management (position sizing, portfolio filters, etc.) before going live.
---
## 6. Practical Notes
* Designed for educational/back-testing purposes—**not financial advice**.
* Long-only by design; add your own short logic if desired.
* Because exits rely on the 21-SMA, extremely low-volume instruments or illiquid intraday timeframes may experience wider drawdowns.
* Commission/slippage values are easily editable in the first line of the script.