Ultimate Moving Average Package (17 MA's)Included is the:
VWAP
Current time frame 10 EMA
Current time frame 20 EMA
Current time frame 50 EMA
Current time frame 10 SMA
Current time frame 20 SMA
Current time frame 50 SMA
Daily 10 EMA
Daily 20 EMA
Daily 50 EMA
Daily 50 SMA
Daily 100 SMA
Daily 200 SMA
Weekly 100 SMA
Weekly 200 SMA
Monthly 100 SMA
Monthly 200 SMA
All Daily/Weekly/Monthly MA's can be seen on intraday charts. Current time frame MA's change depending on your time frame. Obviously you dont need all 17 on your chart but you can pick the ones you like and disable the rest.
ค้นหาในสคริปต์สำหรับ "马斯克+100万"
Bilateral Stochastic Oscillator - For The Sake Of EfficiencyIntroduction
The stochastic oscillator is a feature scaling method commonly used in technical analysis, this method is the same as the running min-max normalization method except that the stochastic oscillator is in a range of (0,100) while min-max normalization is in a range of (0,1). The stochastic oscillator in itself is efficient since it tell's us when the price reached its highest/lowest or crossed this average, however there could be ways to further develop the stochastic oscillator, this is why i propose this new indicator that aim to show all the information a classical stochastic oscillator would give with some additional features.
Min-Max Derivation
The min-max normalization of the price is calculated as follow : (price - min)/(max - min) , this calculation is efficient but there is alternates forms such as :
price - (max - min) - min/(max - min)
This alternate form is the one i chosen to make the indicator except that both range (max - min) are smoothed with a simple moving average, there are also additional modifications that you can see on the code.
The Indicator
The indicator return two main lines, in blue the bull line who show the buying force and in red the bear line who show the selling force.
An orange line show the signal line who represent the moving average of the max(bull,bear), this line aim to show possible exit/reversals points for the current trend.
Length control the highest/lowest period as well as the smoothing amount, signal length control the moving average period of the signal line, the pre-filtering setting indicate which smoothing method will be used to smooth the input source before applying normalization.
The default pre-filtering method is the sma.
The ema method is slightly faster as you can see above.
The triangular moving average is the moving average of another moving average, the impulse response of this filter is a triangular function hence its name. This moving average is really smooth.
The lsma or least squares moving average is the fastest moving average used in this indicator, this filter try to best fit a linear function to the data in a certain window by using the least squares method.
No filtering will use the source price without prior smoothing for the indicator calculation.
Relationship With The Stochastic Oscillator
The crosses between the bull and bear line mean that the stochastic oscillator crossed the 50 level. When the Bull line is equal to 0 this mean that the stochastic oscillator is equal to 0 while a bear line equal to 0 mean a stochastic oscillator equal to 100.
The indicator and below a stochastic oscillator of both period 100
Using Levels
Unlike a stochastic oscillator who would clip at the 0 and 100 level the proposed indicator is not heavily constrained in a range like the stochastic oscillator, this mean that you can apply levels to trigger signals
Possible levels could be 1,2,3... even if the indicator rarely go over 3.
Its then possible to create strategies using such levels as support or resistance one.
Conclusion
I've showed a modified stochastic oscillator who aim to show additional information to the user while keeping all the information a classical stochastic oscillator would give. The proposed indicator is no longer constrained in an hard range and posses more liberty to exploit its scale which in return allow to create strategies based on levels.
For pinescript users what you can learn from this is that alternates forms of specific formulas can be extremely interesting to modify, changes can be really surprising so if you are feeling stuck, modifying alternates forms of know indicators can give great results, use tools such as sympy gamma to get alternates forms of formulas.
Thanks for reading !
If you are looking for something or just want to say thanks try to pm me :)
High/Low bandsGives good idea about trend.
In last 100 days the lowest price was this.
In last 100 days the highest price was this.
Price makes new 100 days high! (uptrend)
Chaikin MF% (CMFP) w. Alerts, Bells & Whistles [LucF]This is Chaikin’s Money Flow indicator on a 0-100 scale with buy/sell signals, alerts and other bells & whistles.
It includes:
- a fast EMA (16 periods by default),
- a slow MA (64 periods by default),
- histograms,
- 3 different sorts of crosses,
- big swings identification,
- buy/sell signals on CMFP crossing back from outside user-defined levels,
- buy/sell signals on the slow MA pivots above/below user-defined levels,
- alerts on big swings and buy/sells.
This indicator started with @LazyBear code (VAPI) at:
@cI8DH then changed the scale to 0-100, which I find very useful:
I then added the rest.
The chart above shows both clean and busy versions of the indicator.
Note that the default length is 10 rather than the commonly used 20. I use CMFP in conjunction with VFI and like the fact that it is faster than VFI. The default inputs show the way I normally use this indicator, with the slow MA shown in histogram mode. I find it gives good context to the signal line. Crosses between the two are often useful.
The buy/sell signals aren’t the main attraction of this indicator, and nothing to write home about. Like the big swing markers, I think it’s more realistic to view them as pointers to potentially interesting areas on charts. Their nature makes them more suited to identifying reversals. They certainly aren’t reliable enough to turn this study into a strategy and I normally don’t use them. The levels pre-defined for the buy/sell signals on CMFP are most useful on short intervals. The buy/sell signals on the slow MA pivots work on a more complete range of intervals. Optimization for your specific instruments and intervals will improve their reliability.
As usual when defining alerts, be sure you already have defined proper inputs and that you are on the intended interval, as they will be used when triggering alerts.
3 of SlowStochastics
스토캐스틱 3개를 한번에 볼수 있습니다. 천장과 바닥은 각 100의 위치마다 존재합니다
You can see three slow stochastics at once. The ceiling and floor are located at each 100 (0 - 100 - 200- 300)
Percentage Price Oscillator (PPO)The Percentage Price Oscillator (PPO) is a momentum oscillator that measures the difference between two moving averages as a percentage of the larger moving average. As with its cousin, MACD, the Percentage Price Oscillator is shown with a signal line, a histogram and a centerline. Signals are generated with signal line crossovers, centerline crossovers, and divergences. First, PPO readings are not subject to the price level of the security. Second, PPO readings for different securities can be compared, even when there are large differences in the price.
Calculations
PPO: {(12-day EMA - 26-day EMA)/26-day EMA} x 100
Signal Line: 9-day EMA of PPO
PPO Histogram: PPO - Signal Line
While MACD measures the absolute difference between two moving averages, PPO makes this a relative value by dividing the difference by the slower moving average (26-day EMA). PPO is simply the MACD value divided by the longer moving average. The result is multiplied by 100 to move the decimal place two spots.
Interpretation
As with MACD, the PPO reflects the convergence and divergence of two moving averages. PPO is positive when the shorter moving average is above the longer moving average. The indicator moves further into positive territory as the shorter moving average distances itself from the longer moving average. This reflects strong upside momentum. The PPO is negative when the shorter moving average is below the longer moving average. Negative readings grow when the shorter moving average distances itself from the longer moving average (goes further negative). This reflects strong downside momentum. The histogram represents the difference between PPO and its 9-day EMA, the signal line. The histogram is positive when PPO is above its 9-day EMA and negative when PPO is below its 9-day EMA. The PPO-Histogram can be used to anticipate signal line crossovers in the PPO.
MACD, PPO and Price
MACD levels are affected by the price of a security. A high-priced security will have higher or lower MACD values than a low-priced security, even if volatility is basically equal. This is because MACD is based on the absolute difference in the two moving averages. Because MACD is based on absolute levels, large price changes can affect MACD levels over an extended period of time. If a stock advances from 20 to 100, its MACD levels will be considerably smaller around 20 than around 100. The PPO solves this problem by showing MACD values in percentage terms.
Conclusions
The Percentage Price Oscillator (PPO) generates the same signals as the MACD, but provides an added dimension as a percentage version of MACD. The PPO levels of the Dow Industrials (price > 20K) can be compared against the PPO levels of IBM (price < 200) because the PPO “levels” the playing field. In addition, PPO levels in one security can be compared over extended periods of time, even if the price has doubled or tripled. This is not the case for the MACD.
Limitations
Despite its advantages, the PPO is still not the best oscillator to identify overbought or oversold conditions because movements are unlimited (in theory). Levels for RSI and the Stochastic Oscillator are limited and this makes them better suited to identify overbought and oversold levels.
Source: Stockcharts
Multiple Moving AveragesThis is really simple. But useful for me as I don't have a paid account. No-pro users can only use 3 indicators at once and because I rely heavily on simple moving averages it can be a real pain.
This one indicator features:
20 MA
50 MA
100 MA
200 MA
which I find are the most useful overall. The 20 and 50 over all time frame but in particular < 1 day, the 100 and 200 at > 4 hr time frames. In general I don't use the 100 MA that much. The daily 200 MA is a critical support for many assets like stocks and cryptos. I'm by no means a pro and if you are learning I recommend becoming familiar with moving averages right at the beginning.
If you want to deactivate some of the lines, you can do it via the indicator's settings icon.
Exponential Moving Average (Set of 3) [Krypt] + 13/34 EMAsI took Krypt's script and essentially added on to it.
the 20/50/100/200 EMAs should be used together as support and resistance as normal.
Wait for price to break 200 EMA
Wait for 50 EMA to cross 200 EMA
Wait for pullback to 50 EMA to open position
20 and 100 EMAs are for extra information about moving support and resistance
and 13/34 EMAs should be used in conjunction
When 13 EMA crosses 34 EMA, open position
When price gets far from 13/34, close position (because price will attempt to revert back to mean)
This is better for scalping and swing trades than the 20/50/100/200 setup.
Twitter: @AzorAhai06
Ichimoku Cloud Score v1.0This script calculates a simple Ichimoku Score based on the signals documented here , with a few additions. Each of the score components can be individually weighted via the script inputs . The output is a plot of the normalized Ichimoku score, in the range of -100 to 100.
This script has been heavily modified from 'Ichimoku Cloud Signal Score v2.0.0 '. Credit to user 'dashed' for the initial implementation.
This has been modified with several refinements:
Clean/Organized Code
Simplified Inputs
Improved Style
Scores normalized to a range (-100, 100)
Bugfixes and Improvements
Script Inputs: i.imgur.com
Volume RatioDefinition:
Volume ratio can be obtained in a similar way to RSI.
Volume Ratio (%) = 100 - 100/(1+vr)
The parameter "vr" is defined as
vr=(A+U/2)/(D+U/2)
A=Total volume of the periods when the price advanced
D=Total volume of the periods when the price declined
U=Total volume of the periods when the price unchanged
After substitution, following expression can be derived and the denominator represents total volume of all periods.
Volume Ratio (%) = 100 x (A+U/2)/(A+D+U)
Notes:
A similar method to interpret RSI can be employed.
1) Overbought level over 70% and oversold level under 30%. These levels need to be adjusted according to the periods, time frames and issues.
2) Bullish picture over 50% line and bearish picture under 50% line.
3) Crossing oversold level to the upside can be taken as a confirmation of bullish reversal. - and vice versa for a bearish reversal.
4) After a long-term bearish market, the increase of volume can happen in the early stage of a bullish market.
5) Buying opportunity can be suggested when the volume ratio is declining and the price is either advancing or leveling off.
CCI with Volume Weighted EMA Here is an attempt to improve on the CCI using a volume weighted ema which is then plugged into the CCI formula.
Use:
The CCI with VW EMA is an oscillator that gives readings between -100 and +100. The usual use is to 'go long' with values over +100 and short on values less than -100.
Another use of this oscillator is a countertrend indicator where one sells at crosses under +100 and buys on crosses over -100.
Multi-Functional Fisher Transform MTF with MACDL TRIGGERWhat this indicator gives you is a true signal when price is exhausted and ready for a fast turnaround. Fisher Transform is set for multi-time frame and also allows the user to change the length. This way a user can compare two or more time spans and lengths to look for these MACDL divergent triggers after a Fisher exhaustion. With so many indicators, it's probably best to merge these indicators and change the Fisher and Trigger colors so you can still have a look at price action (remember to scale right after merger). I've noticed from time to time when you have Fisher 34 100 and 300 up and running on two different time frames such as 5 and 15 min charts, with MACDL triggers on the 100/300 or 34/100 you get a high probability trade trigger. However, there are rare exceptions such as when price moves in a parabolic state up or down for a long period where this indication does not work. Ideally this indicator works best in a sideways market or slow rising/descending moving market.
This indicator was worked on by Glaz, nmike and myself
LazyBear also introduced the MACDL indicator
CCI Crossover AlertThis very simple indicator will give you a blue background where the CCI crossed from below -100 to above -100, and a red background where it crossed from above 100 to below 100.
Sav Fx Dynamic P & D°//@version=5
indicator("Sav Fx Dynamic P & D°", overlay = true, max_boxes_count = 50, max_labels_count = 2, max_lines_count = 10)
// Global Settings (visible)
customLineColor = input.color(#000000, "True Open", group = "Global Settings")
// Input for custom sessionTypeText size and width
sessionTypeTextSize = input.string("small", "Session Type Text Size", options= , group="Text Settings")
// On/Off switches for each open line
show90MinuteCycleOpen = input.bool(true, "90 Minute Cycle Open", group="Open Lines")
showTrueNewYorkOpen = input.bool(true, "True New York Open", group="Open Lines")
showTrueDayOpen = input.bool(true, "True Day Open", group="Open Lines")
showTrueWeekOpen = input.bool(true, "True Week Open", group="Open Lines")
showTrueMonthOpen = input.bool(false, "True Month Open", group="Open Lines")
IsTime(h, m, timezone) =>
not na(time) and hour(time, timezone) == h and minute(time, timezone) == m
IsSession(sess, timezone) =>
not na(time(timeframe.period, sess, timezone))
is6_00Session = IsSession("0600-0730", "America/New_York")
is7_30Session = IsSession("0730-0900", "America/New_York")
is9_00Session = IsSession("0900-1030", "America/New_York")
is10_30Session = IsSession("1030-1200", "America/New_York")
var MOPLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var MOPLabel = label.new(na, na, text = "True Day Open", color = color.rgb(120, 123, 134, 100), textcolor = customLineColor, size = size.small, style = label.style_label_left)
var float trueDayOpen = na
if showTrueDayOpen
if IsTime(0, 0, "America/New_York")
line.set_xy1(MOPLine, bar_index, open)
line.set_xy2(MOPLine, bar_index, open)
label.set_xy(MOPLabel, bar_index, open)
trueDayOpen := open
if barstate.islast
line.set_x2(MOPLine, bar_index + 20)
label.set_x(MOPLabel, bar_index + 20)
else
line.delete(MOPLine)
label.delete(MOPLabel)
var NYTrueOpenLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var NYTrueOpenLabel = label.new(na, na, text = "True New York Open", color = color.rgb(105, 130, 218, 100), textcolor = customLineColor, size = size.small, style = label.style_label_left)
var float NYTrueOpen = na
if showTrueNewYorkOpen
if IsTime(1, 30, "America/New_York") or IsTime(7, 30, "America/New_York") or IsTime(13, 30, "America/New_York")
line.set_xy1(NYTrueOpenLine, bar_index, open)
line.set_xy2(NYTrueOpenLine, bar_index, open)
label.set_xy(NYTrueOpenLabel, bar_index, open)
NYTrueOpen := open
if IsTime(1, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True London Open")
if IsTime(7, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True New York Open")
if IsTime(13, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True PM Session Open")
if barstate.islast
line.set_x2(NYTrueOpenLine, bar_index + 20)
label.set_x(NYTrueOpenLabel, bar_index + 20)
else
line.delete(NYTrueOpenLine)
label.delete(NYTrueOpenLabel)
var lookahead_bars = 20
var MondayLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var MondayLabel = label.new(na, na, text = timeframe.isintraday and timeframe.multiplier >= 5 ? "True week Open" : "", color = #9b27b000, textcolor = customLineColor, size = size.small, style = label.style_label_left)
if showTrueWeekOpen
if dayofweek == dayofweek.monday and IsTime(18, 0, "America/New_York")
line.set_xy1(MondayLine, bar_index, close)
line.set_xy2(MondayLine, bar_index, close)
label.set_xy(MondayLabel, bar_index, close)
if barstate.islast
line.set_x2(MondayLine, bar_index + lookahead_bars)
label.set_x(MondayLabel, bar_index + lookahead_bars)
else
line.delete(MondayLine)
label.delete(MondayLabel)
var ninetyMinuteCycleLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var ninetyMinuteCycleLabel = label.new(na, na, text = "90 Minute Cycle True Open", color = #4caf4f00, textcolor = customLineColor, size = size.small, style = label.style_label_left)
if show90MinuteCycleOpen
if IsTime(3, 23, "America/New_York") or IsTime(9, 23, "America/New_York") or IsTime(15, 23, "America/New_York")
line.set_xy1(ninetyMinuteCycleLine, bar_index, open)
line.set_xy2(ninetyMinuteCycleLine, bar_index, open)
label.set_xy(ninetyMinuteCycleLabel, bar_index, open)
if IsTime(3, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "03:23 Cycle True Open")
if IsTime(9, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "09:23 Cycle True Open")
if IsTime(15, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "15:23 Cycle True Open")
if barstate.islast
line.set_x2(ninetyMinuteCycleLine, bar_index + lookahead_bars)
label.set_x(ninetyMinuteCycleLabel, bar_index + lookahead_bars)
else
line.delete(ninetyMinuteCycleLine)
label.delete(ninetyMinuteCycleLabel)
var monthOpenLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var monthOpenLabel = label.new(na, na, text = "True Month Open", color = #ff990000, textcolor = customLineColor, size = size.small, style = label.style_label_left)
isSecondWeekSunday = dayofweek == dayofweek.sunday and (dayofmonth >= 8 and dayofmonth <= 14)
if showTrueMonthOpen
if isSecondWeekSunday and IsTime(18,0, "America/New_York")
line.set_xy1(monthOpenLine, bar_index, close)
line.set_xy2(monthOpenLine, bar_index + lookahead_bars, close)
label.set_xy(monthOpenLabel, bar_index, close)
if barstate.islast
line.set_x2(monthOpenLine, bar_index + lookahead_bars)
label.set_x(monthOpenLabel, bar_index + lookahead_bars)
else
line.delete(monthOpenLine)
label.delete(monthOpenLabel)
directionalBias = "N/A"
if is6_00Session or is7_30Session or is9_00Session or is10_30Session
directionalBias := open > NYTrueOpen ? "Bullish" : "Bearish"
var directionalBiasLabel = label.new(na, na, text = "Directional Bias: " + directionalBias, color = na, textcolor = customLineColor, size = size.normal, style = label.style_label_left)
if barstate.islast
label.set_x(directionalBiasLabel, bar_index + lookahead_bars)
label.set_text(directionalBiasLabel, "Directional Bias: " + directionalBias)
var float WeekOpen = na
if dayofweek == dayofweek.monday and IsTime(18, 0, "America/New_York")
WeekOpen := close
if showTrueWeekOpen
line.set_xy1(MondayLine, bar_index, close)
line.set_xy2(MondayLine, bar_index, close)
label.set_xy(MondayLabel, bar_index, close)
// New table for static session type display
var sessionTable = table.new(position.bottom_right, 1, 1, bgcolor = #b9b9bab8)
// Update the table.cell function call
if barstate.islast and not na(trueDayOpen) and not na(NYTrueOpen) and not na(WeekOpen)
var string sessionTypeText = syminfo.ticker + " Dead Zone"
var color sessionColor = color.rgb(126, 126, 126, 65)
// Check conditions and set session type text and color accordingly
if close < trueDayOpen and close < NYTrueOpen and close < WeekOpen
sessionTypeText := syminfo.ticker + " Week Discount"
sessionColor := #ba4b4b59
else if close > trueDayOpen and close > NYTrueOpen and close > WeekOpen
sessionTypeText := syminfo.ticker + " Week Premium"
sessionColor := #4b56ba5a
else if close < trueDayOpen and close < NYTrueOpen and close > WeekOpen
sessionTypeText := syminfo.ticker + " Day Discount & Week Dead Zone"
sessionColor := #ba4b4b59
else if close > trueDayOpen and close > NYTrueOpen and close < WeekOpen
sessionTypeText := syminfo.ticker + " Day premium & Week Dead Zone"
sessionColor := #4b56ba5a
// Using only size input for session type text
table.cell(sessionTable, 0, 0, sessionTypeText, bgcolor = sessionColor, text_color = color.black, text_size = sessionTypeTextSize)
VIX 恐慌指數 VOO 抄底策略 VIX 恐慌指數 VOO 抄底策略
📊 策略目的
本策略利用 VIX 恐慌指數作為市場情緒指標,幫助投資人在市場極度恐慌時理性進場抄底,並透過客觀的技術訊號避免情緒化操作。適合用於捕捉 VOO(或其他美股 ETF)在恐慌性下跌後的反彈機會。
🎯 進出場條件
進場條件(同時滿足):
VIX 指數達到設定門檻以上(預設 25,可調整)
VIX 死亡交叉其均線(預設 5 日均線),確認恐慌情緒開始回落
出場條件(三種模式可選):
持有天數模式:持有達到設定天數後出場(預設 100 天)
VIX 回落模式:VIX 降至設定門檻以下時出場(預設 20)
兩者皆可模式:任一條件滿足即出場
⚠️ 重要警語
不適合槓桿型 ETF 抄底:VIX 反映的是市場波動度,使用槓桿 ETF(如 TQQQ、SOXL)會因為衰減效應和更大波動而增加風險,可能在恐慌期間造成更大虧損。
空頭市場失準風險:本策略假設市場會從恐慌中反彈,但在長期空頭或系統性風險(如 2008 金融危機、2022 升息循環)中,VIX 可能長期處於高檔,多次觸發買入訊號卻持續下跌,導致策略失效。
建議搭配大盤趨勢判斷:在多頭格局中使用效果較佳,空頭格局建議提高 VIX 門檻或暫停使用。
僅供參考,非投資建議:歷史績效不代表未來表現,請依個人風險承受度謹慎使用。
VIX Panic Index VOO Bottom-Fishing Strategy
📊 Strategy Overview
This strategy utilizes the VIX (Volatility Index) as a market sentiment indicator to help investors rationally enter positions during periods of extreme market panic, using objective technical signals to avoid emotional decision-making. It is designed to capture rebound opportunities in VOO (or other US equity ETFs) following panic-driven selloffs.
🎯 Entry and Exit Conditions
Entry Conditions (both must be met):
VIX reaches or exceeds the set threshold (default 25, adjustable)
VIX death crosses below its moving average (default 5-day MA), confirming panic sentiment is beginning to recede
Exit Conditions (three modes available):
Holding Period Mode: Exit after holding for the set number of days (default 100 days)
VIX Decline Mode: Exit when VIX falls below the set threshold (default 20)
Either Condition Mode: Exit when either condition is met
⚠️ Important Warnings
Not Suitable for Leveraged ETF Bottom-Fishing: VIX reflects market volatility. Using leveraged ETFs (such as TQQQ, SOXL) increases risk due to decay effects and greater volatility, potentially causing larger losses during panic periods.
Bear Market Inaccuracy Risk: This strategy assumes markets will rebound from panic. However, during prolonged bear markets or systemic risks (such as the 2008 financial crisis or 2022 rate hike cycle), VIX may remain elevated for extended periods, triggering multiple buy signals while prices continue declining, rendering the strategy ineffective.
Recommended to Combine with Market Trend Analysis: Works better in bull market conditions. In bear markets, consider raising VIX thresholds or suspending use.
For Reference Only, Not Investment Advice: Historical performance does not guarantee future results. Please use cautiously according to your personal risk tolerance.
SP500 Session Gap Fade StrategySummary in one paragraph
SPX Session Gap Fade is an intraday gap fade strategy for index futures, designed around regular cash sessions on five minute charts. It helps you participate only when there is a full overnight or pre session gap and a valid intraday session window, instead of trading every open. The original part is the gap distance engine which anchors both stop and optional target to the previous session reference close at a configurable flat time, so every trade’s risk scales with the actual gap size rather than a fixed tick stop.
Scope and intent
• Markets. Primarily index futures such as ES, NQ, YM, and liquid index CFDs that exhibit overnight gaps and regular cash hours.
• Timeframes. Intraday timeframes from one minute to fifteen minutes. Default usage is five minute bars.
• Default demo used in the publication. Symbol CME:ES1! on a five minute chart.
• Purpose. Provide a simple, transparent way to trade opening gaps with a session anchored risk model and forced flat exit so you are not holding into the last part of the session.
• Limits. This is a strategy. Orders are simulated on standard candles only.
Originality and usefulness
• Unique concept or fusion. The core novelty is the combination of a strict “full gap” entry condition with a session anchored reference close and a gap distance based TP and SL engine. The stop and optional target are symmetric multiples of the actual gap distance from the previous session’s flat close, rather than fixed ticks.
• Failure mode it addresses. Fixed sized stops do not scale when gaps are unusually small or unusually large, which can either under risk or over risk the account. The session flat logic also reduces the chance of holding residual positions into late session liquidity and news.
• Testability. All key pieces are explicit in the Inputs: session window, minutes before session end, whether to use gap exits, whether TP or SL are active, and whether to allow candle based closes and forced flat. You can toggle each component and see how it changes entries and exits.
• Portable yardstick. The main unit is the absolute price gap between the entry bar open and the previous session reference close. tp_mult and sl_mult are multiples of that gap, which makes the risk model portable across contracts and volatility regimes.
Method overview in plain language
The strategy first defines a trading session using exchange time, for example 08:30 to 15:30 for ES day hours. It also defines a “flat” time a fixed number of minutes before session end. At the flat bar, any open position is closed and the bar’s close price is stored as the reference close for the next session. Inside the session, the strategy looks for a full gap bar relative to the prior bar: a gap down where today’s high is below yesterday’s low, or a gap up where today’s low is above yesterday’s high. A full gap down generates a long entry; a full gap up generates a short entry. If the gap risk engine is enabled and a valid reference close exists, the strategy measures the distance between the entry bar open and that reference close. It then sets a stop and optional target as configurable multiples of that gap distance and manages them with strategy.exit. Additional exits can be triggered by a candle color flip or by the forced flat time.
Base measures
• Range basis. The main unit is the absolute difference between the current entry bar open and the stored reference close from the previous session flat bar. That value is used as a “gap unit” and scaled by tp_mult and sl_mult to build the target and stop.
Components
• Component one: Gap Direction. Detects full gap up or full gap down by comparing the current high and low to the previous bar’s high and low. Gap down signals a long fade, gap up signals a short fade. There is no smoothing; it is a strict structural condition.
• Component two: Session Window. Only allows entries when the current time is within the configured session window. It also defines a flat time before the session end where positions are forced flat and the reference close is updated.
• Component three: Gap Distance Risk Engine. Computes the absolute distance between the entry open and the stored reference close. The stop and optional target are placed as entry ± gap_distance × multiplier so that risk scales with gap size.
• Optional component: Candle Exit. If enabled, a bullish bar closes short positions and a bearish bar closes long positions, which can shorten holding time when price reverses quickly inside the session.
• Session windows. Session logic uses the exchange time of the chart symbol. When changing symbols or venues, verify that the session time string still matches the new instrument’s cash hours.
Fusion rule
All gates are hard conditions rather than weighted scores. A trade can only open if the session window is active and the full gap condition is true. The gap distance engine only activates if a valid reference close exists and use_gap_risk is on. TP and SL are controlled by separate booleans so you can use SL only, TP only, or both. Long and short are symmetric by construction: long trades fade full gap downs, short trades fade full gap ups with mirrored TP and SL logic.
Signal rule
• Long entry. Inside the active session, when the current bar shows a full gap down relative to the previous bar (current high below prior low), the strategy opens a long position. If the gap risk engine is active, it places a gap based stop below the entry and an optional target above it.
• Short entry. Inside the active session, when the current bar shows a full gap up relative to the previous bar (current low above prior high), the strategy opens a short position. If the gap risk engine is active, it places a gap based stop above the entry and an optional target below it.
• Forced flat. At the configured flat time before session end, any open position is closed and the close price of that bar becomes the new reference close for the following session.
• Candle based exit. If enabled, a bearish bar closes longs, and a bullish bar closes shorts, regardless of where TP or SL sit, as long as a position is open.
What you will see on the chart
• Markers on entry bars. Standard strategy entry markers labeled “long” and “short” on the gap bars where trades open.
• Exit markers. Standard exit markers on bars where either the gap stop or target are hit, or where a candle exit or forced flat close occurs. Exit IDs “long_gap” and “short_gap” label gap based exits.
• Reference levels. Horizontal lines for the current long TP, long SL, short TP, and short SL while a position is open and the gap engine is enabled. They update when a new trade opens and disappear when flat.
• Session background. This version does not add background shading for the session; session logic runs internally based on time.
• No on chart table. All decisions are visible through orders and exit levels. Use the Strategy Tester for performance metrics.
Inputs with guidance
Session Settings
• Trading session (sess). Session window in exchange time. Typical value uses the regular cash session for each contract, for example “0830-1530” for ES. Adjust if your broker or symbol uses different hours.
• Minutes before session end to force exit (flat_before_min). Minutes before the session end where positions are forced flat and the reference close is stored. Typical range is 15 to 120. Raising it closes trades earlier in the day; lowering it allows trades later in the session.
Gap Risk
• Enable gap based TP/SL (use_gap_risk). Master switch for the gap distance exit engine. Turning it off keeps entries and forced flat logic but removes automatic TP and SL placement.
• Use TP limit from gap (use_gap_tp). Enables gap based profit targets. Typical values are true for structured exits or false if you want to manage exits manually and only keep a stop.
• Use SL stop from gap (use_gap_sl). Enables gap based stop losses. This should normally remain true so that each trade has a defined initial risk in ticks.
• TP multiplier of gap distance (tp_mult). Multiplier applied to the gap distance for the target. Typical range is 0.5 to 2.0. Raising it places the target further away and reduces hit frequency.
• SL multiplier of gap distance (sl_mult). Multiplier applied to the gap distance for the stop. Typical range is 0.5 to 2.0. Raising it widens the stop and increases risk per trade; lowering it tightens the stop and may increase the number of small losses.
Exit Controls
• Exit with candle logic (use_candle_exit). If true, closes shorts on bullish candles and longs on bearish candles. Useful when you want to react to intraday reversal bars even if TP or SL have not been reached.
• Force flat before session end (use_forced_flat). If true, guarantees you are flat by the configured flat time and updates the reference close. Turn this off only if you understand the impact on overnight risk.
Filters
There is no separate trend or volatility filter in this version. All trades depend on the presence of a full gap bar inside the session. If you need extra filtering such as ATR, volume, or higher timeframe bias, they should be added explicitly and documented in your own fork.
Usage recipes
Intraday conservative gap fade
• Timeframe. Five minute chart on ES regular session.
• Gap risk. use_gap_risk = true, use_gap_tp = true, use_gap_sl = true.
• Multipliers. tp_mult around 0.7 to 1.0 and sl_mult around 1.0.
• Exits. use_candle_exit = false, use_forced_flat = true. Focus on the structured TP and SL around the gap.
Intraday aggressive gap fade
• Timeframe. Five minute chart.
• Gap risk. use_gap_risk = true, use_gap_tp = false, use_gap_sl = true.
• Multipliers. sl_mult around 0.7 to 1.0.
• Exits. use_candle_exit = true, use_forced_flat = true. Entries fade full gaps, stops are tight, and candle color flips flatten trades early.
Higher timeframe gap tests
• Timeframe. Fifteen minute or sixty minute charts on instruments with regular gaps.
• Gap risk. Keep use_gap_risk = true. Consider slightly higher sl_mult if gaps are structurally wider on the higher timeframe.
• Note. Expect fewer trades and be careful with sample size; multi year data is recommended.
Properties visible in this publication
• On average our risk for each position over the last 200 trades is 0.4% with a max intraday loss of 1.5% of the total equity in this case of 100k $ with 1 contract ES. For other assets, recalculations and customizations has to be applied.
• Initial capital. 100 000.
• Base currency. USD.
• Default order size method. Fixed with size 1 contract.
• Pyramiding. 0.
• Commission. Flat 2 USD per order in the Strategy Tester Properties. (2$ buying + 2$selling)
• Slippage. One tick in the Strategy Tester Properties.
• Process orders on close. ON.
Realism and responsible publication
• No performance claims are made. Past results do not guarantee future outcomes.
• Costs use a realistic flat commission and one tick of slippage per trade for ES class futures.
• Default sizing with one contract on a 100 000 reference account targets modest per trade risk. In practice, extreme slippage or gap through events can exceed this, so treat the one and a half percent risk target as a design goal, not a guarantee.
• All orders are simulated on standard candles. Shapes can move while a bar is forming and settle on bar close.
Honest limitations and failure modes
• Economic releases, thin liquidity, and limit conditions can break the assumptions behind the simple gap model and lead to slippage or skipped fills.
• Symbols with very frequent or very large gaps may require adjusted multipliers or alternative risk handling, especially in high volatility regimes.
• Very quiet periods without clean gaps will produce few or no trades. This is expected behavior, not a bug.
• Session windows follow the exchange time of the chart. Always confirm that the configured session matches the symbol.
• When both the stop and target lie inside the same bar’s range, the TradingView engine decides which is hit first based on its internal intrabar assumptions. Without bar magnifier, tie handling is approximate.
Legal
Education and research only. This strategy is not investment advice. You remain responsible for all trading decisions. Always test on historical data and in simulation with realistic costs before considering any live use.
Multi EMA + Golden Trio Crossover (Bullish & Bearish) by SKL📌 Multi EMA + Golden Trio Crossover (Bullish & Bearish) — by SKL
This indicator plots six key Exponential Moving Averages (EMA 5, 13, 26, 50, 100, 200) and highlights powerful momentum shift signals through the Golden Trio Crossover — a unique setup where EMA 5 crosses both EMA 13 and EMA 26 in the same candle .
It works for both bullish and bearish conditions, making it suitable for intraday, swing, and positional trading.
🔍 What is the Golden Trio Crossover?
A Golden Trio Crossover occurs when:
Bullish: EMA 5 crosses ** above ** EMA 13 *and* EMA 26 in the same candle
Bearish: EMA 5 crosses ** below ** EMA 13 *and* EMA 26 in the same candle
This triple-confirmation crossover often signals:
Early trend reversals
Strong continuation breakouts
Momentum shift points
📈 What This Indicator Includes
1. Six EMA Lines
EMA 5 – Blue
EMA 13 – Green
EMA 26 – Orange
EMA 50 – Black
EMA 100 – Gray
EMA 200 – Red
These EMAs help traders track trend direction, strength, and structure.
🌟 Visual Highlights
Green background → Bullish Golden Trio
Red background → Bearish Golden Trio
Label markers on each signal
“BULL GCO”
“BEAR GCO”
🔔 Alerts Included
You can enable alerts for:
Bullish Golden Trio Crossover
Bearish Golden Trio Crossover
Useful for breakout traders, scalpers, and swing traders.
🎯 How Traders Use This Indicator
Identify early trend shifts
Spot high-probability breakout candles
Confirm entries with multi-EMA confluence
Combine with volume, price action, or RSI for even stronger setups
📌 Notes
Works on all timeframes
Works on all asset classes (Stocks, Indices, Crypto, Forex, Commodities)
Fully automatic signal detection
Frequency Momentum Oscillator [QuantAlgo]🟢 Overview
The Frequency Momentum Oscillator applies Fourier-based spectral analysis principles to price action to identify regime shifts and directional momentum. It calculates Fourier coefficients for selected harmonic frequencies on detrended price data, then measures the distribution of power across low, mid, and high frequency bands to distinguish between persistent directional trends and transient market noise. This approach provides traders with a quantitative framework for assessing whether current price action represents meaningful momentum or merely random fluctuations, enabling more informed entry and exit decisions across various asset classes and timeframes.
🟢 How It Works
The calculation process removes the dominant trend from price data by subtracting a simple moving average, isolating cyclical components for frequency analysis:
detrendedPrice = close - ta.sma(close , frequencyPeriod)
The detrended price series undergoes frequency decomposition through Fourier coefficient calculation across the first 8 harmonics. For each harmonic frequency, the algorithm computes sine and cosine components across the lookback window, then derives power as the sum of squared coefficients:
for k = 1 to 8
cosSum = 0.0
sinSum = 0.0
for n = 0 to frequencyPeriod - 1
angle = 2 * math.pi * k * n / frequencyPeriod
cosSum := cosSum + detrendedPrice * math.cos(angle)
sinSum := sinSum + detrendedPrice * math.sin(angle)
power = (cosSum * cosSum + sinSum * sinSum) / frequencyPeriod
Power measurements are aggregated into three frequency bands: low frequencies (harmonics 1-2) capturing persistent cycles, mid frequencies (harmonics 3-4), and high frequencies (harmonics 5-8) representing noise. Each band's power normalizes against total spectral power to create percentage distributions:
lowFreqNorm = totalPower > 0 ? (lowFreqPower / totalPower) * 100 : 33.33
highFreqNorm = totalPower > 0 ? (highFreqPower / totalPower) * 100 : 33.33
The normalized frequency components undergo exponential smoothing before calculating spectral balance as the difference between low and high frequency power:
smoothLow = ta.ema(lowFreqNorm, smoothingPeriod)
smoothHigh = ta.ema(highFreqNorm, smoothingPeriod)
spectralBalance = smoothLow - smoothHigh
Spectral balance combines with price momentum through directional multiplication, producing a composite signal that integrates frequency characteristics with price direction:
momentum = ta.change(close , frequencyPeriod/2)
compositeSignal = spectralBalance * math.sign(momentum)
finalSignal = ta.ema(compositeSignal, smoothingPeriod)
The final signal oscillates around zero, with positive values indicating low-frequency dominance coupled with upward momentum (trending up), and negative values indicating either high-frequency dominance (choppy market) or downward momentum (trending down).
🟢 How to Use This Indicator
→ Long/Short Signals: the indicator generates long signals when the smoothed composite signal crosses above zero (indicating low-frequency directional strength dominates) and short signals when it crosses below zero (indicating bearish momentum persistence).
→ Upper and Lower Reference Lines: the +25 and -25 reference lines serve as threshold markers for momentum strength. Readings beyond these levels indicate strong directional conviction, while oscillations between them suggest consolidation or weakening momentum. These references help traders distinguish between strong trending regimes and choppy transitional periods.
→ Preconfigured Presets: three optimized configurations are available with Default (32, 3) offering balanced responsiveness, Fast Response (24, 2) designed for scalping and intraday trading, and Smooth Trend (40, 5) calibrated for swing trading and position trading with enhanced noise filtration.
→ Built-in Alerts: the indicator includes three alert conditions for automated monitoring - Long Signal (momentum shifts bullish), Short Signal (momentum shifts bearish), and Signal Change (any directional transition). These alerts enable traders to receive real-time notifications without continuous chart monitoring.
→ Color Customization: four visual themes (Classic green/red, Aqua blue/orange, Cosmic aqua/purple, Custom) allow chart customization for different display environments and personal preferences.
ECG PRICE - mauricioofsousa📉 ECG PRICE – The Price Electrocardiogram
(explained for traders, scientists, and complete beginners)
🔍 1. WHAT IS THE ECG PRICE?
The ECG PRICE protocol is a market-reading system based on the RSI, but with a surgical twist:
👉 You don’t just calculate RSI from price.
👉 You adjust the price using the RSI, and then calculate RSI over this adjusted price.
This creates a filtered, amplified signal that behaves like a heart monitor for price, detecting micro-impulses and subtle market movements long before they show up in the standard RSI.
🧬 2. CORE IDEA
Just like a real ECG amplifies and reveals electrical rhythms hidden inside the heartbeat,
the ECG PRICE amplifies micro-deformations hidden inside the price’s momentum.
It works in three stages:
Compute the regular RSI
Use the RSI to adjust the price (creating an electrocardiographic price)
Compute a second RSI over this modified price
The result is a meta-derived oscillator—more sensitive, more precise, and better at detecting structural changes.
🧩 3. TECHNICAL BREAKDOWN
3.1. First RSI (classic)
The script calculates:
average gains
average losses
relative strength (RS)
and then the standard 0–100 RSI
This is the “normal heart rate monitor” everyone uses.
3.2. Creating the “Adjusted Price”
adjustedPrice = close * (rsi / 100)
This means:
➡️ When RSI is high (strong buying momentum), price is amplified.
➡️ When RSI is low (strong selling momentum), price is compressed.
This converts raw price into a bio-electrical signal, where the price itself is modulated by its own internal momentum.
It’s the financial equivalent of ECG gain adjustment.
3.3. RSI of the Adjusted Price
Now the script calculates a new RSI from this modified price.
That is the actual ECG PRICE.
This second-order oscillator becomes extremely sensitive to:
micro-momentum shifts
early trend fading
volatility shocks
micro-divergences
institutional pressure waves
It reads the electrical pattern behind the price rather than the superficial movement.
🟩🟥 4. Diagnostic Lines of the Protocol
35 (green dotted)
Pre-oversold fatigue zone.
65 (red dotted)
Pre-overbought exhaustion zone.
30 (white solid)
Classic oversold.
70 (white solid)
Classic overbought.
Together they create two diagnostic corridors:
1. Medical corridor (30–70):
Standard RSI clinical range.
2. Electrical corridor (35–65):
The ECG-sensitive zone where micro-shifts appear first.
🧠 5. In Engineering Language (MGO style)
The ECG PRICE is essentially:
A nonlinear second-order oscillator where the RSI feeds back into price, creating a recursive momentum-modulated signal.
It functions like a:
bioinformational modulator
feedback-driven wave processor
impulse amplifier
micro-PID sensitivity enhancer
Very similar to the informational-wave transformations inside the MGO pipeline.
👨⚕️📉 6. Explained for a Total Beginner
Imagine the price is a heart.
The normal RSI shows if the heart is beating fast or slow.
But the ECG PRICE takes that heartbeat…
feeds it back into the heart…
and then measures the new heartbeat.
This creates a much more sensitive exam that detects problems before the normal test would.
💡 7. What It Gives You in Practice
earlier reversal signals
better trend-fatigue detection
clearer micro-divergences
a clean RSI with reduced noise
a smoother momentum curve
advanced behavioral readings before breakouts
It’s an upgrade.
A second-layer RSI that “hears” the inner electrical impulses of price.
Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
Market Profile Dominance Analyzer# Market Profile Dominance Analyzer
## 📊 OVERVIEW
**Market Profile Dominance Analyzer** is an advanced multi-factor indicator that combines Market Profile methodology with composite dominance scoring to identify buyer and seller strength across higher timeframes. Unlike traditional volume profile indicators that only show volume distribution, or simple buyer/seller indicators that only compare candle colors, this script integrates six distinct analytical components into a unified dominance measurement system.
This indicator helps traders understand **WHO controls the market** by analyzing price position relative to Market Profile key levels (POC, Value Area) combined with volume distribution, momentum, and trend characteristics.
## 🎯 WHAT MAKES THIS ORIGINAL
### **Hybrid Analytical Approach**
This indicator uniquely combines two separate methodologies that are typically analyzed independently:
1. **Market Profile Analysis** - Calculates Point of Control (POC) and Value Area (VA) using volume distribution across price channels on higher timeframes
2. **Multi-Factor Dominance Scoring** - Weights six independent factors to produce a composite dominance index
### **Six-Factor Composite Analysis**
The dominance score integrates:
- Price position relative to POC (equilibrium assessment)
- Price position relative to Value Area boundaries (acceptance/rejection zones)
- Volume imbalance within Value Area (institutional bias detection)
- Price momentum (directional strength)
- Volume trend comparison (participation analysis)
- Normalized Value Area position (precise location within fair value zone)
### **Adaptive Higher Timeframe Integration**
The script features an intelligent auto-selection system that automatically chooses appropriate higher timeframes based on the current chart period, ensuring optimal Market Profile structure regardless of the trading timeframe being analyzed.
## 💡 HOW IT WORKS
### **Market Profile Construction**
The indicator builds a Market Profile structure on a higher timeframe by:
1. **Session Identification** - Detects new higher timeframe sessions using `request.security()` to ensure accurate period boundaries
2. **Data Accumulation** - Stores high, low, and volume data for all bars within the current higher timeframe session
3. **Channel Distribution** - Divides the session's price range into configurable channels (default: 20 rows)
4. **Volume Mapping** - Distributes each bar's volume proportionally across all price channels it touched
### **Key Level Calculation**
**Point of Control (POC)**
- Identifies the price channel with the highest accumulated volume
- Represents the price level where the most trading activity occurred
- Serves as a magnetic level where price often returns
**Value Area (VA)**
- Starts at POC and expands both upward and downward
- Includes channels until reaching the specified percentage of total volume (default: 70%)
- Expansion algorithm compares adjacent volumes and prioritizes the direction with higher activity
- Defines the "fair value" zone where most market participants agreed to trade
### **Dominance Score Formula**
```
Dominance Score = (price_vs_poc × 10) +
(price_vs_va × 5) +
(volume_imbalance × 0.5) +
(price_momentum × 100) +
(volume_trend × 5) +
(va_position × 15)
```
**Component Breakdown:**
- **price_vs_poc**: +1 if above POC, -1 if below (shows which side of equilibrium)
- **price_vs_va**: +2 if above VAH, -2 if below VAL, 0 if inside VA
- **volume_imbalance**: Percentage difference between upper and lower VA volumes
- **price_momentum**: 5-period SMA of price change (directional acceleration)
- **volume_trend**: Compares 5-period vs 20-period volume averages
- **va_position**: Normalized position within Value Area (-1 to +1)
The composite score is then smoothed using EMA with configurable sensitivity to reduce noise while maintaining responsiveness.
### **Market State Determination**
- **BUYERS Dominant**: Smooth dominance > +10 (bullish control)
- **SELLERS Dominant**: Smooth dominance < -10 (bearish control)
- **NEUTRAL**: Between -10 and +10 (balanced market)
## 📈 HOW TO USE THIS INDICATOR
### **Trend Identification**
- **Green background** indicates buyers are in control - look for long opportunities
- **Red background** indicates sellers are in control - look for short opportunities
- **Gray background** indicates neutral market - consider range-bound strategies
### **Signal Interpretation**
**Buy Signals** (green triangle) appear when:
- Dominance crosses above -10 from oversold conditions
- Previous state was not already bullish
- Suggests shift from seller to buyer control
**Sell Signals** (red triangle) appear when:
- Dominance crosses below +10 from overbought conditions
- Previous state was not already bearish
- Suggests shift from buyer to seller control
### **Value Area Context**
Monitor the information table (top-right) to understand market structure:
- **Price vs POC**: Shows if trading above/below equilibrium
- **Volume Imbalance**: Positive values favor buyers, negative favors sellers
- **Market State**: Current dominant force (BUYERS/SELLERS/NEUTRAL)
### **Multi-Timeframe Strategy**
The auto-timeframe feature analyzes higher timeframe structure:
- On 1-minute charts → analyzes 2-hour structure
- On 5-minute charts → analyzes Daily structure
- On 15-minute charts → analyzes Weekly structure
- On Daily charts → analyzes Yearly structure
This higher timeframe context helps avoid counter-trend trades against the dominant force.
### **Confluence Trading**
Strongest signals occur when multiple factors align:
1. Price above VAH + positive volume imbalance + buyers dominant = Strong bullish setup
2. Price below VAL + negative volume imbalance + sellers dominant = Strong bearish setup
3. Price at POC + neutral state = Potential breakout/breakdown pivot
## ⚙️ INPUT PARAMETERS
- **Higher Time Frame**: Select specific HTF or use 'Auto' for intelligent selection
- **Value Area %**: Percentage of volume contained in VA (default: 70%)
- **Show Buy/Sell Signals**: Toggle signal triangles visibility
- **Show Dominance Histogram**: Toggle histogram display
- **Signal Sensitivity**: EMA period for dominance smoothing (1-20, default: 5)
- **Number of Channels**: Market Profile resolution (10-50, default: 20)
- **Color Settings**: Customize buyer, seller, and neutral colors
## 🎨 VISUAL ELEMENTS
- **Histogram**: Shows smoothed dominance score (green = buyers, red = sellers)
- **Zero Line**: Neutral equilibrium reference
- **Overbought/Oversold Lines**: ±50 levels marking extreme dominance
- **Background Color**: Highlights current market state
- **Information Table**: Displays key metrics (state, dominance, POC relationship, volume imbalance, timeframe, bars in session, total volume)
- **Signal Shapes**: Triangle markers for buy/sell signals
## 🔔 ALERTS
The indicator includes three alert conditions:
1. **Buyers Dominate** - Fires on buy signal crossovers
2. **Sellers Dominate** - Fires on sell signal crossovers
3. **Dominance Shift** - Fires when dominance crosses zero line
## 📊 BEST PRACTICES
### **Timeframe Selection**
- **Scalping (1-5min)**: Focus on 2H-4H dominance shifts
- **Day Trading (15-60min)**: Monitor Daily and Weekly structure
- **Swing Trading (4H-Daily)**: Track Weekly and Monthly dominance
### **Confirmation Strategies**
1. **Trend Following**: Enter in direction of dominance above/below ±20
2. **Reversal Trading**: Fade extreme readings beyond ±50 when diverging with price
3. **Breakout Trading**: Look for dominance expansion beyond ±30 with increasing volume
### **Risk Management**
- Avoid trading during NEUTRAL states (dominance between -10 and +10)
- Use POC levels as logical stop-loss placement
- Consider VAH/VAL as profit targets for mean reversion
## ⚠️ LIMITATIONS & WARNINGS
**Data Requirements**
- Requires sufficient historical data on current chart (minimum 100 bars recommended)
- Lower timeframes may show fewer bars per HTF session initially
- More accurate results after several complete HTF sessions have formed
**Not a Standalone System**
- This indicator analyzes market structure and participant control
- Should be combined with price action, support/resistance, and risk management
- Does not guarantee profitable trades - past dominance does not predict future results
**Repainting Characteristics**
- Higher timeframe levels (POC, VAH, VAL) update as new bars form within the session
- Dominance score recalculates with each new bar
- Historical signals remain fixed, but current session data is developing
**Volume Limitations**
- Uses exchange-provided volume data which varies by instrument type
- Forex and some CFDs use tick volume (not actual transaction volume)
- Most accurate on instruments with reliable volume data (stocks, futures, crypto)
## 🔍 TECHNICAL NOTES
**Performance Optimization**
- Uses `max_bars_back=5000` for extended historical analysis
- Efficient array management prevents memory issues
- Automatic cleanup of session data on new period
**Calculation Method**
- Market Profile uses actual volume distribution, not TPO (Time Price Opportunity)
- Value Area expansion follows traditional Market Profile auction theory
- All calculations occur on the chart's current symbol and timeframe
## 📚 EDUCATIONAL VALUE
This indicator helps traders understand:
- How institutional traders use Market Profile to identify fair value
- The relationship between price, volume, and market acceptance
- Multi-factor analysis techniques for assessing market conditions
- The importance of higher timeframe structure in trade planning
## 🎓 RECOMMENDED READING
To better understand the concepts behind this indicator:
- "Mind Over Markets" by James Dalton (Market Profile foundations)
- "Markets in Profile" by James Dalton (Value Area analysis)
- Volume Profile analysis in institutional trading
## 💬 USAGE TERMS
This indicator is provided as an educational and analytical tool. It does not constitute financial advice, investment recommendations, or trading signals. Users are responsible for their own trading decisions and should conduct their own research and due diligence.
Trading involves substantial risk of loss. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.
US Leverage Overlay — Margin Debt & Total Credit (YoY / Z-score)What this does
An overlay indicator that brings U.S. leverage proxies from FRED onto your main price chart (left axis). Choose between a proxy for investor margin debt or total credit market debt and view them as YoY %, Z-score of YoY, or an Indexed Level so they’re comparable with price without wrecking the scale.
Data sources (FRED symbols)
--- Margin (investor leverage proxy): FRED:BOGZ1FL663067003Q
Brokers & Dealers; Receivables Due from Customers ≈ margin loans (quarterly).
--- TotalCredit (economy-wide leverage): FRED:TCMDO
All sectors; Debt Securities & Loans; Liability (quarterly).
Note: These are quarterly series. The indicator samples monthly and holds values between official prints, so you’ll see step-like updates when new data drops.
Views (pick one in settings)
--- YoY % — 12-month rate of change. Above 0% = leverage expanding; below 0% = contracting.
--- Z-score (YoY) — Standardizes YoY vs. its recent history to flag unusual moves (regime shifts).
--- Indexed Level — 100 × (level / moving average), a compact “above/below trend” view.
How to read quickly
--- Rising YoY % > 0 → leverage expansion (often supportive for risk).
--- Falling YoY % < 0 → deleveraging headwind.
--- Z-score spikes (±2) → unusually fast changes; watch for volatility or policy inflections.
--- Indexed Level crossing down through 100 → slipping below trend.
Inputs
--- Data source: Margin or TotalCredit
--- YoY/Z-score lookbacks and Index baseline length
--- Overlay: overlay=true, scale=scale.left (uses its own left axis by default)
Tips
--- If it spawns in a sub-pane, right-click the label → Move to → Main chart.
--- For context, consider adding related series on separate panes:
FRED:TOTALSL (Consumer Credit), FRED:REVOLSL (Credit Cards),
FRED:BUSLOANS (C&I Loans), FRED:TDSP (Debt Service Ratio).
--- Occasionally FRED returns “Failed to fetch”; re-add or reload fixes it.
Why it’s useful
Equity drawdowns often line up with turns in leverage (households, corporates, or brokers). This overlay gives you a clean, normalized read so you can spot expansion vs. contraction alongside price action.
Compatibility
--- Pine Script® v6
--- Works on any chart timeframe (data internally sampled monthly)
Educational use only — not financial advice.
Multi EMA + Indicators + Mini-Dashboard + Reversals v6📘 Multi EMA + Indicators + Mini-Dashboard + Reversals v6
🧩 Overview
This indicator is a multi-EMA setup that combines trend, momentum, and reversal analysis in a single visual framework.
It integrates four exponential moving averages (EMAs), key oscillators (RSI, MACD, Stochastic, CCI), volatility filtering (ATR), and a dynamic mini-dashboard that summarizes all signals in real time.
Its purpose is to help traders visually confirm trend alignment, filter valid entries, and identify possible trend continuation or reversal points.
It can display buy/sell arrows, detect reversal candles, and issue alerts when trading conditions are met.
⚙️ Core Components
1. Moving Averages (EMA Setup)
EMA1 (fast) and EMA2 (medium) define the short-term trend and trigger bias.
When the price is above both EMAs → bullish bias.
When below → bearish bias.
EMA3 and EMA4 act as trend filters. Their slopes (up or down) confirm overall momentum and help validate signals.
Each EMA has customizable lengths, sources, and colors for up/down trends.
This “EMA stack” is the foundation of the setup — a structured trend-following framework that adapts to market speed and volatility.
2. Momentum and Confirmation Filters
Each indicator can be individually enabled or disabled for flexibility.
RSI: confirms direction (above/below 50).
MACD: detects momentum crossover (MACD > Signal for bullish confirmation).
Stochastic: identifies trend continuation (K > D for longs, K < D for shorts).
CCI: adds trend bias above/below a threshold.
ATR Filter: filters out small, low-volatility candles to reduce noise.
You can activate only the filters that fit your trading plan — for instance, trend traders often use RSI and MACD, while scalpers may rely on Stochastic and ATR.
3. Reversal Detection
The indicator includes an optional Reversal Section that independently detects potential turning points.
It combines multiple configurable criteria:
Candlestick patterns (Bullish Hammer, Shooting Star).
Large Candle filter — detects unusually large bars (relative to close).
Price-to-EMA distance — identifies overextended moves that might revert.
RSI Divergence — detects potential momentum shifts.
RSI Overbought/Oversold zones (70/30 by default).
Doji Candles — sign of indecision.
A bullish or bearish reversal signal appears when enough selected criteria are met.
All sub-modules can be toggled on/off individually, giving you full control over sensitivity.
4. Signal Logic
Buy and sell signals are triggered when EMA alignment and the chosen confirmations agree:
Buy Signal
→ Price above EMA1 & EMA2
→ Confirmations (RSI/MACD/Stoch/CCI/ATR) pass
→ Trend filters (EMA3/EMA4) point upward
Sell Signal
→ Price below EMA1 & EMA2
→ Confirmations align bearishly
→ Trend filters (EMA3/EMA4) slope downward
Reversal signals can appear independently, even against the current EMA trend, depending on your settings.
5. Visual Dashboard
A mini-dashboard appears near the chart showing:
Current trade bias (LONG / SHORT / NEUTRAL)
EMA3 and EMA4 trend directions (↑ / ↓)
Quick visual bars (🟩 / 🟥) for each filter: RSI, MACD, Stoch, ATR, CCI, EMA filters
Reversal criteria status (Doji, RSI divergence, candle size, etc.)
This panel gives you a compact overview of all indicator states at a glance.
The color of the panel changes dynamically — green for bullish, red for bearish, gray for neutral.
6. Alerts
Built-in alerts allow automation or notifications:
Buy Alert
Sell Alert
Reversal Buy
Reversal Sell
You can connect these alerts to TradingView notifications or external bots for semi-automated execution.
💡 How to Use
✅ Trend-Following Setup
Focus on trades in the direction of EMA1 & EMA2.
Confirm with EMA3 & EMA4 trending in the same direction.
Use RSI/MACD/Stoch filters to ensure momentum supports the trade.
Avoid entries when ATR filter indicates low volatility.
🔄 Reversal Setup
Enable the Reversal section for potential tops/bottoms.
Look for reversal buy signals near support zones or after strong downtrends.
Use RSI divergence or Doji + Hammer signals as confirmation.
Combine with key chart areas (supply/demand or previous swing levels).
⚖️ Combination Approach
Trade continuation signals when all EMAs are aligned and filters are green.
Trade reversals only when at a key area (support/resistance) and confirmed by reversal conditions.
Always check higher-timeframe bias before entering a trade.
🧭 Practical Tips
Use different EMA sets for different timeframes:
9/21/50/100 for swing or trend trades.
5/13/34/89 for intraday scalping.
Turn off filters you don’t use to reduce lag.
Always validate signals with price structure, not just indicator alignment.
Practice in replay mode before live trading.
🗺️ Key Chart Confluence (Highly Recommended)
Although the indicator provides structured signals, its best use is in confluence with:
Support and resistance levels
Supply/demand zones
Trendlines and channels
Liquidity pools
Volume clusters
Signals aligned with strong key areas on the chart tend to have greater reliability than isolated indicator triggers.
I use EMA 1 - 20 Open ; EMA 2 - 20 Close ; EMA 3 - 50 ; EMA 4 - 200 or 100 , but that's me...
⚠️ Important Disclaimer
This indicator is a technical tool, not a guarantee of results.
Trading involves risk, and no signal is ever 100% accurate.
Every trader should develop a personal strategy, use proper risk management, and adapt settings to their instrument and timeframe.
Always combine indicator signals with key chart areas, higher-timeframe context, and your own analysis before taking a trade.






















