Portfolio Backtester Engine█ OVERVIEW
Portfolio Backtester Engine (PBTE). This tool will allow you to backtest strategies across multiple securities at once. Allowing you to easier understand if your strategy is robust. If you are familiar with the PineCoders backtesting engine , then you will find this indicator pleasant to work with as it is an adaptation based on that work. Much of the functionality has been kept the same, or enhanced, with some minor adjustments I made on the account of creating a more subjectively intuitive tool.
█ HISTORY
The original purpose of the backtesting engine (`BTE`) was to bridge the gap between strategies and studies . Previously, strategies did not contain the ability to send alerts, but were necessary for backtesting. Studies on the other hand were necessary for sending alerts, but could not provide backtesting results . Often, traders would have to manage two separate Pine scripts to take advantage of each feature, this was less than ideal.
The `BTE` published by PineCoders offered a solution to this issue by generating backtesting results under the context of a study(). This allowed traders to backtest their strategy and simultaneously generate alerts for automated trading, thus eliminating the need for a separate strategy() script (though, even converting the engine to a strategy was made simple by the PineCoders!).
Fast forward a couple years and PineScript evolved beyond these issues and alerts were introduced into strategies. The BTE was not quite as necessary anymore, but is still extremely useful as it contains extra features and data not found under the strategy() context. Below is an excerpt of features contained by the BTE:
"""
More than `40` built-in strategies,
Customizable components,
Coupling with your own external indicator,
Simple conversion from Study to Strategy modes,
Post-Exit analysis to search for alternate trade outcomes,
Use of the Data Window to show detailed bar by bar trade information and global statistics, including some not provided by TV backtesting,
Plotting of reminders and generation of alerts on in-trade events.
"""
Before I go any further, I want to be clear that the BTE is STILL a good tool and it is STILL very useful. The Portfolio Backtesting Engine I am introducing is only a tangental advancement and not to be confused as a replacement, this tool would not have been possible without the `BTE`.
█ THE PROBLEM
Most strategies built in Pine are limited by one thing. Data. Backtesting should be a rigorous process and researchers should examine the performance of their strategy across all market regimes; that includes, bullish and bearish markets, ranging markets, low volatility and high volatility. Depending on your TV subscription The Pine Engine is limited to 5k-20k historical bars available for backtesting, which can often leave the strategy results wanting. As a general rule of thumb, strategies should be tested across a quantity of historical bars which will allow for at least 100 trades. In many cases, the lack of historical bars available for backtesting and frequency of the strategy signals produces less than 100 trades, rendering your strategy results inconclusive.
█ THE SOLUTION
In order to be confident that we have a robust strategy we must test it across all market regimes and we must have over 100 trades. To do this effectively, researchers can use the Portfolio Backtesting Engine (PBTE).
By testing a strategy across a carefully selected portfolio of securities, researchers can now gather 5k-20k historical bars per security! Currently, the PTBE allows up to 5 securities, which amounts to 25k-100k historical bars.
█ HOW TO USE
1 — Add the indicator to your chart.
• Confirm inputs. These will be the most important initial values which you can change later by clicking the gear icon ⚙ and opening up the settings of the indicator.
2 — Select a portfolio.
• You will want to spend some time carefully selecting a portfolio of securities.
• Each security should be uncorrelated.
• The entire portfolio should contain a mix of different market regimes.
You should understand that strategies generally take advantage of one particular type of market regime. (trending, ranging, low/high volatility)
For example, the default RSI strategy is typically advantageous during ranging markets, whereas a typical moving average crossover strategy is advantageous in trending markets.
If you were to use the standard RSI strategy during a trending market, you might be selling when you should be buying.
Similarily, if you use an SMA crossover during a ranging market, you will find that the MA's may produce many false signals.
Even if you build a strategy that is designed to be used only in a trending market, it is still best to select a portfolio of all market regimes
as you will be able to test how your strategy will perform when the market does something unexpected.
3 — Test a built-in strategy or add your own.
• Navigate to gear icon ⚙ (settings) of strategy.
• Choose your options.
• Select a Main Entry Strat and Alternate Entry Strat .
• If you want to add your own strategy, you will need to modify the source code and follow the built-in example.
• You will only need to generate (buy 1 / sell -1/ neutral 0) signals.
• Select a Filter , by default these are all off.
• Select an Entry Stop - This will be your stop loss placed at the trade entry.
• Select Pyamiding - This will allow you to stack positions. By default this is off.
• Select Hard Exits - You can also think of these as Take Profits.
• Let the strategy run and take note of the display tables results.
• Portfolio - Shows each security.
• The strategy runs on each asset in your portfolio.
• The initial capital is equally distributed across each security.
So if you have 5 securities and a starting capital of 100,000$ then each security will run the strategy starting with 20,000$
The total row will aggregate the results on a bar by bar basis showing the total results of your initial capital.
• Net Profit (NP) - Shows profitability.
• Number of Trades (#T) - Shows # of trades taken during backtesting period.
• Typically will want to see this number greater than 100 on the "Total" row.
• Average Trade Length (ATL) - Shows average # of days in a trade.
• Maximum Drawdown (MD ) - Max peak-to-valley equity drawdown during backtesting period.
• This number defines the minimum amount of capital required to trade the system.
• Typically, this shouldn’t be lower than 34% and we will want to allow for at least 50% beyond this number.
• Maximum Loss (ML) - Shows largest loss experienced on a per-trade basis.
• Normally, don’t want to exceed more than 1-2 % of equity.
• Maximum Drawdown Duration (MDD) - The longest duration of a drawdown in equity prior to a new equity peak.
• This number is important to help us psychologically understand how long we can expect to wait for a new peak in account equity.
• Maximum Consecutive Losses (MCL) - The max consecutive losses endured throughout the backtesting period.
• Another important metric for trader psychology, this will help you understand how many losses you should be prepared to handle.
• Profit to Maximum Drawdown (P:MD) - A ratio for the average profit to the maximum drawdown.
• The higher the ratio is, the better. Large profits and small losses contribute to a good PMD.
• This metric allows us to examine the profit with respect to risk.
• Profit Loss Ratio (P:L) - Average profit over the average loss.
• Typically this number should be higher in trend following systems.
• Mean reversion systems show lower values, but compensate with a better win %.
• Percent Winners (% W) - The percentage of winning trades.
• Trend systems will usually have lower win percentages, since statistically the market is only trending roughly 30% of the time.
• Mean reversion systems typically should have a high % W.
• Time Percentage (Time %) - The amount of time that the system has an open position.
• The more time you are in the market, the more you are exposed to market risk, not to mention you could be using that money for something else right?
• Return on Investment (ROI) - Your Net Profit over your initial investment, represented as a percentage.
• You want this number to be positive and high.
• Open Profit (OP) - If the strategy has any open positions, the floating value will be represented here.
• Trading Days (TD) - An important metric showing how many days the strategy was active.
• This is good to know and will be valuable in understanding how long you will need to run this strategy in order to achieve results.
█ FEATURES
These are additional features that extend the original `BTE` features.
- Portfolio backtesting.
- Color coded performance results.
- Circuit Breakers that will stop trading.
- Position reversals on exit. (Simulating the function of always in the market. Similar to strategy.entry functionality)
- Whipsaw Filter
- Moving Average Filter
- Minimum Change Filter
- % Gain Equity Exit
- Popular strategies, (MACD, MA cross, supertrend)
Below are features that were excluded from the original `BTE`
- 2 stage in-trade stops with kick-in rules (This was a subjective decision to remove. I found it to be complex and thwarted my use of the `BTE` for some time.)
- Simple conversion from Study to Strategy modes. (Not possible with multiple securities)
- Coupling with your own external indicator (Not really practical to use with multiple securities, but could be used if signals were generated based on some indicator which was not based on the current chart)
- Use of the Data Window to show detailed bar by bar trade information and global statistics.
- Post Exit Analysis.
- Plotting of reminders and generation of alerts on in-trade events.
- Alerts (These may be added in the future by request when I find the time.)
█ THANKS
The whole PineCoders team for all their shared knowledge and original publication of the BTE and Richard Weismann for his ideas on building robust strategies.
═════════════════════════════════════════════════════════════════════════
Pesquisar nos scripts por "entry"
RSI+PA+DCA StrategyDear Tradingview community,
This RSI based trading strategy is created as a training exercise. I am not a professional trader, but a committed hobbyist. This not a finished trading strategy meant for trading, but more a combination of different trading ideas I liked to explore deeper. The aim with this exercise was to gain more knowledge and understanding about price averaging and dollar cost averaging strategies. Aside that I wanted to learn how to program a pyramiding strategy, how to plot different order entry layers and how to open positions on a specific time interval.
In this script I adapted code from a couple of strategy examples by Coinrule . Who wrote simple and powerful examples of RSI based strategies and pyramiding strategies.
Also the HOWTO scripts shared by vitvlkv were very helpful for this exercise. In the script description you can find all the sources to the code.
A PA strategy could be a helpful addition to ease the 'stress-management to buy when price drops and resolution in selling when the price is rising' (Coinrule).
The idea behind the strategy is fairly simple and is based on an RSI strategy of buying low. A position is entered when the RSI and moving average conditions are met. The position is closed when it reaches a specified take profit percentage. As soon as the first the position is openend multiple PA (price average) layers are setup based on a specified percentage of price drop. When the price crosses the layer another position with somewhat the same amount of assets is entered. This causes the average cost price (the red plot line) to decrease. If the price drops more, another similar amount of assets is bought with another price average decrease as result. When the price starts rising again the different positions are separately closed when each reaches its specified take profit. The positions can be re-openend when the price drops again. And so on. When the price rises more and crosses over the average price and reached the specified take profit on top of it, it closes all the positions at once and cancels all orders. From that moment on it waits for another price dip before it opens a new position.
Another option is to activate a DCA function that opens a position based on a fixed specified amount. It enters a position at the start of every week and only when there are already other positions openend and if the current price is below the average price of the position. Like this buying on a time interval can help lowering the average price in case the market is down.
I read in some articles that price averaging is also called dollar cost averaging as the result is somewhat the same. Although DCA is really based on buying on fixed time intervals. These strategies are both considered long term investment strategies that can be profitable in the long run and are not suitable for short term investment schemes. The downturn is that the postion size increases when the general market trend is going down and that you have to patiently wait until the market start rising again.
Another notable aspect is that the logic in this strategy works the way it does because the entries are exited based on the FIFO (first in first out) close entry rule. This means that the first exit is applied to the first entry position that is openend. In other words that when the third entry reaches its take profit level and exits, it actually exits the first entry. If you take a close look in the 'List of Trades' of your Strategy Tester panel, you can see that some 'Long1' entries are closed by an 'Exit 3' and not by an 'Exit 1'. This means that your trade partly loses, but causes a decrease in average price that is later balanced out by lower or repeated entering and closing other positions. You can change this logic to a real sequential way of closing your entries, but this changes the averaging logic considerably. In case you want to test this you need to change, in this line in the strategy call 'close_entries_rule = "FIFO"', the word FIFO to ANY.
In the settings you can specify the percentage of portfolio to use for each trade to spread the risk and for each order a trading fee of 0.075% is calculated.
Estratégia Pine Script®
2Tier Ichimoku Pyramiding [Takazudo]Ichimoku based pyramiding strategy example that was tested on 4h TF.
makes the first entry when 2Tier Kumo breakout was occurred.
makes the extra entries when higher-low (on long) or lower-high (on short) was occurred.
uses short term MACD reversal + stop entry as a confirmation of the trend.
slack trailing stop loss.
changes entry quantity by the percentage of SL.
prevents the ranged entry.
This is just an example of how to trade using Ichimoku signals.
Estratégia Pine Script®
RSI Moving Average with Signal LineDefault values:
RSI = white
RSI Prime ( RSI of RSI ) = yellow
EMA 34 = blue
EMA 55 = red
They are listed in order of reactiveness to price changes. Think of them like the Williams Alligator...
White and yellow work the fastest, with WHITE being signal and YELLOW being trigger. Great for LTF
Blue and red work the slowest, with BLUE being frequently testing RED as support/resistance. Great for HTF
Long Entry:
RSIs both > SMAS (signal)
RSI > RSI Prime (confirmation)
Long Exit:
RSI < RSI Prime (signal)
RSIs both < SMAs (confirmation)
Short Entry:
RSIs both < SMAS (signal)
RSI < RSI Prime (confirmation)
Short Exit:
RSI > RSI Prime (signal)
RSIs both > SMAS (confirmation)
Indicador Pine Script®
Triple EMA Scalper low lag stratHi all,
This strategy is based on the Amazing scalper for majors with risk management by SoftKill21
The change is in lines 11-20 where the sma's are replaced with Triple ema's to
lower the lag.
The original author is SoftKill21. His explanation is repeated below:
Best suited for 1M time frame and majors currency pairs.
Note that I tried it at 3M time frame.
Its made of :
Ema ( exponential moving average ) , long period 25
Ema ( exponential moving average ) Predictive, long period 50,
Ema ( exponential moving average ) Predictive, long period 100
Risk management , risking % of equity per trade using stop loss and take profits levels.
Long Entry:
When the Ema 25 cross up through the 50 Ema and 100 EMA . and we are in london or new york session( very important the session, imagine if we have only american or european currencies, its best to test it)
Short Entry:
When the Ema 25 cross down through the 50 Ema and 100 EMA , and we are in london or new york session( very important the session, imagine if we have only american or european currencies, its best to test it)
Exit:
TargetPrice: 5-10 pips
Stop loss: 9-12 pips
Estratégia Pine Script®
Ichimoku Cloud LONG and SHORT indicatorsThis simple script uses 4 rules from Ichimoku Cloud indicator to marks position entry points.
The idea is that by entering a long position just when these 4 criteria are met, you can capture a 2-3% plus move within the next few days:
1. The conversion line is above the base line
2. The price is above the clouds
3. The lagging span is above the clouds
4. The rightmost cloud is green
The same 4 criteria but inverted will indicate a short entry.
In order to avoid 'stale' entries which can lead to chasing, we want the price and conversion line crossovers to be recent, within the past few days. Ideally we want to enter before close on the day the entry signal is given so that we can capture any potential gap up (or down if short). Often the price will make a nice move the next day or day after. If any of the criteria become invalidated, or if after 4-5 days there hasn't been significant movement, then it was a false alarm.
This script will show the basic Ichimoku Cloud indicators, plus labels for bearish and bullish price and conversion line crossovers as well as LONG and SHOT indicators to show when the entry criteria have been met.
Indicador Pine Script®
Amazing scalper for majors with risk managementHello,
Today I am glad to bring you an amazing simple and efficient scalper strategy.
Best suited for 1M time frame and majors currency pairs.
Its made of :
Ema (exponential moving average) , long period 25
Ema(exponential moving average) Predictive, long period 50,
Ema(exponential moving average) Predictive, long period 100
Risk management , risking % of equity per trade using stop loss and take profits levels.
Long Entry:
When the Ema 25 cross up through the 50 Ema and 100 EMA. and we are in london or new york session( very important the session, imagine if we have only american or european currencies, its best to test it)
Short Entry:
When the Ema 25 cross down through the 50 Ema and 100 EMA, and we are in london or new york session( very important the session, imagine if we have only american or european currencies, its best to test it)
Exit:
TargetPrice: 5-10 pips
Stop loss: 9-12 pips
Hope you enjoy it :)
Estratégia Pine Script®
Percent Calculator OverlayFirst and foremost: I'm inspired to publish my scripts by the other member's who publish quality, detailed scripts -a token of my appreciation and support, Thank You.
The percent calculator overlay is an extension of my Percent Calculator indicator that allows one to visualize the percent metrics they're interested in trading: it''s function is to simply output the target price from either the close or ones trade-entry based on a desired percent return on investment (R.O.I.) then plots it on top of the chart as an area plot and notes anytime in the past the desired conditions were met with a {flag "Success"}.
Say you want to profit 15% from your entry: open the settings and plug in your entry value and the number 15 into the appropriate settings and the indicator displays what the target price should be (rounded to two decimal places) right on the chart with the area as well as the horizontal line which is enabled by the "track price" setting.
The percent calculator overlay also goes one step further by finding the average percent return on investment over a desired interval of time (the default is 20 candles) as well as allows one to adjust the size of the price move the average percent return on investment is being calculated for which is displayed on the chart as circles and also displays a horizontal line for the most current value with the enabled "track price" setting.
NOTE: unlike the Percent Calculator the Percent Calculator Overlay creates a visual record of the number of success' the programmed parameters have achieved (based on the closing prices) which self adjusts when the "size of the move" is changed.
Say you want to find the average percent return on investment for a 3 candle swing over a 200 candle interval of time: open the settings and plug the number 200 into the interval setting and the number 3 into the price-move setting and the indicator displays what the average 3 candle swing returns on investment and plots what the target price would be to achieve the average return given the current close (or entry price) with the gray circles and the horizontal line enabled with the "track price" setting.
Practical Application: comparing ones desired return on investment to the average return on investment can help determine how realistic ones goals are... it's unlikely to achieve 100% return on investment if the average is only around 10% (given the parameters one is working within) but on the other hand achieving 5% return on investment is highly likely. By visualizing roughly how often the given parameters have achieved success on the chart one can become a lot more comfortable, confident, and accurate with their goals.
Forward Looking Statement: I believe in the not too distant future plug and play automated trading systems will be made available to the general public. Over the past 4 years we have seen brokers offer free charting software, commission free trading, and now fractional shares; I don't think it will be much longer before we can simply click a few buttons and tell the computer to enter when the stochastic is overbought/sold and exit with a predefined percent gain (and to repeat that process indefinitely). -Imagine the data moving 2-3-4 times a second, the liquidity flowing like Niagara falls, and 95% of the working population not only starting to invest but gains the extra cash flow they desperately need.
Beta testing: please comment or send me a message if you happen to stumble over any bugs or have any suggestions for improvement.
Indicador Pine Script®
percentrank strategySrategy for percentrank
Percent rank is the percents of how many previous values was less than or equal to the current value of given series.
long entry: intersection line 1 from bottom to top
short entry: crossing line 2 from top to bottom
Стратегия для индикатора percentrank
Процентный рейтинг — это процент от количества предыдущих значений, которые были меньше или равны текущему значению данной серии.
вход в лонг: пересечение line 1 снизу вверх
вход в шорт: пересечение line 2 сверху вниз
Estratégia Pine Script®
Short in Bollinger Band Down trend (Weekly and Daily) // © PlanTradePlanMM
// 6/14/2020
// ---------------------------------------------------
// Name: Short in Bollinger Band Down trend (Weekly and Daily)
// ---------------------------------------------------
// Key Points in this study:
// 1. Short in BB Lower band, probability of price going down is more than 50%
// 2. Short at the top 1/4 of Lower band (EMA - Lower line), Stop is EMA, tartget is Lower line; it matches risk:/reward=1:3 naturally
//
// Draw Lines:
// BB Lower : is the Target (Black line)
// BB EMA : is the initial Stop (Black line)
// ShortLine : EMA - 1/4 of (Stop-target), which matches risk:/reward=1:3
// Prepare Zone : between EMA and ShortLine
// shortPrice : Blue dot line only showing when has Short position, Which shows entry price.
// StopPrice : Black dot line only showing when has Short position, Which shows updated stop price.
//
// Add SMA50 to filter the trend. Price <= SMA, allow to short
//
// What (Condition): in BB down trend band
// When (Price action): Price cross below ShortLine;
// How (Trading Plan): Short at ShortLine;
// Initial Stop is EMA;
// Initial Target is BB Lower Line;
// FollowUp: if price moves down first, and EMA is below Short Price. Move stop to EMA, At least "make even" in this trade;
// if Price touched Short Line again and goes down, new EMA will be the updated stop
//
// Exit: 1. Initial stop -- "Stop" when down first, Close above stop
// 2. Target reached -- "TR" when down quickly, Target reached
// 3. make even -- "ME" when small down and up, Exit at Entry Price
// 4. Small Winner -- "SM" when EMA below Entry price, Exit when Close above EMA
//
// --------------
// Because there are too many flags in up trend study already, I created this down trend script separately.
// Uptrend study is good for SPY, QQQ, and strong stocks.
// Downtrend Study is good for weak ETF, stock, and (-2x, -3x) ETFs, such as FAZ, UVXY, USO, XOP, AAL, CCL
// -----------------------------------------------------------------------------------------------------------------
// Back test Weekly and daily chart for SPY, QQQ, XOP, AAL, BA, MMM, FAZ, UVXY
// The best sample is FAZ Weekly chart.
// When SPY and QQQ are good in long term up trend, these (-2x, -3x) ETFs are always going down in long term.
// Some of them are not allowed to short. I used option Put/Put spread for the short entry.
//
Indicador Pine Script®
SSL Crossover + MA choiceThis indicator builds on the SSL channel code by ErwinBeckers @
I have added options for diff MA's to be used in the SSL channel and crossover indicators for buy/sell signals
default MA is set to Arnaud Legaux, but you can set it to whatever you like - original was a Simple Moving Average by ErwinBeckers
The indicator will not repaint as the signals are drawn after close of crossover candles
Let me know if you have any suggestions - happy to add more functionality
Indicador Pine Script®
Mirror MACD by Trader JayThis is my take on the metatrader indicator, the mirror macd. Works pretty good on Forex, haven't tested on anything else
Enter long after the Blue Line Cross Up the Red Line and EXIT after the Green line Cross Up the Red Line (above the Blue Line).
For the opposite position : ENTER SELL after the Red Line Cross Down.
Indicador Pine Script®
Generalized SSL by Vts// Generalized SSL:
// This is the very first time the SSL indicator, whose acronym I ignore, is on Tradingview.
// It is based on moving averages of the highs and lows.
// Similar channel indicators can be found, whereas
// this one implements the persistency inside the channel, which is rather tricky.
// The green line is the base line which decides entries and exits, possibly with trailing stops.
// With respect to the original version, here one can play with different moving averages.
// The default settings are (10,SMA)
//
// Vitelot/Yanez/Vts March 2019
Indicador Pine Script®
Trend is your friendThis indicator evaluates the trend based on crosses of two McGinley moving averages. It paints candles accordingly (it does not repaint), so you can see what the indicator is saying more clearly and stay in your trade until you see a period of consolidation or a reversal. You can control how far away those moving averages need to be for you to consider it a trend. If this distance is not met candles color is not changed and it shows you that the market is in a period of consolidation. I also added visualization of RSI, so you can have an easier time finding appropriate profit targets. For stop loss I would recommend placing it a couple points above or below the previous high / low that is located above / below you final target for entry. You can also use a certain percentage that works for you. I tried adding a stop loss based on ATR, but I did not like the results. Using market structure is a better choice in my opinion.
Here is a basic trading strategy for the default settings:
Wait for the indicator to start printing a series of green or red candles. After that you can enter a long or a short around moving averages. Another valid place to entry is the specific RSI zone. If we are in an uptrend buying when RSI is oversold can be beneficial as you expect market to recover. I do not recommend changing RSI from 14. Vice versa for the downtrend. It gives you an edge as you know at what price RSI will be oversold and allows you to place trades in advance. Pretty neat! You need to realize that no indicator or strategy can give you an exact entry. There will always be some margin of error. What I wanted to say is that if there is a strong trend up and you buy around your key moving averages and when RSI is oversold you entered in good places and there is a pretty good chance you will make money.
Time frame settings:
If you want to use tighter stop losses I would recommend sticking to 15m. Do not go lower. It is not worth the stress. 1h and 4h seems to be very good as well, but expect your stop losses to be wider. What I personally tend to do is display 15m, 30m and 1h and compare it. Think of it as a short, mid and long term. That way you can see things little bit better.
Examples:
1H chart BTC
4h chart EUR / USD
1D chart NASDAQ
15m chart BTC (Daytrading)
That last chart shows that even if you were longing while the trend was about to change you still had a good chance to close it with a little profit and switch to short easily. The default settings is what has worked the best for me. Feel free to change them as you see fit and do not forget to let me know if you find something that works better :)
Notes:
Either disable wick display or change it to a neutral color like gray for both green and red candles. Unfortunately pine script does not allow wick painting, so if you have red / green wicks it will look terrible. If RSI visualization makes your candles look too small you can go to settings and disable the display of individual RSI levels. You will still be able to see the zones, but the scale won't be affected.
Indicador Pine Script®
Daily ATR%If You are using a percentage of the Daily Average True Range in determining your stop placement,
this quick indicator is for You.
excerpt from investopedia.com/articles/trading/06/stopplacement.asp
ATR % Stop Method
The ATR% stop method can be used by any type of trader because the width of the stop is determined by the percentage of average true range (ATR). ATR is a measure of volatility over a specified period of time. The most common length is 14, which is also a common length for oscillators such as the relative strength index (RSI) and stochastics. A higher ATR indicates a more volatile market, while a lower ATR indicates a less volatile market. By using a certain percentage of ATR, you ensure that your stop is dynamic and changes appropriately with market conditions.
For example, for the first four months of 2006, the GBP/USD average daily range was around 110 to 140 pips. A day trader may want to use a 10% ATR stop - meaning that the stop is placed 10% x ATR pips from the entry price.In this instance, the stop would be anywhere from 11 to 14 pips from your entry price. A swing trader might use 50% or 100% of ATR as a stop. In May and June of 2006, daily ATR was anywhere from 150 to 180 pips. As such, the day trader with the 10% stop would have stops from entry of 15 to 18 pips while the swing trader with 50% stops would have stops of 75 to 90 pips from entry.
Indicador Pine Script®
UCS_Squeeze_Timing-V1There is an important information the Squeeze indicator is missing, which is the Pre Squeeze entry. While the Bollinger band begins to curves out of the KC, The breakout usually happens. There are many instances that the Squeeze indicator will fire, after the Major move, I cant blame the indicator, thats the nature (lagging) of all indicators, and we have to live with it.
Therefore pre-squeeze-fire Entry can be critical in timing your entry. Timing it too early could result in stoploss if it turns against you, ( or serious burn on options premium), because we never know when the squeeze will fire with the TTM squeeze, But now We know. Its a little timing tool. Managing position is critical when playing options.
I will code the timing signal when I get some time.
Updated Versions -
Indicador Pine Script®
Bank Nifty Futures Five RoundsNSE:BANKNIFTY1!
STRATEGY OVERVIEW — BIG PICTURE
This is a mean-reversion, intraday, round-number rejection strategy designed for Bank Nifty Futures
on the 1-minute chart. It fades failed moves around major round numbers instead of chasing
momentum.
WHAT THIS STRATEGY IS NOT
• Not a breakout strategy
• Not a trend-following strategy
• Not a scalping strategy
CORE ASSUMPTION
Around 500-point round numbers, Bank Nifty often overshoots by ~50 points and then reverts. This
strategy fades that failed extension.
KEY LEVELS
Every bar identifies the current 500-point block.
Example: Price 59,732 → Block 59,500–60,000
Levels used:
• Exact 500 round (59,500)
• Round +50 (59,550) rejection zone
• Round −50 (59,450) rejection zone
TIME FILTER
Trades allowed only between 09:30 IST and 15:10 IST.
MARKET CONDITION FILTER
Distance from 50 EMA must be reasonable (~300 points max).
Trending markets are avoided.
ENTRY LOGIC
SHORT: Price touches +50 and closes below it (rejection).
LONG: Price touches −50 and closes above it (reclaim).
RISK MANAGEMENT
Hard stop loss from entry:
• Long: −80 points
• Short: +80 points
PROFIT MANAGEMENT
• 50% booked at +60 points
• Remaining 50% targets +160 points
• Break-even activates only after +90 points in favor
SESSION EXIT
All positions closed at 15:10 IST.
EXPECTANCY
Avg loss ≈ −80
Avg win ≈ +110 to +130
Win rate ≈ 45–52%
WHEN THIS STRATEGY FAILS
• Strong trend days
• News-driven sessions
• Very low volatility days
This is a survival-first intraday system designed for consistency, not prediction.
Estratégia Pine Script®
Mamba Protocol: VIPER + SMC (Dash v2)Here is the English translation, ready to copy and paste into the TradingView description box:
🐍 MAMBA PROTOCOL: VIPER + SMC (LuxAlgo Mod)
Developed by: Pink Central (Mamba Rosa)
Base Code: Smart Money Concepts by LuxAlgo
This indicator is an Institutional Trading Suite designed to operate under the VIPER strategy. It combines the precision of Smart Money Concepts (SMC) with a market trend and strength detection engine, allowing you to identify high-probability entry points and avoid dangerous ranging markets.
🚀 KEY FEATURES:
1. Market Structure & SMC (Smart Money Concepts):
Order Blocks (OB): Automatic visualization of supply and demand zones with real-time mitigation.
Fair Value Gaps (FVG): Detection of market inefficiencies for potential rebalancing.
Structure (BOS / CHoCH): Automatic identification of Break of Structure and Change of Character.
Premium & Discount Zones: Visually indicates if the price is "expensive" (Premium) to sell or "cheap" (Discount) to buy.
2. VIPER Trend Engine:
Ranging/Choppiness Detection: The chart background turns Gray/Silver when ADX is low, indicating that trend continuation strategies should NOT be traded.
Institutional SMAs: Simple Moving Averages of 50 and 200 periods to define the macro trend (Golden Cross / Death Cross).
3. Control Dashboard (Info Panel):
Market Status: Indicates "TRENDING" or "RANGING" based on ADX strength.
Dynamic RSI: Real-time overbought/oversold monitoring.
Price Zone: Visual alert indicating if you are operating in a Premium or Discount zone.
⚙️ HOW TO USE (Mamba Strategy):
Identify Trend: Check the SMAs 50/200 and background color. If gray, wait.
Wait for the Sweep: Look for Order Block formations or liquidity grabs (High/Low).
Confirm Entry: Use the Dashboard to validate strength (ADX > 20) and direction.
Execute: Enter on the retest of an OB or FVG in favor of the main trend.
Indicador Pine Script®
Vector Logic: Gator Trend Hunter [v 2.0]MAJOR UPDATE: Added Trend Rider Logic to prevent premature exits.
"Stop getting shaken out of winning trades."
🛑 The Problem:
Most trend-following indicators have a fatal flaw: they exit too early . As soon as a strong trend pauses to take a breath, standard momentum indicators (like MACD or moving average crosses) panic and signal an exit, forcing you to watch from the sidelines as the stock rips higher without you.
✅ The Solution: The "Trend Rider" Logic
The VL: Gator Trend Hunter is an institutional-grade trend system designed to solve the problem of premature exits. It combines the legendary Williams Alligator volatility logic with a 200 Double EMA macro filter, but with a critical twist:
Instead of exiting when lines cross (which is noisy), this script uses a Structure Break Exit . It will keep you in the trade as long as the price candles close above the Alligator's Teeth (the Red Balance Line). This acts as a "Guard Rail," allowing the price to wiggle, pullback, and test support without killing your position.
_______________________________________
🧠 How It Works
1. The Macro Filter (200 DEMA) 🌊
The script first checks the "Big Picture" trend direction.
• Price > Orange Line = 🟢 Longs Only.
• Price < Orange Line = 🔴 Shorts Only.
2. The Trigger (The Alligator) 🐊
It waits for the Alligator lines to "Sleep" (contract/tangle) and then "Eat" (expand).
• LONG: When the Green line crosses above the Red line and price breaks out.
• SHORT: When the Green line crosses below the Red line and price breaks down.
3. The Ride (The Secret Sauce) 🏄♂️
Once in a trade, the script ignores minor crossovers . It only signals an EXIT if the price physically closes beyond the Red Guard Rail.
_______________________________________
📖 The Playbook: How to Trade It
• The Setup: Look for the Macro Trend Line (Orange) to be sloping up.
• The Entry: Wait for the Cyan "BUY" Label . This appears when the Alligator wakes up and expands (you will see the "Gator Cloud" turn bright Blue).
• The "Sit on Your Hands" Phase: This is the hardest part of trading. You will see red candles. You will see pullbacks. Do not sell. Trust the Red Line. As long as the "Gator Cloud" remains visible and price is above the Red line, the trend is healthy.
• The Exit: Sell only when the Yellow "X" appears. This confirms that the trend structure has actually broken.
_______________________________________
⚡ Key Features
• Bi-Directional: Works for both Bull markets (Longs) and Bear markets (Shorts).
• State Machine: No signal spam. You get one clean entry signal, and then silence until the exit.
• Live Dashboard: A status panel in the bottom right corner shows you:
📊 Macro Trend: Bullish/Bearish.
🐊 Gator Phase: Sleeping vs. Expansion.
🎯 Active Action: Long, Short, or Wait.
💎 Best For:
• Trending Assets: High Beta Stocks (NVDA, TSLA), Crypto (BTC, ETH), and Commodities.
• Timeframes: Optimized for 4H and Daily charts to catch major swings.
Part of the Vector Logic Labs quantitative suite.
Indicador Pine Script®
Vector Logic: Gator Trend Hunter
Stop getting shaken out of winning trades.
Most trend-following indicators have a fatal flaw: they exit too early . As soon as a strong trend pauses to take a breath, standard momentum indicators (like MACD or moving average crosses) panic and signal an exit, forcing you to watch from the sidelines as the stock rips higher without you.
The Solution: The "Trend Rider" Logic
The VL: Gator Trend Hunter is an institutional-grade trend system designed to solve the problem of premature exits. It combines the legendary Williams Alligator volatility logic with a 200 Double EMA macro filter, but with a critical twist:
Instead of exiting when lines cross (which is noisy), this script uses a Structure Break Exit. It will keep you in the trade as long as the price candles close above the Alligator's Teeth (the Red Balance Line). This acts as a "Guard Rail," allowing the price to wiggle, pullback, and test support without killing your position.
How It Works:
The Macro Filter (200 DEMA): The script first checks the "Big Picture."
Price > Orange Line = Longs Only.
Price < Orange Line = Shorts Only.
The Trigger (The Alligator): It waits for the Alligator lines to "Sleep" (contract/tangle) and then "Eat" (expand).
LONG: When the Green line crosses above the Red line and price breaks out.
SHORT: When the Green line crosses below the Red line and price breaks down.
The Ride (The Secret Sauce): Once in a trade, the script ignores minor crossovers. It only signals an EXIT if the price physically closes beyond the Red Guard Rail.
How to Use This Indicator (The Playbook):
The Setup: Look for the Macro Trend Line (Orange) to be sloping up.
The Entry: Wait for the Cyan "BUY" Label. This appears when the Alligator wakes up and expands (you will see the "Gator Cloud" turn bright Blue).
The "Sit on Your Hands" Phase: This is the hardest part of trading. You will see red candles. You will see pullbacks. Do not sell. Trust the Red Line. As long as the "Gator Cloud" remains visible and price is above the Red line, the trend is healthy.
The Exit: Sell only when the Yellow "X" appears. This confirms that the trend structure has actually broken.
Features:
Bi-Directional: Works for both Bull markets (Longs) and Bear markets (Shorts).
State Machine: No signal spam. You get one clean entry signal, and then silence until the exit.
Dashboard: A live status panel in the bottom right corner shows you the Macro Trend direction, the Gator Phase (Sleeping vs. Expansion), and your current Active Signal.
Best For:
Trending Assets: High Beta Stocks (NVDA, TSLA), Crypto (BTC, ETH), and Commodities (Gold, Silver).
Timeframes: Optimized for 4H and Daily charts to catch major swings.
Part of the Vector Logic Labs quantitative suite.
Indicador Pine Script®
EMA Cross with MTF Understanding EMA Crossover and Multi-Time Frame SMA Crossover in Technical Analysis
Technical indicators like Exponential Moving Averages (EMAs) and Simple Moving Averages (SMAs) are foundational tools for traders to identify trends, momentum shifts, and potential entry/exit points in markets such as stocks, forex, or cryptocurrencies. Crossovers—where one average line crosses another—signal changes in trend direction. Below, I'll break down EMA crossovers, then extend to multi-time frame (MTF) SMA crossovers, and explain how analyzing from a lower time frame can reveal higher time frame trends.
EMA Crossover: Basics and Application
An EMA crossover involves two or more EMAs of different periods intersecting on a price chart. EMAs give more weight to recent prices compared to SMAs, making them more responsive to new data and ideal for capturing short- to medium-term trends.
How It Works:
Typically, traders use a short-term EMA (e.g., 9-period or 12-period) and a longer-term EMA (e.g., 26-period or 50-period).
Golden Cross (Bullish Signal): When the shorter EMA crosses above the longer EMA, it suggests upward momentum and a potential buy opportunity. This indicates that recent price action is stronger than the historical average.
Death Cross (Bearish Signal): When the shorter EMA crosses below the longer EMA, it signals downward momentum and a potential sell or short opportunity.
Example: On a daily chart, a 12-period EMA crossing above a 26-period EMA might confirm the start of an uptrend, often used in strategies like the MACD (which is derived from EMA differences).
Advantages:
Quick response to price changes due to exponential weighting.
Reduces lag compared to SMAs, helping in volatile markets.
Can be combined with volume or other indicators (e.g., RSI) to filter false signals.
Limitations:
Prone to whipsaws (false crossovers) in sideways or ranging markets.
Best suited for trending environments; in choppy conditions, it may generate too many signals.
Traders often apply EMA crossovers on single time frames, but for broader context, incorporating multi-time frame analysis enhances reliability.
Multi-Time Frame SMA Crossover: Integrating Broader Perspectives
Multi-time frame (MTF) analysis involves examining the same asset across different time intervals (e.g., 5-minute, 1-hour, daily) to align short-term trades with longer-term trends. Here, we focus on SMA crossovers, where SMAs—simple arithmetic averages of closing prices over a set period—are used instead of EMAs. SMAs are smoother and less reactive, making them suitable for identifying sustained trends.
How It Works in MTF:
Choose at least two time frames: a lower one (e.g., 15-minute for intraday trading) and a higher one (e.g., 4-hour or daily for overall trend).
On each frame, plot two SMAs: a shorter one (e.g., 50-period) and a longer one (e.g., 200-period).
Crossover Signals:
Bullish: Shorter SMA crosses above the longer SMA.
Bearish: Shorter SMA crosses below the longer SMA.
In MTF, the higher time frame dictates the dominant trend, while the lower one provides precise entry timing. For instance:
If the daily chart shows a bullish 50/200 SMA crossover (uptrend), look for buy entries on the 1-hour chart when its own SMA crossover aligns.
This "top-down" approach ensures you're trading in the direction of the bigger picture, reducing counter-trend risks.
Advantages:
Filters noise: Higher time frames smooth out short-term volatility.
Improves win rate by confirming trends across scales.
Versatile for strategies like swing trading (daily/weekly) or scalping (5-min/15-min).
Limitations:
SMAs lag more than EMAs, potentially missing early trend entries.
Requires monitoring multiple charts, which can be time-intensive without automation.
Viewing Higher Time Frame Trends from a Lower Time Frame
One of the key benefits of MTF analysis is the ability to "see" higher time frame trends directly on a lower time frame chart, without switching views constantly. This is achieved through anchored or overlaid indicators that project higher-period data onto the lower chart.
How It Enables Trend Tracking:
Overlay Technique: On a lower time frame (e.g., 15-minute), plot SMAs or EMAs calculated from higher time frame data. For example:
Use a 50-period SMA on a daily chart, but recalculate it for the 15-minute chart by multiplying periods (since there are about 96 15-minute bars in a trading day, a daily 50-SMA might approximate to a 4800-period SMA on 15-min).
Tools like TradingView allow "higher time frame" scripts to fetch and display this directly.
Trend Visibility: From the lower frame, you can observe if the price is above/below the higher-frame SMA, indicating the overall trend. A crossover on the lower frame that aligns with the higher frame's direction confirms momentum.
Example: On a 5-minute chart (lower TF), if the overlaid daily 200-SMA acts as support (price bounces off it), it shows the higher TF uptrend is intact, even amid intraday dips. This helps avoid selling into a pullback during a broader bull market.
Practical Benefits:
Early Detection: Lower TFs show granular price action, revealing how higher TF trends are forming in real-time (e.g., a building crossover on daily visible as momentum buildup on hourly).
Risk Management: Use higher TF levels for stop-losses while entering on lower TF signals.
Example Strategy: In forex, on a 1-hour chart, confirm the 4-hour SMA trend is bullish, then wait for a 1-hour EMA crossover for entry. This way, you're "zooming in" on the big trend without losing context.
Indicador Pine Script®
GS Fibonacci Retracement Dynamic Anchor [Buy/Sell]GS Fibonacci Retracement Dynamic Anchor: Institutional Reversal Logic
The GS Fibonacci Retracement Dynamic Anchor is a high-precision Fibonacci tool designed for various assets including Stocks, Forex, and Options. Instead of static lines that become irrelevant as price moves, this script uses a rolling lookback engine to find the absolute Current Range . It then projects a "live grid" starting exactly from the highest and lowest bar indices.
How the Signals Work (Careful Entry):
This script does not just signal because a line was touched. It uses a Validation Phase :
The Pocket Entry: For a BUY signal, price must first dip into the "Golden Pocket" (below the 61.8% line). For a SELL signal, price must rise into the "Premium Pocket" (above 38.2%).
The Verification: The arrow only appears when the price closes back across the 50% Median Line . This confirms that the trend has truly shifted and the high/low is locked in.
Does this Redraw?
The Lines: Yes. The lines are Dynamic . If the market makes a higher high, the Fibonacci levels will automatically recalculate and shift up. This ensures you are always looking at the most current mathematical reality.
The Signals (Arrows): NO. The BUY and SELL arrows are calculated based on bar closes. Once an arrow appears on a closed candle, the logic is locked to that historical data.
Main Trading Applications:
Forex & Stocks: Ideal for catching "Mean Reversion." When a stock is overextended and enters the Premium Zone, the GS SELL signal helps you exit or short before the drop back to the median.
Options: The GS BUY signals represent "Deep Discount" entries where the Greeks (Delta/Theta) are most favorable for a bounce.
Equities/Funds: High-reliability signals for long-term investors to find "The Bottom" of a 75-day consolidation.
Key Features:
Institutional Ratios: Tracks the 21.0, 38.2, 50.0, 61.8, and 79.0 levels—the specific decimals used by automated trading algorithms.
Dynamic Anchor Dashboard: Real-time tracking of whether the price is in a "Premium" (Expensive) or "Discount" (Cheap) state.
Alert Ready: Fully integrated alert conditions for both Bullish and Bearish confirmations.
Points to Note:
Trend Strength: If the market is in a "Super Trend" (making new highs every 3 bars), the anchors will shift frequently. In these cases, wait for the price to stop making new anchors before trusting the 50% reclaim.
Lookback Setting: The 75-bar default is the "Sweet Spot" for most traders. Shortening it to 30 will make it a scalping tool; lengthening it to 200 will make it a macro-trend tool.
Indicador Pine Script®
Quant Professional【设计理念 / Design Philosophy】
"Speed is the edge." This script is dedicated to ultra-short-term traders and scalpers. The core philosophy is "Small Gains, High Frequency" (积少成多). By capturing the very first micro-reversal point without the lag of moving averages, it allows traders to enter and exit quickly before the noise of the market takes over.
“天下武功,唯快不破。” 本脚本专为超短线及日内交易者(Scalpers)设计。核心逻辑在于 “快进快出,积少成多” 。通过不带滞后的价格行为状态机,它能在趋势转折的第一个微小瞬间发出信号,助你在市场噪音干扰前完成套利。
【技术核心 / Technical Highlights】
State-Machine Logic: Utilizing a 12-level recursive price-action matrix to track momentum persistence. It only triggers when a long-term bearish sequence is decisively broken.
Zero Lag: Unlike EMA or MACD, this indicator relies solely on raw price levels (Close vs. Ref Close), ensuring the "Entry" is at the earliest possible stage.
High Frequency: Optimized for 1m, 5m, and 15m timeframes to provide consistent opportunities for accumulating small, steady profits.
状态机逻辑: 采用 12 级递归价格行为矩阵追踪动能持续性。只有当长期的空头序列被果断打破时,才会触发信号。
零滞后性: 不同于 EMA 或 MACD 等指标,该系统完全依赖原始收盘价对比,确保在转折初期即可入场。
高频机会: 针对 1天周期优化,为“积少成多”的复利策略提供源源不断的波段机会。
【实战策略 / Trading Strategy】
Fast Entry: Enter immediately when the "积少成多" arrow appears.
Fast Exit: Target a fixed small percentage (e.g., 0.5% - 1.5%) or exit when price fails to break the high of the next two bars.
Risk Management: Strict stop-loss at the signal bar's low. Focus on win rate and turnover speed, not huge single-trade gains.
快速入场: 当“积少成多”红色箭头出现时,果断切入。
快速离场: 设定较小的固定盈亏比(如 0.5%-1.5%)或在随后两根 K 线未能突破新高时主动退出。
风险控制: 止损严格设在信号 K 线的最低价。核心在于提高周转率和胜率,而非追求单笔暴利。
Indicador Pine Script®






















