How to force strategies fire exit alerts not reversalsPineScript has gone a long way, from very simple and little-capable scripting language to a robust coding platform with reliable execution endpoints. However, this one small intuitivity glitch is still there and is likely to stay, because it is traditionally justified and quite intuitive for significant group of traders. I'm sharing this workaround in response to frequent inquiries about it.
What's the glitch? When setting alerts on strategies to be synchronized with TradingView's Strategy Tester events, using simple alert messages such as "buy" or "sell" based on entry direction seems straightforward by inserting {{strategy.order.action}} into the Create Alert's "Message" field. Because "buy" or "sell" are exactly the strings produced by {{strategy.order.action}} placeholder. However, complications arise when attempting to EXIT positions without reversing, whether triggered by price levels like Stop Loss or Take Profit, or logical conditions to close trades. Those bricks fall apart, because on such events {{strategy.order.action}} sends the same "sell" for exiting buy positions and "buy" for exiting sell positions, instead of something more differentiating like "closebuy" or "closesell". As a result reversal trades are opened, instead of simply closing the open ones.
This convention harkens back to traditional stock market practices, where traders either bought shares to enter positions or sold them to exit. However, modern trading encompasses diverse instruments like CFDs, indices, and Forex, alongside advanced features such as Stop Loss, reshaping the landscape. Despite these advancements, the traditional nomenclature persists.
And is poised to stay on TradingView as well, so we need a workaround to get a simple strategy going. Luckily it is here and is called alert_message . It is a parameter, which needs to be added into each strategy.entry() / strategy.exit() / strategy.close() function call - each call, which causes Strategy Tester to produce entry or exit orders. As in this example script:
line 12: strategy.entry(... alert_message ="buy")
line 14: strategy.entry(... alert_message ="sell")
line 19: strategy.exit(... alert_message ="closebuy")
line 20: strategy.exit(... alert_message ="closesell")
line 24: strategy.close(... alert_message ="closebuy")
line 26: strategy.close(... alert_message ="closesell")
These alert messages are compatible with the Alerts Syntax of TradingConnector - a tool facilitating auto-execution of TradingView alerts in MetaTrader 4 or 5. Yes, simple alert messages like "buy" / "sell" / "closebuy" / "closesell" suffice to carry the execution of simple strategy, without complex JSON files with multiple ids and such. Other parameters can be added (actually plenty), but they are only option and that's not a part of this story :)
Last thing left to do is to replace "Message" in Create Alert popup with {{strategy.order.alert_message}} . This placeholder transmits the string defined in the PineScript alert_message= parameter, as outlined in this publication. With this workaround, executing closing alerts becomes seamless within PineScript strategies on TradingView.
Disclaimer: this content is purely educational, especially please don't pay attention to backtest results on any timeframe/ticker.
Tradingconnector
TrailingTakeProfit exampleQuite recently I came upon a concept of Trailing Take Profit and I couldn't find a PineScript which implements it for the fastest possible execution, so here it is :)
Everybody knows Trailing StopLoss - an invisible mechanism follows the price and exits the trade once the price retreats too much from its recent most extended favourable value. Trailing TakeProfit does the similar thing, but at the opposite end - the trade gets closed if a price moves too well, in too favourable extent.
Why close the trade if it is going so good? Well, whatever goes up, must go down and vice versa. It is expected, that after fast rally a market will soon fall and after a dump it will go up. So Trailing TakeProfit's role is to secure profits.
But how does Trailing TakeProfit differ from the standard one? "Trailing" means, the exit level is moving. Its role is to be executed only after a rapid favourable move within 1-2 candles, not more. We never know when a rapid move happens, but when it does, we wanna catch those pips and quickly exit without looking back.
Visually Trailing TakeProfit levels are... bands. In this script example these are ATR multiplied bands (aka Keltner Channel), but they could also be Bollinger Bands or something else.
The code is simple just to focus on this single functionality, so you can quickly copy-paste it into your script. Entries are triggered by default SMA crosses.
P.S. I wouldn't be myself, if I didn't add alert messages compatible with the syntax of recently revamped TradingConnector - both in the code already and in the table showing them.
TENKAN SCALPER STRATEGYTENKAN SCALP is a fully automatic trading system.
It is a continuation of our previous ichimoku release. This time however we throw out the rule book and use ICHIMOKU in a very different way.
It applies non traditional money management tactics.
While most trading strategies rely on a stop loss and a take profit target to manage risk. This strategy uses either no stop loss at all or a time based stop loss.
You might ask yourself the question why would you keep a trade open if it goes against you? Here are a phew reasons why the script does what it does.
Forex Markets consolidate most of the time. If you wait long enough your Take Profit will get hit anyways most of the time
You don't have to risk everything per trade. I keep my orders small so to keep some powder to get into some more trades
All the extra trades you take while one trade is in drawdown limit the drawdown as they provide cashflow
On lower timeframes the markets are so chaotic that a stop loss is very likely to get hit by a wick
About backtest below
This backtest uses a spread of 2 pips for entries and a default position size of 100% of equity. This is only possible on exchanges where spread is low and you have 10:1 leverage or more. It does not represent results obtainable without leverage. Do take into account that there are a lot of forex exchanges that provide this leverage, however a 2 pip spread is not always guaranteed and only applies to major pairs.
This backtest does not use the TIME BASED STOPS functionality.
Always start with small position sizing and see how the strategy performs before adding risk.
Explanation of variables:
Chikou(lagging span): pink line, this is price plotted 26 bars ago. People ignore the power of this it is crucial to see how chikou behaves towards past price action as seen in the chart below where we got an entry at red arrow because chikou bounced from past fractal bottom.
Kijun-Sen(base line): Black line or color coded line. This is the equilibrium of last 26 candles. To me this is the most important line in the system as it attracts price.
Kijun = (Highest high of 26 periods + Lowest low of 26 periods) ÷ 2
Tenkan-Sen(conversion line): Blue line. This is the equilibrium of last 9 candles. In a strong uptrend price stays above this line.
Tenkan = (Highest high of 9 periods + Lowest low of 9 periods) ÷ 2
Senkou A (Leading span A)= Pink cloud line, this is the average of the 2 components projected 26 bars in the future.
Senkou A = (Tenkan + Kijun) ÷ 2
Senkou B (Leading span B) = Green cloud line, this is the 52 day equilibrium projected 26 bars in the future.
Senkou B = (Highest high of prior 52 periods + Lowest low of prior 52 periods) ÷ 2
projection: Script uses same function for variable calculation and substracts a number on each next bar as to make a projection of where the variable will be in future bars if price stayed the same. This works as ICHIMOKU calculations use the middle point of a past set of data. The shorter that amount of bars will be in line with the data that it will be restricted to in future if price stayed the same.
Detection of Market Environment
To enter trades the script uses a lot of ICHIMOKU concepts. Contrary to how most people trade ICHIMOKU this script takes an environment that ICHIMOKU identifies as trending upwards and shorts in that environment. The same will be applied to a downtrend where it will open LONGS.
List of CRITERIA for a trend:
Grapling Hook: this is a component based on the chikou span (closing price displaced 26 bars into the past). The script will use an ATR based range to define a possible future projection to the CHIKOU line. For a market to be bullish there should be no price action happening within this area. Market is free to move upwards. Vice versa for bearish .
Kumo Cloud: script will check if price is above the cloud for bullish trend and below cloud for bearish trend .
Chikou above Kijun: script will check if the chikou line is above the KIJUN line of 26 bars ago. This is further confirmation that price is trending high enough compared to it's past data. Vice versa for downtrend.
Kijun projection: script will check if past Kijun is lower than future projected Kijun. This to ensure we get an equilibrium in our favour in the future. Vice versa for downtrend
Tenkan projection: script will check if future Tenkan-sen will be higher than Kijun-sen for an uptrend. Vice versa for downtrend.
Cloud projection: script will check if in 9 bars the Senkou Span A will be higher than Senkou Span B for an uptrend. Vice versa for downtrend.
Example:
This script does not visualise the prediction lines like I show in the example. I show them here to clarify how the script works.
Usage
Backtests are not indicative of future results, although a trader may want to use a strategy script to have a deeper understanding of how their strategy responds to varying market conditions, or as a tool for identifying possible flaws for a strategy that may be indicative of good or bad performance in the future.
Strategy Settings:
Minimum Body Size (atr): this is the minimum ATR a signal bar needs to be for entry. This is useful because our TP is based on previous bar.
Lot size per trade: this setting does not impact backtest. It is used to for the signals to let tradingconnect.com know your position size.
Direction: do you want to trade longs or shorts. I personally use both a long bot and a short bot at the same time.
Positions Allowed: the amount of positions the script will keep open as a maximum. You do not want to open too many positions, this is for risk management.
Close all positions at drawdown: if total open positions loss gets to this % target it will close all positions.
MetaTrader Prefix: when the script sends a signal it will put this text right before the symbol name from syminfo.ticker
MetaTrader Suffix: when the script sends a signal it will put this text right after the symbol name from syminfo.ticker
Charts below are some examples on how the script handles orders on default settings:
without time based SL
with time based SL
how it handles pyramiding
www.tradingview.com
Tradingconnector.com:
For full automation of the forex market the script uses this connector to execute trade on MT4. The alerts the script sends using the alerts() function call are structured in a way tradingconnector will recognise and send directly to MT4. You can find documentation about this tool on their own website.
Personal recommendation is to start with a minimum lot size and track performance, if you are comfortable scale the size up. You can do that by increasing the lot size setting in the script and making a new alert. Make sure to delete the old one.
How to access
You can see the Author's Instructions below to visit our telegram to get more information on how to get access.
Joint Conditions Strategy Suite + TradingConnector alerts bot"Please give us combined alerts with the possibility of having several conditions in place to trigger the alert." - was the top voted request from users under one of the recent blogposts by TradingView.
Ask and you shall receive ;)
TradingView is a great platform, with unmatched set of functionalities, yet this particular combo of features indeed seems not to be in place. Fortunately, TradingView is also very open platform, thanks to PineScript coding language, which enables developing combos like the requried one and plenty of other magic.
I have already published numerous "educational" scripts, showing how to code indicators and alerts with PineScript, but... this is not one of them. This one is for real. READY FOR USE on real markets, also by the non-coding traders. Just take my script, set parameters with dropdowns, backtest the strategy, fire the alerts and execute them.
HOW TO USE IT
In "Settings" popup I tried to mimic the CreateAlert popup dropdowns for selecting logic. Let's say you want to enter Long position at Stochastic KxD crossover. In first line of Long Entry conditions set "StochK" + "Crossing Up" + "StochD". Last field doesn't matter because in 3rd dropdown something else than "value" was selected. In second line you could set "maB" + "Greater Than" + "maC" to filter out those entries which are in direction of the uptrend. And yeah, add ADX>25 to make sure the market is actually moving: "ADX" + "Greater Than" + "value" + "25". All condition lines must be TRUE (or skipped) for the entry to be triggered. Toghether with an alert.
The same for Short entries. Combinations are limitless.
INDICATORS AND MTF (MULTI-TIMEFRAME)
In those dropdowns you can select candle values like open/close/high/low/ohlc4, but also some most popular indicators, which I have pre-built into this script: RSI, various Moving Averages, ADX-DMI, Stochastic and Bollinger Bands for start. You can configure parameters of those indicators also in "Settings" popup, in "Indicator Definitions" section. What's important, you can use any of these indicators from higher timeframe, setting MTF multiplier. So if you applied this indicator to 1h chart, but want to use rsi(close,14) from 4h chart, set MTF to 4. If you want to use current timeframe indicators, keep MTF at 1, which is a default setting here.
Note for coders: to keep focus of this script on joining conditions, entire logic for those indicators has been moved to external library, also open source. I encourage you to dig into the code and see how it's done. I love the addition of libraries concept in PineScript.
CUSTOM INDICATOR
Following the "openness" spirit of my master - which is TradingView itself - my work is also open, in 2 ways:
1. This script is open source. So you can grab it, modify or add any functionalities you want. I cannot and don't want to stop you from doing that. I'm asking for only one favor - please mention this source script in your credits.
2. You can import the plot (series) from any other indicator on TradingView. In Settings popup of my script, scroll down to "Indicator Definitions" section, and select the series of your choice in the first dropdown. Now it is ready to use in conditions dropdowns on top of the Settings popup.
Let me give you an example of that last scenario. Take another script of mine, "Pivot Points on SR lines DEMO". You can find it in "Indicators & Strategies" library or here: (). Attach it to your chart. Now come back to THIS script, open Settings popup and in "Custom Indicator aka Imported Source" select "Pivot Points on SR lines: ...". The way it works - it detects if a pivot point happened on Support/Resistance line from the past and returns 1 for PivotLow and -1 for Pivot High. Now in first Long Entry condition set: "custom indicator" + "Greater Than" + "value" + "0" and long entries will be marked on every pivot low noticed on Support/Resistance line.
ALERTS
Last but not least - the alerts. This script produces alerts on the entries calculated by strategy logic, as marked on the chart by the backtester. Moreover, syntax of those alerts is already prepared and fully compatible with TradingConnector - alerts executing tool (bot), if you want to auto-execute those trades. Apart from installing the tool, you need to set
up the alerts in TradingView, here is how:
open CreateAlert popup
in first dropdown select "Joint Conditions Strategy Template"
in second dropdown select "alert() function calls only"
And that's all. You only need to set one alert for the whole script, not one for Longs and one for Shorts as it was in the past. Also, you don't need to setup closing alerts, because stop-loss/take-profit/trailing-stop information is embedded in the entry alert so your broker receives it as early as possible. Alerts sent will look like this: "long sl=40 tp=80", which is exactly what TradingConnector expects.
Phew, that's all folks. If you think I should add something to this template (maybe other indicators?) please let me know in comments or via DM. Happy trading!
P.S. Pyramiding is not supported in this script.
Disclaimer : I'm not saying above combination of conditions will make you money. Actually none of this can be considered financial advice. It is only a software tool. Use it wisely, be aware of the risk and do your own research!
Pivot Reversal Strategy + alerts via TradingConnector to indicesSoftware part of algotrading is simpler than you think. TradingView is a great place to do this actually. To present it, I'm publishing each of the default strategies you can find in Pinescript editor's "built-in" list with slight modification - I'm only adding 2 lines of code, which will trigger alerts, ready to be forwarded to your broker via TradingConnector and instantly executed there. Alerts added in this script: 14 and 22.
How it works:
1. TradingView alert fires.
2. TradingConnector catches it and forwards to MetaTrader4/5 you got from your broker.
3. Trade gets executed inside MetaTrader within 1 second of fired alert.
When configuring alert, make sure to select "alert() function calls only" in CreateAlert popup. One alert per ticker is required.
Adding stop-loss, take-profit, trailing-stop, break-even or executing pending orders is also possible. These topics have been covered in other example posts.
This routing works for Forex, indices, stocks, crypto - anything your broker offers via their MetaTrader4 or 5.
Disclaimer: This concept is presented for educational purposes only. Profitable results of trading this strategy are not guaranteed even if the backtest suggests so. By no means this post can be considered a trading advice. You trade at your own risk.
If you are thinking to execute this particular strategy, make sure to find the instrument, settings and timeframe which you like most. You can do this by your own research only.
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.
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
Pyramiding Strategy To Study [mcristianrios]This script simulates what goes behind scenes in a Strategy and it serves to know in Study mode how many positions are running at the same time.
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 :)