Inverse Fisher Transform on STOCHASTIC (modified graphics)Modified the graphic representation of the script from John Ehlers - From California, USA, he is a veteran trader. With 35 years trading experience he has seen it all. John has an engineering background that led to his technical approach to trading ignoring fundamental analysis (with one important exception). John strongly believes in cycles. He’d rather exit a trade when the cycle ends or a new one starts. He uses the MESA principle to make predictions about cycles in the market and trades one hundred percent automatically.
In the show John reveals:
• What is more appropriate than trading individual stocks
• The one thing he relies upon in his approach to the market
• The detail surrounding his unique trading style
• What important thing underpins the market and gives every trader an edge
About INVERSE FISHER TRANSFORM:
The purpose of technical indicators is to help with your timing decisions to buy or sell. Hopefully, the signals are clear and unequivocal. However, more often than not your decision to pull the trigger is accompanied by crossing your fingers. Even if you have placed only a few trades you know the drill. In this article I will show you a way to make your oscillator-type indicators make clear black-or-white indication of the time to buy or sell. I will do this by using the Inverse Fisher Transform to alter the Probability Distribution Function (PDF) of your indicators. In the past12 I have noted that the PDF of price and indicators do not have a Gaussian, or Normal, probability distribution. A Gaussian PDF is the familiar bell-shaped curve where the long “tails” mean that wide deviations from the mean occur with relatively low probability. The Fisher Transform can be applied to almost any normalized data set to make the resulting PDF nearly Gaussian, with the result that the turning points are sharply peaked and easy to identify. The Fisher Transform is defined by the equation
1)
Whereas the Fisher Transform is expansive, the Inverse Fisher Transform is compressive. The Inverse Fisher Transform is found by solving equation 1 for x in terms of y. The Inverse Fisher Transform is:
2)
The transfer response of the Inverse Fisher Transform is shown in Figure 1. If the input falls between –0.5 and +0.5, the output is nearly the same as the input. For larger absolute values (say, larger than 2), the output is compressed to be no larger than unity. The result of using the Inverse Fisher Transform is that the output has a very high probability of being either +1 or –1. This bipolar probability distribution makes the Inverse Fisher Transform ideal for generating an indicator that provides clear buy and sell signals.
Pesquisar nos scripts por "ha溢价率"
Strenght and MomentumThe scope of this script is to measure momentum and strenght of EURO and DOLLAR using their indexes.
Forza (line) above 0 means EURO is stonger than DOLLAR
Momento (histogram) above 0 means EURO has a positive momentum against DOLLAR
The added value to see MACD and RSI directly on EURUSD chart is that indexes consider also other pairs so their RSI and MACD has a larger view on forex markets.
Script has also an option for multi timeframes.
I think that could be used as filters for LONG or SHORT positions in lower time frames.
XPloRR MA-Trailing-Stop StrategyXPloRR MA-Trailing-Stop Strategy
Long term MA-Trailing-Stop strategy with Adjustable Signal Strength to beat Buy&Hold strategy
None of the strategies that I tested can beat the long term Buy&Hold strategy. That's the reason why I wrote this strategy.
Purpose: beat Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
My buy strategy is triggered by the fast buy EMA (blue) crossing over the slow buy SMA curve (orange) and the fast buy EMA has a certain up strength.
My sell strategy is triggered by either one of these conditions:
the EMA(6) of the close value is crossing under the trailing stop value (green) or
the fast sell EMA (navy) is crossing under the slow sell SMA curve (red) and the fast sell EMA has a certain down strength.
The trailing stop value (green) is set to a multiple of the ATR(15) value.
ATR(15) is the SMA(15) value of the difference between the high and low values.
The scripts shows a lot of graphical information:
The close value is shown in light-green. When the close value is lower then the buy value, the close value is shown in light-red. This way it is possible to evaluate the virtual losses during the trade.
the trailing stop value is shown in dark-green. When the sell value is lower then the buy value, the last color of the trade will be red (best viewed when zoomed)(in the example, there are 2 trades that end in gain and 2 in loss (red line at end))
the EMA and SMA values for both buy and sell signals are shown as a line
the buy and sell(close) signals are labeled in blue
How to use this strategy?
Every stock has it's own "DNA", so first thing to do is tune the right parameters to get the best strategy values voor EMA , SMA, Strength for both buy and sell and the Trailing Stop (#ATR).
Look in the strategy tester overview to optimize the values Percent Profitable and Net Profit (using the strategy settings icon, you can increase/decrease the parameters)
Then keep using these parameters for future buy/sell signals only for that particular stock.
Do the same for other stocks.
Important : optimizing these parameters is no guarantee for future winning trades!
Here are the parameters:
Fast EMA Buy: buy trigger when Fast EMA Buy crosses over the Slow SMA Buy value (use values between 10-20)
Slow SMA Buy: buy trigger when Fast EMA Buy crosses over the Slow SMA Buy value (use values between 30-100)
Minimum Buy Strength: minimum upward trend value of the Fast SMA Buy value (directional coefficient)(use values between 0-120)
Fast EMA Sell: sell trigger when Fast EMA Sell crosses under the Slow SMA Sell value (use values between 10-20)
Slow SMA Sell: sell trigger when Fast EMA Sell crosses under the Slow SMA Sell value (use values between 30-100)
Minimum Sell Strength: minimum downward trend value of the Fast SMA Sell value (directional coefficient)(use values between 0-120)
Trailing Stop (#ATR): the trailing stop value as a multiple of the ATR(15) value (use values between 2-20)
Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now) compared to the Buy&Hold Strategy(=do nothing):
BEKB(Bekaert): EMA-Buy=12, SMA-Buy=44, Strength-Buy=65, EMA-Sell=12, SMA-Sell=55, Strength-Sell=120, Stop#ATR=20
NetProfit: 996%, #Trades: 6, %Profitable: 83%, Buy&HoldProfit: 78%
BAR(Barco): EMA-Buy=16, SMA-Buy=80, Strength-Buy=44, EMA-Sell=12, SMA-Sell=45, Strength-Sell=82, Stop#ATR=9
NetProfit: 385%, #Trades: 7, %Profitable: 71%, Buy&HoldProfit: 55%
AAPL(Apple): EMA-Buy=12, SMA-Buy=45, Strength-Buy=40, EMA-Sell=19, SMA-Sell=45, Strength-Sell=106, Stop#ATR=8
NetProfit: 6900%, #Trades: 7, %Profitable: 71%, Buy&HoldProfit: 2938%
TNET(Telenet): EMA-Buy=12, SMA-Buy=45, Strength-Buy=27, EMA-Sell=19, SMA-Sell=45, Strength-Sell=70, Stop#ATR=14
NetProfit: 129%, #Trade
Inverse Fisher Transform COMBO STO+RSI+CCIv2 by KIVANÇ fr3762A combined 3in1 version of pre shared INVERSE FISHER TRANSFORM indicators on RSI , on STOCHASTIC and on CCIv2 to provide space for 2 more indicators for users...
About John EHLERS:
From California, USA, John is a veteran trader. With 35 years trading experience he has seen it all. John has an engineering background that led to his technical approach to trading ignoring fundamental analysis (with one important exception).
John strongly believes in cycles. He’d rather exit a trade when the cycle ends or a new one starts. He uses the MESA principle to make predictions about cycles in the market and trades one hundred percent automatically.
In the show John reveals:
• What is more appropriate than trading individual stocks
• The one thing he relies upon in his approach to the market
• The detail surrounding his unique trading style
• What important thing underpins the market and gives every trader an edge
About INVERSE FISHER TRANSFORM:
The purpose of technical indicators is to help with your timing decisions to buy or
sell. Hopefully, the signals are clear and unequivocal. However, more often than
not your decision to pull the trigger is accompanied by crossing your fingers.
Even if you have placed only a few trades you know the drill.
In this article I will show you a way to make your oscillator-type indicators make
clear black-or-white indication of the time to buy or sell. I will do this by using the
Inverse Fisher Transform to alter the Probability Distribution Function ( PDF ) of
your indicators. In the past12 I have noted that the PDF of price and indicators do
not have a Gaussian, or Normal, probability distribution. A Gaussian PDF is the
familiar bell-shaped curve where the long “tails” mean that wide deviations from
the mean occur with relatively low probability. The Fisher Transform can be
applied to almost any normalized data set to make the resulting PDF nearly
Gaussian, with the result that the turning points are sharply peaked and easy to
identify. The Fisher Transform is defined by the equation
1)
Whereas the Fisher Transform is expansive, the Inverse Fisher Transform is
compressive. The Inverse Fisher Transform is found by solving equation 1 for x
in terms of y. The Inverse Fisher Transform is:
2)
The transfer response of the Inverse Fisher Transform is shown in Figure 1. If
the input falls between –0.5 and +0.5, the output is nearly the same as the input.
For larger absolute values (say, larger than 2), the output is compressed to be no
larger than unity . The result of using the Inverse Fisher Transform is that the
output has a very high probability of being either +1 or –1. This bipolar
probability distribution makes the Inverse Fisher Transform ideal for generating
an indicator that provides clear buy and sell signals.
Creator: John EHLERS
Inverse Fisher Transform on SMI (Stochastic Momentum Index)Inverse Fisher Transform on SMI (Stochastic Momentum Index)
About John EHLERS:
From California, USA, John is a veteran trader. With 35 years trading experience he has seen it all. John has an engineering background that led to his technical approach to trading ignoring fundamental analysis (with one important exception).
John strongly believes in cycles. He’d rather exit a trade when the cycle ends or a new one starts. He uses the MESA principle to make predictions about cycles in the market and trades one hundred percent automatically.
In the show John reveals:
• What is more appropriate than trading individual stocks
• The one thing he relies upon in his approach to the market
• The detail surrounding his unique trading style
• What important thing underpins the market and gives every trader an edge
About INVERSE FISHER TRANSFORM:
The purpose of technical indicators is to help with your timing decisions to buy or
sell. Hopefully, the signals are clear and unequivocal. However, more often than
not your decision to pull the trigger is accompanied by crossing your fingers.
Even if you have placed only a few trades you know the drill.
In this article I will show you a way to make your oscillator-type indicators make
clear black-or-white indication of the time to buy or sell. I will do this by using the
Inverse Fisher Transform to alter the Probability Distribution Function (PDF) of
your indicators. In the past12 I have noted that the PDF of price and indicators do
not have a Gaussian, or Normal, probability distribution. A Gaussian PDF is the
familiar bell-shaped curve where the long “tails” mean that wide deviations from
the mean occur with relatively low probability. The Fisher Transform can be
applied to almost any normalized data set to make the resulting PDF nearly
Gaussian, with the result that the turning points are sharply peaked and easy to
identify. The Fisher Transform is defined by the equation
1)
Whereas the Fisher Transform is expansive, the Inverse Fisher Transform is
compressive. The Inverse Fisher Transform is found by solving equation 1 for x
in terms of y. The Inverse Fisher Transform is:
2)
The transfer response of the Inverse Fisher Transform is shown in Figure 1. If
the input falls between –0.5 and +0.5, the output is nearly the same as the input.
For larger absolute values (say, larger than 2), the output is compressed to be no
larger than unity. The result of using the Inverse Fisher Transform is that the
output has a very high probability of being either +1 or –1. This bipolar
probability distribution makes the Inverse Fisher Transform ideal for generating
an indicator that provides clear buy and sell signals.
DepthHouse - Moving Average ChannelsThe indicator Moving Average Channels was created for experimental purposes due to the parabolic moves BTC has made in the recent past.
How it works:
The basis, or center line, is a standard moving average that is set by the user.
The bands are then a customizable percentage of the basis.
Which based on the settings, could serve as possible support and resistance.
DepthHouse – Moving Average Channels has been published for you all to see and try for yourselves.
Maybe this indicator has uses elsewhere? If you find something feel free to post it in the comments below!
If you like this indicator, please drop a like or comment!
They are very much appreciated!
Be sure to go to my profile and check out my other indicators!
OHLC Volatility Estimators by @Xel_arjonaDISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The embedded code and ideas within this work are FREELY AND PUBLICLY available on the Web for NON LUCRATIVE ACTIVITIES and must remain as is by Creative-Commons as TradingView's regulations. Any use, copy or re-use of this code should mention it's origin as it's authorship.
WARNING NOTICE!
THE INCLUDED FUNCTION MUST BE CONSIDERED AS DEBUGING CODE The models included in the function have been taken from openly sources on the web so they could have some errors as in the calculation scheme and/or in it's programatic scheme. Debugging are welcome.
WHAT'S THIS?
Here's a full collection of candle based (compressed tick) Volatility Estimators given as a function, openly available for free, it can print IMPLIED VOLATILITY by an external symbol ticker like INDEX:VIX.
Models included in the volatility calculation function:
CLOSE TO CLOSE: This is the classic estimator by rule, sometimes referred as HISTORICAL VOLATILITY and is the must common, accepted and widely used out there. Is based on traditional Standard Deviation method derived from the logarithm return of current close from yesterday's.
ELASTIC WEIGHTED MOVING AVERAGE: This estimator has been used by RiskMetriks®. It's calculation is based on an ElasticWeightedMovingAverage Standard Deviation method derived from the logarithm return of current close from yesterday's. It can be viewed or named as an EXPONENTIAL HISTORICAL VOLATILITY model.
PARKINSON'S: The Parkinson number, or High Low Range Volatility, developed by the physicist, Michael Parkinson, in 1980 aims to estimate the Volatility of returns for a random walk using the high and low in any particular period. IVolatility.com calculates daily Parkinson values. Prices are observed on a fixed time interval. n=10, 20, 30, 60, 90, 120, 150, 180 days.
ROGERS-SATCHELL: The Rogers-Satchell function is a volatility estimator that outperforms other estimators when the underlying follows a Geometric Brownian Motion (GBM) with a drift (historical data mean returns different from zero). As a result, it provides a better volatility estimation when the underlying is trending. However, this Rogers-Satchell estimator does not account for jumps in price (Gaps). It assumes no opening jump. The function uses the open, close, high, and low price series in its calculation and it has only one parameter, which is the period to use to estimate the volatility.
YANG-ZHANG: Yang and Zhang were the first to derive an historical volatility estimator that has a minimum estimation error, is independent of the drift, and independent of opening gaps. This estimator is maximally 14 times more efficient than the close-to-close estimator.
LOGARITHMIC GARMAN-KLASS: The former is a pinescript transcript of the model defined as in iVolatility . The metric used is a combination of the overnight, high/low and open/close range. Such a volatility metric is a more efficient measure of the degree of volatility during a given day. This metric is always positive.
Fractals and Levels by JustUncleLEven though there are a many other Fractal and Level indicators, this indicator has some unique features. The indicator will display Fractals, fractal levels and HH/LL points, they will only be drawn after they have completed. Also the indicator has options to :
Show Ideal Fractals Only.
Use Renko Style Fractals, where open/close values are used instead of high/low to find Fractals. This is used to show the correct Fractals when Renko Wicks are enabled.
Has an optional Filter to only display Fractals that are above/below a MA Ribbon.
References:
This code is based on Fractal Levels V8 by RicardoSantos
This is a Renko Chart with "Renko Style Fractals" enabled, notice that the wicks are ignored and only the true Bricks are used for Fractals:
Adaptive Donchian ChannelThis indicator adds a level of adaptivity to the simple Donchian Channel by adjusting the sensitivity (lookback periods) of the channel's upper and lower bounds based on the amount of time that has elapsed since the price has hit/expanded the channel boundaries. Comparing the results of this indicator to the standard Donchian Channel, the readier level of responsiveness may prove self-evident.
METHODOLOGY:
Specifically, the more recently the channel was expanded in one direction, the longer the lookback period grows in that direction. Conversely, if the channel has not been expanded in a given direction, the lookback period will contract so as to allow for a tighter channel.
For example, let the initial lookback period be 20 bars and let the factor argument be 0.1 (or 2 bars to start, as 20*0.1 = 2). Now say the current bar sets a new 20-period high. Then the lookback period for the upper bound is expanded by 2 bars to 22, and the lookback period for the lower bound is contracted by 2 bars to 18, thereby making it simultaneously harder to set new highs and easier to set new lows (and vice versa for hitting new lows). If neither a new high nor a new low is formed, both periods contract by the given factor.
Guth_3X_ConfirmThis indicator has three built in indicators based on the SMA of HIGH, SMA of LOW, and Stochastic. The baseline indicator is the retreats after departures from SMA of HIGH and LOW.
The first time a HIGH that is above the SMA HIGH has a lower HIGH but it still above the SMA HIGH, a (-) will appear at the bottom. This signals an aggressive entry point for potential coming downtrend. The second time the HIGH produces a lower high but is still above the SMA HIGH, a (S) will appear at the bottom which signals a more conservative entry point for potential coming downtrend. All of the opposite information is true of reversals beyond the SMA LOW.
When these reversals appear the same time the Stochastic is overbought or oversold, a red bar (overbought and potentially coming down) or a green bar (oversold and potentially coming up) will appear. NOTE: Aggressive symbols occur more often and will always occur when a conservative symbol appears. When a conservative indicator and respective overbought/oversold level occur at the same time, the bar is darker in color.
You can enter positions at any one of the indicators, however, the darker bars are what I look for. This has a high success rate but cannot guarantee results every time. I recommend adjusting the SMA, and Stoch parameters as well as time periods. I have had success with this indicator while day trading the 5, 10, 15, 30, 65 minute periods as well as daily and weekly periods. Every symbol traded can provide differing results based on the parameters used.
Please feel free to leave feedback and I know this can work well for you!
AlphaAlpha is a measure of the active return on an investment, the performance of that investment compared to the S&P500 index, where 0.01 = 1%
alpha < 0: the investment has earned too little for its risk (or, was too risky for the return)
alpha = 0: the investment has earned a return adequate for the risk taken
alpha > 0: the investment has a return in excess of the reward for the assumed risk
Mister Transistor 3.0This is a general purpose very flexible program to test the effectiveness of HA bars.
Please note that if you are charting at tradingview using Heikin-Ashi charting, your system will be trading fictitious prices even if you check the "use real prices" box. Thought you might like to know that before you lose all your money.
This program performs the HA calcs internally thus allowing you to use HA bars on a standard bar chart and obtaining real prices for your trades.
Courtesy of Boffin Hollow Lab
Author: Tarzan the Ape Man
Trailing Sharpe RatioThe Sharpe ratio allows you to see whether or not an investment has historically provided a return appropriate to its risk level. A Sharpe ratio above one is acceptable, above 2 is good, and above 3 is excellent. A Sharpe ratio less than one would indicate that an investment has not returned a high enough return to justify the risk of holding it. Interesting in this example, SPY's one year avg Sharpe ratio is above 3. This would mean on average SPY returns 3x better returns than the risk associated with holding it, implying there is some sort of underlying value to the investment.
When the sharpe ratio is above its signal, this implies the investment is currently outperforming compared to its typical return, below the signal means the investment is currently under performing. A negative Shape would mean that the investment has not provided a positive return, and may be a possible short candidate.
Zweig Market Breadth Thrust Indicator [LazyBear]The Breadth Thrust (BT) indicator is a market momentum indicator developed by Dr. Martin Zweig. According to Dr. Zweig a Breadth Thrust occurs when, during a 10-day period, the Breadth Thrust indicator rises from below 40 percent to above 61.5 percent.
A "Thrust" indicates that the stock market has rapidly changed from an oversold condition to one of strength, but has not yet become overbought. This is very rare and has happened only a few times. Dr. Zweig also points out that most bull markets begin with a Breadth Thrust.
All parameters are configurable. You can draw BT for NYSE, NASDAQ, AMEX or based on combined data (i.e., AMEX+NYSE+NASD). There is also a "CUSTOM" mode supported, so you can enter your own ADV/DEC symbols.
More info:
Definition: www.investopedia.com
A Breadth Thrust Signal: www.mcoscillator.com
A Rare "Zweig" Buy Signal: www.moneyshow.com
Zweig Breadth Thrust: recessionalert.com
List of my public indicators: bit.ly
List of my app-store indicators: blog.tradingview.com
KK_Traders Dynamic Index_Bar HighlightingHey guys,
this is one of my favorite scripts as it represents a whole trading system that has given me very good results!
I have only used it on Bitcoin so far but I am sure it will also work for other instruments.
The original code to this was created by LazyBear, so all props to him for this great script!
I have linked his original post down below.
You can find the full rules to the system in this PDF (which has also been taken from LBs post):
www.forexmt4.com
Here is a short summary of the rules:
Go long when (all conditions have to be met):
The green line is above 50
The green line is above the red line
The green line is above the orange line
The close is above the upper Band of the Price Action Channel
The candles close is above its open
(The green line is below 68)
Go short when (all conditions have to be met):
The green line is below 50
The green line is below the red line
The green line is below the orange line
The close is below the lower band of the Price Action Channel
The candles close is below its open
(The green line is above 32)
Close when:
Any of these conditions aren't true anymore.
I have marked two of the rules in brackets as they seem to cut out a lot of the profits this system generates. You can choose to still use these rules by checking the box that says "Use Original Ruleset" in the options.
The system also contains rules regarding the Heiken Ashi bars. However these aren't as specific as the other rules. This is where your personal judgement comes in and this part is hard to explain. Take a look at the PDF I have linked to get a better understanding.
So far, this is just the TDI trading system and LBs script, now what have I changed?
I have incorporated the Price Action Channel to the system and changed it so that it highlights the bars whenever the system is giving a signal. As long as the bars are green the system is giving a long signal, as long as they are red the system is giving a short signal. Keep in mind that this doesn't consider the bar size of the HA bars. I recommend coloring all bars grey via the chart settings in order to be able to see the bar highlighting properly.
I have also published the Price Action Channel seperately in case some of you wish to view the Channel.
I am fairly new to creating scripts so use it with caution and let me know what you think!
LBs original post:
The seperate Price Action Channel script:
CM Stochastic POP Method 1 - Jake Bernstein_V1A good friend ucsgears recently published a Stochastic Pop Indicator designed by Jake Bernstein with a modified version he found.
I spoke to Jake this morning and asked if he had any updates to his Stochastic POP Trading Method. Attached is a PDF Jake published a while back (Please read for basic rules, which also Includes a New Method). I will release the Additional Method Tomorrow.
Jake asked me to share that he has Updated this Method Recently. Now across all symbols he has found the Stochastic Values of 60 and 30 to be the most profitable. NOTE - This can be Significantly Optimized for certain Symbols/Markets.
Jake Bernstein will be a contributor on TradingView when Backtesting/Strategies are released. Jake is one of the Top Trading System Developers in the world with 45+ years experience and he is going to teach how to create Trading Systems and how to Optimize the correct way.
Below are a few Strategy Results....Soon You Will Be Able To Find Results Like This Yourself on TradingView.com
BackTesting Results Example: EUR-USD Daily Chart Since 01/01/2005
Strategy 1:
Go Long When Stochastic Crosses Above 60. Go Short When Stochastic Crosses Below 30. Exit Long/Short When Stochastic has a Reverse Cross of Entry Value.
Results:
Total Trades = 164
Profit = 50, 126 Pips
Win% = 38.4%
Profit Factor = 1.35
Avg Trade = 306 Pips Profit
***Most Consecutive Wins = 3 ... Most Consecutive Losses = 6
Strategy 2:
Rules - Proprietary Optimization Jake Will Teach. Only Added 1 Additional Exit Rule.
Results:
Total Trades = 164
Profit = 62, 876 Pips!!!
Win% = 38.4%
Profit Factor = 1.44
Avg Trade = 383 Pips Profit
***Most Consecutive Wins = 3 ... Most Consecutive Losses = 6
Strategy 3:
Rules - Proprietary Optimization Jake Will Teach. Only added 1 Additional Exit Rule.
Results:
Winning Percent Increases to 72.6%!!! , Same Amount of Trades.
***Most Consecutive Wins = 21 ...Most Consecutive Losses = 4
Indicator Includes:
-Ability to Color Candles (CheckBox In Inputs Tab)
Green = Long Trade
Blue = No Trade
Red = Short Trade
-Color Coded Stochastic Line based on being Above/Below or In Between Entry Lines.
Link To Jakes PDF with Rules
dl.dropboxusercontent.com
We Are Witnessing A Historical Event With A Clear Outcome!!!"Full Disclosure: I came across this information from www.SentimenTrader.com
I have no financial affiliation…They provide incredible statistical facts on
The General Market, Currencies, and Futures. They offer a two week free trial.
I Highly Recommend.
The S&P 500 has gone 43 trading days without a 1% daily move, up or down.
which is the equivalent of two months and one day in trading days.
During this stretch, the S&P has gained more than 4%,
and it has notched a 52-week high recently as well.
Since 1952, there were nine other precedents. All of
these went 42 trading days without a 1% move, all of
them saw the S&P gain at least 4% during their streaks,
and all of them saw the S&P close at a 52-week highs.
***There was consistent weakness a week later, with only three
gainers, and all below +0.5%.
***After that, stocks did better, often continuing an Extraordinary move higher.
Charts can sometimes give us a better nuance than
numbers from a table, and from the charts we can see a
general pattern -
***if stocks held up well in the following
weeks, then they tended to do extremely well in the
months ahead.
***If stocks started to stumble after this two-
month period of calm, however, then the following months
tended to show a lot more volatility.
We already know we're seeing an exceptional market
environment at the moment, going against a large number
of precedents that argued for weakness here, instead of
the rally we've seen. If we continue to head higher in
spite of everything, these precedents would suggest that
we're in the midst of something that could be TRULY EXTRAORDINARY.
Trading Strategy based on BB/KC squeeze**** [Edit: New version (v02) posted, see the comments section for the code *****
Simple strategy. You only consider taking a squeeze play when both the upper and lower Bollinger Bands go inside the Keltner Channel. When the Bollinger Bands (BOTH lines) start to come out of the Keltner Channel, the squeeze has been released and a move is about to take place.
I have added more support indicators -- I highlight the bullish / bearish KC breaches (using GREEN/RED crosses) and a SAR to see where price action is trending.
Appreciate any feedback. Enjoy!
Color codes for v02:
----------------------------
When both the upper and lower Bollinger Bands go inside the Keltner Channel, the squeeze is on and is highlighted in RED.
When the Bollinger Bands (BOTH lines) start to come out of the Keltner Channel, the squeeze has been released and is highlighted in GREEN.
When one of the Bollinger Bands is out of Keltner Channel, no highlighting is done (this means, the background color shows up, so don't get confused if you have RED/GREEN in your chart's bground :))
Color codes for v01:
----------------------------
When both the upper and lower Bollinger Bands go inside the Keltner Channel, the squeeze is on and is highlighted in YELLOW.
When the Bollinger Bands (BOTH lines) start to come out of the Keltner Channel, the squeeze has been released and is highlighted in BLUE.
5m FVGs Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Emac ForecastEMAC Forecast System
What it measures
The EMAC Forecast measures the speed and persistence of trend movement. Instead of only looking at whether one EMA is above or below another, the forecast quantifies how quickly momentum is building or fading across multiple time horizons.
It captures three things at once:
The direction of the underlying trend
The rate at which the trend is strengthening or weakening
The consistency of that change across several smoothing speeds
This produces a forward leaning view of trend conditions, not a trailing confirmation.
How to read the forecast
The EMAC Forecast is displayed as a scaled oscillator, typically ranging between negative and positive values.
Positive forecast values
Indicate that bullish trend pressure is increasing.
Higher readings mean stronger acceleration, not just price rising.
Negative forecast values
Indicate increasing bearish pressure.
Again, the strength of the negative reading reflects how quickly selling momentum is building.
Rising forecast (slope up)
Shows improving momentum, even if the value is still below zero.
Useful for catching early reversals or transitions from chop to trend.
Falling forecast (slope down)
Shows momentum fading, even when trend direction has not flipped yet.
Helps anticipate exhaustions and pullbacks.
Flat forecast
Indicates low conviction and lack of directional drive.
Often corresponds to chop or range conditions.
Why the EMAC Forecast is different from a regular EMAC
A standard EMAC or EMA crossover follows a simple rule:
When fast EMA crosses above slow EMA, bullish.
When fast EMA crosses below slow EMA, bearish.
This is reactive and only changes after price has already moved.
The EMAC Forecast works differently:
1. Uses multiple EMAs rather than two
Instead of comparing one fast and one slow average, it blends several time constants into a composite signal.
This creates a smoother, more reliable directional read.
2. Measures acceleration, not just position
Traditional crossovers only monitor whether lines have crossed.
EMAC Forecast measures the speed and force behind the movement.
It tells you how strong the trend is becoming, not just whether one line is above the other.
3. Adapts to volatility
Sharp markets increase weighting of fast components.
Calm markets increase influence of slower components.
This reduces whipsaws in low-volatility conditions and improves responsiveness in high-volatility environments.
4. Gives actionable information before a crossover happens
The forecast often turns before the EMAC direction flips, allowing early detection of:
Trend ignition
Trend fade
Momentum squeezes
Impending reversals
It effectively “leans forward” into the trend instead of waiting for a full reversal.
Practical Use Cases
Early trend identification
When the forecast first turns positive or negative, trend acceleration is beginning.
This is often visible before the EMAC lines cross.
Confirming the Combined Forecast System
Use the EMAC Forecast to validate signals from your other forecast models.
If both agree, conviction is notably higher.
Filtering noise
Short-term whipsaws are reduced because the composite structure dilutes erratic fast movements.
Trend aging and exhaustion
A falling forecast during a positive trend suggests reduced conviction and potential exhaustion.
Range Oscillator Strategy + Stoch Confirm🔹 Short summary
This is a free, educational long-only strategy built on top of the public “Range Oscillator” by Zeiierman (used under CC BY-NC-SA 4.0), combined with a Stochastic timing filter, an EMA-based exit filter and an optional risk-management layer (SL/TP and R-multiple exits). It is NOT financial advice and it is NOT a magic money machine. It’s a structured framework to study how range-expansion + momentum + trend slope can be combined into one rule-based system, often with intentionally RARE trades.
────────────────────────
0. Legal / risk disclaimer
────────────────────────
• This script is FREE and public. I do not charge any fee for it.
• It is for EDUCATIONAL PURPOSES ONLY.
• It is NOT financial advice and does NOT guarantee profits.
• Backtest results can be very different from live results.
• Markets change over time; past performance is NOT indicative of future performance.
• You are fully responsible for your own trades and risk.
Please DO NOT use this script with money you cannot afford to lose. Always start in a demo / paper trading environment and make sure you understand what the logic does before you risk any capital.
────────────────────────
1. About default settings and risk (very important)
────────────────────────
The script is configured with the following defaults in the `strategy()` declaration:
• `initial_capital = 10000`
→ This is only an EXAMPLE account size.
• `default_qty_type = strategy.percent_of_equity`
• `default_qty_value = 100`
→ This means 100% of equity per trade in the default properties.
→ This is AGGRESSIVE and should be treated as a STRESS TEST of the logic, not as a realistic way to trade.
TradingView’s House Rules recommend risking only a small part of equity per trade (often 1–2%, max 5–10% in most cases). To align with these recommendations and to get more realistic backtest results, I STRONGLY RECOMMEND you to:
1. Open **Strategy Settings → Properties**.
2. Set:
• Order size: **Percent of equity**
• Order size (percent): e.g. **1–2%** per trade
3. Make sure **commission** and **slippage** match your own broker conditions.
• By default this script uses `commission_value = 0.1` (0.1%) and `slippage = 3`, which are reasonable example values for many crypto markets.
If you choose to run the strategy with 100% of equity per trade, please treat it ONLY as a stress-test of the logic. It is NOT a sustainable risk model for live trading.
────────────────────────
2. What this strategy tries to do (conceptual overview)
────────────────────────
This is a LONG-ONLY strategy designed to explore the combination of:
1. **Range Oscillator (Zeiierman-based)**
- Measures how far price has moved away from an adaptive mean.
- Uses an ATR-based range to normalize deviation.
- High positive oscillator values indicate strong price expansion away from the mean in a bullish direction.
2. **Stochastic as a timing filter**
- A classic Stochastic (%K and %D) is used.
- The logic requires %K to be below a user-defined level and then crossing above %D.
- This is intended to catch moments when momentum turns up again, rather than chasing every extreme.
3. **EMA Exit Filter (trend slope)**
- An EMA with configurable length (default 70) is calculated.
- The slope of the EMA is monitored: when the slope turns negative while in a long position, and the filter is enabled, it triggers an exit condition.
- This acts as a trend-protection exit: if the medium-term trend starts to weaken, the strategy exits even if the oscillator has not yet fully reverted.
4. **Optional risk-management layer**
- Percentage-based Stop Loss and Take Profit (SL/TP).
- Risk/Reward (R-multiple) exit based on the distance from entry to SL.
- Implemented as OCO orders that work *on top* of the logical exits.
The goal is not to create a “holy grail” system but to serve as a transparent, configurable framework for studying how these concepts behave together on different markets and timeframes.
────────────────────────
3. Components and how they work together
────────────────────────
(1) Range Oscillator (based on “Range Oscillator (Zeiierman)”)
• The script computes a weighted mean price and then measures how far price deviates from that mean.
• Deviation is normalized by an ATR-based range and expressed as an oscillator.
• When the oscillator is above the **entry threshold** (default 100), it signals a strong move away from the mean in the bullish direction.
• When it later drops below the **exit threshold** (default 30), it can trigger an exit (if enabled).
(2) Stochastic confirmation
• Classic Stochastic (%K and %D) is calculated.
• An entry requires:
- %K to be below a user-defined “Cross Level”, and
- then %K to cross above %D.
• This is a momentum confirmation: the strategy tries to enter when momentum turns up from a pullback rather than at any random point.
(3) EMA Exit Filter
• The EMA length is configurable via `emaLength` (default 70).
• The script monitors the EMA slope: it computes the relative change between the current EMA and the previous EMA.
• If the slope turns negative while the strategy holds a long position and the filter is enabled, it triggers an exit condition.
• This is meant to help protect profits or cut losses when the medium-term trend starts to roll over, even if the oscillator conditions are not (yet) signalling exit.
(4) Risk management (optional)
• Stop Loss (SL) and Take Profit (TP):
- Defined as percentages relative to average entry price.
- Both are disabled by default, but you can enable them in the Inputs.
• Risk/Reward Exit:
- Uses the distance from entry to SL to project a profit target at a configurable R-multiple.
- Also optional and disabled by default.
These exits are implemented as `strategy.exit()` OCO orders and can close trades independently of oscillator/EMA conditions if hit first.
────────────────────────
4. Entry & Exit logic (high level)
────────────────────────
A) Time filter
• You can choose a **Start Year** in the Inputs.
• Only candles between the selected start date and 31 Dec 2069 are used for backtesting (`timeCondition`).
• This prevents accidental use of tiny cherry-picked windows and makes tests more honest.
B) Entry condition (long-only)
A long entry is allowed when ALL the following are true:
1. `timeCondition` is true (inside the backtest window).
2. If `useOscEntry` is true:
- Range Oscillator value must be above `entryLevel`.
3. If `useStochEntry` is true:
- Stochastic condition (`stochCondition`) must be true:
- %K < `crossLevel`, then %K crosses above %D.
If these filters agree, the strategy calls `strategy.entry("Long", strategy.long)`.
C) Exit condition (logical exits)
A position can be closed when:
1. `timeCondition` is true AND a long position is open, AND
2. At least one of the following is true:
- If `useOscExit` is true: Oscillator is below `exitLevel`.
- If `useMagicExit` (EMA Exit Filter) is true: EMA slope is negative (`isDown = true`).
In that case, `strategy.close("Long")` is called.
D) Risk-management exits
While a position is open:
• If SL or TP is enabled:
- `strategy.exit("Long Risk", ...)` places an OCO stop/limit order based on the SL/TP percentages.
• If Risk/Reward exit is enabled:
- `strategy.exit("RR Exit", ...)` places an OCO order using a projected R-multiple (`rrMult`) of the SL distance.
These risk-based exits can trigger before the logical oscillator/EMA exits if price hits those levels.
────────────────────────
5. Recommended backtest configuration (to avoid misleading results)
────────────────────────
To align with TradingView House Rules and avoid misleading backtests:
1. **Initial capital**
- 10 000 (or any value you personally want to work with).
2. **Order size**
- Type: **Percent of equity**
- Size: **1–2%** per trade is a reasonable starting point.
- Avoid risking more than 5–10% per trade if you want results that could be sustainable in practice.
3. **Commission & slippage**
- Commission: around 0.1% if that matches your broker.
- Slippage: a few ticks (e.g. 3) to account for real fills.
4. **Timeframe & markets**
- Volatile symbols (e.g. crypto like BTCUSDT, or major indices).
- Timeframes: 1H / 4H / **1D (Daily)** are typical starting points.
- I strongly recommend trying the strategy on **different timeframes**, for example 1D, to see how the behaviour changes between intraday and higher timeframes.
5. **No “caution warning”**
- Make sure your chosen symbol + timeframe + settings do not trigger TradingView’s caution messages.
- If you see warnings (e.g. “too few trades”), adjust timeframe/symbol or the backtest period.
────────────────────────
5a. About low trade count and rare signals
────────────────────────
This strategy is intentionally designed to trade RARELY:
• It is **long-only**.
• It uses strict filters (Range Oscillator threshold + Stochastic confirmation + optional EMA Exit Filter).
• On higher timeframes (especially **1D / Daily**) this can result in a **low total number of trades**, sometimes WELL BELOW 100 trades over the whole backtest.
TradingView’s House Rules mention 100+ trades as a guideline for more robust statistics. In this specific case:
• The **low trade count is a conscious design choice**, not an attempt to cherry-pick a tiny, ultra-profitable window.
• The goal is to study a **small number of high-conviction long entries** on higher timeframes, not to generate frequent intraday signals.
• Because of the low trade count, results should NOT be interpreted as statistically strong or “proven” – they are only one sample of how this logic would have behaved on past data.
Please keep this in mind when you look at the equity curve and performance metrics. A beautiful curve with only a handful of trades is still just a small sample.
────────────────────────
6. How to use this strategy (step-by-step)
────────────────────────
1. Add the script to your chart.
2. Open the **Inputs** tab:
- Set the backtest start year.
- Decide whether to use Oscillator-based entry/exit, Stochastic confirmation, and EMA Exit Filter.
- Optionally enable SL, TP, and Risk/Reward exits.
3. Open the **Properties** tab:
- Set a realistic account size if you want.
- Set order size to a realistic % of equity (e.g. 1–2%).
- Confirm that commission and slippage are realistic for your broker.
4. Run the backtest:
- Look at Net Profit, Max Drawdown, number of trades, and equity curve.
- Remember that a low trade count means the statistics are not very strong.
5. Experiment:
- Tweak thresholds (`entryLevel`, `exitLevel`), Stochastic settings, EMA length, and risk params.
- See how the metrics and trade frequency change.
6. Forward-test:
- Before using any idea in live trading, forward-test on a demo account and observe behaviour in real time.
────────────────────────
7. Originality and usefulness (why this is more than a mashup)
────────────────────────
This script is not intended to be a random visual mashup of indicators. It is designed as a coherent, testable strategy with clear roles for each component:
• Range Oscillator:
- Handles mean vs. range-expansion states via an adaptive, ATR-normalized metric.
• Stochastic:
- Acts as a timing filter to avoid entering purely on extremes and instead waits for momentum to turn.
• EMA Exit Filter:
- Trend-slope-based safety net to exit when the medium-term direction changes against the position.
• Risk module:
- Provides practical, rule-based exits: SL, TP, and R-multiple exit, which are useful for structuring risk even if you modify the core logic.
It aims to give traders a ready-made **framework to study and modify**, not a black box or “signals” product.
────────────────────────
8. Limitations and good practices
────────────────────────
• No single strategy works on all markets or in all regimes.
• This script is long-only; it does not short the market.
• Performance can degrade when market structure changes.
• Overfitting (curve fitting) is a real risk if you endlessly tweak parameters to maximise historical profit.
Good practices:
- Test on multiple symbols and timeframes.
- Focus on stability and drawdown, not only on how high the profit line goes.
- View this as a learning tool and a basis for your own research.
────────────────────────
9. Licensing and credits
────────────────────────
• Core oscillator idea & base code:
- “Range Oscillator (Zeiierman)”
- © Zeiierman, licensed under CC BY-NC-SA 4.0.
• Strategy logic, Stochastic confirmation, EMA Exit Filter, and risk-management layer:
- Modifications by jokiniemi.
Please respect both the original license and TradingView House Rules if you fork or republish any part of this script.
────────────────────────
10. No payments / no vendor pitch
────────────────────────
• This script is completely FREE to use on TradingView.
• There is no paid subscription, no external payment link, and no private signals group attached to it.
• If you have questions, please use TradingView’s comment system or private messages instead of expecting financial advice.
Use this script as a tool to learn, experiment, and build your own understanding of markets.
────────────────────────
11. Example backtest settings used in screenshots
────────────────────────
To avoid any confusion about how the results shown in screenshots were produced, here is one concrete example configuration:
• Symbol: BTCUSDT (or similar major BTC pair)
• Timeframe: 1D (Daily)
• Backtest period: from 2018 to the most recent data
• Initial capital: 10 000
• Order size type: Percent of equity
• Order size: 2% per trade
• Commission: 0.1%
• Slippage: 3 ticks
• Risk settings: Stop Loss and Take Profit disabled by default, Risk/Reward exit disabled by default
• Filters: Range Oscillator entry/exit enabled, Stochastic confirmation enabled, EMA Exit Filter enabled
If you change any of these settings (symbol, timeframe, risk per trade, commission, slippage, filters, etc.), your results will look different. Please always adapt the configuration to your own risk tolerance, market, and trading style.
grinpapedro
pedro02599
En línea
Canal de texto
No Somos Liquidez:【📖】biblioteca
Buscar No Somos Liquidez
Hilos
Hermit.exe
Hermit.exe
hace >30 días
Notion Trade Tracker
Herramientas
0
Hermit.exe
Hermit.exe
hace >30 días
Notion Journal
Herramientas
0
9
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador Judas Swing
SMC
Herramientas
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador TV Samurái V1
SMC
Herramientas
0
2
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Hábitos Atómicos
Psicologia
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
El trading como negocio
Psicologia
0
Hilo
Hilo:Indicador TV Samurái V1
Chat de Indicador TV Samurái V1
Indicador TV Samurái V1
SMC
22 de septiembre de 2024
Hermit.exe
NSL
Senior Mod
AO
Autor(a) original — 22/09/2024 16:06domingo, 22 de septiembre de 2024 16:06
@VIP
Primero agradecer al compañero @Romulo por su generosidad y compartir el indicador para la comunidad, todos los créditos de creación para el
El indicador tal como su nombre indica sirve para marcar el horario de operativa y elementos de la estrategia Samurái V1. Este indicador no esta publico en TV por lo que tendrán que añadirlo de manera manual a través de un script a TradingView, cabe recalcar que no es nada complicado, para hacerlo aquí les dejamos un pequeño tutorial:
www.youtube.com
Indicaciones para agregarlo de manera manual:
Entramos a TV y buscamos "editor de Pine" en la parte inferior izquierda de la pantalla.,
Le damos click y aparecerá un nuevo menú,
Posteriormente eliminamos todo lo que este dentro del menú,
Ahora copiamos todo el texto del archivo del indicador y lo pegamos en el menú de TV,
Finalmente le damos a "añadir al grafico" que se encuentra en la parte derecha de la misma barra donde estaba "editor de pine".,
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST)\n - DST Start : Second Sunday in March at 2:00\n - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
... (413 líneas restantes)
Contraer
Contraer (513 líneas)
Ver todo el archivo
SAMURAI v1.txt
SAMURAI v1.txt (23 KB)
23 KB
SAMURAI v1.txt (23 KB)
Descargar SAMURAI v1.txt (23 KB)Cambiar de idioma
Reenviar
Más
2
Seguir
Añade esta publicación a tu lista de canales y recibe notificaciones sobre ella.
Copiar enlace
No tienes permiso para enviar mensajes en este canal.
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST)\n - DST Start : Second Sunday in March at 2:00\n - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
// @function get the current bar's unix time, hour and minute
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _utcTimeOffset (array) array storing the utc info
// @param _utcCity (array) array storing the major city info
// @param _inAd (int) ofsset value in minutes
// @param _tf_m (int) timeframe multiplier
// @returns A tuple containing (int) index, (int) hour and (int) minute
method f_getBarTime(string _utc, _dst, _utcTimeOffset, _utcCity, _inAd, _tf_m) =>
utcTime = (array.get(_utcTimeOffset, array.indexof(_utcCity, _utc)) + (_dst ? 1 : 0)) * 3600000 + _inAd * 60000 + time
h = math.floor(utcTime / 3600000) % 24
m = math.floor(utcTime / 60000) % 60
int idx = 0
if _tf_m == 3
if m == 48
m := m + 2
idx := 2
else if m == 9
m := m + 1
idx := 1
//else if m == 12 or m == 42
// idx := 0
else if _tf_m == 5
if (m == 0 and h == 9) or (m == 30 and h == 7)
m := m + 3
idx := 3
// @function calculate and get customized pivot points high low and time values
// @param _len (int) length for the pivot points high low calculation
// @param _loc (string) if set to 'wick' highest/lowest values of the detected pivot points high low will be calculated
// if set to 'Body' the highest/lowest values of the candel bodies will be returend as pivot points high low
// @returns A tuple containing (float) ph - pivot high, (float) pl - pivot low, (int) pht - pivot high unix time (int) plt - pivot low unix time
method f_getPivotPoint(int _len, _loc) =>
ph = ta.pivothigh(_len, _len)
if ph and _loc == 'Body'
ph := math.max(open , close )
pl = ta.pivotlow (_len, _len)
if pl and _loc == 'Body'
pl := math.min(open , close )
pht = ph ? time : na
plt = pl ? time : na
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
tf_m = timeframe.multiplier
bi = bar_index
var a_majorCity = array.new_string(), var a_utcTimeOffset = array.new_float(), var a_utcCity = array.new_string()
if barstate.isfirst
array.push(a_majorCity, 'NEW YORK'), array.push(a_utcTimeOffset, -5), array.push(a_utcCity, '(UTC-05:00) NEW YORK')
array.push(a_majorCity, 'LONDON' ), array.push(a_utcTimeOffset, 0 ), array.push(a_utcCity, '(UTC+00:00) LONDON' )
// Lower TF bar UDT array
ltfB = request.security_lower_tf(syminfo.tickerid, '1', bar.new())
// Lower TF pivotPoint UDT arrays
var pivotPoint p = pivotPoint.new()
= request.security_lower_tf(syminfo.tickerid, '1', f_getPivotPoint(pLen, pLoc))
if not na(array.min(a_pL))
p.l := array.min(a_pL)
p.lt := array.min(a_pLt)
if not na(array.max(a_pH))
p.h := array.max(a_pH)
p.ht := array.max(a_pHt)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//units and multipliers for versatility across asset classes
pUnits = syminfo.type== 'index' or syminfo.type == 'futures'? ' $':
syminfo.type=='forex'?' pips':na
mult= str.tonumber(timeframe.period)<=5? 1: str.tonumber(timeframe.period)<=240? 60: timeframe.isdwm? 1440:na
pMult = syminfo.type== 'index' or syminfo.type == 'futures'? 1:
syminfo.type=='forex'? 100:1
tUnits = mult==1? ' mins': mult==60? ' hours':mult==1440? ' days':na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------}
//Detect ICT macros
//-----------------------------------------------------------------------------{
var macro mc = macro.new()
// @function main function : detects macros, draws nad controls macro components and classifies macros
// @param _m (bool) enable/disable specific macro
// @param _msh (int) macro start hour
// @param _msm (int) macro start minute
// @param _mh (bool) macro top line control option
// @param _ml (bool) macro bottom line control option
// @param _mm (bool) macro middle line control option
// @param _me (bool) macro extended lines control option
// @param _mt (bool) macro label text value
//
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _tf_m (int) timeframe multiplier
// @param _alert (bool) next macro time start location, displays in _alertM minutes
// @param _alertM (int) alert in _alertM minutes
// @returns macro UDT components created
processMacro(_m, _msh, _msm, _mh, _ml, _mm, _me, _mt, _utc, _dst, _tf_m, _alert, _alertM) =>
if _m
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, _alertM, _tf_m)
if ha == _msh and ma == _msm
alert(_mt + ' macro will be in play in ' + str.tostring(_alertM) + ' minutes for instrument ' + syminfo.ticker)
if _alert
mc.lnf := line.new(time + _alertM * 60000 , high, time + _alertM * 60000, low, xloc.bar_time, extend.both, mc.color, line.style_solid , 1)
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, 0, _tf_m)
if h == 08 or h == 07 or h == 1 or h == 3 or h == 5
if m == 0
mc.len := 10
else
mc.len := 180
if h == 11
if m == 0
mc.len := 10
else
mc.len := 300
if h == _msh and m == _msm
mc.lnf.delete()
if ltfB.size() > idx
if not na(ltfB.get(idx).h)
mc.t := ltfB.get(idx).t
mc.o := ltfB.get(idx).o
mc.top := ltfB.get(idx).h
mc.bottom := ltfB.get(idx).l
if idx == 0
mc.x2 := bi + math.round(mc.len / _tf_m)
else
mc.x2 := bi + math.round(mc.len / _tf_m) + 1
mc.lnh := line.new(bi, mc.top, int(mc.x2), mc.top, color = _mh ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnhe := line.new(int(mc.x2), mc.top, int(mc.x2), mc.top, color = _me ? _mh ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnl := line.new(bi, mc.bottom, int(mc.x2), mc.bottom, color =_ml ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnle := line.new(int(mc.x2), mc.bottom, int(mc.x2), mc.bottom, color = _me ? _ml ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnm := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _mm ? mc.color : mc.nocolor, style = line.style_dotted, width = 1)
mc.lnme := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _me ? _mm ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 1)
mc.lf := linefill.new(mc.lnh, mc.lnl, color.new(color.gray, 100))
mc.lb := label.new(bi + int(mc.len / _tf_m / 2), mc.top, mcText != 'None' ? 'SAMURAI\n' + _mt : '', xloc.bar_index, yloc.price, #00000000, label.style_label_down, chart.fg_color, mcSize, text.align_left, '')
p.l1 := p.l
p.h1 := p.h
else if bi < int(mc.x2) and time >= mc.t
mc.top := math.max(high, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(low , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(high, mc.lnh.get_y1()), math.min(low , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(high, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if bi == int(mc.x2)
if ltfB.size() > idx
if not na(ltfB.get(idx).c)
mc.co := ltfB.get(idx).o
mc.ch := ltfB.get(idx).h
mc.cl := ltfB.get(idx).l
mc.cc := ltfB.get(idx).c
mc.top := math.max(mc.ch, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(mc.cl , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(mc.top, mc.lnh.get_y1()), math.min(mc.bottom , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(mc.top, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if mc.t == mc.t
mc.lnhe.set_x2(bi), mc.lnle.set_x2(bi), mc.lnme.set_x2(bi)
if bi == int(mc.x2) + 1 and not str.contains(mc.lb.get_text(), 'on NSL')
mc.lb.set_tooltip('mc open : '+ str.tostring(mc.o , format.mintick) +
'\nmc close : ' + str.tostring(mc.cc , format.mintick) +
'\nmc top : ' + str.tostring(mc.top , format.mintick) +
'\nmc mid : ' + str.tostring(mc.mid , format.mintick) +
'\nmc bottom : ' + str.tostring(mc.bottom, format.mintick) )
if mc.bottom < p.l1 and mc.top > p.h1
if (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(mColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else if mc.bottom < p.l1 or mc.top > p.h1
if (mc.co > mc.mid and mc.cc < mc.mid) or (mc.co < mc.mid and mc.cc > mc.mid) or (mc.o < mc.mid and mc.cc < mc.mid) or (mc.o > mc.mid and mc.cc > mc.mid) // pL > pmcPL or pmcPH < pH
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
if p.l == p.l1 and p.h == p.h1 and (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
//-----------------------------------------------------------------------------}
//Process macros
//-----------------------------------------------------------------------------{
if tf_m <= 15
processMacro(m07000710, 11, 00, m07_top, m07_bot, m07_mid, m07_ext, '07:00 AM - 07:10', '(UTC+00:00) LONDON' , lnSummerTime, tf_m, mcAlert, mcAlertM)
processMacro(m08000810, 08, 00, m08_top, m08_bot, m08_mid, m08_ext, '08:00 AM - 08:10', '(UTC-05:00) NEW YORK', nySummerTime, tf_m, mcAlert, mcAlertM)
else
var table note = table.new(position.bottom_right, 1, 1)
if barstate.islast
table.cell(note, 0, 0, 'ICT Macros are supported on:\n 1 min, 3, 5 mins and 15 mins charts\n\n', text_size=size.small, text_color=chart.fg_color)
//-----------------------------------------------------------------------------}
//OPEN RANGO DE ESTRATEGIA
// INPUTS
i_time = input.session ('0800-0801:1234567', "OPEN SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz = input ("GMT-4", "Timezone")
i_vline = input.bool (true, "VLine", inline="in1")
i_vcol = input.color (#006eff, "", inline="in1")
i_txtcol = input.color (#006eff, " Text color", inline="in1")
i_vstyle = input.string ("Solid", "Style", options= )
i_hline = label.style_none
i_linecol = label.style_none
i_linestyle = label.style_none
i_ex = label.style_none
i_ex2 = label.style_none
i_ex3 = label.style_none
// MISC
nymidz = time ("1", i_time, i_tz)
linestyle = i_linestyle == "Solid" ? line.style_solid : i_linestyle == "Dotted" ? line.style_dotted : line.style_dashed
vstyle = i_vstyle == "Solid" ? line.style_solid : i_vstyle == "Dotted" ? line.style_dotted : line.style_dashed
ex = i_ex == "1 Day" ? extend.none : i_ex == "2 Days" ? extend.none : i_ex == "Right" ? extend.right : extend.both
htime = i_ex == "2 Days" ? 172800000 : 86400000
hourtime = label.style_none
// CALC
var openprice = 0.0
if nymidz
if not nymidz
openprice := open
else
openprice := math.max(open, openprice)
// OBJECTS
var label lb = na
if openprice != openprice
var line lne = na
line.set_x2(lne, nymidz)
line.set_extend(lne, extend.none)
if i_vline and nymidz == nymidz
vl1 = line.new(nymidz, high, nymidz, low, xloc.bar_time, extend.both, i_vcol, vstyle, 1)
if line.get_y1(vl1) == line.get_y2(vl1)
line.delete(vl1)
///////////////////////////////////////////////////////////////////////////////////
//CLOSE RANGO DE ESTRATEGIA
// INPUTS
i_time0 = input.session ('0810-0811:1234567', "CLOSE SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz0 = i_tz
i_vline0 = i_vline
i_vcol0 = i_vcol
i_txtcol0 = i_txtcol
i_vstyle0 = i_vstyle
i_hline0 = label.style_none
i_linecol0 = label.style_none
i_linestyle0 = label.style_none
i_ex0 = label.style_none
i_ex20 = label.style_none
i_ex30 = label.style_none
// MISC
nymid0 = time ("1", i_time0, i_tz0)
linestyle0 = i_linestyle0 == "Solid" ? line.style_solid : i_linestyle0 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle0 = i_vstyle0 == "Solid" ? line.style_solid : i_vstyle0 == "Dotted" ? line.style_dotted : line.style_dashed
ex0 = i_ex0 == "1 Day" ? extend.none : i_ex0 == "2 Days" ? extend.none : i_ex0 == "Right" ? extend.right : extend.both
htime0 = i_ex0 == "2 Days" ? 172800000 : 86400000
hourtime0 = label.style_none
// CALC
var openprice0 = 0.0
if nymid0
if not nymid0
openprice0 := open
else
openprice0 := math.max(open, openprice0)
// OBJECTS
var label lb0 = na
if openprice0 != openprice0
var line lne0 = na
line.set_x2(lne0, nymid0)
line.set_extend(lne0, extend.none)
if i_vline0 and nymid0 == nymid0
vl10 = line.new(nymid0, high, nymid0, low, xloc.bar_time, extend.both, i_vcol0, vstyle0, 1)
if line.get_y1(vl10) == line.get_y2(vl10)
line.delete(vl10)
///////////////////////////////////////////////////////////////////////////////////////////////
//CLOSE MAX 8:45
// INPUTS
i_time1 = input.session ('0845-0846:1234567', "END", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz1 = i_tz
i_vline1 = i_vline
i_vcol1 = i_vcol
i_txtcol1 = i_txtcol
i_vstyle1 = i_vstyle
i_hline1 = label.style_none
i_linecol1 = label.style_none
i_linestyle1 = label.style_none
i_ex1 = label.style_none
i_ex21 = label.style_none
i_ex31 = label.style_none
// MISC
nymid1 = time ("1", i_time1, i_tz1)
linestyle1 = i_linestyle1 == "Solid" ? line.style_solid : i_linestyle1 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle1 = i_vstyle1 == "Solid" ? line.style_solid : i_vstyle1 == "Dotted" ? line.style_dotted : line.style_dashed
ex1 = i_ex1 == "1 Day" ? extend.none : i_ex1 == "2 Days" ? extend.none : i_ex1 == "Right" ? extend.right : extend.both
htime1 = i_ex1 == "2 Days" ? 172800000 : 86400000
hourtime1 = label.style_none
// CALC
var openprice1 = 0.0
if nymid1
if not nymid1
openprice1 := open
else
openprice1 := math.max(open, openprice1)
// OBJECTS
var label lb1 = na
if openprice1 != openprice1
var line lne1 = na
line.set_x2(lne1, nymid1)
line.set_extend(lne1, extend.none)
if i_vline1 and nymid1 == nymid1
vl11 = line.new(nymid1, high, nymid1, low, xloc.bar_time, extend.both, i_vcol1, vstyle1, 1)
if line.get_y1(vl11) == line.get_y2(vl11)
line.delete(vl11)
// EN
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.






















