Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

moving a stoploss stop to breakeven

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

    moving a stoploss stop to breakeven

    I've tried to write some very basic code (most of which was taken from
    SamplePriceModification from support. The idea is to has a 5 tick stop which is changed
    to breakeven after a move of 10 ticks. The code is below. It doesn't work at all.

    protected override void OnBarUpdate()
    {

    // Resets the stop loss to the original value when all positions are closed
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss(CalculationMode.Ticks, stoplossticks);
    }
    else if (Position.MarketPosition == MarketPosition.Long)
    {

    if (Close[0] > Position.AvgPrice + 10 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
    }
    else if (Position.MarketPosition == MarketPosition.Short)
    {
    if (Close[0] < Position.AvgPrice - 10 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
    }
    }

    // Entry Condition: see below

    if (Close[0]>Close[1]&& (Median [0]>Median[1])&& enteredLong==false)
    {
    EnterLong();
    }
    if (Close[0]<Close[1]&& (Median [0]<Median[1])&& enteredShort==false)

    {
    EnterShort();

    }

    #2
    stephenszpak, what are the issue you face with this? Are no traded triggered at all, do you see any errors in the log? Are are the stops not trailed as you would expect? On which symbol and connection did you test this?

    For debugging your order behavior, we recommend using the TraceOrders feature -

    BertrandNinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Bertrand View Post
      stephenszpak, what are the issue you face with this? Are no traded triggered at all, do you see any errors in the log? Are are the stops not trailed as you would expect? On which symbol and connection did you test this?

      For debugging your order behavior, we recommend using the TraceOrders feature -

      http://www.ninjatrader-support2.com/...ead.php?t=3627
      Sorry Bertrand. No it didn't do anything. I thought it might be some obvious error.
      I must have hit F5 100 times in the past few days. Usually it compiles. Never did what
      I wanted so I tried to pretty much take support's SamplePriceModification and make
      that work. When I just did the long side as here:

      if (Close[0]>Close[1]&& (Median [0]>Median[1])&& enteredLong==false)
      {
      EnterLong();
      }
      ...I was getting the strategy to at least do something. I'll have to go back to that
      if you see nothing in TraceOrders below...just groping in the dark really. I've asked
      questions at a similar thread, but I haven't been able to understand the answers.



      I just used TraceOrders for the first time. This is what it gave me:
      (YM Market Replay of 12/11/2009 using Strategy "December 15th")

      Date,Category,Message,
      1/2/2010 7:32:39 AM,Strategy,Starting NinjaScript strategy 'December15th/baa4db5efd954c00917edeeb41270eb5' : On starting a real-time strategy - StrategySync=SubmitLive EntryHandling=AllEntries EntriesPerDirection=1 StopTargetHandling=PerEntryExecution ErrorHandling=StopStrategyCancelOrdersClosePositio ns ExitOnClose=True/ triggering 420 before close Set order quantity by=Strategy,


      1/2/2010 7:32:38 AM,Strategy,Starting NinjaScript strategy 'December15th/299f26675dc3467688f8337e2d81ddf5' : On starting a real-time strategy - StrategySync=SubmitLive EntryHandling=AllEntries EntriesPerDirection=1 StopTargetHandling=PerEntryExecution ErrorHandling=StopStrategyCancelOrdersClosePositio ns ExitOnClose=True/ triggering 420 before close Set order quantity by=Strategy,


      1/2/2010 7:26:58 AM,Strategy,Starting NinjaScript strategy 'December15th/ecaf3bd16c8e4cf89b2e84a4307a9a30' : On starting a real-time strategy - StrategySync=SubmitLive EntryHandling=AllEntries EntriesPerDirection=1 StopTargetHandling=PerEntryExecution ErrorHandling=StopStrategyCancelOrdersClosePositio ns ExitOnClose=True/ triggering 420 before close Set order quantity by=Strategy,

      Comment


        #4
        No worries Stephen - do you see Stop orders placed if you run the strategy? This would tell you your condition to move the stops does not trigger (is there a point where you're 10 ticks in profit) - Print statements throughout your code would help you here to see if the codes makes into sections you just assume it makes it. If you attach what you have as a zip I can give it a run quickly here.
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Bertrand

          You wrote: If you attach what you have as a zip I can give it a run quickly here.

          I'm taking you up on that. Be advised there is a lot of code commented out
          as I re-did this over and over. Also a number of useless variables. It did compile
          before I sent it.

          Thanks,

          - Stephen
          Attached Files

          Comment


            #6
            Ok Stephen, will check into it and report back what I spot.
            BertrandNinjaTrader Customer Service

            Comment


              #7
              Your code grouping did not allow for any trades to trigger, the attached should give you trades and a base to continue working from.
              Attached Files
              BertrandNinjaTrader Customer Service

              Comment


                #8
                Bertrand

                Thanks. It does what it's supposed to do, for a while. (I appreciate the help by
                the way a lot )
                Unfortunately it then crashes.

                I have enclosed 3 attachments. I'm quite sure I ran into the exact error
                many times before in writing this strategy. I still have no idea what causes it.
                Less of an idea how to fix it.
                I always use NoGapRange bars (written by another poster). I don't see why that
                would be the problem. Ran Market Replay on the chart enclosed from about 9:30 AM
                until the error, which was about 2 o'clock.

                (This is where I got it from should you have great need to look at it. I also might
                not be on-line for a couple days after extremely early Monday morning eastern U.S time.)

                The best futures trading community on the planet: futures trading, market news, trading charts, trading platforms, trading strategies



                Edit::::
                Original generic range bars provided by NT, also seem to
                generate the same problem. Also 15 Minute bars as well.


                mrlogik has suggested some coding. Do you feel such coding will help in this matter?
                (I would just try it, but I could spend 4 hours easy trying it and not really know if it's
                me not writing it correctly or whatever.)





                Any thoughts are valued,

                - Stephen
                Attached Files
                Last edited by stephenszpak; 01-03-2010, 06:28 PM.

                Comment


                  #9
                  Steph,

                  Just a quick thought without looking at the code based on the error you're seeing. Whenever you submit a stop or limit order, make sure you always use a price that incorporates both the bid and the ask.

                  For example, if you're going long you have to .

                  Code:
                  double vEntryLongPrice = Math.Max(Math.Max(GetCurrentBid(), GetCurrentAsk()), limit/stop price);
                  Opposite for short (Math.Min)

                  Hope this helps.
                  mrlogik
                  NinjaTrader Ecosystem Vendor - Purelogik Trading

                  Comment


                    #10
                    Originally posted by mrlogik View Post
                    Steph,

                    Just a quick thought without looking at the code based on the error you're seeing. Whenever you submit a stop or limit order, make sure you always use a price that incorporates both the bid and the ask.

                    For example, if you're going long you have to .

                    Code:
                    double vEntryLongPrice = Math.Max(Math.Max(GetCurrentBid(), GetCurrentAsk()), limit/stop price);
                    Opposite for short (Math.Min)

                    Hope this helps.

                    mrlogik

                    Thanks. I am not familiar with this coding but I appreciate the effort.

                    Comment


                      #11
                      mrlogik

                      Here is the code below if you still have time for input. Be advised that some
                      variables are not in use. (I haven't touched the code since Bertrand modified it.)
                      It seems reasonably straight forward.

                      I looked at your coding. Is your idea to take the higher value, bid or ask, and only
                      enter long if the higher of these is higher than the stop loss? If this is correct or
                      not, I still don't get it. Though I don't have any real ideas myself at this point.

                      - Stephen


                      Code:
                       #region Variables
                              // Wizard generated variables
                              // User defined variables (add any user defined variables below)
                      		
                      		bool enteredLong=false;
                      		bool enteredShort=false;
                      		private double SLPrice=0;
                      		private double TSPrice=0;
                      		private int	   trailingstopticks=5;
                      		private int		stoplossticks		= 5;
                      		//private IOrder goinglong1st=null;
                      		//private IOrder goinglong2nd=null;
                      		
                              #endregion
                      
                              /// <summary>
                              /// This method is used to configure the strategy and is called once before any strategy method is called.
                              /// </summary>
                              protected override void Initialize()
                              {
                      				//Always calculate on bar close!
                                  
                      			TraceOrders      = true;
                      			ExitOnClose=true;
                      			ExitOnCloseSeconds=420;
                      			SetStopLoss(CalculationMode.Ticks, stoplossticks);
                      			CalculateOnBarClose = true;
                      			
                      			
                      			
                                  
                              }
                      
                              /// <summary>
                              /// Called on each bar update event (incoming tick)
                              /// </summary>
                              protected override void OnBarUpdate()
                      			{
                      				
                      					
                      			if (Close[0]>Close[1]&& (Median [0]>Median[1])&& enteredLong==false)				
                      				EnterLong();			
                      					
                      			if (Close[0]<Close[1]&& (Median [0]<Median[1])&& enteredShort==false)
                      				EnterShort();
                      			
                      				// Resets the stop loss to the original value when all positions are closed
                      			if (Position.MarketPosition == MarketPosition.Flat)
                      			{
                      				SetStopLoss(CalculationMode.Ticks, stoplossticks);
                      			}			
                      			else if (Position.MarketPosition == MarketPosition.Long)
                      			{
                      			
                      				if (Close[0] > Position.AvgPrice + 10 * TickSize)
                      				{
                      					SetStopLoss(CalculationMode.Price, Position.AvgPrice);
                      				}
                      				else if (Position.MarketPosition == MarketPosition.Short)
                      			{
                      				if (Close[0] < Position.AvgPrice - 10 * TickSize)
                      				{
                      					SetStopLoss(CalculationMode.Price, Position.AvgPrice);
                      				}
                      			}
                      			
                      			}
                      			
                      	
                      	}

                      Comment


                        #12
                        Originally posted by stephenszpak View Post
                        Is your idea to take the higher value, bid or ask, and only enter long if the higher of these is higher than the stop loss?
                        Stephen, the idea is to submit the orders on the right side of the market so you don't get the errors you've been seeing. For example, a buy stop order cannot be placed below current market prices (just like the error says). So to get around this issue, you can check the current bid/ask price and make sure you place the order at the right price.

                        MrLogik's code just makes a comparison between three values (current ask, current bid, and the price you want to submit the order) and returns the largest value of the three.
                        AustinNinjaTrader Customer Service

                        Comment


                          #13
                          Hey Stephen,

                          I suspect some sort of race condition when

                          -->The break even is triggered
                          -->Trade is exited
                          -->New trade is entered before breakeven
                          -->Stoploss code uses Position.AvgPrice which is at the current price, hence an illegal order

                          I have attached an updated version of the code you posted to try and make this a little clearer. Its good practice to comment all if statements / code blocks for readability.

                          hope this helps.
                          Attached Files
                          mrlogik
                          NinjaTrader Ecosystem Vendor - Purelogik Trading

                          Comment


                            #14
                            Yes I see the comments. Thanks.

                            The " limit/stop price" you mentioned, I don't get. Austin calls it the "and the price you want to submit the order". Well, I want to submit the order instantly. I don't know the value
                            or command to put here.

                            Code:
                            	vEntryLongPrice = Math.Max(Math.Max(GetCurrentBid(), GetCurrentAsk()), ????);
                            								
                            			if (Close[0]>Close[1]&& (Median [0]>Median[1])&& enteredLong==false)
                            There does seem to be a race or conflict. Isn't there some way that after this is true:

                            if (Close[0]>Close[1]&& (Median [0]>Median[1]) and the previous position was either
                            flat or short...then flatten everything EnterLong() and not be concerned about
                            Math.Max(Math.Max(GetCurrentBid(), GetCurrentAsk()), etc etc etc

                            When I was doing something somewhat similar to this a while back. (Then I tried to
                            make stop loss go to breaeven then to trailing. )At this point I don't have that much
                            ambition. I think stop loss to breakeven would be fine.
                            ================================================== ============
                            Anyway Baruch suggested this:

                            The problem is that you are not in a position, so you don't have Position.AvgPrice.
                            You execute EnterLong(), but it takes time to enter a position and its not on OnBarUpdate() of a current bar.
                            As I said before, I don't use SetStoploss, and I advise you the same.
                            Use ExitLong() instead.




                            ================================================== ==============

                            I did try EnterLong() and tried to use ExitLong() to keep it very simple. I had problems
                            which I can't recall now. I'm hoping to find some answer to all this (someday). It all about
                            the coding. What I need is extremely simple at this point.

                            I'm done for a couple days here since I have stuff to do. Thanks to those who helped.

                            - Stephen
                            Last edited by stephenszpak; 01-04-2010, 12:18 AM.

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Skifree, Today, 03:41 AM
                            1 response
                            2 views
                            0 likes
                            Last Post Skifree
                            by Skifree
                             
                            Started by usazencort, Today, 01:16 AM
                            0 responses
                            1 view
                            0 likes
                            Last Post usazencort  
                            Started by kaywai, 09-01-2023, 08:44 PM
                            5 responses
                            603 views
                            0 likes
                            Last Post NinjaTrader_Jason  
                            Started by xiinteractive, 04-09-2024, 08:08 AM
                            6 responses
                            23 views
                            0 likes
                            Last Post xiinteractive  
                            Started by Pattontje, Yesterday, 02:10 PM
                            2 responses
                            23 views
                            0 likes
                            Last Post Pattontje  
                            Working...
                            X