How to code a TRAILING STOP LOSS in Pine Script

Поделиться
HTML-код
  • Опубликовано: 28 окт 2024

Комментарии • 104

  • @TheArtOfTrading
    @TheArtOfTrading  Год назад +5

    🚩 *My Socials, Newsletter & More Free Content:* theartoftrading.com
    🚩 *Pine Script Mastery Course:* courses.theartoftrading.com/courses/pine-script-mastery
    🚩 *My Indicators & Strategies Course (Steal My Code!):* courses.theartoftrading.com/courses/my-indicators
    🚩 *Lesson Source Code:* courses.theartoftrading.com/pages/how-to-code-a-trailing-stop-loss-in-pine-script

    • @alextop1850
      @alextop1850 Год назад

      Great vids, can you do an update vid on how to code pinescipt with chat gpt4 . Helpful

    • @the1count
      @the1count Год назад

      Hi, thanks for the vid its a great one. Ive tried to implement on my strat but the stop loss is not resetting at the star of every new trade. Not sure where I've gone wrong.

  • @ИгорьЦ-е9п
    @ИгорьЦ-е9п 18 дней назад

    Thank you for your brilliant explanation of every code! I'm not fluent in English, but I've managed to understand all your video classes that I've watched!!! Wish you good luck!!!

  • @ezrakoper
    @ezrakoper Год назад +13

    Matt i have two feedbacks to improve your demo code for trailing stop.
    1. When trying to extend your code demo to multiple trailing stop events and not only one, it turns out that plot is an endless line. At the moment another trailing stop will be opened, a plot line will be drawn from the close of earlier trailing stop scenario to the start of the new one. To avoid it, the code has to continue and plot trailing stop with 100% opacity when there is no open position and 0 opacity on bars with open position. In my case i changed to the of the plot to look like:
    // Plot trailing-stop to chart. Use 100% transparency on bars that trailing stop is not in use
    plot(trailPrice, color=color.new(color.red, strategy.position_size != 0 ? 0 : 100), title="Trailing Stop", style = plot.style_stepline)
    2. When plotting the trailing stop it is better to plot it using plot style as: style = plot.style_stepline (see the plot line in my 1st comment) This gives the exact levels and doesn't create the elution of cutting through bars as in your explanation on how plot looks after two big red candles were created.
    Thanks for your excellent code, and explains on your RUclips videos.

    • @al3xf103
      @al3xf103 Год назад

      Thank you so much for this, I was wondering how on earth to do this with na / bgcolor etc and almost resorting to putting 0 instead of na. Your solution works great!

    • @OkiemTaty
      @OkiemTaty Год назад +1

      Except it doesn't work... when not in position your plot does exactly the same thing which is to remain static until another position is opened

  • @justrecorded4u984
    @justrecorded4u984 8 месяцев назад +2

    The best content on Pine Script in the YT.

  • @aniconicarden
    @aniconicarden Год назад +6

    This is the exact video I was waiting for, perfect addition to your excellent mastery course! Thank you Sir!

  • @yassermahmoud4275
    @yassermahmoud4275 Год назад +1

    I really can't thank you enough. You made me love both coding and trading. Good luck

  • @parinazfathi9531
    @parinazfathi9531 Год назад

    I just finished your basics course and just wanted to let you know how grateful I am for the amazing content you taught me. I can't wait to learn more from you and build amazing tools. I think you just changed my financial life forever

  • @glennone5898
    @glennone5898 Год назад +3

    Hi Matt, i love your videos and how you teach and share your knowledge, and the time and effort you put in. This was a great session and I got a lot of great information out of it so thank you very much. I have been following your videos for about a year and enjoying it immensely. I was having a bit of an issue when I tried to apply the trail stop to a trading strategy in that it would just carry the trail stop from the first trade all the way through, I couldn't get it to reset on the next trade. I played around with it for quite a few days and ended up adding in "if strategy.position_size == 0, then trailPrice := na" Not sure if this is correct but it seemed to do something. Thanks again for your video!!

    • @al3xf103
      @al3xf103 Год назад

      I was having the same problem but as I'm still not that great with Pinescript I asked chatgpt for a solution and it gave me the same one as yours inserted at the beginning of // Check for trailing stop update. And it appears to work! Edit: Doesn't seem to trigger every time for some reason! Edit2: Something funky is up with my code but it does indeed appear to work.

  • @greekboydinos
    @greekboydinos 6 месяцев назад

    dude, really looking forward to you one day creating a video on how different types of trailing methods could be used (you mentioned parabolic SAR and standard deviation, but what about other possible indicators like the ADX? etc.)
    very exciting. keep up the great work, you're seriously the best and i look forward to watching every new video you come out with

  • @sanatsahu
    @sanatsahu Год назад

    Very nice and lucid explanation of Trailing stops in Pine Script

  • @gestionprofesional
    @gestionprofesional Год назад +1

    oh congratulations! very well coded and excellent explanation, thank you very much

  • @seans9168
    @seans9168 Год назад +1

    Great topic! Very useful example. I really appreciate that about your videos and the style in which you explain reasoning behind why you selected specific functions or trade concepts. Thanks for being thorough too, as it helps when considering different approaches. Really outstanding overall.

  • @nevillebatty4776
    @nevillebatty4776 Год назад

    An outstanding trailing stop explanation and code WELL DONE Matt !!!!

  • @parinazfathi9531
    @parinazfathi9531 Год назад

    really awesome explanation of the code. you leave no questions for your viewers 👍👍

  • @typingsquirrel27
    @typingsquirrel27 5 месяцев назад

    Excellent !!
    You are an awesome teacher. Best wishes !!

  • @fabiocoutinho4074
    @fabiocoutinho4074 6 месяцев назад

    This is awesome!!! Unbeliveble explanation class!!! Thank you!!!

  • @tarve79
    @tarve79 Год назад

    Thank you very much for sharing. You have explained it in very detailed manner.

  • @xyuso
    @xyuso Год назад

    I was struggling with this for so long... thanks a lot

  • @Uraaaaa2
    @Uraaaaa2 10 месяцев назад

    Thank you for the content, your explanation was easy to understand 👌

  • @waharley
    @waharley Год назад

    awesome video! I'll definitely be doing the mastery course after I complete the basics course. learning so much, thanks!

  • @Dr3amwave
    @Dr3amwave Год назад

    Most pine code for trailing sl is usually overcoded. Thank you for covering all bases, like at the end of the video with the close tip. Like in the mastery course thorough as always to cover as many scenarios as possible.

  • @jt-oz
    @jt-oz Год назад

    Brilliant video thanks very much. Nicely put together. You have agreat teaching style. You've saved me a lot of time in learning all this from trial and error from pinescript documentation.

  • @doge2themoon373
    @doge2themoon373 Год назад +1

    Perfect timing 😊

  • @theoargy8428
    @theoargy8428 Год назад

    Great video. Thanks Matt. Very helpful.

  • @sevencarter7190
    @sevencarter7190 Год назад

    We are following up. Thanks 👍

  • @patriciogalvan7595
    @patriciogalvan7595 Год назад

    Thank you Matt, excelente script!! Suggest you to talk about Machine learning in trade. Kernel funciona, etc.

  • @chidinduuwaeziozi7360
    @chidinduuwaeziozi7360 Год назад

    Amazing. I needed to add this to my bag. Thank you.

  • @ezrakoper
    @ezrakoper Год назад +1

    Thanks for the educational video

  • @knarim1
    @knarim1 Год назад

    This video is a gem. I love you 😄😄.

  • @anungnug
    @anungnug Год назад

    Hi Matt, do you have a video that show how to create a script of our strategy and will use as a stock screener.
    Thanks in advance...🙏🙏🙏

  • @ВадимХырбу
    @ВадимХырбу Год назад +1

    Thanks for video! want to comment, The code you provided contains some syntax errors. The "switch" statement is not supported in Pine Script version 5. To fix this issue, you can modify the code to use "if-else" statements instead.

  • @ezrakoper
    @ezrakoper Год назад +1

    Will be helpful if you could expand the example by adding the string to be send to pineconnector using alerts

    • @frankjonestba
      @frankjonestba Год назад +3

      @Ezra Koper Opening that request with some form of a thank you/show of gratitude would probably go a long way...

    • @reylopez5337
      @reylopez5337 Год назад

      i am very thankful and appreciative of Matt's videos, especially this one. I too use pineconnector and i am having trouble figuring out how to get everything to work properly, i've been trying different options for hours and still no luck.

  • @evaltools
    @evaltools 10 месяцев назад

    Excellent! Thank you.

  • @romanbcz
    @romanbcz Год назад +1

    Can you please create a similar script on Trailing Take Profit (TTP)? Thanks

  • @automiamo
    @automiamo Год назад

    Good snippet. I'm using native trailing stoploss in pinescript. Why do you use a dedicated script instead of native variables in the pinescript strategy library? Thanks

  • @theod3634
    @theod3634 Год назад

    Thanks a lot for your content!
    I have a couple of questions about writing and using trade strategies, please, help me to understand:
    1) Still, is it possible to write such strategies that would carry out entry and exit from a position, based on data from several indicators simultaneously? That is, so that entry and exit are made when the necessary conditions coincide simultaneously on 2-3 indicators? If this is not possible with some indicators, then how do you know which ones are possible and which ones are not.
    ..and the 2nd question: For example, we have written the necessary strategy on Pine in Tradingview and it suits us. Is it possible to make this code enter and exit positions with a real account on a real exchange, like a trading bot? If yes, how can this be done?
    Thanks a lot!

  • @greatemmanuel8051
    @greatemmanuel8051 Год назад +1

    Pls I will really appreciate if you can create a video on how to create a back testing template 🙏🏾🙏🏾

  • @GreenStickStrategies
    @GreenStickStrategies Год назад

    Quick question, there`s any way to do something similar to this but with Trailing Take Profit? Greetings from South America.

  • @Eridanus_13
    @Eridanus_13 7 месяцев назад +1

    Trailing percentage of what exactly! Of price highest and lowest value, of invest equity for the trade, of offset values, of ROI percentage, of PNL percentage or of distance values based !

    • @TheArtOfTrading
      @TheArtOfTrading  7 месяцев назад +1

      Price-based, and depends which one you select in the settings (open/close or most recent swing low/swing high)
      Not sure what you mean by trailing by invest equity for the trade or trailing by offset values. This is a simple template for getting start trailing a stop loss from a source value, you can swap the source value for whatever you like once you understand the code template :)

    • @Eridanus_13
      @Eridanus_13 7 месяцев назад

      @@TheArtOfTrading I'm asking this because i recently came across a type of trailing tp n sl which makes my strategy so much profitable but i don't really understand it's core functionality lol so that's why i thought maybe you could explain that based on the types that i mentioned and i meant to say percentage or invest equity for a single trade and offset values mean similar type of trailing tp n sl of last traded highest or lowest price or rate based! And surprisingly, the trailing tp n sl that i implemented using ChatGPT, is so much profitable but i'm trying to figure out how works because ChatGPT isn't doing a good job of explaining that lol !😅🙏

  • @StRosen
    @StRosen Год назад

    Howdy, I was just wondering.... I use 3 atr as a separate indicator to set my both SL and TP, is there a way to implement TP line into this overlay with separate ATR multiplier option?

  • @michaelhaase1
    @michaelhaase1 Год назад

    Thanks a lot! I learned a lot again!

  • @thayrovg
    @thayrovg Год назад

    @TheArtofTrading Thank you as always for your great content! I have a doubt I wish you could help me solve: so far I've been using the built-in trailing parameters of trading view "trail_price" and "trail_offset". Are there any disadvantages in using them for backtesting? Would you recommend the method you showed us in this video instead? Thank you in advanced for your time :)

  • @mertymen2010
    @mertymen2010 Год назад +1

    Great video. Only issue I have is stop loss not resetting per strategy entry. It just remains persistant from previous trade, there for closing my next trade immedietly if my new open is below last stop loss. Hope that makes sense.

    • @mertymen2010
      @mertymen2010 Год назад

      For anyone with the same issue. I have found, if you add "trailPrice := na // reset trailing stop line" to the end of each exit condition. It will reset the trail price.

    • @mattdemaster
      @mattdemaster Год назад

      Agreed, having same issue. Not sure how to fix it.

    • @marcinmw
      @marcinmw Год назад +1

      I've just added
      trailPrice := na
      for every strategy entry/close. This way you reset the trailPrice value back to na for every new trade.

    • @vikart1689
      @vikart1689 Год назад

      @@marcinmw Did this fix this problem? Where did you add this line of code?

    • @al3xf103
      @al3xf103 Год назад

      See @glennone5898 comment above. Solution appears to be "if strategy.position_size == 0, then trailPrice := na" at the start of the // Check for trailing stop update block.

  • @edwardsciacca8012
    @edwardsciacca8012 Год назад

    Long Trade Short Trade if U need to set what your looking for it's a Bad script . what is needed is to track Live Streaming Data .
    VolumeAccumulations and use it to determine Direction for a Buy Sell Signal is Triggered at Time of TRADE . INCORPERATING IT INTO
    Your Script would HELP . this my work in progress triggers look good for BUY and SELL signals . ( ALL )in ThinkScript still testing .

  • @GXR-TRADING
    @GXR-TRADING Год назад

    You're just a boss, subbed instantly after this video and others you've made.
    Very difficult script, without your help I would have not found a easy way of doing it. It's annoying to activate/desactivate everytime but I prefer this to work at least for now. Thanks🙏

  • @jasonn5196
    @jasonn5196 Год назад

    Thanks for making these videos, I am having trouble making strategies that stay profitable over time, I understand that market conditions or sentiment among many other variables may impact chart conditions. do you have any tips for writing strategies that stand the test of time ?
    cheers bud.

  • @MrSmelly13cat
    @MrSmelly13cat Год назад

    Awesome vid, thanks!!

  • @reylopez5337
    @reylopez5337 Год назад

    i love this, thank you so much. i added this ATR stoploss to my strategy and i love the strategy.close option but i noticed that my trades dont close out via PineConnector but it does exit when i use the strategy.exit code,, please help

  • @kedamo123
    @kedamo123 Год назад

    How can you forward this technique to manage your trades with pineconnector?

  • @reinerneubert9117
    @reinerneubert9117 Год назад

    Matt, could you please include a pineconnector alert function?

  • @cryptomaniac5705
    @cryptomaniac5705 Год назад

    cheers mate ive just stumbled across the video while searching for this exact thing. ive got a strategy with multiple long, short, sell and cover signals which i select from a checkbox list. ive added the trailing stop loss code in from this video and ive tried to use it as another selection in the cover and sell lists. say i use atr_stop_long == true when the trail condition is met ie if strategy.position_size > 0 and low < trail_price
    atr_stop_long == true
    then in my sell selections i have a trailing stop loss option....which means this should trigger a sell signal. unfortuntely it doesnt seem to work :(

  • @OGJeff685
    @OGJeff685 Год назад

    Does this work with any brokerage in trading view? if not is that possible?

  • @mvvideo26
    @mvvideo26 Год назад

    Hi Matt! I tried this code however the trailPrice is not resetting when my strategy get a new position, any inputs?? Thank you!

  • @PertPlz
    @PertPlz Год назад +2

    I copy code into my strategy script, which only use long side.
    Problem is, when price action drop from previous resistant zone, Trail price is always higher than current trade. :(
    how can I reset "Trailprice" to zero after i end each trade.

  • @premop2940
    @premop2940 Год назад

    Hello. Do you have a strategy that is using this script please? I tried to implement it in my strategy and it doesnt work in 100% thank you

  • @jimray8122
    @jimray8122 7 месяцев назад

    What’s the point in all this if the stop doesn’t execute at the price set? It always does the next bar which is never the price of the stop loss. Is there anyway around this in pinescript?

  • @ariaabbasbeigii
    @ariaabbasbeigii Год назад

    Can’t we use the predefined trailing stops code in the strategy.exit function ?

  • @alanoliver618
    @alanoliver618 7 месяцев назад

    This script does no longer function as demonstrated in the video?? It doesn't seek bar to start, i.e. confirm is true doesn't seem to be working now?

  • @kankrz
    @kankrz Год назад +1

    I may have messed something up but it doesn't work well with my strategy. Unfortunately, I can't upload a picture here. Greetings.

  • @impulsiveguys7599
    @impulsiveguys7599 Год назад

    I tried implementing this one with supertrend, didnt work for me, can you help me out. The line would run through the candles so idk what isnto working

  • @tobytrades3683
    @tobytrades3683 Год назад

    I want my stop loss to be bigger at New York session. How do I code in that from 9 till 2am the stop loss is 210 ticks and then from 2 till 6pm to 310 ticks and then back to 210 ticks.

  • @robertvasilescu3326
    @robertvasilescu3326 Год назад

    nice and bravo for your hard work to make noobies like us how these things are working properly. I want to know something, this is for Long Entry, if I wish my TSL to be at EMA21 and keep EMA21 value after each bar closed but first this TSL will be activated of next syntax: rsi crossed over 77 and Aroon >99, how can I add all of this to your code lines and make it to work ???? All the best, body.

  • @penator
    @penator Год назад

    i added this code and removed the confirm= true in all user input, i also removed the bartime as well as the enter mocktrade code.
    when my script enters a trade this code does not exit trade when price hits trailPrice,
    when i use the original code it does exit the trade as it should.
    any idea how i can faullttrace my code?

  • @alexhalliday7427
    @alexhalliday7427 Год назад

    How can I get in touch with you for help?

  • @deltaiv9738
    @deltaiv9738 8 месяцев назад

    Bro how can i add the Alert for Trailing Stop Loss ?

  • @AbderrahmanAboda
    @AbderrahmanAboda Год назад

    Hi I have error message when I try the script in 'timber'!!!!!!????? 🤔🤔

  • @nickshv8727
    @nickshv8727 Год назад

    Some trades are being closed on the same bar in my case which is not good. Does anyone know how to fix that?

  • @mustmak8365
    @mustmak8365 11 месяцев назад

    // Display a message at the specified "Bar Time"
    if (time == barTime)
    label.new(
    x=bar_index,
    y=high,
    text="TES",
    color=color.red,
    style=label.style_labelup
    );
    // Trigger alert at the same time
    if (time == barTime)
    alert("TES Alert", alert.freq_once_per_bar_close)
    in above script i am getting repeated error {Error at 111:6 no viable alternative at character ';') V5. please help me to resolve this error

  • @PrakaS-qq8mu
    @PrakaS-qq8mu 4 месяца назад

    Bro "set the bartime" which show when i run the script

  • @OkiemTaty
    @OkiemTaty Год назад

    some youtube crap for you :) thanks for this content

  • @mohdhamizi1431
    @mohdhamizi1431 9 месяцев назад

    How to code a trailing stop loss base on the highest price of the current candle? a strategy that can execute stop price without waiting for the candle close.

  • @semcorda
    @semcorda Год назад

    So strategy.exit does not need to be prompted with "if" condition? Damn I feel dumb, I was trying to figure out for hours how to do a refreshing "if" for strategy.exit so it would be placing a new exit order when trailing point changes. Thanks to this video I know now that strategy.exit can just sit in the code , it will simply trigger when trail point is hit. I'll go eat some crayons now..

  • @edwardsciacca8012
    @edwardsciacca8012 Год назад

    the way i see it if your using a 1 hr BAR and it is triggered at the close of the Bar it is useless if the price changes direction 15 or 30 Min into the 1Hr BAR .THIS IS THE REASON TO HAVE NO TIME DELAY IN YOUR SCRIPT . TRADING FROM 1967

  • @abeni45xo
    @abeni45xo Год назад

    its really hard annd complicated can you please work for mt5 and downloadable

  • @tianruiz5925
    @tianruiz5925 Год назад

    😍😍😍😍

  • @johnnyhotwiel5409
    @johnnyhotwiel5409 Год назад

    🙏👍

  • @snikmotrenbue
    @snikmotrenbue Год назад

    Hey, Matt. Typed your script successfully. However, the Draw code did not work for me. Please tell what I may have done wrong. Thank you for your help and your time sharing.
    // Draw data to chart
    plot(strategy.position_size != 0 ? trailPrice : na, color=color.red, title="Trailing Stop")

  • @terlapu
    @terlapu 4 месяца назад

    @TheArtOfTrading - How can we add smoothing for this strategy. Kindly assist

  • @reylopez5337
    @reylopez5337 Год назад

    thank you Matthew, I have been trying to plug this beautiful ATR SL into my script which is connected to Pineconnector and i haven't had any luck, hopefully you can make a video that will explain how to add/ implement this ATR into a strategy code that uses Pineconnector. Matthew if you or any coders can help me please reach out, we can exchange contact info. Thanks in Advance.

  • @ADA_BTC
    @ADA_BTC Год назад

    Maybe you could use "math.round_to_mintick(trialPrice)" instead of str.toString(trialPrice, "#.####").
    round_to_mintick function know what precision to use.

  • @edsbloggingcom
    @edsbloggingcom Год назад

    Super! ❤. thxxxxxxxxxxx!!!!!!!

  • @lt3066
    @lt3066 Год назад

    hello buddy!
    I am glad you are keeping us update, you are saving life's
    I sent you a message on Instragram, i want to get in contact with you, I want to set up an auto trading, I am wiling to pay of course!
    I need your help! Please!

  • @gigitomuta766
    @gigitomuta766 Год назад

    Thank you for your videos Matt GBU

  • @alexhalliday7427
    @alexhalliday7427 Год назад

    How can I get in touch with you for help?