Sortino Ratio Oscillator [MarkitTick]💡 The Sortino Ratio Oscillator introduces a sophisticated, risk-adjusted performance metric typically reserved for portfolio analysis, adapting it into a highly responsive momentum oscillator. By strictly penalizing downside volatility while rewarding upside momentum, it provides a much clearer picture of market strength compared to traditional oscillators that treat all volatility equally.
✨ Originality and Utility
Standard momentum indicators measure the velocity of price movement based on general variance. However, traditional models penalize both upside and downside volatility. A massive bullish breakout creates "high volatility," which standard indicators often misinterpret as an overextended or risky market condition.
This script resolves that inherent flaw by migrating the academic Sortino Ratio into a technical trading framework. It isolates "bad" volatility (price drops) from "good" volatility (price gains). The utility here is immense: traders can identify trends where the price action is genuinely supported by positive risk-adjusted returns, filtering out noisy markets where the downside deviation is too high. Furthermore, this tool features an integrated divergence detection engine, dynamic histogram coloring, and built-in webhook alert formatting, making it a comprehensive suite for algorithmic and discretionary traders alike.
🔬 Methodology and Concepts
The core engine of this indicator relies on continuously assessing the bar-to-bar percentage return of the asset.
First, it calculates the raw percentage return between the current close and the previous close.
Next, it isolates the downside returns. If a return is positive, it is ignored for the risk calculation (treated as zero). If it is negative, it is squared to emphasize larger drawdowns, following standard variance practices.
The script then computes the Simple Moving Average of these squared negative returns over a user-defined lookback window, calculating the square root to determine the final Downside Deviation.
Simultaneously, the Simple Moving Average of the raw returns is calculated to find the mean return over the same period.
The final Sortino Ratio is produced by dividing the mean return by the downside deviation.
To smooth the output and generate actionable crossovers, a secondary Signal Line is derived by applying an average to the raw Sortino Ratio.
To enhance the analytical depth, the script incorporates a robust divergence engine that scans for pivot highs and lows over a customizable lookback window. By comparing price action pivots with the oscillator's momentum peaks and troughs, it systematically maps out both regular and hidden divergences.
🎨 Visual Guide
The visual presentation is meticulously structured to provide instant clarity on risk-adjusted momentum states.
• The Sortino Histogram
The core oscillator is plotted as a multi-colored histogram. It utilizes a four-state coloring system to indicate momentum shifts:
Solid Bull Color: The ratio is above zero and rising, indicating accelerating positive risk-adjusted returns.
Transparent Bull Color: The ratio is above zero but falling, suggesting positive momentum is decelerating.
Solid Bear Color: The ratio is below zero and falling, indicating accelerating downside risk.
Transparent Bear Color: The ratio is below zero but rising, showing that downside risk is waning.
• Signal Line and Cloud Fill
A highlighted Signal Line tracks the moving average of the Sortino Ratio. The space between the Sortino histogram and the Signal Line is filled with a dynamic cloud, helping traders easily spot shifts in immediate trend strength.
• Threshold Lines
Dashed lines represent the Overbought and Oversold thresholds. A solid gray line marks the Zero Level, acting as the primary baseline for positive versus negative risk-adjusted states.
• Divergence Mapping
Regular Bullish (RB): Displayed as a solid line connecting price lows to oscillator lows, complete with a label below the candle.
Hidden Bullish (HB): Displayed as a dashed line, indicating trend continuation.
Regular Bearish (RD): Displayed as a solid line connecting price highs to oscillator highs.
Hidden Bearish (HD): Displayed as a dashed line.
• Candle Coloring
When enabled, the price chart's candles are painted to match the four-state color logic of the Sortino Histogram, linking the oscillator's data directly to the price action on the main chart.
📖 How to Use
Traders can interpret the Sortino Ratio Oscillator through several distinct frameworks depending on their trading style.
• Zero-Line Crossovers
A baseline shift occurs when the histogram crosses the zero line. A cross into positive territory confirms that the average returns now outweigh the downside deviation, signaling a structurally sound bullish environment. Conversely, a drop below zero warns that downside volatility is dominating the asset's behavior.
• Signal Line Interactions
Watch for the histogram to cross the Signal Line. When the Sortino Ratio spikes above its signal line, momentum is expanding. When it crosses below, it often precedes a consolidation or a reversal, as highlighted by the cloud fill changing colors.
• Extremes and Reversals
The Overbought and Oversold threshold lines act as exhaustion markers. An asset sustaining a Sortino Ratio above the Overbought level is exhibiting unusually high, unpenalized upside movement. While strong, traders should watch for the histogram to peak and cross back below the Signal Line as an early warning of a pullback.
• Trading Divergences
Divergences are perhaps the most powerful signals generated by this tool. Look for Regular Bullish Divergences when the price makes a lower low, but the Sortino Ratio makes a higher low. This indicates that despite the price drop, the underlying downside volatility is shrinking relative to the mean return, hinting at a bottom. Hidden Divergences are excellent for trading pullbacks in the direction of the macro trend.
⚙️ Inputs and Settings
• Sortino Settings
Lookback Length: Defines the period used to calculate the mean return and downside deviation. A shorter length is highly reactive, while a longer length provides macroscopic trend stability.
Signal Length: Adjusts the smoothness of the Signal Line.
Overbought / Oversold Levels: Customizes the threshold lines for extreme readings.
• Candle Coloring
A simple toggle to enable or disable the dynamic coloring of the main chart price candles based on the oscillator's state.
• Divergence Settings
Enable Divergence: Master toggle for the divergence engine.
Show Regular / Hidden: Independent toggles to filter specific divergence types.
Pivot Lookback Left / Right: Determines the strictness of the pivot point detection. Higher values require more significant peaks and troughs to form a valid pivot, filtering out noise.
• Webhook Action Names
Customizable string inputs allowing algorithmic traders to map specific script events directly to JSON payloads for automated execution platforms.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
The Sortino Ratio, developed by Dr. Frank A. Sortino, is a vital modification of the Sharpe Ratio. In Modern Portfolio Theory, the Sharpe Ratio evaluates the performance of an investment by adjusting for its risk, defined universally as the standard deviation of its returns. However, standard deviation measures total volatility, treating an unexpected positive gain exactly the same as a negative loss.
This oscillator resolves that mathematical paradox by isolating downside deviation. The scientific framework dictates that a minimum acceptable return—in this script's case, zero—must be established. Only returns falling strictly below this threshold are aggregated and squared to calculate the downside variance. By exclusively measuring the standard deviation of negative asset returns, the formula effectively removes the penalty for upside volatility.
In a purely academic sense, a high Sortino Ratio mathematically proves that the asset is generating its returns without suffering significant, erratic drawdowns. Translated into technical analysis, when the indicator rises, it mathematically proves that the ratio of upward momentum relative to downward variance is expanding. This makes it an incredibly robust statistical measure, completely immune to the standard look-around bias of typical mathematical oscillators that collapse under the weight of sudden, positive price shocks.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
Pine Script® インジケーター






