Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Set additional requirement in LongorShortTrail Stop example

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Set additional requirement in LongorShortTrail Stop example


    Hi I want to set initial stopprice to a Swing Low value for longs. And then as usual. In other words have an additional initial requirement, where first CurrentLongStopPrice is set to SwingLow value
    and then CurrentLongStopPrice is set to LongTrailStopDistance once price trigggers CurrentLongTriggerPrice. Is it possible?



    LongTrailFrequency = 5;
    -LongTrailStopDistance = -5;
    -ShortTrailFrequency = -5;
    ShortTrailStopDistance = 5;
    LongProfitTargetTicks = 20;
    ShortProfitTargetTicks = -20;
    -CurrentLongTriggerPrice = 0;
    -CurrentLongStopPrice = 0;
    CurrentShortTriggerPrice = 0;
    CurrentShortStopPrice = 0;​

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    // Set 1
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    CurrentLongStopPrice = 0;
    CurrentShortStopPrice = 0;
    region trail area start
    swinghlLong = Swing(5).SwingLow[1];
    swinghlShort = Swing(5).SwingHigh[1];
    #endregion

    }

    if (CurrentBars[0] < 1)
    return;

    // Set 2
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (State == State.Realtime)
    && (Close[0] > Open[0]))
    {
    CurrentLongTriggerPrice = (Close[0] + (LongTrailFrequency * TickSize)) ;
    //CurrentLongStopPrice = (Close[0] + (LongTrailStopDistance * TickSize)) ;
    CurrentLongStopPrice = swinghlLong;
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    }

    // Set 3
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (State == State.Realtime)
    && (Close[0] < Open[0]))
    {
    CurrentShortTriggerPrice = (Close[0] + (ShortTrailFrequency * TickSize)) ;
    CurrentShortStopPrice = (Close[0] + (ShortTrailStopDistance * TickSize)) ;
    EnterShort(Convert.ToInt32(DefaultQuantity), "");
    }

    // Set 4
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Close[0] > CurrentLongTriggerPrice))
    {
    CurrentLongTriggerPrice = (Close[0] + (LongTrailFrequency * TickSize)) ;
    CurrentLongStopPrice = (Close[0] + (LongTrailStopDistance * TickSize)) ;
    }

    // Set 5
    if ((Position.MarketPosition == MarketPosition.Short)
    && (Close[0] < CurrentShortTriggerPrice))
    {
    CurrentShortTriggerPrice = (Close[0] + (ShortTrailFrequency * TickSize)) ;
    CurrentShortStopPrice = (Close[0] + (ShortTrailStopDistance * TickSize)) ;
    }

    // Set 6
    if (CurrentLongStopPrice != 0)
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), CurrentLongStopPrice, "", "");
    }

    // Set 7
    if (CurrentShortStopPrice != 0)
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), CurrentShortStopPrice, "", "");
    }

    // Set 8
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Close[0] >= (Position.AveragePrice + (LongProfitTargetTicks * TickSize)) ))
    {
    ExitLong(Convert.ToInt32(DefaultQuantity), @"Profit Long", "");
    }

    // Set 9
    if ((Position.MarketPosition == MarketPosition.Short)
    && (Close[0] <= (Position.AveragePrice + (ShortProfitTargetTicks * TickSize)) ))
    {
    ExitShort(Convert.ToInt32(DefaultQuantity), @"ProfitShort", "");
    }

    }​


    #2
    Hello tkaboris,

    You can make any modifications that you would like so long as they can become true and make sense in the use case. The purpose of the sample you are using is only to show how buttons can be added to the chart and how they can toggle values that are used from OnBarUpdate. Beyond that you can make any other modifications that you wanted to the scripts OnBarUpdate to change how it evaluates conditions.

    In what you provided you are only setting the indicators price to CurrentLongStopPrice when the script is initially flat, you may or may not need to move that code to before the entry depending on what overall outcome you wanted. You will need to run the script and test it to make sure the modifications that you made work toward your goal.

    Comment


      #3
      ok i actually went with supertrend indicator as traililng stop but i have an issue. If i am in short or long, when in profit it doesnt trail right, trail moves with the price. What should i do?
      Thank you

      StopTicksLong = -20;
      StopTicksShort = 20;
      MySTStop = 1;​

      EnterShort(PositionSize, "TMS");
      MySTStop = (Position.AveragePrice + (StopTicksShort * TickSize)) ;

      if (SetTrailST)
      {

      if ((Position.MarketPosition == MarketPosition.Long)
      && (TSSuperTrend1.UpTrend[0] <= Low[0]))
      // && (TSSuperTrend1.UpTrend[0] < MySTStop))
      {
      MySTStop = TSSuperTrend1.UpTrend[0];
      Print("MySTStop step2 long" + MySTStop);
      Print("TSSuperTrend1.upTrend[0]" + TSSuperTrend1.UpTrend[0]);
      Print("TSSuperTrend1.downTrend[0]" + TSSuperTrend1.DownTrend[0]);
      }


      if (Position.MarketPosition == MarketPosition.Long)
      {
      ExitLongStopMarket(1, true, Position.Quantity, MySTStop, "SLL", "TML");
      Print("MySTStop step3 long" + MySTStop);
      }

      // shorts trail
      if ((Position.MarketPosition == MarketPosition.Short)
      && (TSSuperTrend1.DownTrend[0] >= High[0]))
      // && (TSSuperTrend1.DownTrend[0] < MySTStop))
      {
      MySTStop = TSSuperTrend1.DownTrend[0];
      Print("MySTStop step2 short" + MySTStop);
      }


      if (Position.MarketPosition == MarketPosition.Short)
      {
      ExitShortStopMarket(1, true, Position.Quantity, MySTStop, "SLS", "TMS"); //Sets Stop
      Print("MySTStop step2 short" + MySTStop);

      }​

      Comment


        #4
        Hello tkaboris,

        The order is being resubmitted on each bar with the price you give it, if you are setting it to a indicators price the target should follow the indicator exactly.

        Comment


          #5
          HI thank you,
          yes i am setting price to indicator. I thought i set the price to follow indicator exactly.

          MySTStop = TSSuperTrend1.DownTrend[0];
          and in last step
          ExitShortStopMarket(1, true, Position.Quantity, MySTStop, "SLS", "TMS"); //Sets Stop

          Comment


            #6
            Hello tkaboris,

            Yes you are setting the variable to the indicator value and the variable is used with that order. I am not sure what problem you are describing here.

            Comment


              #7
              HI once again. I was able to figure it out it actually was working as suppose to. I am coming back to trail based on sar indicator. I dont know what the causes this short trade to give out this error. it opens longs and shorts fine and trail as suppose to but occasionally it gives this error and i cant figure out why.

              My entry logic is simply when green line go long, when red line go short. There was no green line but something is parabolic. Should there be another condition to parabolic trail indicator to prevent this?
              In the image i was in short trade and i got this message. Error happened on teh last bar of the cahrt

              'TrendMagicAlgoAlgo/284764661' submitted an order that generated the following error 'Unable to change order'. Strategy has sent cancel requests, attempted to close the position and terminated itself.

              Thank you

              private ParabolicSAR ParabolicSAR1;
              private double MySarStop;​
              StopTicksLong = -20;
              StopTicksShort = 20;
              MySarStop = 1;​

              ParabolicSAR1 = ParabolicSAR(Close, 0.02, 0.2, 0.02);
              ParabolicSAR1.Plots[0].Brush = Brushes.Goldenrod;
              AddChartIndicator(ParabolicSAR1);​



              if (SetTrail)
              {

              if ((Position.MarketPosition == MarketPosition.Long)
              && (ParabolicSAR1[0] <= Low[0]))
              // && (ParabolicSAR1[0] > MySarStop))
              {
              MySarStop = ParabolicSAR1[0];
              }


              if (Position.MarketPosition == MarketPosition.Long)
              {
              ExitLongStopMarket(1, true, Position.Quantity, MySarStop, "SLL", "TML");
              }

              if ((Position.MarketPosition == MarketPosition.Short)
              && (ParabolicSAR1[0] >= High[0]))
              // && (ParabolicSAR1[0] < MySarStop))
              {
              MySarStop = ParabolicSAR1[0];
              }


              if (Position.MarketPosition == MarketPosition.Short)
              {
              ExitShortStopMarket(1, true, Position.Quantity, MySarStop, "SLS", "TMS"); //Sets Stop

              }
              }​


              Click image for larger version  Name:	image.png Views:	0 Size:	1.30 MB ID:	1260234
              Last edited by tkaboris; 07-13-2023, 11:52 AM.

              Comment


                #8
                Hello tkaboris,

                The error only lets me know that there was a problem with changing the order, I can't tell what part that may have been. For this type of error you would need to isolate the specific situation that causes that and the associated logic. Once you know what order the logic was executed in we could explore why that may be happening based on that finding.

                Its possible this could happen if you tried to execute multiple orders in the same bar using the same signal name. From the code provided I can't see what the problem may be.

                Comment


                  #9
                  i isolated all other code that may have conflicts and i still gave this error, only at this time it was StopCancelClose. I am attaching couple of screenshots and a short video and trace order file about what happens.

                  I cant figure out why it would do this occasionally. Please help. Thank you
                  my code for trail long
                  if (SetTrail )
                  {

                  if ((Position.MarketPosition == MarketPosition.Long && myFreeTradeLong == true)
                  && (ParabolicSAR1[0] <= Low[0]))
                  // && (ParabolicSAR1[0] > MySarStop))
                  {
                  if(MySarStop <= bid && (ParabolicSAR1[0] <= Low[0])){
                  MySarStop = ParabolicSAR1[0];
                  Print("step 2");
                  }
                  }

                  if (Position.MarketPosition == MarketPosition.Long )
                  {
                  // if(MySarStop <= bid){
                  ExitLongStopMarket(1, true, Position.Quantity, MySarStop, "SLL", "TML");
                  ExitLongLimit(1, true, Position.Quantity, Position.AveragePrice + (TickSize * TrailTakeProfit), "PTL", "TML");

                  Print("step 3");
                  // }
                  }​

                  Strategy 'TrendMagicAlgoAlgo/284764661' submitted an order that generated the following error 'Unable to change order'. Strategy has sent cancel requests, attempted to close the position and terminated itself.
                  Disabling NinjaScript strategy 'TrendMagicAlgoAlgo/284764661'
                  step 3
                  Strategy 'TrendMagicAlgoAlgo/284764661' submitted a cancellation request for Order ID 'orderId='b65cabea8a534881992cfe684bfb6bd3' account='Playback101' name='PTL' orderState=Working instrument='MNQ 09-23' orderAction=Sell orderType='Limit' limitPrice=15296 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=276732 time='2023-06-15 10:30:41' gtd='2099-12-01' statementDate='2023-06-15'' which has not been confirmed cancelled. Please check your account orders and positions.​

                  https://drive.google.com/file/d/1Zaw...ew?usp=sharing



                  Attached Files
                  Last edited by tkaboris; 07-14-2023, 05:00 AM.

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by NullPointStrategies, Yesterday, 05:17 AM
                  0 responses
                  64 views
                  0 likes
                  Last Post NullPointStrategies  
                  Started by argusthome, 03-08-2026, 10:06 AM
                  0 responses
                  139 views
                  0 likes
                  Last Post argusthome  
                  Started by NabilKhattabi, 03-06-2026, 11:18 AM
                  0 responses
                  75 views
                  0 likes
                  Last Post NabilKhattabi  
                  Started by Deep42, 03-06-2026, 12:28 AM
                  0 responses
                  45 views
                  0 likes
                  Last Post Deep42
                  by Deep42
                   
                  Started by TheRealMorford, 03-05-2026, 06:15 PM
                  0 responses
                  50 views
                  0 likes
                  Last Post TheRealMorford  
                  Working...
                  X