Custom EMAs, SMA y VWAP con Puntos en CrucesHighly configurable moving average indicator for each person's trading strategy.
Indicators and strategies
Enhanced 3-Month Reversal Strategy v6 (TSLA)### **Strategy Overview: Enhanced 3-Month Reversal Strategy v6 for TSLA**
This custom-designed strategy is tailored specifically for **Tesla Inc. (TSLA)**, incorporating a multi-factor scoring model to capture short-term mean-reversion opportunities within a broader trend-aware framework.
---
### **Methodology**
The strategy blends **technical reversal signals** with **trend filtering** and **volatility-adjusted risk management**. It assigns dynamic weights to six core technical indicators for both long and short entries:
- **RSI (7-period):** Identifies overbought/oversold conditions based on percentile ranks.
- **MACD (8/17/9):** Captures short-term momentum shifts with trend confirmation.
- **ADX (14):** Ensures trades are taken only in strong trending environments.
- **Volume Spike:** Confirms breakout or reversal intensity.
- **SMA Crossovers (20 & 50):** Filters trend direction on a medium scale.
- **Implied Volatility Rank (126-period HV proxy):** Measures relative volatility levels to confirm timing.
All inputs are scored based on weighted signals, and trades are only entered when the composite score exceeds a defined threshold.
---
### **Features**
- ✅ **Volatility-based dynamic stop-loss and take-profit** for adaptive risk management.
- ✅ **Intraday trading window filter** to restrict trades to regular market hours (default: 9AM–4PM EST).
- ✅ **Trend filter (200-SMA)** to allow long trades only in bullish markets.
- ✅ **Score threshold parameters** are fully adjustable for optimization.
- ✅ **Individual trade P&L tracking** via chart annotations.
---
### **Backtest Summary**
- **Time period:** Backtested on TSLA from **January 2022 to March 2025**.
- **Data granularity:** 15-minute and 1-hour timeframes show best performance consistency.
- **Market regime:** Performs well in both trending and volatile mean-reversion phases.
---
### **Best Input Parameters (from hyperparameter tuning)**
**Long Entry Weights:**
- RSI: `0.35`
- IV Rank: `0.10`
- MACD: `0.15`
- SMA Condition: `0.25`
- ADX: `0.15`
- Volume Spike: `0.25`
**Short Entry Weights:**
- RSI: `0.20`
- IV Rank: `0.15`
- MACD: `0.30`
- SMA Condition: `0.00`
- ADX: `0.15`
- Volume Spike: `0.30`
**Other Settings:**
- MACD Signal Period: `9`
- RSI Length: `7`
- IV Period: `126`
- SMA Periods: `20 & 50`
- Trend Filter SMA: `200`
- Stop Loss / Take Profit: `1.0 × HV` multiplier
---
--- Optuna 优化完成 ---
最佳 Trial 编号: 29
最佳 Total Return : 17927.75678703037
最佳参数:
rsi_length: 13
iv_length: 140
macd_fast: 7
macd_slow: 30
adx_length: 25
sma_short_period: 21
sma_long_period: 78
volume_ma_period: 14
rsi_low_percentile: 21
rsi_high_percentile: 60
iv_low_percentile: 11
iv_high_percentile: 89
take_profit_mult: 4.0
stop_loss_mult: 5.0
bullish_threshold: 0.65
bearish_threshold: 0.9
rsi_bull_weight: 0.5
iv_bull_weight: 0.25
macd_bull_weight: 0.30000000000000004
sma_bull_weight: 0.1
adx_bull_weight: 0.0
volume_bull_weight: 0.3
rsi_bear_weight: 0.5
iv_bear_weight: 0.2
macd_bear_weight: 0.15000000000000002
sma_bear_weight: 0.1
adx_bear_weight: 0.1
volume_bear_weight: 0.15000000000000002
macd_signal: 9
Bollinger Band Long & Short Strategy### **Strategy Summary: Bollinger Band Long & Short Strategy**
#### **Bollinger Band Setup:**
- Uses a **20-period Simple Moving Average (SMA)** as the basis.
- **Standard deviation multiplier = 1.5**.
- Calculates **upper** and **lower Bollinger Bands**.
#### **Entry Conditions:**
- **Short Trade:**
- A candle must fully form **above** the upper Bollinger Band.
- The **low of this candle** must be broken by one of the **next four candles**.
- A **short position** is then entered.
- **Long Trade:**
- A candle must fully form **below** the lower Bollinger Band.
- The **high of this candle** must be broken by one of the **next four candles**.
- A **long position** is then entered.
#### **Risk Management:**
- **Stop Loss:**
- **Short Trade:** High of the candle that formed outside the upper Bollinger Band.
- **Long Trade:** Low of the candle that formed outside the lower Bollinger Band.
- **Position Sizing:**
- The number of shares/contracts is calculated such that the **maximum loss per trade is INR 4000**.
- **Risk-to-Reward Ratio:**
- **Target Profit = 3x Risk (1:3 R:R).**
- Once **1:2 profit is reached, the stop loss moves to breakeven**.
- The trade is **closed at 1:3 profit**.
#### **Additional Features:**
- **Trades are only considered if the breakout happens within four candles** after the alert candle.
- **Bollinger Bands are plotted for visibility** on the chart.
Let me know if you need any modifications! 🚀
Killzones (UTC+3) by Roy באנגלית (Professional Style):
This script highlights the key Forex/Indices trading Killzones in Israel Time (UTC+3), including background colors and dynamic labels for:
Asian Session: 02:00–08:00
London Open: 10:00–12:00
New York Open: 14:00–17:00
London Close: 18:00–19:00
These are the hours with high institutional activity and increased market volatility – ideal for smart intraday setups.
✨ תיאור הסקריפט:
סקריפט זה מציג באופן ויזואלי את אזורי המסחר הפעילים ("Killzones") לפי שעון ישראל (UTC+3), כולל רקע צבעוני ותוויות טקסט לכל אזור חשוב:
🟤 Asian Killzone – בין השעות 02:00–08:00
🟢 London Killzone – בין השעות 10:00–12:00
🔵 New York Killzone – בין השעות 14:00–17:00
🔴 London Close – בין השעות 18:00–19:00
אידיאלי לסוחרים המחפשים לזהות מתי השוק נמצא בשיא התנודתיות והנפח.
Moving Average x5 (EMA/SMA) + ATR5 EMA/SMA lines at your disposal. Set your own timeframe. Made this by ChatGPT.
Plus ATR.
All things can be customized.
Moving Average 50+200+365Moving Average 50+200+365
What Are the 50, 200, and 365 Moving Averages for CRYPTOCAP:BTC ?
A Moving Average (MA) smooths out price data over a specified number of periods to reveal trends by filtering out short-term noise. For Bitcoin, these periods (50, 200, and 365) are typically applied on a daily chart, meaning they represent 50 days, 200 days, and 365 days, respectively.
50-period MA: A medium-term indicator, covering about 1.5–2 months (50 trading days), used to identify shorter-term trends in Bitcoin’s price.
200-period MA: A long-term indicator, spanning roughly 9–10 months (200 trading days), widely used to gauge Bitcoin’s overall trend.
365-period MA: A very long-term indicator, covering a full year (365 days), often used to assess multi-year trends or significant support/resistance levels in Bitcoin’s market cycles.
Volatility Layered Supertrend [NLR]We’ve all used Supertrend, but do you know where to actually enter a trade? Volatility Layered Supertrend (VLS) is here to solve that! This advanced trend-following indicator builds on the classic Supertrend by not only identifying trends and their strength but also guiding you to the best trade entry points. VLS divides the main long-term trend into “Strong” and “Weak” Zones, with a clear “Trade Entry Zone” to help you time your trades with precision. With layered trends, dynamic profit targets, and volatility-adaptive bands, VLS delivers actionable signals for any market.
Why I Created VLS Over a Plain Supertrend
I built VLS to address the gaps in traditional Supertrend usage and make trade entries clearer:
Single-Line Supertrend Issues: The default Supertrend sets stop-loss levels that are too wide, making it impractical for most traders to use effectively.
Unclear Entry Points: Standard Supertrend doesn’t tell you where to enter a trade, often leaving you guessing or entering too early or late.
Multi-Line Supertrend Enhancement: Many traders use short, medium, and long Supertrends, which is helpful but can lack focus. In VLS, I include Short, Medium, and Long trends (using multipliers 1 to 3), and add multipliers 4 and 5 to track extra long-term trends—helping to avoid fakeouts that sometimes occur with multiplier 3.
My Solution: I focused on the main long-term Supertrend and split it into “Weak Zone” and “Strength Zone” to show the trend’s reliability. I also defined a “Trade Entry Zone” (starting from the Mid Point, with the first layer’s background hidden for clarity) to guide you on where to enter trades. The zones include Short, Medium, and Long Trend layers for precise entries, exits, and stop-losses.
Practical Trading: This approach provides realistic stop-loss levels, clear entry points, and a “Profit Target” line that aligns with your risk tolerance, while filtering out false signals with longer-term trends.
Key Features
Layered Trend Zones: Short, Medium, Long, and Extra Long Trend layers (up to multipliers 4 and 5) for timing entries and exits.
Strong & Weak Zones: See when the trend is reliable (Strength Zone) or needs caution (Weak Zone).
Trade Entry Zone: A dedicated zone starting from the Mid Point (first layer’s background hidden) to show the best entry points.
Dynamic Profit Targets: A “Profit Target” line that adjusts with the trend for clear goals.
Volatility-Adaptive: Uses ATR to adapt to market conditions, ensuring reliable signals.
Color-Coded: Green for uptrends, red for downtrends—simple and clear.
How It Works
VLS enhances the main long-term Supertrend by dividing it into two zones:
Weak Zone: Indicates a less reliable trend—use tighter stop-losses or wait for the price to reach the Trade Entry Zone.
Strength Zone: Signals a strong trend—ideal for entries with wider stop-losses for bigger moves.
The “Trade Entry Zone” starts at the Mid Point (last layer’s background hidden for clarity), showing you the best area to enter trades. Each zone includes Short, Medium, Long, and Extra Long Trend sublevels (up to multipliers 4 and 5) for precise trade timing and to filter out fakeouts. The “Profit Target” updates dynamically based on trend direction and volatility, giving you a clear goal.
How to Use
Spot the Trend: Green bands = buy, red bands = sell.
Check Strength: Price in Strength Zone? Trend’s reliable—trade confidently. In Weak Zone? Use tighter stops or wait.
Enter Trades: Use the “Trade Entry Zone” (from the Mid Point upward) for the best entry points.
Use Sublevels: Short, Medium, Long, and Extra Long layers in each zone help fine-tune entries and exits.
Set Targets: Follow the Profit Target line for goals—it updates automatically.
Combine Tools: Pair with RSI, MACD, or support/resistance for added confirmation.
Settings
ATR Length: Adjust the ATR period (default 10) to change sensitivity.
Up/Down Colors: Customize colors—green for up, red for down, by default.
bollingerBandsV2Library "bollingerBandsV2"
Bollinger bands related functions
get_multiple_bollinger_bands(stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, length, source)
: Calculates 7 sets of bollinger bands, with 7 different standard deviations
Parameters:
stdv1 (float) : (simple int): standard deviation 1
stdv2 (float) : (simple int): standard deviation 2
stdv3 (float) : (simple int): standard deviation 3
stdv4 (float) : (simple int): standard deviation 4
stdv5 (float) : (simple int): standard deviation 5
stdv6 (float) : (simple int): standard deviation 6
stdv7 (float) : (simple int): standard deviation 7
length (simple int) : (simple int): Length for the bands
source (float) : (simple float): source for the calculation
Returns: : Returns 8 levels plus the range of all the levels.
get_bb_volatility(bb_highest, bb_lowest, ma_length, lookback)
: Provides a volatility indicator based on Bollinger Bands, and indicates wheather the volatility is increasing or decreasing.
Parameters:
bb_highest (float) : (simple float): Top Bollinger Band on which to calculate the range.
bb_lowest (float) : (simple float): Bottom Bollinger Band on which to calculate the range.
ma_length (simple int) : (simple int): Length to use in the smoothing of Bollinger Bands range.
lookback (int) : (simple int): Lookback period to identify a change in the Bollinger Bands range.
Returns: : Returns 8 levels plus the range of all the levels.
get_bbVolatility_data(source, length, stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, trend_direction)
: Generates Bollinger Bands Volatility
Parameters:
source (float) : (float): Source for Bollinger Bands
length (simple int) : (int): Length for Bollinger Bands
stdv1 (int) : (int): Standard Deviation 1
stdv2 (int) : (int): Standard Deviation 2
stdv3 (int) : (int): Standard Deviation 3
stdv4 (int) : (int): Standard Deviation 4
stdv5 (int) : (int): Standard Deviation 5
stdv6 (int) : (int): Standard Deviation 6
stdv7 (int) : (int): Standard Deviation 7
trend_direction (string) : (string): Current direction of the trend
Returns: : Returns a map with the levels, plus direction flag and the data table
Multi-EMA Crossover StrategyMulti-EMA Crossover Strategy
This strategy uses multiple exponential moving average (EMA) crossovers to identify bullish trends and execute long trades. The approach involves progressively stronger signals as different EMA pairs cross, indicating increasing bullish momentum. Each crossover triggers a long entry, and the intensity of bullish sentiment is reflected in the color of the bars on the chart. Conversely, bearish trends are represented by red bars.
Strategy Logic:
First Long Entry: When the 1-day EMA crosses above the 5-day EMA, it signals initial bullish momentum.
Second Long Entry: When the 3-day EMA crosses above the 10-day EMA, it confirms stronger bullish sentiment.
Third Long Entry: When the 5-day EMA crosses above the 20-day EMA, it indicates further trend strength.
Fourth Long Entry: When the 10-day EMA crosses above the 40-day EMA, it suggests robust long-term bullish momentum.
The bar colors reflect these conditions:
More blue bars indicate stronger bullish sentiment as more short-term EMAs are above their longer-term counterparts.
Red bars represent bearish conditions when short-term EMAs are below longer-term ones.
Example: Bitcoin Trading on a Daily Timeframe
Bullish Scenario:
Imagine Bitcoin is trading at $30,000 on March 31, 2025:
First Signal: The 1-day EMA crosses above the 5-day EMA at $30,000. This suggests initial upward momentum, prompting a small long entry.
Second Signal: A few days later, the 3-day EMA crosses above the 10-day EMA at $31,000. This confirms strengthening bullish sentiment; another long position is added.
Third Signal: The 5-day EMA crosses above the 20-day EMA at $32,500, indicating further upward trend development; a third long entry is executed.
Fourth Signal: Finally, the 10-day EMA crosses above the 40-day EMA at $34,000. This signals robust long-term bullish momentum; a fourth long position is entered.
Bearish Scenario:
Suppose Bitcoin reverses from $34,000 to $28,000:
The 1-day EMA crosses below the 5-day EMA at $33,500.
The 3-day EMA dips below the 10-day EMA at $32,000.
The 5-day EMA falls below the 20-day EMA at $30,000.
The final bearish signal occurs when the 10-day EMA drops below the 40-day EMA at $28,000.
The bars turn increasingly red as bearish conditions strengthen.
Advantages of This Strategy:
Progressive Confirmation: Multiple crossovers provide layered confirmation of trend strength.
Visual Feedback: Bar colors help traders quickly assess market sentiment and adjust positions accordingly.
Flexibility: Suitable for trending markets like Bitcoin during strong rallies or downturns.
Limitations:
Lagging Signals: EMAs are lagging indicators and may react slowly to sudden price changes.
False Breakouts: Crossovers in choppy markets can lead to whipsaws or false signals.
This strategy works best in trending markets and should be combined with additional risk management techniques, e.g., stop loss or optimal position sizes (Kelly Criterion).
Volume > 1.5x 20-Day Avg VolumeI am trying to understand on a 20 period basis if the volume spike is over 1.5 times the average. If this indicator works well the, it shows a triangle whenever the spike in the volume matches the rule.
Multi-Period VWAP30day 90day and 365day vwap
its just a vwap
that anchores 30day before the current day
anchores 90day before current day
anchores 365day before current day
ZigZag█ Overview
This Pine Script™ library provides a comprehensive implementation of the ZigZag indicator using advanced object-oriented programming techniques. It serves as a developer resource rather than a standalone indicator, enabling Pine Script™ programmers to incorporate sophisticated ZigZag calculations into their own scripts.
Pine Script™ libraries contain reusable code that can be imported into indicators, strategies, and other libraries. For more information, consult the Libraries section of the Pine Script™ User Manual.
█ About the Original
This library is based on TradingView's official ZigZag implementation .
The original code provides a solid foundation with user-defined types and methods for calculating ZigZag pivot points.
█ What is ZigZag?
The ZigZag indicator filters out minor price movements to highlight significant market trends.
It works by:
1. Identifying significant pivot points (local highs and lows)
2. Connecting these points with straight lines
3. Ignoring smaller price movements that fall below a specified threshold
Traders typically use ZigZag for:
- Trend confirmation
- Identifying support and resistance levels
- Pattern recognition (such as Elliott Waves)
- Filtering out market noise
The algorithm identifies pivot points by analyzing price action over a specified number of bars, then only changes direction when price movement exceeds a user-defined percentage threshold.
█ My Enhancements
This modified version extends the original library with several key improvements:
1. Support and Resistance Visualization
- Adds horizontal lines at pivot points
- Customizable line length (offset from pivot)
- Adjustable line width and color
- Option to extend lines to the right edge of the chart
2. Support and Resistance Zones
- Creates semi-transparent zone areas around pivot points
- Customizable width for better visibility of important price levels
- Separate colors for support (lows) and resistance (highs)
- Visual representation of price areas rather than just single lines
3. Zig Zag Lines
- Separate colors for upward and downward ZigZag movements
- Visually distinguishes between bullish and bearish price swings
- Customizable colors for text
- Width customization
4. Enhanced Settings Structure
- Added new fields to the Settings type to support the additional features
- Extended Pivot type with supportResistance and supportResistanceZone fields
- Comprehensive configuration options for visual elements
These enhancements make the ZigZag more useful for technical analysis by clearly highlighting support/resistance levels and zones, and providing clearer visual cues about market direction.
█ Technical Implementation
This library leverages Pine Script™'s user-defined types (UDTs) to create a robust object-oriented architecture:
- Settings : Stores configuration parameters for calculation and display
- Pivot : Represents pivot points with their visual elements and properties
- ZigZag : Manages the overall state and behavior of the indicator
The implementation follows best practices from the Pine Script™ User Manual's Style Guide and uses advanced language features like methods and object references. These UDTs represent Pine Script™'s most advanced feature set, enabling sophisticated data structures and improved code organization.
For newcomers to Pine Script™, it's recommended to understand the language fundamentals before working with the UDT implementation in this library.
█ Usage Example
//@version=6
indicator("ZigZag Example", overlay = true, shorttitle = 'ZZA', max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
import andre_007/ZigZag/1 as ZIG
var group_1 = "ZigZag Settings"
//@variable Draw Zig Zag on the chart.
bool showZigZag = input.bool(true, "Show Zig-Zag Lines", group = group_1, tooltip = "If checked, the Zig Zag will be drawn on the chart.", inline = "1")
// @variable The deviation percentage from the last local high or low required to form a new Zig Zag point.
float deviationInput = input.float(5.0, "Deviation (%)", minval = 0.00001, maxval = 100.0,
tooltip = "The minimum percentage deviation from a previous pivot point required to change the Zig Zag's direction.", group = group_1, inline = "2")
// @variable The number of bars required for pivot detection.
int depthInput = input.int(10, "Depth", minval = 1, tooltip = "The number of bars required for pivot point detection.", group = group_1, inline = "3")
// @variable registerPivot (series bool) Optional. If `true`, the function compares a detected pivot
// point's coordinates to the latest `Pivot` object's `end` chart point, then
// updates the latest `Pivot` instance or adds a new instance to the `ZigZag`
// object's `pivots` array. If `false`, it does not modify the `ZigZag` object's
// data. The default is `true`.
bool allowZigZagOnOneBarInput = input.bool(true, "Allow Zig Zag on One Bar", tooltip = "If checked, the Zig Zag calculation can register a pivot high and pivot low on the same bar.",
group = group_1, inline = "allowZigZagOnOneBar")
var group_2 = "Display Settings"
// @variable The color of the Zig Zag's lines (up).
color lineColorUpInput = input.color(color.green, "Line Colors for Up/Down", group = group_2, inline = "4")
// @variable The color of the Zig Zag's lines (down).
color lineColorDownInput = input.color(color.red, "", group = group_2, inline = "4",
tooltip = "The color of the Zig Zag's lines")
// @variable The width of the Zig Zag's lines.
int lineWidthInput = input.int(1, "Line Width", minval = 1, tooltip = "The width of the Zig Zag's lines.", group = group_2, inline = "w")
// @variable If `true`, the Zig Zag will also display a line connecting the last known pivot to the current `close`.
bool extendInput = input.bool(true, "Extend to Last Bar", tooltip = "If checked, the last pivot will be connected to the current close.",
group = group_1, inline = "5")
// @variable If `true`, the pivot labels will display their price values.
bool showPriceInput = input.bool(true, "Display Reversal Price",
tooltip = "If checked, the pivot labels will display their price values.", group = group_2, inline = "6")
// @variable If `true`, each pivot label will display the volume accumulated since the previous pivot.
bool showVolInput = input.bool(true, "Display Cumulative Volume",
tooltip = "If checked, the pivot labels will display the volume accumulated since the previous pivot.", group = group_2, inline = "7")
// @variable If `true`, each pivot label will display the change in price from the previous pivot.
bool showChgInput = input.bool(true, "Display Reversal Price Change",
tooltip = "If checked, the pivot labels will display the change in price from the previous pivot.", group = group_2, inline = "8")
// @variable Controls whether the labels show price changes as raw values or percentages when `showChgInput` is `true`.
string priceDiffInput = input.string("Absolute", "", options = ,
tooltip = "Controls whether the labels show price changes as raw values or percentages when 'Display Reversal Price Change' is checked.",
group = group_2, inline = "8")
// @variable If `true`, the Zig Zag will display support and resistance lines.
bool showSupportResistanceInput = input.bool(true, "Show Support/Resistance Lines",
tooltip = "If checked, the Zig Zag will display support and resistance lines.", group = group_2, inline = "9")
// @variable The number of bars to extend the support and resistance lines from the last pivot point.
int supportResistanceOffsetInput = input.int(50, "Support/Resistance Offset", minval = 0,
tooltip = "The number of bars to extend the support and resistance lines from the last pivot point.", group = group_2, inline = "10")
// @variable The width of the support and resistance lines.
int supportResistanceWidthInput = input.int(1, "Support/Resistance Width", minval = 1,
tooltip = "The width of the support and resistance lines.", group = group_2, inline = "11")
// @variable The color of the support lines.
color supportColorInput = input.color(color.red, "Support/Resistance Color", group = group_2, inline = "12")
// @variable The color of the resistance lines.
color resistanceColorInput = input.color(color.green, "", group = group_2, inline = "12",
tooltip = "The color of the support/resistance lines.")
// @variable If `true`, the support and resistance lines will be drawn as zones.
bool showSupportResistanceZoneInput = input.bool(true, "Show Support/Resistance Zones",
tooltip = "If checked, the support and resistance lines will be drawn as zones.", group = group_2, inline = "12-1")
// @variable The color of the support zones.
color supportZoneColorInput = input.color(color.new(color.red, 70), "Support Zone Color", group = group_2, inline = "12-2")
// @variable The color of the resistance zones.
color resistanceZoneColorInput = input.color(color.new(color.green, 70), "", group = group_2, inline = "12-2",
tooltip = "The color of the support/resistance zones.")
// @variable The width of the support and resistance zones.
int supportResistanceZoneWidthInput = input.int(10, "Support/Resistance Zone Width", minval = 1,
tooltip = "The width of the support and resistance zones.", group = group_2, inline = "12-3")
// @variable If `true`, the support and resistance lines will extend to the right of the chart.
bool supportResistanceExtendInput = input.bool(false, "Extend to Right",
tooltip = "If checked, the lines will extend to the right of the chart.", group = group_2, inline = "13")
// @variable References a `Settings` instance that defines the `ZigZag` object's calculation and display properties.
var ZIG.Settings settings =
ZIG.Settings.new(
devThreshold = deviationInput,
depth = depthInput,
lineColorUp = lineColorUpInput,
lineColorDown = lineColorDownInput,
textUpColor = lineColorUpInput,
textDownColor = lineColorDownInput,
lineWidth = lineWidthInput,
extendLast = extendInput,
displayReversalPrice = showPriceInput,
displayCumulativeVolume = showVolInput,
displayReversalPriceChange = showChgInput,
differencePriceMode = priceDiffInput,
draw = showZigZag,
allowZigZagOnOneBar = allowZigZagOnOneBarInput,
drawSupportResistance = showSupportResistanceInput,
supportResistanceOffset = supportResistanceOffsetInput,
supportResistanceWidth = supportResistanceWidthInput,
supportColor = supportColorInput,
resistanceColor = resistanceColorInput,
supportResistanceExtend = supportResistanceExtendInput,
supportResistanceZoneWidth = supportResistanceZoneWidthInput,
drawSupportResistanceZone = showSupportResistanceZoneInput,
supportZoneColor = supportZoneColorInput,
resistanceZoneColor = resistanceZoneColorInput
)
// @variable References a `ZigZag` object created using the `settings`.
var ZIG.ZigZag zigZag = ZIG.newInstance(settings)
// Update the `zigZag` on every bar.
zigZag.update()
//#endregion
The example code demonstrates how to create a ZigZag indicator with customizable settings. It:
1. Creates a Settings object with user-defined parameters
2. Instantiates a ZigZag object using these settings
3. Updates the ZigZag on each bar to detect new pivot points
4. Automatically draws lines and labels when pivots are detected
This approach provides maximum flexibility while maintaining readability and ease of use.
Stock Buy SignalThis is for daily purchase strategy, buying at crosses of super trend followed by exit at 3%
Support and Resistance Entry/ExitThis Pine Script strategy uses Support and Resistance levels for entry and exit:
Buy Signal: Enter a long position when the price breaks above the Resistance (pivotHigh).
Sell Signal: Enter a short position when the price breaks below the Support (pivotLow).
Exit Conditions:
Exit the long position when the price hits the Support.
Exit the short position when the price hits the Resistance.
Open Price on Selected TimeframeIndicator Name: Open Price on Selected Timeframe
Short Title: Open Price mtf
Type: Technical Indicator
Description:
Open Price on Selected Timeframe is an indicator that displays the Open price of a specific timeframe on your chart, with the ability to dynamically change the color of the open price line based on the change between the current candle's open and the previous candle's open.
Selectable Timeframes: You can choose the timeframe you wish to monitor the Open price of candles, ranging from M1, M5, M15, H1, H4 to D1, and more.
Dynamic Color Change: The Open price line changes to green when the open price of the current candle is higher than the open price of the previous candle, and to red when the open price of the current candle is lower than the open price of the previous candle. This helps users quickly identify trends and market changes.
Features:
Easy Timeframe Selection: Instead of editing the code, users can select the desired timeframe from the TradingView interface via a dropdown.
Dynamic Color Change: The color of the Open price line changes automatically based on whether the open price of the current candle is higher or lower than the previous candle.
Easily Track Open Price Levels: The indicator plots a horizontal line at the Open price of the selected timeframe, making it easy for users to track this important price level.
How to Use:
Select the Timeframe: Users can choose the timeframe they want to track the Open price of the candles.
Interpret the Color Signal: When the open price of the current candle is higher than the open price of the previous candle, the Open price line is colored green, signaling an uptrend. When the open price of the current candle is lower than the open price of the previous candle, the Open price line turns red, signaling a downtrend.
Observe the Open Price Levels: The indicator will draw a horizontal line at the Open price level of the selected timeframe, allowing users to easily monitor this important price.
Benefits:
Enhanced Technical Analysis: The indicator allows you to quickly identify trends and market changes, making it easier to make trading decisions.
User-Friendly: No need to modify the code; simply select your preferred timeframe to start using the indicator.
Disclaimer:
This indicator is not a complete trading signal. It only provides information about the Open price and related trends. Users should combine it with other technical analysis tools to make more informed trading decisions.
Summary:
Open Price on Selected Timeframe is a simple yet powerful indicator that helps you track the Open price on various timeframes with the ability to change colors dynamically, providing a visual representation of the market's trend.
Pivot Length Percentiles Oscillator# Pivot Length Percentiles Oscillator: Technical Mechanics Explained
## Introduction
The Pivot Length Percentiles Oscillator is a statistical approach to identifying potential market reversals by analyzing the distribution of price movements relative to pivot points. This publication explains the technical mechanics behind the indicator.
## Core Mechanics
### 1. Pivot Point Detection
The indicator begins by identifying significant pivot highs and lows using a user-defined lookback period:
- `lft`: Number of bars to the left of potential pivot point
- `rht`: Number of bars to the right of potential pivot point
These parameters determine how "significant" a pivot needs to be to qualify for analysis.
### 2. Distance Measurement & Historical Database
For each new pivot point identified, the indicator:
- Calculates the absolute price distance from the previous pivot of the same type
- Records the number of candles between consecutive pivots
- Stores these measurements in dynamic arrays that build a historical database
### 3. Statistical Distribution Analysis
Rather than using fixed values, the oscillator analyzes the complete distribution of historical pivot distances and calculates key percentile values:
- `lw` (Low Percentile): Lower boundary for statistical significance
- `md` (Mid Percentile): Median statistical boundary
- `hi` (High Percentile): Upper boundary for statistical extremes
### 4. Oscillator Construction
Two primary oscillator lines are calculated:
- Green line (`osc1`): Measures current price's fall below recent highs with `low - ta.highest(high, lft)`
- Red line (`osc2`): Measures current price's rise above recent lows with `high - ta.lowest(low, lft)`
### 5. Threshold Generation
The percentile values from the historical distribution create dynamic threshold lines:
- For downside movements: Scaled versions of the low percentile (`lw_distance_low`) and high percentile (`hi_distance_low`)
- For upside movements: Scaled versions of the low percentile (`lw_distance_high`) and high percentile (`hi_distance_high`)
### 6. Signal Logic
Entry signals are generated when:
- **Bullish Signal**: The downside oscillator crosses below a statistical threshold while price continues showing downward momentum (close < previous close AND close < previous open)
- **Bearish Signal**: The upside oscillator crosses above a statistical threshold while price continues showing upward momentum (close > previous close AND close > previous open)
### 7. Visualization Options
Users can toggle between:
- Standard view: Shows the oscillator and threshold lines
- Percentile view: Displays the current movement's percentile rank within the historical distribution
## Implementation Notes
- The indicator scales threshold values by 0.9 to create a slight buffer that reduces false signals
- The movement's continuation is confirmed by checking both close-to-close and close-to-open relationships
- Arrays dynamically update throughout the chart's history, making the indicator increasingly accurate as more data is processed
## Mathematical Framework
The core statistical function calculates percentiles using linear interpolation between values when needed:
```
calculate_percentile(array, percentile) =
sortedValue +
fraction * (sortedValue - sortedValue )
```
where `index = (array.size - 1) * percentile / 100`
This mathematical approach ensures the thresholds adapt dynamically to changing market conditions rather than relying on fixed values.
levels and eqsGenerates Range & EQ levels and removes duplicates. Prioritizes by higher timeframe for duplicates. For example, on Monday's open, weekly open is displayed while daily open is hidden automatically.
Original rumpypumpydumpy
Doji Breakout 3:1 DetectorFinds a proper doji for you to buy its high or sell its low for a 3:1 reward
PunkAlgo Oscillator [1.0]//@version=5
indicator(title='PunkAlgo Oscillator ', shorttitle='Punk Oscillator')
n1 = input(4, 'Channel Length')
n2 = input(15, 'Average Length')
obLevel1 = input(88, 'Over Bought Level 1')
obLevel2 = input(81, 'Over Bought Level 2')
osLevel1 = input(-83, 'Over Sold Level 1')
osLevel2 = input(-76, 'Over Sold Level 2')
ap = hlc3
esa = ta.ema(ap, n1)
d = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)
wt1 = tci
wt2 = ta.sma(wt1, 4)
var indbot=0
var indtop=0
if wt1 > wt2 and wt1 < wt2
indbot := bar_index
if wt1 < wt2 and wt1 > wt2
indtop := bar_index
bott = bar_index - indbot
topp = bar_index - indtop
// Histogram
lookbackPeriod = input(35, "Lookback Period")
// Calculate the percentage change in price for each bar
priceChange = close - close
priceChangePercentage = priceChange / close * 100
// Calculate the average volume over the lookback period
averageVolume = ta.ema(volume, lookbackPeriod)
// Initialize the counters for upward and downward trends
upwardTrends = 0
downwardTrends = 0
// Iterate over the lookback period and count the number of upward and downward trends
for i = 1 to lookbackPeriod
if priceChangePercentage > 0
upwardTrends := upwardTrends + 1
else if priceChangePercentage < 0
downwardTrends := downwardTrends + 1
// Calculate the probabilities of upward, downward, and neutral trends
totalTrends = upwardTrends + downwardTrends
probabilityUpward = math.round(upwardTrends / totalTrends, 2) * 100
probabilityDownward = math.round(downwardTrends / totalTrends, 2) * 100
// Determine the probability trend based on the probabilities
probabilityTrend = ""
if probabilityUpward > probabilityDownward
probabilityTrend := "Upward"
else if probabilityUpward < probabilityDownward
probabilityTrend := "Downward"
// Calculate the oscillator value based on the difference between upward and downward trends
oscillatorValue = probabilityUpward - probabilityDownward
// Determine the histogram color based on the difference between the oscillator value and zero line
histogramColor = oscillatorValue >= 0 ? (oscillatorValue < oscillatorValue ? color.new(#089981, 50) : color.new(#089981, 50)) : (oscillatorValue < oscillatorValue ? color.new(#f23645, 50) : color.new(#f23645, 50))
// Smoothning the Histogram
smooth_hist = input.bool(true, "Smoothen Histogram", inline="smooth_hist")
smoothning_scale = input.int(defval=3, title="", minval=1, maxval=10, step=1, inline="smooth_hist")
smooth_len = smoothning_scale * 2
smooth_hist_val = smooth_hist ? ta.ema(oscillatorValue, smooth_len) : oscillatorValue
// Plot the histogram
plot(smooth_hist_val, color=histogramColor, style=plot.style_area, linewidth=1, title="Probability Histogram")
// Histogram
plot(0, color=color.new(#787b86, 100))
top1 = plot(obLevel1, color=color.new(#4caf4f, 100))
top2 = plot(osLevel1, color=color.new(#ff5252, 100))
bottom1 = plot(obLevel2, color=color.new(#4caf4f, 100))
bottom2 = plot(osLevel2, color=color.new(#ff5252, 100))
fill(plot1=top1, plot2=bottom1, color=wt2 > 0 and (wt1 - wt2) > 0 ? #089981 : wt2 > 0 or (wt1 - wt2) > 0 ?color.new(#363a45, 60) : color.new(#363a45, 70))
fill(plot1=top2, plot2=bottom2, color=wt2 < 0 and (wt1 - wt2) < 0 ? #f23645 : wt2 < 0 or (wt1 - wt2) < 0 ? color.new(#363a45, 60) : color.new(#363a45, 70))
plot1 = plot(wt1, color=wt1 > wt2 ? color.new(color.green, 0) : color.gray ,title="Signal")
plot2 = plot(wt2, color=color.new(#ff5252, 100),title="Signal Dots")
fill(plot1=plot1, plot2=plot2, color=wt1 > wt2 ? color.rgb(8, 153, 129, 80) : color.rgb(120, 123, 134, 80),title="Signal Shadow")
plot(ta.cross(wt1, wt2) ? wt2 : na, color=color.new(color.black, 0), style=plot.style_circles, linewidth=3,title="Dot Shadows")
plot(ta.cross(wt1, wt2) ? wt2 : na, color=wt2 - wt1 > 0 ? color.gray : color.green , style=plot.style_circles, linewidth=2)
// Divergences Module
tsi1 = wt1
tsi2 = ta.sma(wt2, 4)
long = n1
short = n2
signal22 = n2
price = hlc3
src2 = hlc3
src = hlc3
input_src = tsi1
// Divergences Options
up = ta.rma(math.max(ta.change(src), 0), short)
down = ta.rma(-math.min(ta.change(src), 0), short)
lbR = input(title='Divergence Pivot Lookback Right', defval=1)
lbL = input(title='Divergence Pivot Lookback Left', defval=5)
rangeUpper = input(title='Max of Lookback Range', defval=100)
rangeLower = input(title='Min of Lookback Range', defval=2)
plotBull = input(title='Plot Bullish', defval=true)
plotHiddenBull = input(title='Plot Hidden Bullish', defval=false)
plotBear = input(title='Plot Bearish', defval=true)
plotHiddenBear = input(title='Plot Hidden Bearish', defval=false)
bearColor = color.new(#f23645, 10)
bullColor = color.new(#2157f3, 10)
hiddenBullColor = color.new(color.aqua, 0)
hiddenBearColor = color.new(color.orange, 0)
textColor = color.new(color.white, 0)
noneColor = color.new(color.white, 100)
osc = tsi1
plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc > ta.valuewhen(plFound, osc , 1) and _inRange(plFound )
// Price: Lower Low
priceLL = low < ta.valuewhen(plFound, low , 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(plFound ? osc : na, offset=-lbR, title='Regular Bullish', linewidth=1, color=bullCond ? bullColor : noneColor, transp=0)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc < ta.valuewhen(plFound, osc , 1) and _inRange(plFound )
// Price: Higher Low
priceHL = low > ta.valuewhen(plFound, low , 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(plFound ? osc : na, offset=-lbR, title='Hidden Bullish', linewidth=1, color=hiddenBullCond ? hiddenBullColor : noneColor, transp=0)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc < ta.valuewhen(phFound, osc , 1) and _inRange(phFound )
// Price: Higher High
priceHH = high > ta.valuewhen(phFound, high , 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(phFound ? osc : na, offset=-lbR, title='Regular Bearish', linewidth=1, color=bearCond ? bearColor : noneColor, transp=0)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc > ta.valuewhen(phFound, osc , 1) and _inRange(phFound )
// Price: Lower High
priceLH = high < ta.valuewhen(phFound, high , 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(phFound ? osc : na, offset=-lbR, title='Hidden Bearish', linewidth=1, color=hiddenBearCond ? hiddenBearColor : noneColor, transp=0)
// Signals Module
string TT_HARSI = 'Period for the RSI calculations used to generate the' + 'candles. This seperate from the RSI plot/histogram length.'
string TT_PBIAS = 'Smoothing feature for the OPEN of the HARSI candles.' + ' Increases bias toward the prior open value which can' + ' help provide better visualisation of trend strength.' + ' ** By changing the Open values, High and Low can also' + ' be distorted - however Close will remain unchanged.'
string TT_SMRSI = 'This option smoothes the RSI in a manner similar to HA' + ' open, but uses the realtime rsi rather than the prior' + ' close value.'
string TT_STOCH = 'Uses the RSI generated by the above settings, and as such' + ' will be affected by the smoothing option.'
string TT_STFIT = 'Adjusts the vertical scaling of the stochastic, can help' + ' to prevent distortion of other data in the channel.' + ' Has no impact cross conditions.'
////////////////////////////////////////////////////////////////////////////////
// //
// ====== INPUTS ====== //
// //
////////////////////////////////////////////////////////////////////////////////
// -- Candle config
string GROUP_CAND = 'Config » HARSI Candles'
i_lenHARSI = input.int(10, 'Length', group=GROUP_CAND, minval=1, tooltip=TT_HARSI)
i_smoothing = input.int(5, 'Open Smoothing', group=GROUP_CAND, minval=1, maxval=100, tooltip=TT_PBIAS)
string INLINE_COL = 'Colour Pallette'
i_colUp = input.color(color.teal, 'Colour Pallette ', group=GROUP_CAND, inline=INLINE_COL)
i_colDown = input.color(color.red, ' ', group=GROUP_CAND, inline=INLINE_COL)
i_colWick = input.color(color.gray, ' ', group=GROUP_CAND, inline=INLINE_COL)
// -- RSI plot config
string GROUP_PLOT = 'Config » RSI Plot'
i_source = input.source(ohlc4, 'Source', group=GROUP_PLOT)
i_lenRSI = input.int(7, 'Length', group=GROUP_PLOT, minval=1)
i_mode = input.bool(true, 'Smoothed Mode RSI?', group=GROUP_PLOT, tooltip=TT_SMRSI)
i_showPlot = input.bool(true, 'Show RSI Plot?', group=GROUP_PLOT)
i_showHist = input.bool(true, 'Show RSI Histogram?', group=GROUP_PLOT)
// -- Channel OB/OS config
string GROUP_CHAN = 'Config » OB/OS Boundaries'
i_upper = input.int(50, 'OB', group=GROUP_CHAN, inline='OB', minval=1, maxval=50)
i_upperx = input.int(30, 'OB Extreme', group=GROUP_CHAN, inline='OB', minval=1, maxval=50)
i_lower = input.int(-50, 'OS', group=GROUP_CHAN, inline='OS', minval=-50, maxval=-1)
i_lowerx = input.int(-30, 'OS Extreme', group=GROUP_CHAN, inline='OS', minval=-50, maxval=-1)
// Settins
// WaveTrend
wwttShow = input(false, title='Show WaveTrend')
wwttBuyShow = input(true, title='Show Buy dots')
wwttGoldShow = input(true, title='Show Gold dots')
wwttSellShow = input(true, title='Show Sell dots')
wwttDivShow = input(true, title='Show Div. dots')
vwapShow = input(true, title='Show Fast wwtt')
wwttChannelLen = input(9, title='wwtt Channel Length')
wwttAverageLen = input(12, title='wwtt Average Length')
wwttMASource = input(hlc3, title='wwtt MA Source')
wwttMALen = input(3, title='wwtt MA Length')
// WaveTrend Overbought & Oversold lines
OOBBLevel = input(53, title='wwtt Overbought Level 1')
OOBBLevel2 = input(60, title='wwtt Overbought Level 2')
OOBBLevel3 = input(100, title='wwtt Overbought Level 3')
oosLevel = input(-53, title='wwtt Oversold Level 1')
oosLevel2 = input(-60, title='wwtt Oversold Level 2')
oosLevel3 = input(-75, title='wwtt Oversold Level 3')
// Divergence wwtt
wwttShowDiv = input(true, title='Show wwtt Regular Divergences')
wwttShowHiddenDiv = input(false, title='Show wwtt Hidden Divergences')
showHiddenDiv_nl = input(true, title='Not apply OB/OS Limits on Hidden Divergences')
wwttDivOOBBLevel = input(45, title='wwtt Bearish Divergence min')
wwttDivoosLevel = input(-65, title='wwtt Bullish Divergence min')
// Divergence extra range
wwttDivOOBBLevel_addshow = input(true, title='Show 2nd wwtt Regular Divergences')
wwttDivOOBBLevel_add = input(15, title='wwtt 2nd Bearish Divergence')
wwttDivoosLevel_add = input(-40, title='wwtt 2nd Bullish Divergence 15 min')
// RSI+MFI
rsiMFIShow = input(true, title='Show MFI')
rsiMFIperiod = input(60, title='MFI Period')
rsiMFIMultiplier = input.float(150, title='MFI Area multiplier')
rsiMFIPosY = input(2.5, title='MFI Area Y Pos')
// RSI
rsiShow = input(false, title='Show RSI')
rsiSRC = input(close, title='RSI Source')
rsiLen = input(14, title='RSI Length')
rsiOversold = input.int(30, title='RSI Oversold', minval=29, maxval=100)
rsiOverbought = input.int(60, title='RSI Overbought', minval=0, maxval=60)
// Divergence RSI
rsiShowDiv = input(false, title='Show RSI Regular Divergences')
rsiShowHiddenDiv = input(false, title='Show RSI Hidden Divergences')
rsiDivOOBBLevel = input(60, title='RSI Bearish Divergence min')
rsiDivoosLevel = input(30, title='RSI Bullish Divergence min')
// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff
colorwwtt1 = #49536195
colorwwtt2 = #7b9fd596
colorwwtt2_ = #131722
colormacdwwtt1a = #4caf58
colormacdwwtt1b = #af4c4c
colormacdwwtt1c = #7ee57e
colormacdwwtt1d = #ff3535
colormacdwwtt2a = #305630
colormacdwwtt2b = #310101
colormacdwwtt2c = #132213
colormacdwwtt2d = #770000
////////////////////////////////////////////////////////////////////////////////
// //
// ====== FUNCTIONS ====== //
// //
////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS
// zero median rsi helper function, just subtracts 50.
f_zrsi(_source, _length) =>
ta.rsi(_source, _length) - 50
// zero median stoch helper function, subtracts 50 and includes % scaling
f_zstoch(_source, _length, _smooth, _scale) =>
float _zstoch = ta.stoch(_source, _source, _source, _length) - 50
float _smoothed = ta.sma(_zstoch, _smooth)
float _scaled = _smoothed / 100 * _scale
_scaled
// mode selectable rsi function for standard, or smoothed output
f_rsi(_source, _length, _mode) =>
// get base rsi
float _zrsi = f_zrsi(_source, _length)
// smoothing in a manner similar to HA open, but rather using the realtime
// rsi in place of the prior close value.
var float _smoothed = na
_smoothed := na(_smoothed ) ? _zrsi : (_smoothed + _zrsi) / 2
// return the requested mode
_mode ? _smoothed : _zrsi
// RSI Heikin-Ashi generation function
f_rsiHeikinAshi(_length) =>
// get close rsi
float _closeRSI = f_zrsi(close, _length)
// emulate "open" simply by taking the previous close rsi value
float _openRSI = nz(_closeRSI , _closeRSI)
// the high and low are tricky, because unlike "high" and "low" by
// themselves, the RSI results can overlap each other. So first we just go
// ahead and get the raw results for high and low, and then..
float _highRSI_raw = f_zrsi(high, _length)
float _lowRSI_raw = f_zrsi(low, _length)
// ..make sure we use the highest for high, and lowest for low
float _highRSI = math.max(_highRSI_raw, _lowRSI_raw)
float _lowRSI = math.min(_highRSI_raw, _lowRSI_raw)
// ha calculation for close
float _close = (_openRSI + _highRSI + _lowRSI + _closeRSI) / 4
// ha calculation for open, standard, and smoothed/lagged
var float _open = na
_open := na(_open ) ? (_openRSI + _closeRSI) / 2 : (_open * i_smoothing + _close ) / (i_smoothing + 1)
// ha high and low min-max selections
float _high = math.max(_highRSI, math.max(_open, _close))
float _low = math.min(_lowRSI, math.min(_open, _close))
// return the OHLC values
// Divergences
f_top_fractal(src) =>
src < src and src < src and src > src and src > src
f_bot_fractal(src) =>
src > src and src > src and src < src and src < src
f_fractalize(src) =>
f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit, useLimits) =>
fractalTop = f_fractalize(src) > 0 and (useLimits ? src >= topLimit : true) ? src : na
fractalBot = f_fractalize(src) < 0 and (useLimits ? src <= botLimit : true) ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
bearDivHidden = fractalTop and high < highPrice and src > highPrev
bullDivHidden = fractalBot and low > lowPrice and src < lowPrev
// RSI+MFI
f_rsimfi(_period, _multiplier, _tf) =>
request.security(syminfo.tickerid, _tf, ta.sma((close - open) / (high - low) * _multiplier, _period) - rsiMFIPosY)
// WaveTrend
f_wavetrend(src, chlen, avg, malen, tf) =>
tfsrc = request.security(syminfo.tickerid, tf, src)
esa = ta.ema(tfsrc, chlen)
de = ta.ema(math.abs(tfsrc - esa), chlen)
ci = (tfsrc - esa) / (0.015 * de)
wwtt1 = request.security(syminfo.tickerid, tf, ta.ema(ci, avg))
wwtt2 = request.security(syminfo.tickerid, tf, ta.sma(wwtt1, malen))
wwttVwap = wwtt1 - wwtt2
wwttOversold = wwtt2 <= oosLevel
wwttOverbought = wwtt2 >= OOBBLevel
wwttCross = ta.cross(wwtt1, wwtt2)
wwttCrossUp = wwtt2 - wwtt1 <= 0
wwttCrossDown = wwtt2 - wwtt1 >= 0
wwttCrosslast = ta.cross(wwtt1 , wwtt2 )
wwttCrossUplast = wwtt2 - wwtt1 <= 0
wwttCrossDownlast = wwtt2 - wwtt1 >= 0
// MACD
f_macd(src, fastlen, slowlen, sigsmooth, tf) =>
fast_ma = request.security(syminfo.tickerid, tf, ta.ema(src, fastlen))
slow_ma = request.security(syminfo.tickerid, tf, ta.ema(src, slowlen))
macd = fast_ma - slow_ma
signal = request.security(syminfo.tickerid, tf, ta.sma(macd, sigsmooth))
hist = macd - signal
// Get higher timeframe candle
f_getTFCandle(_tf) =>
_open = request.security(ticker.heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on)
_close = request.security(ticker.heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on)
_high = request.security(ticker.heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on)
_low = request.security(ticker.heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on)
hl2 = (_high + _low) / 2.0
newBar = ta.change(_open)
candleBodyDir = _close > _open
////////////////////////////////////////////////////////////////////////////////
// //
// ====== SERIES, LINES and LABELS ====== //
// //
////////////////////////////////////////////////////////////////////////////////
// CALCULATE INDICATORS {
// RSI
rsi = ta.rsi(rsiSRC, rsiLen)
rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple
// Calculates WaveTrend
= f_wavetrend(wwttMASource, wwttChannelLen, wwttAverageLen, wwttMALen, timeframe.period)
// wwtt Divergences
= f_findDivs(wwtt2, wwttDivOOBBLevel, wwttDivoosLevel, true)
= f_findDivs(wwtt2, wwttDivOOBBLevel_add, wwttDivoosLevel_add, true)
= f_findDivs(wwtt2, 0, 0, false)
wwttBearDivHidden_ = showHiddenDiv_nl ? wwttBearDivHidden_nl : wwttBearDivHidden
wwttBullDivHidden_ = showHiddenDiv_nl ? wwttBullDivHidden_nl : wwttBullDivHidden
wwttBearDivColor = wwttShowDiv and wwttBearDiv or wwttShowHiddenDiv and wwttBearDivHidden_ ? colorRed : na
wwttBullDivColor = wwttShowDiv and wwttBullDiv or wwttShowHiddenDiv and wwttBullDivHidden_ ? colorGreen : na
wwttBearDivColor_add = wwttShowDiv and wwttDivOOBBLevel_addshow and wwttBearDiv_add or wwttShowHiddenDiv and wwttDivOOBBLevel_addshow and wwttBearDivHidden_add ? #9a0202 : na
wwttBullDivColor_add = wwttShowDiv and wwttDivOOBBLevel_addshow and wwttBullDiv_add or wwttShowHiddenDiv and wwttDivOOBBLevel_addshow and wwttBullDivHidden_add ? #1b5e20 : na
// RSI Divergences
= f_findDivs(rsi, rsiDivOOBBLevel, rsiDivoosLevel, true)
= f_findDivs(rsi, 0, 0, false)
rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden
rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden
rsiBearDivColor = rsiShowDiv and rsiBearDiv or rsiShowHiddenDiv and rsiBearDivHidden_ ? colorRed : na
rsiBullDivColor = rsiShowDiv and rsiBullDiv or rsiShowHiddenDiv and rsiBullDivHidden_ ? colorGreen : na
// Buy signal.
buySignal = wwttCross and wwttCrossUp and wwttOversold
buySignalDiv = wwttShowDiv and wwttBullDiv or wwttShowDiv and wwttBullDiv_add or rsiShowDiv and rsiBullDiv
buySignalDiv_color = wwttBullDiv ? colorGreen : wwttBullDiv_add ? color.new(colorGreen, 60) : rsiShowDiv ? colorGreen : na
// Sell signal
sellSignal = wwttCross and wwttCrossDown and wwttOverbought
sellSignalDiv = wwttShowDiv and wwttBearDiv or wwttShowDiv and wwttBearDiv_add or rsiShowDiv and rsiBearDiv
sellSignalDiv_color = wwttBearDiv ? colorRed : wwttBearDiv_add ? color.new(colorRed, 60) : rsiBearDiv ? colorRed : na
// standard, or ha smoothed rsi for the line plot and/or histogram
float RSI = f_rsi(i_source, i_lenRSI, i_mode)
// get OHLC values to use in the plotcandle()
= f_rsiHeikinAshi(i_lenHARSI)
// shadow, invisible
color colShadow = color.rgb(0, 0, 0, 100)
color colNone = color.rgb(0, 0, 0, 100)
// rsi color
//color colRSI = RSI >=30 ? color.red : color.gray
color colRSI = RSI < -31 ? color.lime : RSI > 31 ? color.red : color.gray
cross_up = RSI > 30
cross_down = RSI < -30
// candle body colouring
color bodyColour = C > O ? i_colUp : i_colDown
color wickColour = i_colWick
////////////////////////////////////////////////////////////////////////////////
// //
// ====== DRAWING and PLOTTING ====== //
// //
////////////////////////////////////////////////////////////////////////////////
plotchar(cross_down and wwttBuyShow and buySignal ? -107 : na, title='Buy circle', char='·', color=color.new(colorGreen, 10), location=location.absolute, size=size.small)
plotchar(cross_up and wwttSellShow and sellSignal ? 105 : na, title='Sell circle', char='·', color=color.new(colorRed, 10), location=location.absolute, size=size.small)
plotchar(cross_down and wwttDivShow and buySignalDiv and wwttBuyShow and buySignal ? -106 : na, title='Divergence buy circle', char='▲', color=buySignalDiv_color, location=location.absolute, size=size.tiny, offset=-2, transp=10)
plotchar(cross_up and wwttDivShow and sellSignalDiv and wwttSellShow and sellSignal ? 106 : na, title='Divergence sell circle', char='▼', color=sellSignalDiv_color, location=location.absolute, size=size.tiny, offset=-2, transp=10)
//Alerts
alertcondition((cross_down and wwttBuyShow and buySignal and wwttDivShow and buySignalDiv) or (cross_up and wwttSellShow and sellSignal and wwttDivShow and sellSignalDiv), title='Buy/Sell Signal', message='Buy/Sell Signal')