Поиск скриптов по запросу "富时中国50期指"
UO_30-50-70Ultimate Oscillator with bands present at the 30, 50, and 70 pt levels.
Personally use this every time, created a script to hard code these lines so I wouldn't need to redraw them all the time.
Enjoy
The Lazy Trader - Index (ETF) Trend Following Robot50/150 moving average, index (ETF) trend following robot. Coded for people who cannot psychologically handle dollar-cost-averaging through bear markets and extreme drawdowns (although DCA can produce better results eventually), this robot helps you to avoid bear markets. Be a fair-weathered friend of Mr Market, and only take up his offer when the sun is shining! Designed for the lazy trader who really doesn't care...
Recommended Chart Settings:
Asset Class: ETF
Time Frame: Daily
Necessary ETF Macro Conditions:
a) Country must have healthy demographics, good ratio of young > old
b) Country population must be increasing
c) Country must be experiencing price-inflation
Default Robot Settings:
Slow Moving Average: 50 (integer) //adjust to suit your underlying index
Fast Moving Average: 150 (integer) //adjust to suit your underlying index
Bullish Slope Angle: 5 (degrees) //up angle of moving averages
Bearish Slope Angle: -5 (degrees) //down angle of moving averages
Average True Range: 14 (integer) //input for slope-angle formula
Risk: 100 (%) //100% risk means using all equity per trade
ETF Test Results (Default Settings):
SPY (1993 to 2020, 27 years), 332% profit, 20 trades, 6.4 profit factor, 7% drawdown
EWG (1996 to 2020, 24 years), 310% profit, 18 trades, 3.7 profit factor, 10% drawdown
EWH (1996 to 2020, 24 years), 4% loss, 26 trades, 0.9 profit factor, 36% drawdown
QQQ (1999 to 2020, 21 years), 232% profit, 17 trades, 3.6 profit factor, 2% drawdown
EEM (2003 to 2020, 17 years), 73% profit, 17 trades, 1.1 profit factor, 3% drawdown
GXC (2007 to 2020, 13 years), 18% profit, 14 trades, 1.3 profit factor, 26% drawdown
BKF (2009 to 2020, 11 years), 11% profit, 13 trades, 1.2 profit factor, 33% drawdown
A longer time in the markets is better, with the exception of EWH. 6 out of 7 tested ETFs were profitable, feel free to test on your favourite ETF (default settings) and comment below.
Risk Warning:
Not tested on commodities nor other financial products like currencies (code will not work), feel free to leave comments below.
Moving Average Slope Angle Formula:
Reproduced and modified from source:
50-Line Oscillator // (\_/)
// ( •.•)
// (")_(")
25-Line Oscillator
Description:
The 25-Line Oscillator is a sophisticated technical analysis tool designed to visualize market trends through the use of multiple Simple Moving Averages (SMAs). This indicator computes a series of 26 SMAs, incrementally increasing the base length, providing traders with a comprehensive view of price dynamics.
Features:
Customizable Base Length: Adjust the base length of the SMAs according to trading preferences, enhancing versatility for different market conditions.
Rainbow Effect: The indicator employs a visually appealing rainbow color scheme to differentiate between the various trend lines, making it easy to identify crossovers and momentum shifts.
Crossovers Detection: The script includes logic to detect crossover events between consecutive trend lines, which can serve as signals for potential entry or exit points in trading.
Clear Visualization: Suitable for both novice and seasoned traders, the plots enable quick interpretation of trends and market behavior.
How to Use:
Add the indicator to your chart and customize the base length as desired.
Observe the rainbow-colored lines for trend direction.
Look for crossover events between the SMAs as potential trading signals.
Application: This indicator is particularly useful for swing traders and trend followers who aim to capitalize on market momentum and identify reversals. By monitoring the behavior of multiple SMAs, traders can gain insights into the strength and direction of price movements over various time frames.
AK Simple Moving Average 50 days Simple Moving average suitable for Intraday on 1Hr,30Min.15Min Time frames
1. When candle crossing above SMA Line - Go for Long Entries
2. When candle crossing below SMA Line - Go for short Entries
50 SMA / 200 EMA / 128EMA Moving Average CrossFound success using 50SMA vs 200EMA.
128 EMA also charted for it's BTC relevance.
50/100/200 Moving Averages (Pine Script For Copy)by fresca
SCRIPT LANGUAGE
Copy script below and adjust based on your preferences.
-function (change function from "sma" to "ema", "wma" and more)
-length (25 Day, 150 Day or add more averages to the three in this script.)
-color, (red, yellow, etc. or use color hex codes i.e. #FEDA15, #FFAD8F, etc.)
-transparency (set to desired level 1-100)
Or add more options.
RESOURCES
Color hex codes site: www.canva.com
Trading View Pine Script Editor Reference Guide: www.tradingview.com
Taint's Multi Time Frame MA50-100-200 SMA with two 200 EMA's all with the ability choose a time frame for each.
Martingale Strategy Simulator [BackQuant]Martingale Strategy Simulator
Purpose
This indicator lets you study how a martingale-style position sizing rule interacts with a simple long or short trading signal. It computes an equity curve from bar-to-bar returns, adapts position size after losing streaks, caps exposure at a user limit, and summarizes risk with portfolio metrics. An optional Monte Carlo module projects possible future equity paths from your realized daily returns.
What a martingale is
A martingale sizing rule increases stake after losses and resets after a win. In its classical form from gambling, you double the bet after each loss so that a single win recovers all prior losses plus one unit of profit. In markets there is no fixed “even-money” payout and returns are multiplicative, so an exact recovery guarantee does not exist. The core idea is unchanged:
Lose one leg → increase next position size
Lose again → increase again
Win → reset to the base size
The expectation of your strategy still depends on the signal’s edge. Sizing does not create positive expectancy on its own. A martingale raises variance and tail risk by concentrating more capital as a losing streak develops.
What it plots
Equity – simulated portfolio equity including compounding
Buy & Hold – equity from holding the chart symbol for context
Optional helpers – last trade outcome, current streak length, current allocation fraction
Optional diagnostics – daily portfolio return, rolling drawdown, metrics table
Optional Monte Carlo probability cone – p5, p16, p50, p84, p95 aggregate bands
Model assumptions
Bar-close execution with no slippage or commissions
Shorting allowed and frictionless
No margin interest, borrow fees, or position limits
No intrabar moves or gaps within a bar (returns are close-to-close)
Sizing applies to equity fraction only and is capped by your setting
All results are hypothetical and for education only.
How the simulator applies it
1) Directional signal
You pick a simple directional rule that produces +1 for long or −1 for short each bar. Options include 100 HMA slope, RSI above or below 50, EMA or SMA crosses, CCI and other oscillators, ATR move, BB basis, and more. The stance is evaluated bar by bar. When the stance flips, the current trade ends and the next one starts.
2) Sizing after losses and wins
Position size is a fraction of equity:
Initial allocation – the starting fraction, for example 0.15 means 15 percent of equity
Increase after loss – multiply the next allocation by your factor after a losing leg, for example 2.00 to double
Reset after win – return to the initial allocation
Max allocation cap – hard ceiling to prevent runaway growth
At a high level the size after k consecutive losses is
alloc(k) = min( cap , base × factor^k ) .
In practice the simulator changes size only when a leg ends and its PnL is known.
3) Equity update
Let r_t = close_t / close_{t-1} − 1 be the symbol’s bar return, d_{t−1} ∈ {+1, −1} the prior bar stance, and a_{t−1} the prior bar allocation fraction. The simulator compounds:
eq_t = eq_{t−1} × (1 + a_{t−1} × d_{t−1} × r_t) .
This is bar-based and avoids intrabar lookahead. Costs, slippage, and borrowing costs are not modeled.
Why traders experiment with martingale sizing
Mean-reversion contexts – if the signal often snaps back after a string of losses, adding size near the tail of a move can pull the average entry closer to the turn
Behavioral or microstructure edges – some rules have modest edge but frequent small whipsaws; size escalation may shorten time-to-recovery when the edge manifests
Exploration and stress testing – studying the relationship between streaks, caps, and drawdowns is instructive even if you do not deploy martingale sizing live
Why martingale is dangerous
Martingale concentrates capital when the strategy is performing worst. The main risks are structural, not cosmetic:
Loss streaks are inevitable – even with a 55 percent win rate you should expect multi-loss runs. The probability of at least one k-loss streak in N trades rises quickly with N.
Size explodes geometrically – with factor 2.0 and base 10 percent, the sequence is 10, 20, 40, 80, 100 (capped) after five losses. Without a strict cap, required size becomes infeasible.
No fixed payout – in gambling, one win at even odds resets PnL. In markets, there is no guaranteed bounce nor fixed profit multiple. Trends can extend and gaps can skip levels.
Correlation of losses – losses cluster in trends and in volatility bursts. A martingale tends to be largest just when volatility is highest.
Margin and liquidity constraints – leverage limits, margin calls, position limits, and widening spreads can force liquidation before a mean reversion occurs.
Fat tails and regime shifts – assumptions of independent, Gaussian returns can understate tail risk. Structural breaks can keep the signal wrong for much longer than expected.
The simulator exposes these dynamics in the equity curve, Max Drawdown, VaR and CVaR, and via Monte Carlo sketches of forward uncertainty.
Interpreting losing streaks with numbers
A rough intuition: if your per-trade win probability is p and loss probability is q=1−p , the chance of a specific run of k consecutive losses is q^k . Over many trades, the chance that at least one k-loss run occurs grows with the number of opportunities. As a sanity check:
If p=0.55 , then q=0.45 . A 6-loss run has probability q^6 ≈ 0.008 on any six-trade window. Across hundreds of trades, a 6 to 8-loss run is not rare.
If your size factor is 1.5 and your base is 10 percent, after 8 losses the requested size is 10% × 1.5^8 ≈ 25.6% . With factor 2.0 it would try to be 10% × 2^8 = 256% but your cap will stop it. The equity curve will still wear the compounded drawdown from the sequence that led to the cap.
This is why the cap setting is central. It does not remove tail risk, but it prevents the sizing rule from demanding impossible positions
Note: The p and q math is illustrative. In live data the win rate and distribution can drift over time, so real streaks can be longer or shorter than the simple q^k intuition suggests..
Using the simulator productively
Parameter studies
Start with conservative settings. Increase one element at a time and watch how the equity, Max Drawdown, and CVaR respond.
Initial allocation – lower base reduces volatility and drawdowns across the board
Increase factor – set modestly above 1.0 if you want the effect at all; doubling is aggressive
Max cap – the most important brake; many users keep it between 20 and 50 percent
Signal selection
Keep sizing fixed and rotate signals to see how streak patterns differ. Trend-following signals tend to produce long wrong-way streaks in choppy ranges. Mean-reversion signals do the opposite. Martingale sizing interacts very differently with each.
Diagnostics to watch
Use the built-in metrics to quantify risk:
Max Drawdown – worst peak-to-trough equity loss
Sharpe and Sortino – volatility and downside-adjusted return
VaR 95 percent and CVaR – tail risk measures from the realized distribution
Alpha and Beta – relationship to your chosen benchmark
If you would like to check out the original performance metrics script with multiple assets with a better explanation on all metrics please see
Monte Carlo exploration
When enabled, the forecast draws many synthetic paths from your realized daily returns:
Choose a horizon and a number of runs
Review the bands: p5 to p95 for a wide risk envelope; p16 to p84 for a narrower range; p50 as the median path
Use the table to read the expected return over the horizon and the tail outcomes
Remember it is a sketch based on your recent distribution, not a predictor
Concrete examples
Example A: Modest martingale
Base 10 percent, factor 1.25, cap 40 percent, RSI>50 signal. You will see small escalations on 2 to 4 loss runs and frequent resets. The equity curve usually remains smooth unless the signal enters a prolonged wrong-way regime. Max DD may rise moderately versus fixed sizing.
Example B: Aggressive martingale
Base 15 percent, factor 2.0, cap 60 percent, EMA cross signal. The curve can look stellar during favorable regimes, then a single extended streak pushes allocation to the cap, and a few more losses drive deep drawdown. CVaR and Max DD jump sharply. This is a textbook case of high tail risk.
Strengths
Bar-by-bar, transparent computation of equity from stance and size
Explicit handling of wins, losses, streaks, and caps
Portable signal inputs so you can A–B test ideas quickly
Risk diagnostics and forward uncertainty visualization in one place
Example, Rolling Max Drawdown
Limitations and important notes
Martingale sizing can escalate drawdowns rapidly. The cap limits position size but not the possibility of extended adverse runs.
No commissions, slippage, margin interest, borrow costs, or liquidity limits are modeled.
Signals are evaluated on closes. Real execution and fills will differ.
Monte Carlo assumes independent draws from your recent return distribution. Markets often have serial correlation, fat tails, and regime changes.
All results are hypothetical. Use this as an educational tool, not a production risk engine.
Practical tips
Prefer gentle factors such as 1.1 to 1.3. Doubling is usually excessive outside of toy examples.
Keep a strict cap. Many users cap between 20 and 40 percent of equity per leg.
Stress test with different start dates and subperiods. Long flat or trending regimes are where martingale weaknesses appear.
Compare to an anti-martingale (increase after wins, cut after losses) to understand the other side of the trade-off.
If you deploy sizing live, add external guardrails such as a daily loss cut, volatility filters, and a global max drawdown stop.
Settings recap
Backtest start date and initial capital
Initial allocation, increase-after-loss factor, max allocation cap
Signal source selector
Trading days per year and risk-free rate
Benchmark symbol for Alpha and Beta
UI toggles for equity, buy and hold, labels, metrics, PnL, and drawdown
Monte Carlo controls for enable, runs, horizon, and result table
Final thoughts
A martingale is not a free lunch. It is a way to tilt capital allocation toward losing streaks. If the signal has a real edge and mean reversion is common, careful and capped escalation can reduce time-to-recovery. If the signal lacks edge or regimes shift, the same rule can magnify losses at the worst possible moment. This simulator makes those trade-offs visible so you can calibrate parameters, understand tail risk, and decide whether the approach belongs anywhere in your research workflow.
RSI Multi Time FrameWhat it is
A clean, two-layer RSI that shows your chart-timeframe RSI together with a higher-timeframe (HTF) RSI on the same pane. The HTF line is drawn as a live segment plus frozen “steps” for each completed HTF bar, so you can see where the higher timeframe momentum held during your lower-timeframe bars.
How it works
Auto HTF mapping (when “Auto” is selected):
Intraday < 30m → uses 60m (1-hour) RSI
30m ≤ tf < 240m (4h) → uses 240m (4-hour) RSI
240m ≤ tf < 1D → uses 1D RSI
1D → uses 1W RSI
1W or 2W → uses 1M RSI
≥ 1M → keeps the same timeframe
The HTF series is requested with request.security(..., gaps_off, lookahead_off), so values are confirmed bar-by-bar. When a new HTF bar begins, the previous value is “frozen” as a horizontal segment; the current HTF value is shown by a short moving segment and a small dot (so you can read the last value easily).
Visuals
Current RSI (chart TF): solid line (color/width configurable).
HTF RSI: same-pane line + tiny circle for the latest value; historical step segments show completed HTF bars.
Guides: dashed 70 / 30 bands, dotted 60/40 helpers, dashed 50 midline.
Inputs
Higher Time Frame: Auto or a fixed TF (1, 3, 5, 10, 15, 30, 45, 60, 120, 180, 240, 360, 480, 720, D, W, 2W, M, 3M, 6M, 12M).
Length: RSI period (default 14).
Source: price source for RSI.
RSI / HTF RSI colors & widths.
Number of HTF RSI Bars: how many frozen HTF segments to keep.
Reading it
Alignment: When RSI (current TF) and HTF RSI both push in the same direction, momentum is aligned across frames.
Divergence across frames: Current RSI failing to confirm HTF direction can warn about chops or early slowdowns.
Zones: 70/30 boundaries for classic overbought/oversold; 60/40 can be used as trend bias rails; 50 is the balance line.
This is a context indicator, not a signal generator. Combine with your entry/exit rules.
Notes & limitations
HTF values do not repaint after their bar closes (lookahead is off). The short “live” segment will evolve until the HTF bar closes — this is expected.
Very small panels or extremely long histories may impact performance if you keep a large number of HTF segments.
Credits
Original concept by LonesomeTheBlue; Pine v6 refactor and auto-mapping rules by trading_mura.
Suggested use
Day traders: run the indicator on 5–15m and keep HTF on Auto to see 1h/4h momentum.
Swing traders: run it on 1h–4h and watch the daily HTF.
Position traders: run on daily and watch the weekly HTF.
If you find it useful, a ⭐ helps others discover it.
Multi SMA + Golden/Death + Heatmap + BB**Multi SMA (50/100/200) + Golden/Death + Candle Heatmap + BB**
A practical trend toolkit that blends classic 50/100/200 SMAs with clear crossover labels, special 🚀 Golden / 💀 Death Cross markers, and a readable candle heatmap based on a dynamic regression midline and volatility bands. Optional Bollinger Bands are included for context.
* See trend direction at a glance with SMAs.
* Get minimal, de-cluttered labels on important crosses (50↔100, 50↔200, 100↔200).
* Highlight big regime shifts with special Golden/Death tags.
* Read momentum and volatility with the candle heatmap.
* Add Bollinger Bands if you want classic mean-reversion context.
Designed to be lightweight, non-repainting on confirmed bars, and flexible across timeframes.
# What This Indicator Does (plain English)
* **Tracks trend** using **SMA 50/100/200** and lets you optionally compute each SMA on a higher or different timeframe (HTF-safe, no lookahead).
* **Prints labels** when SMAs cross each other (up or down). You can force signals only after bar close to avoid repaint.
* **Marks Golden/Death Crosses** (50 over/under 200) with special labels so major regime changes stand out.
* **Colors candles** with a **heatmap** built from a regression midline and volatility bands—greenish above, reddish below, with a smooth gradient.
* **Optionally shows Bollinger Bands** (basis SMA + stdev bands) and fills the area between them.
* **Includes alert conditions** for Golden and Death Cross so you can automate notifications.
---
# Settings — Simple Explanations
## Source
* **Source**: Price source used to calculate SMAs and Bollinger basis. Default: `close`.
## SMA 50
* **Show 50**: Turn the SMA(50) line on/off.
* **Length 50**: How many bars to average. Lower = faster but noisier.
* **Color 50** / **Width 50**: Visual style.
* **Timeframe 50**: Optional alternate timeframe for SMA(50). Leave empty to use the chart timeframe.
## SMA 100
* **Show 100**: Turn the SMA(100) line on/off.
* **Length 100**: Bars used for the mid-term trend.
* **Color 100** / **Width 100**: Visual style.
* **Timeframe 100**: Optional alternate timeframe for SMA(100).
## SMA 200
* **Show 200**: Turn the SMA(200) line on/off.
* **Length 200**: Bars used for the long-term trend.
* **Color 200** / **Width 200**: Visual style.
* **Timeframe 200**: Optional alternate timeframe for SMA(200).
## Signals (crossover labels)
* **Show crossover signals**: Prints triangle labels on SMA crosses (50↔100, 50↔200, 100↔200).
* **Wait for bar close (confirmed)**: If ON, signals only appear after the candle closes (reduces repaint).
* **Min bars between same-pair signals**: Minimum spacing to avoid duplicate labels from the same SMA pair too often.
* **Trend filter (buy: 50>100>200, sell: 50<100<200)**: Only show bullish labels when SMAs are stacked bullish (50 above 100 above 200), and only show bearish labels when stacked bearish.
### Label Offset
* **Offset mode**: Choose how to push labels away from price:
* **Percent**: Offset is a % of price.
* **ATR x**: Offset is ATR(14) × multiplier.
* **Percent of price (%)**: Used when mode = Percent.
* **ATR multiplier (for ‘ATR x’)**: Used when mode = ATR x.
### Label Colors
* **Bull color** / **Bear color**: Background of triangle labels.
* **Bull label text color** / **Bear label text color**: Text color inside the triangles.
## Golden / Death Cross
* **Show 🚀 Golden Cross (50↑200)**: Show a special “Golden” label when SMA50 crosses above SMA200.
* **Golden label color** / **Golden text color**: Styling for Golden label.
* **Show 💀 Death Cross (50↓200)**: Show a special “Death” label when SMA50 crosses below SMA200.
* **Death label color** / **Death text color**: Styling for Death label.
## Candle Heatmap
* **Enable heatmap candle colors**: Turns the heatmap on/off.
* **Length**: Lookback for the regression midline and volatility measure.
* **Deviation Multiplier**: Band width around the midline (bigger = wider).
* **Volatility basis**:
* **RMA Range** (smoothed high-low range)
* **Stdev** (standard deviation of close)
* **Upper/Middle/Lower color**: Gradient colors for the heatmap.
* **Heatmap transparency (0..100)**: 0 = solid, 100 = invisible.
* **Force override base candles**: Repaint base candles so heatmap stays visible even if your chart has custom coloring.
## Bollinger Bands (optional)
* **Show Bollinger Bands**: Toggle the overlay on/off.
* **Length**: Basis SMA length.
* **StdDev Multiplier**: Distance of bands from the basis in standard deviations.
* **Basis color** / **Band color**: Line colors for basis and bands.
* **Bands fill transparency**: Opacity of the fill between upper/lower bands.
---
# Features & How It Works
## 1) HTF-Safe SMAs
Each SMA can be calculated on the chart timeframe or a higher/different timeframe you choose. The script pulls HTF values **without lookahead** (non-repainting on confirmed bars).
## 2) Crossover Labels (Three Pairs)
* **50↔100**, **50↔200**, **100↔200**:
* **Triangle Up** label when the first SMA crosses **above** the second.
* **Triangle Down** label when it crosses **below**.
* Optional **Trend Filter** ensures only signals aligned with the overall stack (50>100>200 for bullish, 50<100<200 for bearish).
* **Debounce** spacing avoids repeated labels for the same pair too close together.
## 3) Golden / Death Cross Highlights
* **🚀 Golden Cross**: SMA50 crosses **above** SMA200 (often a longer-term bullish regime shift).
* **💀 Death Cross**: SMA50 crosses **below** SMA200 (often a longer-term bearish regime shift).
* Separate styling so they stand out from regular cross labels.
## 4) Candle Heatmap
* Builds a **regression midline** with **volatility bands**; colors candles by their position inside that channel.
* Smooth gradient: lower side → reddish, mid → yellowish, upper side → greenish.
* Helps you see momentum and “where price sits” relative to a dynamic channel.
## 5) Bollinger Bands (Optional)
* Classic **basis SMA** ± **StdDev** bands.
* Light visual context for mean-reversion and volatility expansion.
## 6) Alerts
* **Golden Cross**: `🚀 GOLDEN CROSS: SMA 50 crossed ABOVE SMA 200`
* **Death Cross**: `💀 DEATH CROSS: SMA 50 crossed BELOW SMA 200`
Add these to your alerts to get notified automatically.
---
# Tips & Notes
* For fewer false positives, keep **“Wait for bar close”** ON, especially on lower timeframes.
* Use the **Trend Filter** to align signals with the broader stack and cut noise.
* For HTF context, set **Timeframe 50/100/200** to higher frames (e.g., H1/H4/D) while you trade on a lower frame.
* Heatmap “Length” and “Deviation Multiplier” control smoothness and channel width—tune for your asset’s volatility.
Parameter Free RSI [InvestorUnknown]The Parameter Free RSI (PF-RSI) is an innovative adaptation of the traditional Relative Strength Index (RSI), a widely used momentum oscillator that measures the speed and change of price movements. Unlike the standard RSI, which relies on a fixed lookback period (typically 14), the PF-RSI dynamically adjusts its calculation length based on real-time market conditions. By incorporating volatility and the RSI's deviation from its midpoint (50), this indicator aims to provide a more responsive and adaptable tool for identifying overbought/oversold conditions, trend shifts, and momentum changes. This adaptability makes it particularly valuable for traders navigating diverse market environments, from trending to ranging conditions.
PF-RSI offers a suite of customizable features, including dynamic length variants, smoothing options, visualization tools, and alert conditions.
Key Features
1. Dynamic RSI Length Calculation
The cornerstone of the PF-RSI is its ability to adjust the RSI calculation period dynamically, eliminating the need for a static parameter. The length is computed using two primary factors:
Volatility: Measured via the standard deviation of past RSI values.
Distance from Midpoint: The absolute deviation of the RSI from 50, reflecting the strength of bullish or bearish momentum.
The indicator offers three variants for calculating this dynamic length, allowing users to tailor its responsiveness:
Variant I (Aggressive): Increases the length dramatically based on volatility and a nonlinear scaling of the distance from 50. Ideal for traders seeking highly sensitive signals in fast-moving markets.
Variant II (Moderate): Combines volatility with a scaled distance from 50, using a less aggressive adjustment. Strikes a balance between responsiveness and stability, suitable for most trading scenarios.
Variant III (Conservative): Applies a linear combination of volatility and raw distance from 50. Offers a stable, less reactive length adjustment for traders prioritizing consistency.
// Function that returns a dynamic RSI length based on past RSI values
// The idea is to make the RSI length adaptive using volatility (stdev) and distance from the RSI midpoint (50)
// Different "variant" options control how aggressively the length changes
parameter_free_length(free_rsi, variant) =>
len = switch variant
// Variant I: Most aggressive adaptation
// Uses standard deviation scaled by a nonlinear factor of distance from 50
// Also adds another distance-based term to increase length more dramatically
"I" => math.ceil(
ta.stdev(free_rsi, math.ceil(free_rsi)) *
math.pow(1 + (math.ceil(math.abs(50 - (free_rsi - 50))) / 100), 2)
) +
(
math.ceil(math.abs(free_rsi - 50)) *
(1 + (math.ceil(math.abs(50 - (free_rsi - 50))) / 100))
)
// Variant II: Moderate adaptation
// Adds the standard deviation and a distance-based scaling term (less nonlinear)
"II" => math.ceil(
ta.stdev(free_rsi, math.ceil(free_rsi)) +
(
math.ceil(math.abs(free_rsi - 50)) *
(1 + (math.ceil(math.abs(50 - (free_rsi - 50))) / 100))
)
)
// Variant III: Least aggressive adaptation
// Simply adds standard deviation and raw distance from 50 (linear scaling)
"III" => math.ceil(
ta.stdev(free_rsi, math.ceil(free_rsi)) +
math.ceil(math.abs(free_rsi - 50))
)
2. Smoothing Options
To refine the dynamic RSI and reduce noise, the PF-RSI provides smoothing capabilities:
Smoothing Toggle: Enable or disable smoothing of the dynamic length used for RSI.
Smoothing MA Type for RSI MA: Choose between SMA and EMA
Smoothing Length Options for RSI MA:
Full: Uses the entire calculated dynamic length.
Half: Applies half of the dynamic length for smoother output.
SQRT: Uses the square root of the dynamic length, offering a compromise between responsiveness and smoothness.
The smoothed RSI is complemented by a separate moving average (MA) of the RSI itself, further enhancing signal clarity.
3. Visualization Tools
The PF-RSI includes visualization options to help traders interpret market conditions at a glance.
Plots:
Dynamic RSI: Displayed as a white line, showing the adaptive RSI value.
RSI Moving Average: Plotted in yellow, providing a smoothed reference for trend and momentum analysis.
Dynamic Length: A secondary plot (in faint white) showing how the calculation period evolves over time.
Histogram: Represents the RSI’s position relative to 50, with color gradients.
Fill Area: The space between the RSI and its MA is filled with a gradient (green for RSI > MA, red for RSI < MA), highlighting momentum shifts.
Customizable bar colors on the price chart reflect trend and momentum:
Trend (Raw RSI): Green (RSI > 50), Red (RSI < 50).
Trend (RSI MA): Green (MA > 50), Red (MA < 50).
Trend (Raw RSI) + Momentum: Adds momentum shading (lighter green/red when RSI and MA diverge).
Trend (RSI MA) + Momentum: Similar, but based on the MA’s trend.
Momentum: Green (RSI > MA), Red (RSI < MA).
Off: Disables bar coloring.
Intrabar Updating: Optional real-time updates within each bar for enhanced responsiveness.
4. Alerts
The PF-RSI supports customizable alerts to keep traders informed of key events.
Trend Alerts:
Raw RSI: Triggers when the RSI crosses above (uptrend) or below (downtrend) 50.
RSI MA: Triggers when the moving average crosses 50.
Off: Disables trend alerts.
Momentum Alerts:
Triggers when the RSI crosses its moving average, indicating rising (RSI > MA) or declining (RSI < MA) momentum.
Alerts are fired once per bar close, with descriptive messages including the ticker symbol (e.g., " Uptrend on: AAPL").
How It Works
The PF-RSI operates in a multi-step process:
Initialization
On the first run, it calculates a standard RSI with a 14-period length to seed the dynamic calculation.
Dynamic Length Computation
Once seeded, the indicator switches to a dynamic length based on the selected variant, factoring in volatility and distance from 50.
If smoothing is enabled, the length is further refined using an SMA.
RSI Calculation
The adaptive RSI is computed using the dynamic length, ensuring it reflects current market conditions.
Moving Average
A separate MA (SMA or EMA) is applied to the RSI, with a length derived from the dynamic length (Full, Half, or SQRT).
Visualization and Alerts
The results are plotted, and alerts are triggered based on user settings.
This adaptive approach minimizes lag in fast markets and reduces false signals in choppy conditions, offering a significant edge over fixed-period RSI implementations.
Why Use PF-RSI?
The Parameter Free RSI stands out by eliminating the guesswork of selecting an RSI period. Its dynamic length adjusts to market volatility and momentum, providing timely signals without manual tweaking.