Stop loss and Take profit indicator TradingView

Here you go, with couple of additions

// This source code is subject to the terms of the Mozilla Public License 2.0 at //mozilla.org/MPL/2.0/ // © SafetyHammer //@version=4 strategy[title="Take profit [% of instrument price]", overlay=true, pyramiding=1] // STEP 1: // Make inputs that set the take profit % [optional] FastPeriod = input[title="Fast MA Period", type=input.integer, defval=20, minval=1, group="Moving Average"] SlowPeriod = input[title="Slow MA Period", type=input.integer, defval=60, minval=1, group="Moving Average"] TP1Perc = input[title="Long Take Profit [%]", type=input.float, minval=0.0, step=0.1, defval=2, group="TP & SL"] TP2Perc = input[title="Long Take Profit [%]", type=input.float, minval=0.0, step=0.1, defval=4, group="TP & SL"] SLPerc = input[title="Long Stop Loss [%]", type=input.float, minval=0.0, step=0.1, defval=2, group="TP & SL"] TP1_Ratio = input[title="Sell Postion Size % @ TP1", type=input.float, defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached"]/100 // Calculate moving averages fastSMA = sma[close, FastPeriod] slowSMA = sma[close, SlowPeriod] // Calculate trading conditions enterLong = crossover[fastSMA, slowSMA] // Plot moving averages plot[series=fastSMA, color=color.green, title="Fase MA"] plot[series=slowSMA, color=color.red, title="Slow MA"] // STEP 2: // Figure out take profit price percentAsPoints[pcnt] => strategy.position_size != 0 ? round[pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick] : float[na] percentAsPrice[pcnt] => strategy.position_size != 0 ? [[pcnt / 100.0] + 1.0] * strategy.position_avg_price : float[na] current_position_size = abs[strategy.position_size] initial_position_size = abs[valuewhen[strategy.position_size[1] == 0.0, strategy.position_size, 0]] TP1 = strategy.position_avg_price + percentAsPoints[TP1Perc] * syminfo.mintick * strategy.position_size / abs[strategy.position_size] TP2 = strategy.position_avg_price + percentAsPoints[TP2Perc] * syminfo.mintick * strategy.position_size / abs[strategy.position_size] SL = strategy.position_avg_price - percentAsPoints[SLPerc] * syminfo.mintick * strategy.position_size / abs[strategy.position_size] // Submit entry orders if [enterLong] strategy.entry[id="Long", long=true] // STEP 3: // Submit exit orders based on take profit price if strategy.position_size > 0 strategy.exit["TP1", from_entry="Long", qty = initial_position_size * TP1_Ratio, limit = TP1, stop = SL] strategy.exit["TP2", from_entry="Long", limit = TP2, stop = SL] // Plot take profit values for confirmation plot[series=[strategy.position_size > 0] ? TP1 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 1"] plot[series=[strategy.position_size > 0] ? TP2 : na, color=color.green, style=plot.style_circles, linewidth=1, title=" Take Profit 2"] plot[series=[strategy.position_size > 0] ? SL : na, color=color.red, style=plot.style_circles, linewidth=1, title="Stop Loss"]

We made sure that all the graphical elements on the chart will be updated in real-time whenever our user change anything on the TradingView indicator configuration.
We also enabled dynamic alerts for the Trade Manager component.
More info available in the Alerts section below

Connect your own external indicator to the Trade Manager

When you'll load the trade manager for the first time, it won't be connected to any TradingView indicator.
That's why you'll see a error message as per the image above. Once you'll connect your indicator, the error disappears

On the screenshot above, we're showing how to connect a two SMA cross indicator to our Trade Manager, but the process is exactly the same for any other indicator. 
Our subscribers have access to the tutorial for updating their indicator quickly, and then connect it to our indicator. 

For the Algorithm Builders, you won't have anything to do - this is already included. 

This is not magic, neither is sorcery, but certainly is way beyond the most remarkable technical trading tool we've ever developed on TradingView [even across all brokers we know].

Unconnect your Trade Manager indicator from the chart

In case you don't want to use the Trade Manager, you can deactivate the it from your chart in 2 ways

1. Select a different external indicator/connector. As an example, below I'm chosing close referring to the candle close value


2. click on the 👁️‍🗨️ [eye icon] next to the Trade Manager indicator name on your chart. [top left]

Candles coloring and labels location


  • Colour candles based on trend state: automatic candles coloring based on profitability. Light color when beyond the entry price, dark color otherwise.
  • SL/TP Labels X Position: You can adjust the horizontal labels positions with the field SL/TP Labels X Position

Stop-Loss Management

Selecting the Default option means the trader doesn't use a custom Stop-Loss. And solely use the included hard-exit as the Stop-Loss signal.

For what's following, let's assume that 2 is the stop-loss percentage value you inserted in the indicator and the Algorithm Builder gives a BUY signal. This is NOT a recommendation at all, only an example to explain how this feature works.

- % Trailing : The Stop-Loss starts 2% away from the entry price - and will move up [because we're on a BUY trade as per our example] every time your trade will gain 2% profit


- Percentage : The Stop-Loss stays static 2% away from the entry price.
- ATR Multiple: Set the Stop-Loss 2 times the ATR value below the entry price.

Now using 100 as example for the options below:

Fixed Price Value: Set the Stop-Loss at a fixed position [value should be in currency/units of value/price level on the chart]


Fixed Price Value: Set the Stop-Loss at a fixed position [value should be in currency/units of value/price level on the chart]
Fixed Distance Value: Set the Stop-Loss at a fixed points/pips distance value [example for a LONG: 100 sets the stop level 100 pips below the entry price].

Pips Trailing : This one is a unique trailing-stop we invented.

Your pips trailing needs an Entry-Stop value - basically the stop value when the entry signal appears. Then it needs a trailing in pips [or fiat like EUR, USD, ...] value. For instance for a LONG entry, Entry Stop pips = 50 and Stop Loss [Pips trailing] = 100 will: - Set the entry stop 50 pips below the entry

- Once the move will be 100 pips profitable [aka 100 pips above the entry price], the stop level will be trailed from this trigger level of entry_price + 100 pips.

Use TP Trailing : This is a very remarkable feature. The stop-loss is set 2% away when the trades starts.

When the TP1 is hit, the stop-loss will be moved to the Entry price [also called breakeven]. Then when the TP2 is hit, the SL is moved to the previous TP1 position.

And when TP3 is hit, the SL is moved to the previous TP2 level.

Take Profits Management

You can manage up to 3 take profit levels based either on percentage or price value target.
- Percentage: for instance, setting the % TP1 to 2% will set the TP1 level 2% away from the entry price.
- Price value: for instance, setting the value for Bitcoin TP1 target 10000, sets the TP1 level at that price level.
- Distance value: for instance, setting the value for BTC/USD TP1 target 200, sets the TP1 level 200 USD away, from the entry price.
- ATR multiple: Set the 3 Take Profit levels based on ATR multiple values

Labels Lines

❌ Hard Exits ❌

We included the hard exit indicators in the Trade Manager - as we also did for the Algorithm Builders.
The hard exit [or invalidation] is a fundamental part of the Best Trading Indicator™ method. We explained numerous times on TradingView, our website, and social media channels why we "love" this concept so much, and how it saved our capital numerous times from getting savagely wrecked by the market.

Note: We'll be adding new Hard Exits indicators, and as you might know already; the subscribers will benefit from the upgrades for free :] - as explained on our Pricing page]

❌ Hard Exits - MACD ❌

On the left image, we use a MACD 20/50/50 as a dummy example.

Rule #1: A trader must keep using his/her logic : If enabled, the hard exit MACD has to make sense with your indicator signals. For example, if a trader uses entries based on a MACD 12/26/9, but invalidates using a MACD 20/50/50 - what do you think will happen ?


Answer: Probably nothing sensible because the hard-exit MACD 20/50/50 is more significant than the entries given by the MACD 12/26/9.
Without going any further into this edge case, our point is : the feature works if it has been thought of to exit a trade before a SL gets hit.

Rule #2: Must be used to reduce your losses - not your wins


A MACD is a momentum indicator - meaning when there is a decrease in the trend strength/velocity, the MACD will drop, and might turns negative - When in a LONG trend, this is a valuable input as it alerts the trader the trend might goes south [perhaps a time to move up the SL and take a bit of profits or closing the trade if not already with a positive balance on that trade] ❌ Hard Exits - RSI Divergence ❌

The 2.RSI exits a signal whenever a regular or hidden RSI divergence in the opposite direction of the trade will be detected. 

If you're looking to display those R[egular] and H[idden] small labels, I recommend that RSI divergence detector script.

The 3.MM Cross exits a signal whenever a moving average cross in the opposite direction occurs

When the settings change, the alerts already created aren't updated automatically.

If you change any settings, you'll have to delete the alert[s] related to that setting and recreate it/them.

For example, let's assume you would change the stop-loss of your trade manager but already created an alert for it days ago. As the previous alert is based on your previous configuration, you'll have to recreate it.

Please let us know if that doesn't make sense to you.

The screenshot should be self-explanatory enough

You mandatory need to create 1 alert for the BUY event and 1 alert for the SELL event

The Algorithm Builder allows to capture the alerts on those BUY green triangles and SELL red triangles.

You'll have to create 1 alert per event [buy or sell] per asset [BTC, DOW, APPL, ...] per timeframe [m5, m15, ...].

For instance, if you add your Algorithm Builder to your chart. You have to create 2 alerts. A first one to capture the MAIN BUY event, a second one to capture the MAIN SELL event.

According to your TradingView subscription type, you might receive the alerts by email and by SMS

Hard Exits BUY, and SELL alerts must be with the Once per bar close option.
The framework is made to invalidate when the hard exits sub-indicators give the signal, at the end/close of the m1 candle.

You'll be able to create alerts based on our Trade Manager. It's recommended to wait to be in a trade, and after creating the Trade Manager alerts.

As we could recommend to trigger the BUY/SELL alerts on candle close [for more security/less risk for fakeouts], it's generally a best practice to set the Trade Manager alerts using the Only Once or Once per bar because traders want to exit their trades at a specific price in real-time.

We mean, once the SL/TP1/TP2 are hit, you might not want to wait for the candle close to act, because it could be too late, and very often won't be in the trader favor.

Here are the list of third-parties capturing TradingView alerts and forwarding them to many FOREX [CFD] brokers. The process to connect the Algorithm Builder entries/exits signals to those systems is fairly easy.

You'll find more insight to make your alerts compatible with those systems here.

  • choosing a selection results in a full page refresh

Video liên quan

Chủ Đề