Hidden Markov ModelDescription
This model uses a Hidden Markov Model to detect potential tops and bottoms. It is designed to probabilistically identify market regime changes and predict potential reversal point using a forward algorithm to calculate the probability of a state.
State 0: (Normal Trading): Market continuation patterns, balanced buying/selling
State 1: (Top Formation): Exhaustion patterns at price highs
State 2: (Bottom Formation): Capitulation patterns at price lows
Background: The HMM assumes that market behavior follows hidden states that aren't directly observable, but can be inferred from observable market data (emissions). The model uses a (somewhat simplified) Bayesian inference to estimate these probabilities.
How to use
1) Identify the trend (you can also use it counter-trend)
2) For longing, look for a green arrow. The probability values should be red. For shorting, look for a red arrow. The probability values should be green
3) For added confluence, look for high probability values
Statistics
Alpha Trend Strength Pro🔥 What You’ll See on the Chart
✅ A floating label appears near the most recent candle.
✅ Label shows:
🔥 Trend direction: Uptrend / Downtrend / Neutral / Near VWAP
💪 Trend strength: Strong / Moderate / Weak / Range
📈 EMA alignment
🎯 RSI momentum state
💥 MACD crossover
📊 Volatility condition (Expanding / Contracting)
🔵 VWAP proximity if enabled
✅ The chart background turns:
Green for Uptrend
Red for Downtrend
Neutral/Gray if in range (no background color)
⚙️ Customize Settings
Click the gear icon ⚙️ next to the script’s name on your chart.
Change things like:
Show/hide background color
Toggle VWAP-based filtering
Adjust RSI, MACD, Bollinger parameters
xetra//@version=5
indicator("First Candle Range", overlay=true)
// Налаштування сесії
session = input.session("0930-1030", title="Сесія")
// Визначити, чи поточна свічка — перша у сесії
is_new_session = ta.change(time(session))
// Змінні для збереження значень першої свічки
var float first_high = na
var float first_low = na
var int first_index = na
// Коли настає нова сесія — зберігаємо high та low першої свічки
if is_new_session
first_high := high
first_low := low
first_index := bar_index
// Побудова ліній
if not na(first_index)
line.new(first_index, first_high, bar_index, first_high, color=color.green, width=1, extend=extend.right)
line.new(first_index, first_low, bar_index, first_low, color=color.red, width=1, extend=extend.right)
// (Опційно) Заливка області між high та low
bgcolor(time(session) and bar_index == first_index ? color.new(color.orange, 85) : na)
ORB Screener-Multiple Indicators [Marin adjusted]ORB screener for multiple instruments. it needs just the customization of time/ timezone.
CLMM Vault策略回测 (专业版) v5Explanation of the CLMM (Concentrated Liquidity - Market Maker) Strategy Backtesting Model Developed for the Sui Chain Vaults Protocol
Why Are We Doing This?
Conducting strategy backtesting is a crucial step for us to make data-driven decisions, validate the feasibility of strategies, and manage potential risks before committing real funds and significant development resources. A strategy that appears to have a high APY may perform entirely differently once real-world frictional costs (such as rebalancing fees and slippage) are deducted. The goal of this backtesting model is to quickly and cost-effectively identify which strategy parameter combinations have the potential to be profitable and which ones pose risks before formal development, thereby avoiding significant losses and providing data support for the project's direction.
Core Features of the Backtesting Model
We have built a "pro version" (v5) strategy simulator using TradingView's Pine Script. It can quickly simulate the core performance of our auto-compounding and rebalancing Vaults on historical price data, with the following main features:
Auto-Compounding: Continuously adds the generated fee income to the principal based on the set profit range (e.g., 0.01%).
Auto-Rebalancing: Simulates automatic rebalancing actions when the price exceeds the preset profit range and deducts the corresponding costs.
Smart Filtering Mechanism: To make the simulation closer to our ideal "smart" decision-making, it integrates three freely combinable filtering mechanisms:
Buffer Zone: Tolerates minor and temporary breaches of the profit range to avoid unnecessary rebalancing.
Breakout Confirmation: Requires the price to be in the trigger zone for N consecutive candles to confirm a breakout, filtering out market noise from "false breakouts."
Time Cooldown: Enforces a minimum time interval between two rebalances to prevent value-destroying high-frequency trading in extreme market conditions.
Important: Simplifications and Assumptions of the Model
To quickly prototype and iterate on the TradingView platform, we have made some key simplifications to the model.
A fully accurate backtest would require a deep simulation of on-chain liquidity pools (Pool Pair), calculating the price impact (Slippage) and impermanent loss (IL) caused by each rebalance on the pool. Since TradingView cannot access real-time on-chain liquidity data, we have made the following simplifications:
Simplified Rebalancing Costs: Instead of simulating real transaction slippage, we use a unified input parameter of single rebalance cost (%) to "bundle" and approximate the total of Gas fees, slippage, and realized impermanent loss.
Simplified Fee Income: Instead of calculating fees based on real-time trading volume, we directly input an average fee annualized return (%) as the core income assumption for our strategy.
How to Use and Test
Team members can load this script and test different strategies by adjusting the input parameters on the panel. The most critical parameters include: position profit range, average fee annualized return, single rebalance cost, and the switches and corresponding values of the above three smart filters.
Previous Day O H L C Calculation By Md//@version=6
indicator("Previous Day O H L C Calculation By Md", overlay=true)
// Check if the previous daily candle is green (bullish) or red (bearish)
previousCandleBullish = close > open
previousCandleBearish = close < open
// Calculate the difference for bullish candles: previous day's high minus previous day's open
bullishCalculation = high - open
// Calculate the difference for bearish candles: previous day's low minus previous day's close
bearishCalculation = low - close
// Show the result at the top of the current daily candle if the previous candle was bullish
if previousCandleBullish
label.new(bar_index, high, "Bullish Calc: " + str.tostring(bullishCalculation), color=color.green, textcolor=color.white, style=label.style_label_left, size=size.small)
// Show the result at the bottom of the current daily candle if the previous candle was bearish
if previousCandleBearish
label.new(bar_index, low, "Bearish Calc: " + str.tostring(bearishCalculation), color=color.red, textcolor=color.white, style=label.style_label_left, size=size.small)
Previous Day/Week/Month - High/Lows + Open/Close (RC)Its an indicator marking previous day and previous week and last month's high, low open, close.
FastMetrixLibrary "FastMetrix"
This is a library I've been tweaking and working with for a while and I find it useful to get valuable technical analysis metrics faster (why its called FastMetrix). A lot of is personal to my trading style, so sorry if it does not have everything you want. The way I get my variables from library to script is by copying the return function into my new script.
TODO: Volatility and short term price analysis functions
slope(source, smoothing)
Parameters:
source (float)
smoothing (int)
integral(topfunction, bottomfunction, start, end)
Parameters:
topfunction (float)
bottomfunction (float)
start (int)
end (int)
deviation(x, y)
Parameters:
x (float)
y (float)
getema(len)
TODO: return important exponential long term moving averages and derivatives/variables
Parameters:
len (simple int)
getsma(len)
TODO: return requested sma
Parameters:
len (int)
kc(mult, len)
TODO: Return Keltner Channels variables and calculations
Parameters:
mult (simple float)
len (simple int)
bollinger(len, mult)
TODO: returns bollinger bands with optimal settings
Parameters:
len (int)
mult (simple float)
volatility(atrlen, smoothing)
TODO: Returns volatility indicators based on atr
Parameters:
atrlen (simple int)
smoothing (int)
premarketfib()
countinday(xcondition)
Parameters:
xcondition (bool)
countinsession(condition, n)
Parameters:
condition (bool)
n (int)
Session SizeAnalyze previous Sessions Size (Asia, London, New York) and give back the average range size in points.
Great tool if you want to take seriously the time and price
Open Interest Footprint IQ [TradingIQ]Hello Traders!
Th e Open Interest Footprint IQ indicator is an advanced visualization tool designed for cryptocurrency markets. It provides a granular, real-time breakdown of open interest changes across different price levels, allowing traders to see how aggressive market participation is distributed within each bar.
Unlike standard footprint charts that rely solely on volume, this indicator offers unique insights by focusing on the interaction between price action and changes in open interest (OI) — a leading metric often used to infer trader intent and positioning.
How it works
The Open Interest Footprint IQ processes lower timeframe price and open interest data to build a footprint-style chart that shows how traders are positioning themselves within each candle.
Here’s a breakdown of the process:
1. Granular OI & Price Sampling
The script retrieves lower-timeframe data (1-minute, 1-second, or 1-tick, based on your setting).
For each candle, it captures:
High and low prices
Price change direction
Change in open interest (OI)
2. Classifying Trader Behavior
For each lower-timeframe segment, the indicator determines the type of positioning occurring based on price movement and OI change:
If price is moving up and open interest is increasing, it suggests that long positions are being opened. This is considered a "Longs Opening" event, labeled as UU (Up/Up).
If price is moving up but open interest is decreasing, it indicates that short positions are being closed. This is referred to as UD (Up/Down), or "Shorts Closing."
If price is moving down and open interest is increasing, it signals that short positions are being opened. This is known as DU (Down/Up), or "Shorts Opening."
If price is moving down while open interest is also decreasing, it means that long positions are being closed. This is labeled as DD (Down/Down), or "Longs Closing."
These are stored in separate arrays and displayed at specific price levels.
It is particularly useful for identifying:
Where longs or shorts are opening/closing positions
Stacked imbalances (indicative of potential absorption or exhaustion)
Value area zones and POC (Point of Control) based on OI, not volume
This footprint runs on your choice of sub-bar granularity and is ideal for high-frequency trading, scalping, and entries based on order flow dynamics.
Key Features
Footprint Visualization
At each price level within a candle:
Long/short opening and closing behavior is broken down.
Delta (net open interest change) is displayed both numerically and color-coded.
Optional gradient coloring shows intensity and type of flow (longs/shorts opened/closed).
Cumulative or per-bar reset modes allow you to track OI evolution over time.
The image above explains the information that each Footprint box shows across a candlestick!
Each footprint box shows:
OI Delta
OI Delta %
Longs Opened (LO)
Longs Closed (LC)
Shorts Opened (SO)
Shorts Closed (SC)
The image above explains the color-coding feature of the indicator.
Boxes are color coded to show which position action
dominated at the price area.
For this example:
Green boxes = Long positions being opened dominated
Purple boxes = Long positions being closed dominated
Red boxes = Short positions being opened dominated
Yellow boxes = Short positions being closed dominated
All colors are customizable.
Additionally, for traders who are only interested in whether OI increased/decreased, a "two-color" option is available in the settings.
For the two-color option, footprint boxes can be one of two colors. Showing whether OI increased or decreased at the level.
Cumulative Levels
Open Interest Footprint IQ contains a "Cumulative Levels" feature that tracks/stores open interest change at tick levels over time, rather than resetting per bar.
With the "Cumulative Levels" feature enabled, traders can see open interest changes persist across all candlesticks. This feature is useful for determining whether longs opening, longs closing, shorts opening, or shorts closing are dominating at particular price areas over time rather than on a single bar.
A useful feature to see if shorts/longs are favoring certain price throughout the day, week, month, etc.
Input Settings Explained
Granularity (Dropdown: Granularity)
Options: 1-Minute, 1-Second, 1-Tick
Determines how finely the script samples the lower timeframe data to construct the footprint.
For precision:
1-Tick = Highest accuracy, but more resource-intensive.
1-Second/1-Minute = Suitable for broader or more zoomed-out analysis.
Tick Level Distance (Tick Level Distance (0 = Auto))
Defines the vertical spacing between levels in the footprint chart.
If 0, the script uses an automatic calculation based on ATR to adapt to volatility.
Set a manual value (e.g., 5) to control the height granularity of each level in ticks.
Cumulative Levels (Toggle)
If enabled, the footprint builds cumulatively over time, rather than resetting per candle.
Use case: Visualize ongoing buildup of OI activity across a session or day.
Cumulative Levels Reset TF (Timeframe)
Sets the reset interval for the cumulative view (e.g., reset daily, hourly, etc.)
Works only when Cumulative Levels is enabled.
Delta Box Display Settings
Show Delta Percentage
Toggles the display of the percentage change in OI across the footprint level.
Helpful to gauge how aggressive positioning is relative to total OI at that level.
Show Longs/Shorts (Opened/Closed)
Show Longs Opened: Displays OI increase in up candles (price ↑, OI ↑).
Show Longs Closed: Displays OI decrease in down candles (price ↓, OI ↓).
Show Shorts Opened: OI increase in down candles (price ↓, OI ↑).
Show Shorts Closed: OI decrease in up candles (price ↑, OI ↓).
These behaviors are color-coded to give traders instant context:
Blue-green for longs opening.
Purple for longs closing.
Red for shorts opening.
Yellow for shorts closing.
Value Area & POC
Value Area % (Value Area %)
Controls how much cumulative open interest is used to define the value area.
Example: 70% means the smallest range of prices that contains 70% of total OI in that bar will be marked.
Helps identify zones of interest, support/resistance, and institutional levels.
The image above explains how to identify the VAH/VAL/POC shown by Open Interest Footprint IQ.
VAH = Upper 🞂
POC = ●
VAL = Lower 🞂
Imbalances
Imbalance Percentage
Defines the minimum delta % required at a level to be marked as an imbalance.
If the net open interest change at a level exceeds this threshold, a visual marker appears.
Stacked Imbalance Count
If the number of consecutive imbalance levels meets this count, a “Stacked Imbalance” alert will trigger.
This can signal aggressive buying or selling pressure, potential breakout zones, or institutional absorption.
Color Settings
Longs Opened / Closed, Shorts Opened / Closed
Customize the color palette for each order flow behavior.
These colors appear in the background gradient of the footprint boxes.
Up/Down Only Mode
Toggle to override all behavior-based colors with a single Up Color and Down Color.
Useful if you prefer a simple bull/bear view.
Up Color / Down Color
If "Up/Down Only" is enabled, these two colors are used to represent all net positive or negative deltas.
Special Notes
Crypto only: This script works only with crypto tickers on TradingView.
For other assets (stocks, futures), a warning message will appear instead.
OI data must be available from the exchange (many perpetual pairs support this).
If the footprint is too small or invisible, increase your tick level spacing in the settings.
Alerts
When a stacked imbalance is detected, an alert is fired ("Stacked Imbalance").
This feature is useful for automated systems, bots, or simply staying informed of potential trade setups.
And that's all for now!
If you have any questions or features you'd like to see feel free to share them in the comments below!
Thank you traders!
LoggersLibrary "Loggers"
helper functions for easily logging debug info into the console and for coloring them dynamically according to their meaning.
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
loginfo(name, value, unit)
Parameters:
name (string)
value (float)
unit (string)
loginfo(name, value, unit)
Parameters:
name (string)
value (bool)
unit (string)
loginfo(name, value, unit)
Parameters:
name (string)
value (int)
unit (string)
logwarning(name, value, unit)
Parameters:
name (string)
value (float)
unit (string)
logwarning(name, value, unit)
Parameters:
name (string)
value (bool)
unit (string)
logwarning(name, value, unit)
Parameters:
name (string)
value (int)
unit (string)
logerror(name, value, unit)
Parameters:
name (string)
value (float)
unit (string)
logerror(name, value, unit)
Parameters:
name (string)
value (bool)
unit (string)
logerror(name, value, unit)
Parameters:
name (string)
value (int)
unit (string)
logdynamic_lowbad(name, value, unit, treshold_yellow, treshold_red)
Parameters:
name (string)
value (float)
unit (string)
treshold_yellow (float)
treshold_red (float)
logdynamic_lowbad(name, value, unit, treshold_yellow, treshold_red)
Parameters:
name (string)
value (int)
unit (string)
treshold_yellow (float)
treshold_red (float)
logdynamic_highbad(name, value, unit, treshold_yellow, treshold_red)
Parameters:
name (string)
value (float)
unit (string)
treshold_yellow (float)
treshold_red (float)
logdynamic_highbad(name, value, unit, treshold_yellow, treshold_red)
Parameters:
name (string)
value (int)
unit (string)
treshold_yellow (float)
treshold_red (float)
logdynamic_falsebad(name, value, unit)
Parameters:
name (string)
value (bool)
unit (string)
logdynamic_truebad(name, value, unit)
Parameters:
name (string)
value (bool)
unit (string)
Auto LevelsAutomatically paints open, high, low, and close levels from previous periods.
RTH data only in traditional cash markets.
Previous periods included are:
- Day
- Week
- Month
- Quarter
- Year.
Customization options allow for:
- Enabling/disabling of each type of level for each period
- Text size and colors of labels
- Colors and styles of lines
- Line extension length
*Also, there is a close-price ray included. Can be disabled.
Creates new levels once they generate, and removes old and outdated levels.
The idea is to be transparent about the relevancy of levels and portray them as they generate in time. Full 2-way-ray horizontal lines can appear to give false-reaction data in historical bars from before the level was generated. This can give traders a false sense of importance to a level.
Works on any ticker/symbol.
Known bugs:
** Open levels distort based on open/closed status in traditional markets. Fix pending.
** Different candle types (Heikin Ashi) distort all open/close level data. Fix pending.
** Line extension doesn't work in closed markets. Fix pending.
Message me on twitter for other bug reports.
Z Score Overlay [BigBeluga]🔵 OVERVIEW
A clean and effective Z-score overlay that visually tracks how far price deviates from its moving average. By standardizing price movements, this tool helps traders understand when price is statistically extended or compressed—up to ±4 standard deviations. The built-in scale and real-time bin markers offer immediate context on where price stands in relation to its recent mean.
🔵 CONCEPTS
Z Score Calculation:
Z = (Close − SMA) ÷ Standard Deviation
This formula shows how many standard deviations the current price is from its mean.
Statistical Extremes:
• Z > +2 or Z < −2 suggests statistically significant deviation.
• Z near 0 implies price is close to its average.
Standardization of Price Behavior: Makes it easier to compare volatility and overextension across timeframes and assets.
🔵 FEATURES
Colored Z Line: Gradient coloring based on how far price deviates—
• Red = oversold (−4),
• Green = overbought (+4),
• Yellow = neutral (~0).
Deviation Scale Bar: A vertical scale from −4 to +4 standard deviations plotted to the right of price.
Active Z Score Bin: Highlights the current Z-score bin with a “◀” arrow
Context Labels: Clear numeric labels for each Z-level from −4 to +4 along the side.
Live Value Display: Shows exact Z-score on the active level.
Non-intrusive Overlay: Can be applied directly to price chart without changing scaling behavior.
🔵 HOW TO USE
Identify overbought/oversold areas based on +2 / −2 thresholds.
Spot potential mean reversion trades when Z returns from extreme levels.
Confirm strong trends when price remains consistently outside ±2.
Use in multi-timeframe setups to compare strength across contexts.
🔵 CONCLUSION
Z Score Overlay transforms raw price action into a normalized statistical view, allowing traders to easily assess deviation strength and mean-reversion potential. The intuitive scale and color-coded display make it ideal for traders seeking objective, volatility-aware entries and exits.
Daily Trading Barometer (DTB) with DJIA OverlayThe "Daily Trading Barometer (DTB) with DJIA Overlay" is a custom technical indicator designed to identify intermediate-term overbought and oversold conditions in the stock market, inspired by Edson Gould's original DTB methodology. This indicator combines three key components:
A 7-day advance-decline oscillator, a 20-day volume oscillator, and a 28-day DJIA price ratio, normalized into a composite index scaled around 110–135. Values below 110 signal potential oversold conditions, while values above 135 indicate overbought territory, aiding in timing market reversals.
The overlay of a normalized DJIA plot allows for visual correlation with the broader market trend. Use this tool to anticipate turning points in oscillating markets, though it’s best combined with other indicators for confirmation. Ideal for traders seeking probabilistic insights into bear or bull market transitions.
How to use -
If the DTB line (blue) and normalized DJIA (orange) are under the green dashed line, high probability for a long and reversal.
Use with the symbol SPX/QQQ
Dow Jones Industrial Average - DJIA
Gap % Distribution Table (2% Bins)Description
This indicator displays a Gap % Distribution Table categorized in 2% bins ranging from `< -20%` to `> +20%`. It calculates the gap between today’s open and the previous day’s close, and groups occurrences into defined bins. The table includes:
Gap range, count, and percentage for each bin
A total row summarizing all entries
Customizable appearance including:
Font color, cell background fill (with transparency), and table border color
Column headers and full outer border
Date filtering using selectable start and end dates
Position control for placing the table on the chart area
Ideal for analyzing the historical behavior of opening gaps for any instrument.
Average Day Range(%)Average Day Range in percentages. This indicator shows that average movement of the stock price in last n number of candles in percentages. This gives you an idea of the volatility of the stock's price.
SIP Evaluator and Screener [Trendoscope®]The SIP Evaluator and Screener is a Pine Script indicator designed for TradingView to calculate and visualize Systematic Investment Plan (SIP) returns across multiple investment instruments. It is tailored for use in TradingView's screener, enabling users to evaluate SIP performance for various assets efficiently.
🎲 How SIP Works
A Systematic Investment Plan (SIP) is an investment strategy where a fixed amount is invested at regular intervals (e.g., monthly or weekly) into a financial instrument, such as stocks, mutual funds, or ETFs. The goal is to build wealth over time by leveraging the power of compounding and mitigating the impact of market volatility through disciplined, consistent investing. Here’s a breakdown of how SIPs function:
Regular Investments : In an SIP, an investor commits to investing a fixed sum at predefined intervals, regardless of market conditions. This consistency helps inculcate a habit of saving and investing.
Cost Averaging : By investing a fixed amount regularly, investors purchase more units when prices are low and fewer units when prices are high. This approach, known as dollar-cost averaging, reduces the average cost per unit over time and mitigates the risk of investing a large amount at a peak price.
Compounding Benefits : Returns generated from the invested amount (e.g., capital gains or dividends) are reinvested, leading to exponential growth over the long term. The longer the investment horizon, the greater the potential for compounding to amplify returns.
Dividend Reinvestment : In some SIPs, dividends received from the underlying asset can be reinvested to purchase additional units, further enhancing returns. Taxes on dividends, if applicable, may reduce the reinvested amount.
Flexibility and Accessibility : SIPs allow investors to start with small amounts, making them accessible to a wide range of individuals. They also offer flexibility in terms of investment frequency and the ability to adjust or pause contributions.
In the context of the SIP Evaluator and Screener , the script simulates an SIP by calculating the number of units purchased with each fixed investment, factoring in commissions, dividends, taxes and the chosen price reference (e.g., open, close, or average prices). It tracks the cumulative investment, equity value, and dividends over time, providing a clear picture of how an SIP would perform for a given instrument. This helps users understand the impact of regular investing and make informed decisions when comparing different assets in TradingView’s screener. It offers insights into key metrics such as total invested amount, dividends received, equity value, and the number of installments, making it a valuable resource for investors and traders interested in understanding long-term investment outcomes.
🎲 Key Features
Customizable Investment Parameters: Users can define the recurring investment amount, price reference (e.g., open, close, HL2, HLC3, OHLC4), and whether fractional quantities are allowed.
Commission Handling: Supports both fixed and percentage-based commission types, adjusting calculations accordingly.
Dividend Reinvestment: Optionally reinvests dividends after a user-specified period, with the ability to apply tax on dividends.
Time-Bound Analysis: Allows users to set a start year for the analysis, enabling historical performance evaluation.
Flexible Dividend Periods: Dividends can be evaluated based on bars, days, weeks, or months.
Visual Outputs: Plots key metrics like total invested amount, dividends, equity value, and remainder, with customizable display options for clarity in the data window and chart.
🎲 Using the script as an indicator on Tradingview Supercharts
In order to use the indicator on charts, do the following.
Load the instrument of your choice - Preferably a stable stocks, ETFs.
Chose monthly timeframe as lower timeframes are insignificant in this type of investment strategy
Load the indicator SIP Evaluator and Screener and set the input parameters as per your preference.
Indicator plots, investment value, dividends and equity on the chart.
🎲 Visualizations
Installments : Displays the number of SIP installments (gray line, visible in the data window).
Invested Amount : Shows the cumulative amount invested, excluding reinvested dividends (blue area plot).
Dividends : Tracks total dividends received (green area plot).
Equity : Represents the current market value of the investment based on the closing price (purple area plot).
Remainder : Indicates any uninvested cash after each installment (gray line, visible in the data window).
🎲 Deep dive into the settings
The SIP Evaluator and Screener offers a range of customizable settings to tailor the Systematic Investment Plan (SIP) simulation to your preferences. Below is an explanation of each setting, its purpose, and how it impacts the analysis:
🎯 Duration
Start Year (Default: 2020) : Specifies the year from which the SIP calculations begin. When Start Year is enabled via the timebound option, the script only considers data from the specified year onward. This is useful for analyzing historical SIP performance over a defined period. If disabled, the script uses all available data.
Timebound (Default: False) : A toggle to enable or disable the Start Year restriction. When set to False, the SIP calculation starts from the earliest available data for the instrument.
🎯 Investment
Recurring Investment (Default: 1000.0) : The fixed amount invested in each SIP installment (e.g., $1000 per period). This represents the regular contribution to the SIP and directly influences the total invested amount and quantity purchased.
Allow Fractional Qty (Default: True) : When enabled, the script allows the purchase of fractional units (e.g., 2.35 shares). If disabled, only whole units are purchased (e.g., 2 shares), with any remaining funds carried forward as Remainder. This setting impacts the precision of investment allocation.
Price Reference (Default: OPEN): Determines the price used for purchasing units in each SIP installment. Options include:
OPEN : Uses the opening price of the bar.
CLOSE : Uses the closing price of the bar.
HL2 : Uses the average of the high and low prices.
HLC3 : Uses the average of the high, low, and close prices.
OHLC4 : Uses the average of the open, high, low, and close prices. This setting affects the cost basis of each purchase and, consequently, the total quantity and equity value.
🎯 Commission
Commission (Default: 3) : The commission charged per SIP installment, expressed as either a fixed amount (e.g., $3) or a percentage (e.g., 3% of the investment). This reduces the amount available for purchasing units.
Commission Type (Default: Fixed) : Specifies how the commission is calculated:
Fixed ($) : A flat fee is deducted per installment (e.g., $3).
Percentage (%) : A percentage of the investment amount is deducted as commission (e.g., 3% of $1000 = $30). This setting affects the net amount invested and the overall cost of the SIP.
🎯 Dividends
Apply Tax On Dividends (Default: False) : When enabled, a tax is applied to dividends before they are reinvested or recorded. The tax rate is set via the Dividend Tax setting.
Dividend Tax (Default: 47) : The percentage of tax deducted from dividends if Apply Tax On Dividends is enabled (e.g., 47% tax reduces a $100 dividend to $53). This reduces the amount available for reinvestment or accumulation.
Reinvest Dividends After (Default: True, 2) : When enabled, dividends received are reinvested to purchase additional units after a specified period (e.g., 2 units of time, defined by Dividends Availability). If disabled, dividends are tracked but not reinvested. Reinvestment increases the total quantity and equity over time.
Dividends Availability (Default: Bars) : Defines the time unit for evaluating when dividends are available for reinvestment. Options include:
Bars : Based on the number of chart bars.
Weeks : Based on weeks.
Months : Based on months (approximated as 30.5 days). This setting determines the timing of dividend reinvestment relative to the Reinvest Dividends After period.
🎯 How Settings Interact
These settings work together to simulate a realistic SIP. For example, a $1000 recurring investment with a 3% commission and fractional quantities enabled will calculate the number of units purchased at the chosen price reference after deducting the commission. If dividends are reinvested after 2 months with a 47% tax, the script fetches dividend data, applies the tax, and adds the net dividend to the investment amount for that period. The Start Year and Timebound settings ensure the analysis aligns with the desired timeframe, while the Dividends Availability setting fine-tunes dividend reinvestment timing.
By adjusting these settings, users can model different SIP scenarios, compare performance across instruments in TradingView’s screener, and gain insights into how commissions, dividends, and price references impact long-term returns.
🎲 Using the script with Pine Screener
The main purpose of developing this script is to use it with Tradingview Pine Screener so that multiple ETFs/Funds can be compared.
In order to use this as a screener, the following things needs to be done.
Add SIP Evaluator and Screener to your favourites (Required for it to be added in pine screener)
Create a watch list containing required instruments to compare
Open pine screener from Tradingview main menu Products -> Screeners -> Pine or simply load the URL - www.tradingview.com
Select the watchlist created from Watchlist dropdown.
Chose the SIP Evaluator and Screener from the "Choose Indicator" dropdown
Set timeframe to 1 month and update settings as required.
Press scan to display collected data on the screener.
🎲 Use Case
This indicator is ideal for educational purposes, allowing users to experiment with SIP strategies across different instruments. It can be applied in TradingView’s screener to compare SIP performance for stocks, ETFs, or other assets, helping users understand how factors like commissions, dividends, and price references impact returns over time.
QQQ NQ NDX SPY SPX ES Price Convert Overlay
_____________________________________________________________________
QQQ NQ NDX SPY SPX ES Price Convert Overlay Indicator
____________________
This 'Prices Overlay' indicator is a minimalist tool for traders who want to track and compare Nasdaq and S&P 500 instruments quickly and clearly, boosting efficiency and decision-making with minimal distraction.
How to Use It
____________________
Add the indicator onto your TradingView chart.
Adjust your Right Margin in TradingView Settings > Canvas to show as much or as little of the line as you want, based on the "Price Buffer" indicator setting.
Select which instruments to overlay (e.g., QQQ, SPX).
Adjust levels, buffer, font, transparency, and update interval.
Features and Functions
____________________
1. Automatic Ticker Detection:
The indicator identifies the ticker of your current chart (e.g., NQ, ES, SPY).
It then shows price levels for related instruments, eg:
On an NQ or MNQ chart, it can display QQQ or NDX levels.
On an ES or MES chart, it can display SPY or SPX levels.
...and vice versa
2. Adjustable Number of Levels
You can choose how many price levels to show, from 10 to 100.
This lets you decide how much detail you want based on your trading needs.
3. Visual Customization
Price Buffer: Move the lines and labels horizontally closer/further price action.
Font Size: Pick from "Tiny," "Small," or "Normal" for label text size.
Line Transparency: Adjust the opacity of the lines (0% = solid, 100% = invisible) to blend them with your chart.
4. Support for Micro Futures
Works with both regular futures (NQ, ES) and micro futures (MNQ, MES), perfect for traders using smaller contract sizes.
5. Update Frequency
Set how often the price levels refresh, from every 5 seconds to every 60 seconds.
This keeps the data current without slowing down your chart.
6. Accurate Price Conversion
Uses specific multipliers for each instrument (e.g., 100.0 for NDX and SPX, 1.0 for QQQ and SPY) to calculate and display price levels correctly.
Fetches real-time prices and converts them to match your chart’s scale.
Price conversions courtesy of PtGambler.
Benefits
____________________
Easier Analysis: See how prices from different instruments line up on one chart—no need for multiple screens or math.
Customizable: Turn on/off instruments and tweak visuals to fit your trading style.
Time-Saving: Automates price conversions, letting you focus on trading decisions.
Thanks!
____________________
Thank you for your interest in my work. This is something I use every day for my trading and wanted to share it with the public. If you have any comments, bugs, or suggestions, please leave them here, or you can find me on Twitter or Discord.
@ ContrarianIRL
Open-source developer for over 25 years
AMT Regime-Switch Long/ShortAMT Switch Long / Short.
Pos. Taking
Up‑triangles (green) = Long entry signals
Down‑triangles (red) = Short entry signals
Green background = Trending regime (ATR above its MA and volatility in top 40 %).
Orange background = Ranging regime (ATR below MA and vol in bottom 40 %).
No shading = Transition zone (mixed regime).
This tells you which sub‑strategy is active.
Pos. Taking
Up‑triangles (green) = Long entry signals
Down‑triangles (red) = Short entry signals
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*