Alert(), alertcondition() or strategy alerts?Variety of possibilities offered by PineScript, especially thanks to recent additions, created some confusion. Especially one question repeats quite often - which method to use to trigger alerts?
I'm posting this to clarify and give some syntax examples. I'll discuss these 3 methods in chronological order, meaning - in the order they were introduced to PineScript.
ALERTCONDITION() - it is a function call, which can be used only in study-type script. Since years ago, you could create 2 types of a script: strategy and study. First one enables creating a backtest of a strategy. Second was to develop scripts which didn't require backtesting and could trigger alerts. alertcondition() calls in strategy-type scripts were rejected by Pine compiler. On the other hand compiling study-type scripts rejected all strategy...() calls. That created difficulties, because once you had a nice and backtested strategy, you had to rip it off from all strategy...() function calls to convert your script to study-type so you could produce alerts. Maintenance of two versions of each script was necessary and it was painful.
"STRATEGY ALERTS" were introduced because of alertcondition() pains. To create strategy alert, you need to click "Add alert" button inside Strategy Tester (backtester) and only there. Alerts set-up this way are bound with the backtester - whenever backtester triggers an order, which is visible on the chart, alert is also fired. And you can customize alert message using some placeholders like {{strategy.order.contracts}} or {{ticker}}.
ALERT() was added last. This is an alerts-triggering function call, which can be run from strategy-type script. Finally it is doable! You can connect it to any event coded in PineScript and generate any alert message you want, thanks to concatenation of strings and wrapping variables into tostring() function.
Out of these three alertcondition() is obviously archaic and probably will be discontinued. There is a chance this makes strategy/study distinction not making sense anymore, so I wouldn't be surprised if "studies" are deprecated at some point.
But what are the differences between "Strategy alerts" and alert()? "Strategy alerts" seem easier to set-up with just a few clicks and probably easier to understand and verify, because they go in sync with the backtester and on-chart trade markers. It is especially important to understand how they work if you're building strategy based on pending orders (stop and limit) - events in your code might trigger placing pending order, but alert will be triggered only (and when) such order is executed.
But "Strategy Alerts" have some limitations - not every variable you'd like to include in alert message is available from PineScript. And maybe you don't need the alert fired when the trade hit a stop-loss or take-profit, because you have already forwarded info about closing conditions in entry alert to your broker/exchange.
Alert() was added to PineScript to fill all these gaps. Is allows concatenating any alert message you want, with any variable you want inside it and you can attach alert() function at any event in your PineScript code. For example - when placing orders, crossing variables, exiting trades, but not explicitly at pending orders execution.
The Verdict
"Strategy Alerts" might seem a better fit - easier to set-up and verify, flexible and they fire only when a trade really happens, not producing unnecessary mess when each pending order is placed. But these advantages are illusionary, because they don't give you the full-control which is needed when trading with real money. Especially when using pending orders. If an alert is fired when price actually hit a stop-order or limit-order level, and even if you are executing such alert within 1 second thanks to a tool like TradingConnector, you might already be late and you are making entry at a market price. Slippage will play a great role here. You need to send ordering alert when logical conditions are met - then it will be executed at the price you want. Even if you need to cancel all the pending orders which were not executed. Because of that I strongly recommend sticking to ALERT() when building your alerts system.
Below is an example strategy, showing syntax to manage placing the orders and cancelling them. Yes, this is another spin-off from my TradingView Alerts to MT4 MT5 . As usual, please don't pay attention to backtest results, as this is educational script only.
P.S. For the last time - farewell alertcondition(). You served us well.
Indices
TradingView Alerts to MT4 MT5 - Forex, indices, commoditiesHowdy Algo-Traders! This example script has been created for educational purposes - to present how to use and automatically execute TradingView Alerts on real markets.
I'm posting this script today for a reason. TradingView has just released a new feature of the PineScript language - ALERT() function. Why is it important? It is finally possible to set alerts inside PineScript strategy-type script, without the need to convert the script into study-type. You may say triggering alerts straight from strategies was possible in PineScript before (since June 2020), but it had its limitations. Starting today you can attach alert to any custom event you might want to include in your PineScript code.
With the new feature, it is easier not only to execute strategies, but to maintain codebase - having to update 2 versions of the code with each single modification was... ahem... inconvenient. Moreover, the need to convert strategy into study also meant it was required to rip the code from all strategy...() calls, which carried a lot of useful information, like entry price, position size, and more, definitely influencing results calculated by strategy backtest. So the strategy without these features very likely produced different results than with them. While it was possible to convert these features into study with some advanced "coding gymnastics", it was also quite difficult to test whether those gymnastics didn't introduce serious, bankrupting bugs.
//////
How does this new feature work? It is really simple. On your custom events in the code like "GoLong" or "GoShort", create a string variable containing all the values you need inside your alert and this string variable will be your alert's message. Then, invoke brand new alert() function and that's it (see lines 67 onwards in the script). Set it up in CreateAlert popup and enjoy. Alerts will trigger on candle close as freq= parameter specifies. Detailed specification of the new alert() function can be found in TradingView's PineScript Reference (www.tradingview.com), but there's nothing more than message= and freq= parameters. Nothing else is needed, it is very simple. Yet powerful :)
//////
Alert syntax in this script is prepared to work with TradingConnector. Strategy here is not too complex, but also not the most basic one: it includes full exits, partial exits, stop-losses and it also utilizes dynamic variables calculated by the code (such as stop-loss price). This is only an example use case, because you could handle variety of other functionalities as well: conditional entries, pending entries, pyramiding, hedging, moving stop-loss to break-even, delivering alerts to multiple brokers and more.
//////
This script is a spin-off from my previous work, posted over a year ago here: Some comments on strategy parameters have been discussed there, but let me copy-paste most important points:
* Commission is taken into consideration.
* Slippage is intentionally left at 0. Due to shorter than 1 second delivery time of TradingConnector, slippage is practically non-existing.
* This strategy is NON-REPAINTING and uses NO TRAILING-STOP or any other feature known to be causing problems.
* The strategy was backtested on EURUSD 6h timeframe, will perform differently on other markets and timeframes.
Despite the fact this strategy seems to be still profitable, it is not guaranteed it will continue to perform well in the future. Remember the no.1 rule of backtesting - no matter how profitable and good looking a script is, it only tells about the past. There is zero guarantee the same strategy will get similar results in the future.
Full specs of TradingView alerts and how to set them up can be found here: www.tradingview.com
PpSignal Algorithmic trading system this strategy uses
1) trend
2) volatility
3) volume
Also, you can find in additional tools, rsi wilders on the chart and its standard deviation.
CFB composite fractal behavior and smoothed atr.
Candle converter MTF.
The strategy uses these four indicators to generate inputs and outputs.
Basically buy when cfb, rsi and atr go in the same direction upwards and the movement is accompanied by a rising volume (cfb green color and rsi Aqua ATR).
Idem in reverse for sell, when cfb, atra and rsi are giving a sell signal (Red color) and the volume is descending.
It is important that you also use other trading systems that you consider convenient. Support and resistance and also fibonacci levels all help to better trading.
Not all assets have or use the same configuration, for this, you must find the appropriate parameters with the variables, long length, short length, source, and period.
for example for btcusd the optimal parameters for me are:
long length = 2
short length = 2
signal length = 2
source = ohlc4
period = 9
It also has a take profit and stops loss tool in percentage.
remember to use parameters according to your tolerance as a trader or investor.
enjoy it
PD: you can write to me privately I have many optimizations and settings already done
este estrategia usa
1) trend
2)volatilidad
3)volumen
Tambien usted podrá encontrar en herramientas adicionales, rsi wilder on the chart y su desviación estándar.
CFB composite fractal behavior y atr suavizado.
Candle converter MTF.
La estrategia usa estos cuatro indicadores para generar entradas y salidas.
Básicamente buy cuándo cfb, rsi y atr van en la misma dirección hacia arriba y el movimiento está acompañado por un volumen ascendente (color verde cfb y rsi Aqua ATR).
Idem a la inversa para el sell, cuando cfb, atra y rsi están dando señal de venta (color Rojo) y el volumen es descendente.
Es importante que también use otros sistemas de trading que usted crea conveniente. Soporte y resistencia y también niveles fibonacci todo ayuda a un mejor trading.
No todos los activos tienen o usan la misma configuración para esto usted deberá encontrar los parámetros adecuado con las variables, long length, short length, source y period.
por ejemplo para btcusd los parámetros óptimos para mi son:
long length = 2
short length = 2
signal length = 2
source = ohlc4
period = 9
También posee una herramienta de take profit y stop lose en porcentaje.
recuerde usar parámetros acorde a su tolerancia como trader o inversor.
disfrutelo
PowerBot Binary Backtest FrameworkHello Traders,
This is the backtest framework for testing the Powerbot algorithm before activating alerts which can be used for precise Trading.
Powerbot can be used across any timeframe and across any expiration based on the performance
This backtest comes with some features to help traders make a decision on the following:
When using the indicator itself.
1. We use our proprietary algorithm - "Powerbot binary algorithm script", which is Public but can only be accessed based on request. If you would like to use the algorithm please ensure you have tested different assets and varying expiration for your trades through the backtest - if you don't know how to do that please contact us by sending a message.
EXPLORE YOUR OPTIONS FOR TRADING THROUGH VARIED ITERATION.
2. You can choose any expiration time by changing the expiration time period from the 'settings' button, this will display new results. example; on a 5 minutes chart timeframe, 6 bars would be 30 minutes, which means 5 minutes times 6, which is 30 and minutes because your timeframe is set to minutes. Another example is that on a 1-hour timeframe, 12 bars would be 12 hours, given 1 * 12 is 12hours, because your timeframe is set to hours.
3. You can choose the trading session you want, please note that we have included the three most active sessions - ASIAN, EU/UK, & US Session, by default, the scripts checks for performance on 24/7, which means it does not omit trades outside of the trading session. The Tradingview time is in UTC (or GMT -4). The best times to trade are during sessions most active times.
This backtesting indicator is free to add to the chart if you would like to use the algorithm during your trading session you need to contact us. After which you can use the algorithm for as long as you want.
Please note that no signal can work in all timeframe across all markets that is why backtesting to search for algorithms with at least 50% performance ratio is excellent for trading. All you need is to diversify alerts across to assets or more to rake in profits.
If you require assistance in understanding what session would work best, you can send us a message to work through the process together.
Thank you for you support. This script is free to use to see potential of the indicator itself.
We are NOT allowed to advertise any script on sale based on tradingview house rules.
Wishing you all the best.
Blue FX Trend StrategyHi, welcome to the Blue FX Trend Strategy Script.
What does it do?
Our strategy will help you identify the current trend in the markets and highlight when this is changing. The strategy itself is based upon 4 indicators lining up in total confluence to increase the probability of the trade being a success, this is specifically an EMA, MACD settings, Supertrend criteria and also Momentum.
Absolutely no technical analysis is needed to trade this successfully - this can be used on all time frames and all pairs - obviously with varying profitability as all pairs work differently - this can be reviewed quickly in 'Strategy Tester' to hone in on your own desired settings.
When all criteria is in alignment the strategy will convert all candles to the relevant colour - Green for an uptrend and Red for a downtrend; a candle that is printed normally simply shows that no current trend is in place to warrant a colour change. A normal coloured candle could possibly indicate a change in current market direction or the market consolidating before a further move in the initial direction. When a new signal is valid 'Blue FX Buy'' or 'Blue FX Sell' will be displayed and the small arrow shown on candle open for entry.
How do I use it?
Our strategy is invite only - upon joining our group we will allow you access to the script. This will then simply display on your device ready for you to start trading from. There is substantial functionality within the strategy, you can;
See the success of the default settings in the past using the 'Strategy Tester' Function for numerous settings
1. Following the settings 'Trail'
2. Changing your TP function with the other criteria listed
3. Using a Fixed TP or SL function
Upon changing the Script to 'Fixed' you will see numerous trades on the chart displayed differently.
Scaling into a profitable position is also possible - this is ideally done when the candle colour confirms the trend is continuing after rejection/support from the EMA; we show this below;
You could also enter here if you missed the initial sell signal, we have MA rejection and a red printed candle indicating all confluences are in play and we have high probability for the move to continue.
How do I know its profitable?
We have built numerous customisable settings into the strategy for you to see that this is profitable - you can visually see this too. The settings are also customisable to find the right criteria for the right pair on the right time-frame. Ultimately, with the strategy confluences in place, you are putting probability in your favour and can quickly determine the trend in place if there is one. Within the customisable settings there is a compound function too, so if you were to compound your profit the results can be exceptional.
We have also added an H4 confluence, so you can ensure if trading on a lower time-frame you are in the overall direction of the H4 trend too, a useful setting for more confluence again.
Where do I set my Stop loss or Take Profit?
There is no right or wrong to this and we have attempted to build numerous ways of doing this into the strategy for reference.
For setting a SL you could;
1. Use a fixed SL.
2. Place the SL below the last high or low in the trend.
3. Use an ATR function.
4. Place the SL 5 pips below the last 3 candles.
5. Or, trail the price if you are on screen until the next signal is given and a new trend starts - although unless a big trend, you may miss out on some profit by the time price has pulled back.
For placing a Take Profit, you could;
1. Use a fixed TP.
2. Look for the next supply/demand area on the chart (if it breaks and candle colour supports direction - you could enter again).
3. Use an ATR function.
5. Or, trail the price if you are on screen until the next signal is given and a new trend starts - although unless a big trend, you may miss out on some profit by the time price has pulled back.
6. Secure multiple TPs - 20/50/100 pips with Stop loss to entry after the first target is hit.
Here are some examples of the Buy and Sell signals in action;
Will also work on Commodities and Indices as shown below too;
Our recommended visual settings are below;
1. Set to'Trail' Strategy
2. Under 'Style' tab, select Trades on Chart, but un-select both Signal Labels and Quantity to clean up the chart - these settings are useful when testing to see where the trades are opened and closed.
3. We like the candles changing colour to the trend and criteria set however, these can be turned off to display normal bullish and bearish candles.
When reviewing profitability you can do this by selecting 'Overview' 'Performance Summary' and 'List of Trades'.
Please consider that the settings based into the strategy could differ to your own money management rules and your management of your SL and TP as outlined above - we have tried to cover as many bases as possible here.
We look forward to you using this strategy to profit from the market, please share your feedback and results with us.
Kind regards
Blue FX Team
TradingView Alerts to MT4 MT5 + dynamic variables NON-REPAINTINGAccidentally, I’m sharing open-source profitable Forex strategy. Accidentally, because this was aimed to be purely educational material. A few days ago TradingView released a very powerful feature of dynamic values from PineScript now being allowed to be passed in Alerts. And thanks to TradingConnector, they could be instantly executed in MT4 or MT5 platform of any broker in the world. So yeah - TradingConnector works with indices and commodities, too.
The logic of this EURUSD 6h strategy is very simple - it is based on Stochastic crossovers with stop-loss set under most recent pivot point. Setting stop-loss with surgical precision is possible exactly thanks to allowance of dynamic values in alerts. TradingConnector has been also upgraded to take advantage of these dynamic values and it now enables executing trades with pre-calculated stop-loss, take-profit, as well as stop and limit orders.
Another fresh feature of TradingConnector, is closing positions only partly - provided that the broker allows it, of course. A position needs to have trade_id specified at entry, referred to in further alerts with partial closing. Detailed spec of alerts syntax and functionalities can be found at TradingConnector website. How to include dynamic variables in alert messages can be seen at the very end of the script in alertcondition() calls.
The strategy also takes commission into consideration.
Slippage is intentionally left at 0. Due to shorter than 1 second delivery time of TradingConnector, slippage is practically non-existing. This can be achieved especially if you’re using VPS server, hosted in the same datacenter as your brokers’ servers. I am using such setup, it is doable. Small slippage and spread is already included in commission value.
This strategy is NON-REPAINTING and uses NO TRAILING-STOP or any other feature known to be faulty in TradingView backtester. Does it make this strategy bulletproof and 100% success-guaranteed? Hell no! Remember the no.1 rule of backtesting - no matter how profitable and good looking a script is, it only tells about the past. There is zero guarantee the same strategy will get similar results in the future.
To turn this script into study so that alerts can be produced, do 2 things:
1. comment “strategy” line at the beginning and uncomment “study” line
2. comment lines 54-59 and uncomment lines 62-65.
Then add script to the chart and configure alerts.
This script was build for educational purposes only.
Certainly this is not financial advice. Anybody using this script or any of its parts in any way, must be aware of high risks connected with trading.
Thanks @LucF and @a.tesla2018 for helping me with code fixes :)
Lazy Trend System 2019latest, more powerful and applicable on FX, indices, stocks and cryptocurrencies!
Strategy - Bobo's Pivot ATR SwingHi there, welcome to my pivot ATR swing bot. I put this out there with source code hidden to see what ideas others have to use it. Also if there are any coders of trading systems out there who wanted to work with me to put this into a form that could trade automatically we could both use... I'd welcome that kind of collaboration and will happily share the underlying rules of this and the more highly developed version that isn't public.
But as it is, the signals are free for all, use them as you wish and at your own risk. If you want to discuss the code, strategy or ideas, I'm around fairly regularly just message.
The bot is fairly simple design that will give you signals for long and short intraday/week on equity futures / CFDs / ETFs. You'll see it backtests fairly well on an hourly SPX500 chart as configured. You will need to set up certain parameters to account for any different timeframes and markets you wish to trade. For me it's most effective pick out a few good swing trades per week in equity futures. However part of the idea of putting this in the public domain is to see if other people will have good but different ideas how to use it. Please share with me if so :).
The basic concept is a series of 3 lines that define the area and movement we wish to trade. The daily pivot is the central line (blue). We are looking to capture reversions to this middle line from extremes (red and green). Therefore the bot will signal exit at the close of every candle that has passed through the pivot.
Entry is decided by the outer bands around the blue line. Red is the top band, green the bottom. As configured, these are simply placed a daily ATR value apart, centred around the pivot. You can change this quite a lot though, so let's go through the settings:
Pivot Timeframe - simple, a daily pivot is calculated from the previous day's values (high + low + close)/3 . BUt the same calculation can be applied to any length candle, day, minute, month or whatever. This makes the middle target line more or less responsive to recent price action.
ATR Band Timeframe - When we calculate the average range, we need to know what candle length makes up our series. Daily candles is the default, but you can change that here.
ATR Lookback - When we calculate the average range, we need to know how many instances of the timeframe (day, minute, hour etc) we look back to create an average. The lower the lookback value, the more the width of the bands (the distance from pivot) will change quickly based on the volatility of previous candles. The higher the lookback value, the more stable the band width will be to recent volatility.
ATR divisor - The ATR value above is divided by this value, before being added or subtracted to the pivot to create the red and green lines. Default value is 2, and this means the distance from the red band to the green band will be equal to 1 ATR, as calculated according to the parameters above. Setting this to 1 would mean that each band is one ATR away from pivot (ie the bands got wider apart). Set this to 4, and it means that it is only 1/2 an ATR from green to red.
Take Profit / Stop Loss. - We know what a stop and profit target are, but worth nothing that a 0 value disables stop loss or profit targets. The bot will still close positions when crossing pivot.
Also, note the mintick value of the instrument you apply this to. For example for the CFD chart SPX500 the mintick value is 0.1. So a 100 value for stop loss = 10 points on SPX500. but if you were to trade the same thing basically, but the emini future ES, the mintick value is 0.25. So for a 10 point stop on the ES chart, you would need a value of 40 in this bot. US30 and YM have convenient mintick values of 1. Currencies can be a bit of a nightmare :).