Macro-Sentiment Index Model (MSIM)Macro-Sentiment Index Model (MSIM) is a comprehensive trading strategy developed to analyze and interpret the broader macroeconomic and market sentiment. The strategy integrates various quantitative signals, including market volatility, trading volume, market breadth, and economic indicators, to assess the prevailing mood in the financial markets. This sentiment analysis is then used to guide trading decisions, helping identify optimal entry and exit points based on underlying market conditions. The model is specifically designed to capture the shifts in investor sentiment, which have been shown to significantly influence market behavior (Fleming et al., 2001).
The MSIM utilizes a multi-faceted approach to measure sentiment. Drawing from the theory that macroeconomic variables can influence financial markets (Stock & Watson, 2002), the strategy incorporates market volatility (VIX), volume measures, and long-term market trends. These indicators help form a robust view of the market’s risk appetite and potential for price movement. For instance, high volatility often signals increased market uncertainty (Bollerslev, 1986), while volume-based indicators provide insights into investor conviction (Chen, 1991).
Additionally, the model incorporates macroeconomic proxies like GDP growth, interest rates, and unemployment data, leveraging the findings of macroeconomic studies that indicate a direct correlation between these factors and market performance (Hamilton, 1994). By normalizing these economic indicators, the model provides a standardized sentiment score that reflects the aggregated impact of these factors on the market’s outlook.
The MSIM aims to exploit market inefficiencies by responding to shifts in sentiment before they manifest in price movements. Studies have shown that sentiment indicators, such as the Advance-Decline Line and the Stock-Bond Ratio, can be predictive of future price movements (Neely, 2010). The model integrates these indicators into a single composite sentiment score, which is then filtered through momentum signals to refine entry points. This approach is grounded in behavioral finance theory, which suggests that investor sentiment plays a crucial role in driving asset prices, sometimes beyond the reach of fundamental data alone (Shiller, 2000).
The strategy is designed to identify long opportunities when sentiment is particularly favorable, with a focus on minimizing risk during adverse conditions. By analyzing market trends alongside macroeconomic signals, the MSIM helps traders stay aligned with the prevailing market forces.
References:
• Bollerslev, T. (1986). Generalized autoregressive conditional heteroskedasticity. Journal of Econometrics, 31(3), 307-327.
• Chen, S. S. (1991). The determinants of stock market liquidity. Journal of Financial and Quantitative Analysis, 26(3), 283-305.
• Fleming, M. J., Kirby, C. W., & Ostdiek, B. (2001). The economic value of volatility timing. Journal of Financial and Quantitative Analysis, 36(1), 113-134.
• Hamilton, J. D. (1994). Time series analysis. Princeton University Press.
• Neely, C. J. (2010). The behavior of exchange rates: A survey of recent empirical literature. International Finance Discussion Papers, 981.
• Shiller, R. J. (2000). Irrational Exuberance. Princeton University Press.
• Stock, J. H., & Watson, M. W. (2002). Macroeconomic forecasting using diffusion indexes. Journal of Business & Economic Statistics, 20(2), 147-162.
Indicateurs et stratégies
John Bob-Trading-BotDeveloped by Ayebale John Bob with the help of his bestie, this innovative strategy combines advanced Smart Money Concepts with practical risk management tools to help traders identify and capitalize on key market moves.
Key Features:
Smart Money Concepts & Fair Value Gaps (FVG):
The strategy monitors price action for fair value gaps, which are visualized as extremely faint horizontal lines on the chart. These FVGs signal potential areas where institutional traders might have entered or exited positions.
Dynamic Entry Signals:
Buy signals are triggered when the price crosses above the 50-bar lowest low or when a bullish FVG is detected. Conversely, sell signals are generated when the price falls below the 50-bar highest high or a bearish FVG is identified. Each signal is visually marked on the chart with clear buy (green) and sell (red) labels.
Multi-Level Order Execution:
Once an entry signal occurs, the strategy places five separate orders, each with its own take-profit (TP) level. The TP levels are calculated dynamically using the Average True Range (ATR) and a set of predefined multipliers. This allows traders to scale out of positions as the market moves favorably.
Dynamic Risk Management:
A stop-loss is automatically set at a distance determined by the ATR, ensuring that risk is managed in accordance with current market volatility.
Real-Time Trade Information Table:
In the bottom-right corner of the chart, a trade information table displays essential details about the current trade:
Side: Displays "BUY NOW" (with a dark green background) for long entries or "SELL NOW" (with a dark red background) for short entries.
Entry Price & Stop-Loss: Shows the entry price (highlighted in green) and the corresponding stop-loss level (highlighted in red).
Take-Profit Levels: Lists the five TP levels, each of which turns green once the market price reaches that target.
Timer: A live timer in minutes counts from the moment the current trade trigger started, helping traders track the duration of their active trades.
Visual Progress Bar:
A histogram-style progress bar is plotted on the chart, visually representing the percentage gain (or loss) relative to the entry price.
This strategy was meticulously designed to incorporate both technical analysis and smart risk management, offering a robust trading solution that adapts to changing market conditions. Whether you're a seasoned trader or just starting out, the AyebaleJohnBob Trading Bot equips you with the tools and visual cues needed to make well-informed trading decisions. Enjoy a seamless blend of strategy and style—crafted with passion by Ayebale John Bob and his bestie!
Source StrategyThis strategy converts indicator signals into long and short entries and exits. It looks for non-zero values from your chosen entry sources to enter positions, and from exit sources to close positions.
The strategy supports both longs and shorts. For long trades, it looks at your selected long source and long exit source; for short trades, it looks at your chosen short source and short exit source. The strategy enters a position when either source produces any value except zero.
Stop loss and take profit orders are incorporated for risk management. These orders are calculated as a percentage of your position's value, providing dynamic risk management as price moves. The percentage levels for stop loss and take profit orders are configurable in the settings, allowing you to adjust your risk parameters based on market conditions and trading style.
To use the strategy, add it to your chart. The input parameters can be configured in the strategy's settings panel, including your signal sources for long and short entries and exits, and the percentage levels for stop loss and take profit orders.
Dow Theory Swing Trading-DexterThis Pine Script strategy that implements a basic price action-based trading system inspired by Dow Theory, focusing on swing highs and swing lows. This strategy will generate buy and sell signals based on the formation of higher highs (HH) and higher lows (HL) for an uptrend, and lower highs (LH) and lower lows (LL) for a downtrend.
Swing Highs and Swing Lows:
The script identifies swing highs and swing lows using the ta.highest and ta.lowest functions over a specified lookback period.
A swing high is identified when the high of the current bar is the highest high over the lookback period.
A swing low is identified when the low of the current bar is the lowest low over the lookback period.
Trend Detection:
An uptrend is detected when the current low is higher than the last identified swing low.
A downtrend is detected when the current high is lower than the last identified swing high.
Buy and Sell Signals:
A buy signal is generated when the price closes above the last swing high during an uptrend.
A sell signal is generated when the price closes below the last swing low during a downtrend.
Plotting:
Swing highs and swing lows are plotted on the chart using plotshape.
Buy and sell signals are also plotted on the chart for visual reference.
How to Use:
Copy and paste the script into the Pine Script editor in TradingView.
Adjust the lookback period as needed to suit your trading style and timeframe.
Apply the script to your chart and it will generate buy and sell signals based on the price action.
NOTE: Please uncheck the all the unwanted symbol from chart for clear view .
Delta SMA 1-Year High/Low Strategy### Summary:
This Pine Script code implements a trading strategy based on the **Delta SMA (Simple Moving Average)** of buy and sell volumes over a 1-year lookback period. The strategy identifies potential buy and sell signals by analyzing the relationship between the Delta SMA and its historical high/low thresholds. Key features include:
1. **Delta Calculation**:
- The Delta is calculated as the difference between buy volume (when close > open) and sell volume (when close < open).
- A 14-period SMA is applied to the Delta to smooth the data.
2. **1-Year High/Low Thresholds**:
- The strategy calculates the 1-year high and low of the Delta SMA.
- Buy and sell conditions are derived from thresholds set at 70% of the 1-year low and 90% and 50% of the 1-year high, respectively.
3. **Buy Condition**:
- A buy signal is triggered when the Delta SMA crosses above 0 after being below 70% of the 1-year low.
4. **Sell Condition**:
- A sell signal is triggered when the Delta SMA drops below 60% of the 1-year high after crossing above 90% of the 1-year high.
5. **Visualization**:
- The Delta SMA and its thresholds are plotted on the chart for easy monitoring.
- Optional buy/sell signals can be plotted as labels on the chart.
This strategy is designed to capture trends in volume-based momentum over a long-term horizon, making it suitable for swing or position trading.
High-Low Breakout Strategy with ATR traling Stop LossThis script is a TradingView Pine Script strategy that implements a High-Low Breakout Strategy with ATR Trailing Stop.created by SK WEALTH GURU, Here’s a breakdown of its key components:
Features and Functionality
Custom Timeframe and High-Low Detection
Allows users to select a custom timeframe (default: 30 minutes) to detect high and low levels.
Tracks the high and low within a user-specified period (e.g., first 30 minutes of the session).
Draws horizontal lines for high and low, persisting for a specified number of days.
Trade Entry Conditions
Long Entry: If the closing price crosses above the recorded high.
Short Entry: If the closing price crosses below the recorded low.
The user can choose to trade Long, Short, or Both.
ATR-Based Trailing Stop & Risk Management
Uses Average True Range (ATR) with a multiplier (default: 3.5) to determine a dynamic trailing stop-loss.
Trades reset daily, ensuring a fresh start each day.
Trade Execution and Partial Profit Taking
Stop-loss: Default at 1% of entry price.
Partial profit: Books 50% of the position at 3% profit.
Max 2 trades per day: If the first trade hits stop-loss, the strategy allows one re-entry.
Intraday Exit Condition
All positions close at 3:15 PM to ensure no overnight risk.
Ultimate Stochastics Strategy by NHBprod Use to Day Trade BTCHey All!
Here's a new script I worked on that's super simple but at the same time useful. Check out the backtest results. The backtest results include slippage and fees/commission, and is still quite profitable. Obviously the profitability magnitude depends on how much capital you begin with, and how much the user utilizes per order, but in any event it seems to be profitable according to backtests.
This is different because it allows you full functionality over the stochastics calculations which is designed for random datasets. This script allows you to:
Designate ANY period of time to analyze and study
Choose between Long trading, short trading, and Long & Short trading
It allows you to enter trades based on the stochastics calculations
It allows you to EXIT trades using the stochastics calculations or take profit, or stop loss, Or any combination of those, which is nice because then the user can see how one variable effects the overall performance.
As for the actual stochastics formula, you get control, and get to SEE the plot lines for slow K, slow D, and fast K, which is usually not considered.
You also get the chance to modify the smoothing method, which has not been done with regular stochastics indicators. You get to choose the standard simple moving average (SMA) method, but I also allow you to choose other MA's such as the HMA and WMA.
Lastly, the user gets the option of using a custom trade extender, which essentially allows a buy or sell signal to exist for X amount of candles after the initial signal. For example, you can use "max bars since signal" to 1, and this will allow the indicator to produce an extra sequential buy signal when a buy signal is generated. This can be useful because it is possible that you use a small take profit (TP) and quickly exit a profitable trade. With the max bars since signal variable, you're able to reenter on the next candle and allow for another opportunity.
Let me know if you have any questions! Please take a look at the performance report and let me know your thoughts! :)
Gold Pro StrategyHere’s the strategy description in a chat format:
---
**Gold (XAU/USD) Trend-Following Strategy**
This **trend-following strategy** is designed for trading gold (XAU/USD) by combining moving averages, MACD momentum indicators, and RSI filters to capture sustained trends while managing volatility risks. The strategy uses volatility-adjusted stops to protect gains and prevent overexposure during erratic price movements. The aim is to take advantage of trending markets by confirming momentum and ensuring entries are not made at extreme levels.
---
**Key Components**
1. **Trend Identification**
- **50 vs 200 EMA Crossover**
- **Bullish Trend:** 50 EMA crosses above 200 EMA, and the price closes above the 200 EMA
- **Bearish Trend:** 50 EMA crosses below 200 EMA, and the price closes below the 200 EMA
2. **Momentum Confirmation**
- **MACD (12,26,9)**
- **Buy Signal:** MACD line crosses above the signal line
- **Sell Signal:** MACD line crosses below the signal line
- **RSI (14 Period)**
- **Bullish Zone:** RSI between 50-70 to avoid overbought conditions
- **Bearish Zone:** RSI between 30-50 to avoid oversold conditions
3. **Entry Criteria**
- **Long Entry:** Bullish trend, MACD bullish crossover, and RSI between 50-70
- **Short Entry:** Bearish trend, MACD bearish crossover, and RSI between 30-50
4. **Exit & Risk Management**
- **ATR Trailing Stops (14 Period):**
- Initial Stop: 3x ATR from entry price
- Trailing Stop: Adjusts to lock in profits as price moves favorably
- **Position Sizing:** 100% of equity per trade (high-risk strategy)
---
**Key Logic Flow**
1. **Trend Filter:** Use the 50/200 EMA relationship to define the market's direction
2. **Momentum Confirmation:** Confirm trend momentum with MACD crossovers
3. **RSI Validation:** Ensure RSI is within non-extreme ranges before entering trades
4. **Volatility-Based Risk Management:** Use ATR stops to manage market volatility
---
**Visual Cues**
- **Blue Line:** 50 EMA
- **Red Line:** 200 EMA
- **Green Triangles:** Long entry signals
- **Red Triangles:** Short entry signals
---
**Strengths**
- **Clear Trend Focus:** Avoids counter-trend trades
- **RSI Filter:** Prevents entering overbought or oversold conditions
- **ATR Stops:** Adapts to gold’s inherent volatility
- **Simple Rules:** Easy to follow with minimal inputs
---
**Weaknesses & Risks**
- **Infrequent Signals:** 50/200 EMA crossovers are rare
- **Potential Missed Opportunities:** Strict RSI criteria may miss some valid trends
- **Aggressive Position Sizing:** 100% equity allocation can lead to large drawdowns
- **No Profit Targets:** Relies on trailing stops rather than defined exit targets
---
**Performance Profile**
| Metric | Expected Range |
|----------------------|---------------------|
| Annual Trades | 4-8 |
| Win Rate | 55-65% |
| Max Drawdown | 25-35% |
| Profit Factor | 1.8-2.5 |
---
**Optimization Recommendations**
1. **Increase Trade Frequency**
Adjust the EMAs to shorter periods:
- `emaFastLen = input.int(30, "Fast EMA")`
- `emaSlowLen = input.int(150, "Slow EMA")`
2. **Relax RSI Filters**
Adjust the RSI range to:
- `rsiBullish = rsi > 45 and rsi < 75`
- `rsiBearish = rsi < 55 and rsi > 25`
3. **Add Profit Targets**
Introduce a profit target at 1.5% above entry:
```pine
strategy.exit("Long Exit", "Long",
stop=longStopPrice,
profit=close*1.015, // 1.5% target
trail_offset=trailOffset)
```
4. **Reduce Position Sizing**
Risk a smaller percentage per trade:
- `default_qty_value=25`
---
**Best Use Case**
This strategy excels in **strong trending markets** such as gold rallies during economic or geopolitical crises. However, during sideways or choppy market conditions, the strategy might require manual intervention to avoid false signals. Additionally, integrating fundamental analysis—like monitoring USD weakness or geopolitical risks—can enhance its effectiveness.
---
This strategy offers a balanced approach for trading gold, combining trend-following principles with risk management tailored to the volatility of the market.
XAU-USD - OANDA - Updated Jan 2025 - by PB ver 5Script Title: XAU-USD - OANDA - Updated Jan 2025 - by PB ver 5
Description:
This strategy is designed for trading XAU/USD (Gold) on the OANDA platform, optimized with a session-based filter and Renko bar indicators for enhanced price action analysis. The script utilizes trailing stop loss functionality to manage risk effectively and allows flexibility for both long and short trades.
Key Features:
Date Filter: This strategy includes a time filter to backtest the performance from January 1st, 2025 to December 31st, 2025. Users can enable or disable the filter based on their preference.
Session Filter: Customizable session inputs allow the user to define the active trading session using a time range (default is 09:20-15:16) and the days of the week (default is all days, 1-7). The strategy will only enter trades during the active session, ensuring more controlled and focused trading.
Renko Bar Strategy: This strategy uses Renko charts, a popular price action tool, to detect buy and sell signals based on the crossover of Renko close and open prices. Users can adjust the Renko block size and the Renko value used for detecting price action shifts.
Trailing Stops: The script applies a trailing stop loss mechanism for both long and short trades. The trailing stop is dynamically updated to follow the market as prices move in favor of the trade. It uses a 5000-point trailing stop (adjustable by the user).
Flexible Trade Settings: Users can enable or disable long and short positions through simple toggle switches. The strategy allows for full control over trade entry and exit.
How It Works:
Long Trades: A long position is entered when the Renko close crosses above the Renko open. The position will be exited using a trailing stop, which follows the price in the market.
Short Trades: A short position is entered when the Renko close crosses below the Renko open. The position will also exit using a trailing stop.
The strategy will automatically close positions if the session ends or if the user manually exits the trades.
Customization Options:
Backtest Date Range: Set the start and end dates to backtest the strategy over a specific time period.
Session and Days: Adjust the session time and which days of the week the strategy is active.
Renko Block Size: Customize the Renko block size for finer control over price action signals.
Trailing Stop Distance: Adjust the trailing stop loss to your preferred risk levels.
Limitations and Considerations:
Renko Charting: Renko charts may not suit every trading style, as they are based on price movement rather than time. This strategy is designed for traders who prefer this style of charting.
Backtest Results: Always review the strategy's backtest results with realistic parameters. The strategy uses historical data, and past performance is not indicative of future results. Be aware of slippage and commission costs in real-world trading scenarios.
Manual Intervention: Users should monitor active trades and intervene manually if required.
Ideal Usage:
This strategy is suited for traders looking to use price action-based strategies with Renko charts for XAU/USD on the OANDA platform.
Ideal for those who want to automate their entry and exit points with trailing stop mechanisms while having control over the session time and backtesting period.
Disclaimer:
Past performance does not guarantee future results. Always use caution when using trading strategies and adjust parameters based on market conditions. The strategy is provided for educational purposes and should be tested on paper before live trading.
Statistical Arbitrage Pairs Trading - Long-Side OnlyThis strategy implements a simplified statistical arbitrage (" stat arb ") approach focused on mean reversion between two correlated instruments. It identifies opportunities where the spread between their normalized price series (Z-scores) deviates significantly from historical norms, then executes long-only trades anticipating reversion to the mean.
Key Mechanics:
1. Spread Calculation: The strategy computes Z-scores for both instruments to normalize price movements, then tracks the spread between these Z-scores.
2. Modified Z-Score: Uses a robust measure combining the median and Median Absolute Deviation (MAD) to reduce outlier sensitivity.
3. Entry Signal: A long position is triggered when the spread’s modified Z-score falls below a user-defined threshold (e.g., -1.0), indicating extreme undervaluation of the main instrument relative to its pair.
4. Exit Signal: The position closes automatically when the spread reverts to its historical mean (Z-score ≥ 0).
Risk management:
Trades are sized as a percentage of equity (default: 10%).
Includes commissions and slippage for realistic backtesting.
Tutorial - Adding sessions to strategiesA simple script to illustrate how to add sessions to trading strategies.
In this interactive tutorial, you'll learn how to add trading sessions to your strategies using Pine Script. By the end of this session (pun intended!), you'll be able to create custom trading windows that adapt to changing market conditions.
What You'll Learn:
Defining Trading Sessions: Understand how to set up specific time frames for buying and selling, tailored to your unique trading style.
RSI-Based Entry Signals: Discover how to use the Relative Strength Index (RSI) as a trigger for buy and sell signals, helping you capitalize on market trends.
Combining Session Logic with Trading Decisions: Learn how to integrate session-based logic into your strategy, ensuring that trades are executed only during designated times.
By combining these elements, we create an interactive strategy that:
1. Generates buy and sell signals based on RSI levels.
2. Checks if the market is open during a specific trading session (e.g., 1300-1700).
3. Executes trades only when both conditions are met.
**Tips & Variations:**
* Experiment with different RSI periods, thresholds, and sessions to optimize your strategy for various markets and time frames.
* Consider adding more advanced logic, such as stop-losses or position sizing, to further refine your trading approach.
Get ready to take your Pine Script skills to the next level!
~Description partially generated with Llama3_8B
FRAMA-LRO📌 FRAMA × LRO Auto-Trading Strategy - Adaptive Trend & Momentum System
Overview
This Pine Script provides an automated trading strategy that combines FRAMA (Fractal Adaptive Moving Average) and LRO (Linear Regression Oscillator) to enhance trend detection and momentum analysis. Unlike traditional moving averages, FRAMA dynamically adjusts to price volatility, while LRO effectively measures momentum for high-precision entries.
📌 Key Features
1. Dynamic Trend & Momentum Synergy
FRAMA: Detects price trends by adjusting to market conditions using fractal dimensions.
LRO: Filters trades based on linear regression slope momentum.
Breakout Confirmation: Entry is validated when price breaks FRAMA bands with LRO support.
2. Realistic Backtesting Settings
Initial Capital: $5,000 (more in line with retail traders).
Risk Management: 5% equity per trade.
Slippage & Commission: Adjusted to realistic values (1 pip slippage, 94 pips spread per trade).
Backtest Data: Covers at least 100 trades for statistical significance.
3. Clear Trade Logic
Long Entry: Price breaks above FRAMA upper band & LRO > 0.
Short Entry: Price breaks below FRAMA lower band & LRO < 0.
Stop-Loss: Dynamic ATR-based calculation.
Take-Profit: Fixed risk-reward ratio (1:2).
📌 How It Works
The system identifies trend strength with FRAMA, then confirms momentum shifts with LRO before executing trades. This ensures higher accuracy and filters false breakouts.
📌 Visual Aids for Clarity
Color-Coded Candles:
🟢 Uptrend (LRO > 0)
🔵 Downtrend (LRO < 0)
⚪ Neutral (LRO ≈ 0)
Chart Annotations: Clearly marked trade signals for easy reference.
📌 Risk Management & Automation
Fully automated execution of entries, stop-loss, and take-profit.
ATR-based volatility adaptation for dynamic SL adjustments.
Customizable parameters (period, volatility settings, risk percentage).
📌 Originality & Enhancements
This script is not just a combination of FRAMA & LRO, but an optimized system designed to:
Improve signal accuracy using adaptive trend detection.
Eliminate noise with LRO-based momentum filtering.
Implement dynamic risk management via ATR-based SL.
Influences & Acknowledgments
This strategy builds on methodologies inspired by ChartPrime and BigBeluga, refining their concepts for a systematic approach.
📌 Disclaimer
This script is for educational purposes only. Past performance does not guarantee future results. Always manage risk appropriately.
SMA + RSI + Volume + ATR StrategySMA + RSI + Volume + ATR Strategy
1. Indicators Used:
SMA (Simple Moving Average): This is a trend-following indicator that calculates the average price of a security over a specified period (50 periods in this case). It's used to identify the overall trend of the market.
RSI (Relative Strength Index): This measures the speed and change of price movements. It tells us if the market is overbought (too high) or oversold (too low). Overbought is above 70 and oversold is below 30.
Volume: This is the amount of trading activity. A higher volume often indicates strong interest in a particular price move.
ATR (Average True Range): This measures volatility, or how much the price is moving in a given period. It helps us adjust stop losses and take profits based on market volatility.
2. Conditions for Entering Trades:
Buy Signal (Green Up Arrow):
Price is above the 50-period SMA (indicating an uptrend).
RSI is below 30 (indicating the market might be oversold or undervalued, signaling a potential reversal).
Current volume is higher than average volume (indicating strong interest in the move).
ATR is increasing (indicating higher volatility, suggesting that the market might be ready for a move).
Sell Signal (Red Down Arrow):
Price is below the 50-period SMA (indicating a downtrend).
RSI is above 70 (indicating the market might be overbought or overvalued, signaling a potential reversal).
Current volume is higher than average volume (indicating strong interest in the move).
ATR is increasing (indicating higher volatility, suggesting that the market might be ready for a move).
3. Take Profit & Stop Loss:
Take Profit: When a trade is made, the strategy will set a target price at a certain percentage above or below the entry price (1.5% in this case) to automatically exit the trade once that target is hit.
Stop Loss: If the price goes against the position, a stop loss is set at a percentage below or above the entry price (0.5% in this case) to limit losses.
4. Execution of Trades:
When the buy condition is met, the strategy will enter a long position (buying).
When the sell condition is met, the strategy will enter a short position (selling).
5. Visual Representation:
Green Up Arrow: Appears on the chart when the buy condition is met.
Red Down Arrow: Appears on the chart when the sell condition is met.
These arrows help you see at a glance when the strategy suggests you should buy or sell.
In Summary:
This strategy uses a combination of trend-following (SMA), momentum (RSI), volume, and volatility (ATR) to decide when to buy or sell a stock. It looks for opportunities when the market is either oversold (buy signal) or overbought (sell signal) and makes sure there’s enough volume and volatility to back up the move. It also includes take-profit and stop-loss levels to manage risk.
Multi-Timeframe RSI Grid Strategy with ArrowsKey Features of the Strategy
Multi-Timeframe RSI Analysis:
The strategy calculates RSI values for three different timeframes:
The current chart's timeframe.
Two higher timeframes (configurable via higher_tf1 and higher_tf2 inputs).
It uses these RSI values to identify overbought (sell) and oversold (buy) conditions.
Grid Trading System:
The strategy uses a grid-based approach to scale into trades. It adds positions at predefined intervals (grid_space) based on the ATR (Average True Range) and a grid multiplication factor (grid_factor).
The grid system allows for pyramiding (adding to positions) up to a maximum number of grid levels (max_grid).
Daily Profit Target:
The strategy has a daily profit target (daily_target). Once the target is reached, it closes all open positions and stops trading for the day.
Drawdown Protection:
If the open drawdown exceeds 2% of the account equity, the strategy closes all positions to limit losses.
Reverse Signals:
If the RSI conditions reverse (e.g., from buy to sell or vice versa), the strategy closes all open positions and resets the grid.
Visualization:
The script plots buy and sell signals as arrows on the chart.
It also plots the RSI values for the current and higher timeframes, along with overbought and oversold levels.
How It Works
Inputs:
The user can configure parameters like RSI length, overbought/oversold levels, higher timeframes, grid spacing, lot size multiplier, maximum grid levels, daily profit target, and ATR length.
RSI Calculation:
The RSI is calculated for the current timeframe and the two higher timeframes using ta.rsi().
Grid System:
The grid system uses the ATR to determine the spacing between grid levels (grid_space).
When the price moves in the desired direction, the strategy adds positions at intervals of grid_space, increasing the lot size by a multiplier (lot_multiplier) for each new grid level.
Entry Conditions:
A buy signal is generated when the RSI is below the oversold level on all three timeframes.
A sell signal is generated when the RSI is above the overbought level on all three timeframes.
Position Management:
The strategy scales into positions using the grid system.
It closes all positions if the daily profit target is reached or if a reverse signal is detected.
Visualization:
Buy and sell signals are plotted as arrows on the chart.
RSI values for all timeframes are plotted, along with overbought and oversold levels.
Example Scenario
Suppose the current RSI is below 30 (oversold), and the RSI on the 60-minute and 240-minute charts is also below 30. This triggers a buy signal.
The strategy enters a long position with a base lot size.
If the price moves against the position by grid_space, the strategy adds another long position with a larger lot size (scaled by lot_multiplier).
This process continues until the maximum grid level (max_grid) is reached or the daily profit target is achieved.
Key Variables
grid_level: Tracks the current grid level (number of positions added).
last_entry_price: Tracks the price of the last entry.
base_size: The base lot size for the initial position.
daily_profit_target: The daily profit target in percentage terms.
target_reached: A flag to indicate whether the daily profit target has been achieved.
Potential Use Cases
This strategy is suitable for traders who want to combine RSI-based signals with a grid trading approach to capitalize on mean-reverting price movements.
It can be used in trending or ranging markets, depending on the RSI settings and grid parameters.
Limitations
The grid trading system can lead to significant drawdowns if the market moves strongly against the initial position.
The strategy relies heavily on RSI, which may produce false signals in strongly trending markets.
The daily profit target may limit potential gains in highly volatile markets.
Customization
You can adjust the input parameters (e.g., RSI length, overbought/oversold levels, grid spacing, lot multiplier) to suit your trading style and market conditions.
You can also modify the drawdown protection threshold or add additional filters (e.g., volume, moving averages) to improve the strategy's performance.
In summary, this script is a sophisticated trading strategy that combines RSI-based signals with a grid trading system to manage entries, exits, and position sizing. It includes features like daily profit targets, drawdown protection, and multi-timeframe analysis to enhance its robustnes
21DMTSHere's a test Pine Script that looks for the 21 ema to be rising or falling. Just really testing out if I can link a chart with a strategy.
Candle Emotion Index (CEI) StrategyThe Candle Emotion Index (CEI) Strategy is an innovative sentiment-based trading approach designed to help traders identify and capitalize on market psychology. By analyzing candlestick patterns and combining them into a unified metric, the CEI Strategy provides clear entry and exit signals while dynamically managing risk. This strategy is ideal for traders looking to leverage market sentiment to identify high-probability trading opportunities.
How It Works
The CEI Strategy is built around three core oscillators that reflect key emotional states in the market:
Indecision Oscillator . Measures market uncertainty using patterns like Doji and Spinning Tops. High values indicate hesitation, signaling potential turning points.
Fear Oscillator . Tracks bearish sentiment through patterns like Shooting Star, Hanging Man, and Bearish Engulfing. Helps identify moments of intense selling pressure.
Greed Oscillator . Detects bullish sentiment using patterns like Marubozu, Hammer, Bullish Engulfing, and Three White Soldiers. Highlights periods of strong buying interest.
These oscillators are averaged into the Candle Emotion Index (CEI):
CEI = (Indecision + Fear + Greed) / 3
This single value quantifies overall market sentiment and drives the strategy’s trading decisions.
Key Features
Sentiment-Based Trading Signals . Long Entry: Triggered when the CEI crosses above a lower threshold (e.g., 0.1), indicating increasing bullish sentiment. Short Entry: Triggered when the CEI crosses above a higher threshold (e.g., 0.2), signaling rising bearish sentiment.
Volume Confirmation . Trades are validated only if volume exceeds a user-defined multiplier of the average volume over the lookback period. This ensures entries are backed by significant market activity.
Break-Even Recovery Mechanism . If a trade moves into a loss, the strategy attempts to recover to break-even instead of immediately exiting at a loss. This feature provides flexibility, allowing the market to recover while maintaining disciplined risk management.
Dynamic Risk Management . Maximum Holding Period: Trades are closed after a user-defined number of candles to avoid overexposure to prolonged uncertainty. Profit-Taking Conditions: Positions are exited when favorable price moves are confirmed by increased volume, locking in gains. Loss Threshold: Trades are exited early if the price moves unfavorably beyond a set percentage of the entry price, limiting potential losses.
Cooldown Period . After a trade is closed, a cooldown period prevents immediate re-entry, reducing overtrading and improving signal quality.
Why Use This Strategy?
The CEI Strategy combines advanced sentiment analysis with robust trade management, making it a powerful tool for traders seeking to understand market psychology and identify high-probability setups. Its unique features, such as the break-even recovery mechanism and volume confirmation, add an extra layer of discipline and reliability to trading decisions.
Best Practices
Combine with Other Indicators . Use trend-following tools (e.g., moving averages, ADX) and momentum oscillators (e.g., RSI, MACD) to confirm signals.
Align with Key Levels . Incorporate support and resistance levels for refined entries and exits.
Multi-Market Compatibility . Apply this strategy to forex, crypto, stocks, or any asset class with strong volume and price action.
MA Crossover with Demand/Supply Zones + Stop Loss/Take ProfitStop Loss and Take Profit Inputs:
Added stopLossPerc and takeProfitPerc as inputs to allow the user to define the stop loss and take profit levels as a percentage of the entry price.
Stop Loss and Take Profit Calculation:
For long positions, the stop loss is calculated as strategy.position_avg_price * (1 - stopLossPerc), and the take profit is calculated as strategy.position_avg_price * (1 + takeProfitPerc).
For short positions, the stop loss is calculated as strategy.position_avg_price * (1 + stopLossPerc), and the take profit is calculated as strategy.position_avg_price * (1 - takeProfitPerc).
Exit Strategy:
Added strategy.exit to define the stop loss and take profit levels for each trade. The from_entry parameter ensures that the exit is tied to the specific entry order.
Flexibility:
The stop loss and take profit levels are dynamic and adjust based on the entry price of the trade.
How It Works:
When a buy signal is generated (MA crossover near a demand zone), the strategy enters a long position and sets a stop loss and take profit level based on the input percentages.
When a sell signal is generated (MA crossunder near a supply zone), the strategy enters a short position and sets a stop loss and take profit level based on the input percentages.
The trade will exit automatically if either the stop loss or take profit level is hit.
Example:
If the entry price for a long position is $100, and the stop loss is set to 1% while the take profit is set to 2%:
Stop loss level =
100
∗
(
1
−
0.01
)
=
100∗(1−0.01)=99
Take profit level =
100
∗
(
1
+
0.02
)
=
100∗(1+0.02)=102
Notes:
You can adjust the stopLossPerc and takeProfitPerc inputs to suit your risk management preferences.
Always backtest the strategy to ensure the stop loss and take profit levels are appropriate for your trading instrument and timeframe.
New intraday high with weak barStrategy Logic:
The strategy checks if the current bar’s high is the highest high of the last 10 bar and if internal bar strength is less than 0.15.
Position is closed when close is greater than the previous bar’s high.
When a position is open, the script applies a light green background on the chart to signal that you are in a trade.
IU Range Trading StrategyIU Range Trading Strategy
The IU Range Trading Strategy is designed to identify range-bound markets and take trades based on defined price ranges. This strategy uses a combination of price ranges and ATR (Average True Range) to filter entry conditions and incorporates a trailing stop-loss mechanism for better trade management.
User Inputs:
- Range Length: Defines the number of bars to calculate the highest and lowest price range (default: 10).
- ATR Length: Sets the length of the ATR calculation (default: 14).
- ATR Stop-Loss Factor: Determines the multiplier for the ATR-based stop-loss (default: 2.00).
Entry Conditions:
1. A range is identified when the difference between the highest and lowest prices over the selected range is less than or equal to 1.75 times the ATR.
2. Once a valid range is formed:
- A long trade is triggered at the range high.
- A short trade is triggered at the range low.
Exit Conditions:
1. Trailing Stop-Loss:
- The stop-loss adjusts dynamically using ATR targets.
- The strategy locks in profits as the trade moves in your favor.
2. The stop-loss and take-profit levels are visually plotted for transparency and easier decision-making.
Features:
- Automated box creation to visualize the trading range.
- Supports one position at a time, canceling opposite-side entries.
- ATR-based trailing stop-loss for effective risk management.
- Clear visual representation of stop-loss and take-profit levels with colored bands.
This strategy works best in markets with defined ranges and can help traders identify breakout opportunities when the price exits the range.
Adaptive Fractal Grid Scalping StrategyThis Pine Script v6 component implements an "Adaptive Fractal Grid Scalping Strategy" with an added volatility threshold feature.
Here's how it works:
Fractal Break Detection: Uses ta.pivothigh and ta.pivotlow to identify local highs and lows.
Volatility Clustering: Measures volatility using the Average True Range (ATR).
Adaptive Grid Levels: Dynamically adjusts grid levels based on ATR and user-defined multipliers.
Directional Bias Filter: Uses a Simple Moving Average (SMA) to determine trend direction.
Volatility Threshold: Introduces a new input to specify a minimum ATR value required to activate the strategy.
Trade Execution Logic: Places limit orders at grid levels based on trend direction and fractal levels, but only when ATR exceeds the volatility threshold.
Profit-Taking and Stop-Loss: Implements profit-taking at grid levels and a trailing stop-loss based on ATR.
How to Use
Inputs: Customize the ATR length, SMA length, grid multipliers, trailing stop multiplier, and volatility threshold through the input settings.
Visuals: The script plots fractal points and grid levels on the chart for easy visualization.
Trade Signals: The strategy automatically places buy/sell orders based on the detected fractals, trend direction, and volatility threshold.
Profit and Risk Management: The script includes logic for taking profits and setting stop-loss levels to manage trades effectively.
This strategy is designed to capitalize on micro-movements during high volatility and avoid overtrading during low-volatility trends. Adjust the input parameters to suit your trading style and market conditions.
DCA (ASAP) V0 PTTScript Name: DCA (ASAP) V0 PTT
Detailed Description:
This script implements the Dollar-Cost Averaging (DCA) strategy, allowing you to automatically manage buy/sell orders safely and efficiently. Below are the key features of this script:
1. Purpose and Operation:
o Supports both Long and Short trading modes.
o Designed to optimize profitability using the DCA method, where Safety Orders are triggered when the price moves against the predicted direction.
o Helps users maintain their Target Profit in various market conditions.
2. Main Features:
o Automatic Order Placement: The initial Base Order is opened as soon as no active order exists.
o Safety Order Management: Safety Orders are automatically placed when the price moves against the initial order. The volume and distance of these orders are customizable.
o Order Closing: Orders are closed upon reaching the Target Profit, accounting for transaction fees.
o Detailed Information Display: Displays open orders, trading statistics, and performance metrics directly on the chart.
3. Customizable Parameters:
o Base Order Size: The size of the initial order.
o Target Profit (%): Target profit as a percentage of the total order volume.
o Safety Order Size: The size of each Safety Order.
o Price Deviation (%): The percentage distance between consecutive Safety Orders.
o Safety Order Volume Scale: The scaling factor for increasing the volume of subsequent Safety Orders.
o Max Safety Orders: The maximum number of Safety Orders allowed per deal.
4. Unique Features:
o Backtest Range Support: Enables you to limit backtesting to a specific time range of interest.
o Comprehensive Statistics: Displays detailed tables including open trades, pending orders, ROI, trading days, and realized profit.
o Integrated Trading Fees: Includes transaction fees in profit calculations for precise results.
5. Usage Instructions:
o Select the trading mode (Long or Short) from the "Strategy" input.
o Customize parameters such as Base Order, Safety Order, and Target Profit according to your requirements and the asset being traded.
o Monitor the performance of the strategy through the displayed information tables.
Notes:
• This script does not disclose detailed calculation logic but provides an overview of the concepts and usage.
• Designed for trading on exchanges that support margin or spot trading.
Dynamic Ticks Oscillator Model (DTOM)The Dynamic Ticks Oscillator Model (DTOM) is a systematic trading approach grounded in momentum and volatility analysis, designed to exploit behavioral inefficiencies in the equity markets. It focuses on the NYSE Down Ticks, a metric reflecting the cumulative number of stocks trading at a lower price than their previous trade. As a proxy for market sentiment and selling pressure, this indicator is particularly useful in identifying shifts in investor behavior during periods of heightened uncertainty or volatility (Jegadeesh & Titman, 1993).
Theoretical Basis
The DTOM builds on established principles of momentum and mean reversion in financial markets. Momentum strategies, which seek to capitalize on the persistence of price trends, have been shown to deliver significant returns in various asset classes (Carhart, 1997). However, these strategies are also susceptible to periods of drawdown due to sudden reversals. By incorporating volatility as a dynamic component, DTOM adapts to changing market conditions, addressing one of the primary challenges of traditional momentum models (Barroso & Santa-Clara, 2015).
Sentiment and Volatility as Core Drivers
The NYSE Down Ticks serve as a proxy for short-term negative sentiment. Sudden increases in Down Ticks often signal panic-driven selling, creating potential opportunities for mean reversion. Behavioral finance studies suggest that investor overreaction to negative news can lead to temporary mispricings, which systematic strategies can exploit (De Bondt & Thaler, 1985). By incorporating a rate-of-change (ROC) oscillator into the model, DTOM tracks the momentum of Down Ticks over a specified lookback period, identifying periods of extreme sentiment.
In addition, the strategy dynamically adjusts entry and exit thresholds based on recent volatility. Research indicates that incorporating volatility into momentum strategies can enhance risk-adjusted returns by improving adaptability to market conditions (Moskowitz, Ooi, & Pedersen, 2012). DTOM uses standard deviations of the ROC as a measure of volatility, allowing thresholds to contract during calm markets and expand during turbulent ones. This approach helps mitigate false signals and aligns with findings that volatility scaling can improve strategy robustness (Barroso & Santa-Clara, 2015).
Practical Implications
The DTOM framework is particularly well-suited for systematic traders seeking to exploit behavioral inefficiencies while maintaining adaptability to varying market environments. By leveraging sentiment metrics such as the NYSE Down Ticks and combining them with a volatility-adjusted momentum oscillator, the strategy addresses key limitations of traditional trend-following models, such as their lagging nature and susceptibility to reversals in volatile conditions.
References
• Barroso, P., & Santa-Clara, P. (2015). Momentum Has Its Moments. Journal of Financial Economics, 116(1), 111–120.
• Carhart, M. M. (1997). On Persistence in Mutual Fund Performance. The Journal of Finance, 52(1), 57–82.
• De Bondt, W. F., & Thaler, R. (1985). Does the Stock Market Overreact? The Journal of Finance, 40(3), 793–805.
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65–91.
• Moskowitz, T. J., Ooi, Y. H., & Pedersen, L. H. (2012). Time Series Momentum. Journal of Financial Economics, 104(2), 228–250.
Volatility-Adjusted Rate of Change (VARC) ModelThe Volatility-Adjusted Rate of Change (VARC) Model is a dynamic trading strategy designed to identify potential market opportunities by incorporating volatility and skewness data. The model relies on the CBOE Skew Index (CBOE:SKEW) and adjusts the traditional Rate of Change (ROC) indicator based on market volatility, offering a more refined approach to trading based on price momentum.
1. CBOE Skew Index (SKEW) and ROC Calculation
At its core, the VARC model uses the CBOE Skew Index as a measure of market sentiment. The SKEW index represents the perceived risk of extreme negative movements in the S&P 500, providing insight into the balance of risks in the market (CBOE, 2021). This sentiment-based index is often used by traders and analysts to gauge the likelihood of a market downturn.
The Rate of Change (ROC) is applied to the Skew Index, calculated over a specified lookback period (rocLength = 29). The ROC measures the percentage change in price from one period to another and is widely used to gauge the momentum of an asset (Chande & Kroll, 1994). In the VARC model, the ROC of the Skew Index is employed to assess shifts in market sentiment that may signal turning points or potential volatility.
2. Volatility Adjustment
Volatility plays a significant role in market behavior and risk management. The VARC model uses a volatility-adjusted threshold to dynamically adjust the sensitivity of the trading signals. This is achieved by calculating the standard deviation of the ROC over a defined volatility lookback period (volatilityLookback = 20) and applying a volatility multiplier (volatilityMultiplier = 1.5). These parameters define upper and lower thresholds for trade entry and exit.
The model adjusts the sensitivity of the ROC signals based on market volatility, ensuring that the strategy adapts to changing market conditions. When volatility is high, the thresholds are widened, allowing the model to filter out noise and avoid unnecessary trades. Conversely, during periods of low volatility, the thresholds tighten, enabling the model to capture smaller price movements.
3. Entry and Exit Conditions
The VARC model generates trading signals based on the behavior of the ROC relative to the dynamically adjusted volatility thresholds. A long position is initiated when the ROC crosses below the lower threshold, indicating that the market is becoming oversold or showing signs of excessive pessimism. The position is closed when the ROC exceeds the upper threshold, signaling a potential reversal or a return to normal market conditions. These entry and exit conditions are defined as follows:
• Long Condition: The ROC is below the lower threshold (roc < dynamicThresholdLow).
• Exit Condition: The ROC is above the upper threshold (roc > dynamicThresholdHigh).
This approach provides a systematic method for entering and exiting positions based on volatility-adjusted momentum, helping traders to capitalize on shifts in market sentiment.
4. Visualization and Signal Highlighting
The model includes several visual aids to help traders interpret the signals. The ROC, dynamic thresholds, and a zero line are plotted on the chart to provide a clear representation of market momentum and the current trading range. Furthermore, a background color is used to highlight periods when a position is open, visually reinforcing the model’s decisions.
5. Conclusion
The VARC model offers a robust framework for trading by combining momentum (through the ROC) with a volatility-adjusted approach that refines trade signals based on market conditions. The use of the CBOE Skew Index adds an additional layer of market sentiment analysis, providing context to the ROC values. This volatility-adaptive strategy offers traders a more nuanced way to navigate the markets, making it suitable for both short-term and longer-term trading horizons.
References:
• CBOE. (2021). CBOE Skew Index (SKEW). Chicago Board Options Exchange. Retrieved from www.cboe.com
• Chande, T., & Kroll, J. (1994). The New Technical Trader: Boost Your Profit by Plugging into the Latest Indicators. Wiley.
This model can be particularly useful in volatile markets, where traditional fixed thresholds may not perform as well. By adjusting the thresholds dynamically based on the underlying volatility, the VARC model offers a more flexible and responsive approach to market trading.