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

2 entry orders help!

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

    #31
    Chelsea, that is a very interesting script. I learned new things.

    The use of Bool Variables/State.SetDefaults values
    PHP Code:
            ChaseProfitTarget  true;
            
    PrintDetails        false;                         
            
    TrailStopLoss        true;                     
            
    UseProfitTarget     true;
            
    UseStopLoss        true

    as Properties Region Variables
    PHP Code:
     #region Properties
    [NinjaScriptProperty]
    [
    Display(Name "Chase profit target"Order 2GroupName "NinjaScriptStrategyParameters")]
    public 
    bool ChaseProfitTarget
    getset; }

    [
    NinjaScriptProperty]
    [
    Display(Name "Print details"Order 7GroupName "NinjaScriptStrategyParameters")]
    public 
    bool PrintDetails
    getset; }

    [
    NinjaScriptProperty]
    [
    Display(Name "Trail stop loss"Order 5GroupName "NinjaScriptStrategyParameters")]
    public 
    bool TrailStopLoss
    getset; }

    [
    NinjaScriptProperty]
    [
    Display(Name "Use profit target"Order 1GroupName "NinjaScriptStrategyParameters")]
    public 
    bool UseProfitTarget
    getset; }

    [
    NinjaScriptProperty]
    [
    Display(Name "Use stop loss"Order 4GroupName "NinjaScriptStrategyParameters")]
    public 
    bool UseStopLoss
    getset; }
    #endregion 

    to create Checkboxes in the indicator Properties Windows (from the Chart window, Ctrl+I - attached image boolsascheckboxes).

    Then the use of a a List to store submitted and changed orders
    PHP Code:
    private List<Order>                    changeOrdersArraysubmitOrdersArray

    Then changing an order using it's limitPrice/stopPrice parameter value only (new way to change order)
    PHP Code:
    profitTargetOrder.LimitPriceChanged currentPtPrice
    PHP Code:
    stopLossOrder.StopPriceChanged        currentSlPrice
    ​​​​​​​
    Then the way the chase is made

    currentPtPrice = orderUpdateArgs.AverageFillPrice + ProfitTargetDistance * TickSize;

    profitTargetOrder = submissionAccount.CreateOrder(orderUpdateArgs.Orde r.Instrument, OrderAction.Sell, OrderType.Limit, OrderEntry.Automated,
    TimeInForce.Day, orderUpdateArgs.Quantity, currentPtPrice, 0, oco, "Profit Target", Core.Globals.MaxDate, null);

    if (ChaseProfitTarget && profitTargetOrder != null &&
    (profitTargetOrder.OrderState == OrderState.Accepted || profitTargetOrder.OrderState == OrderState.Working) &&
    Close[0] < currentPtPrice - ProfitTargetDistance * TickSize)
    {
    currentPtPrice = Close[0] + ProfitTargetDistance * TickSize;
    profitTargetOrder.LimitPriceChanged = currentPtPrice;
    changeOrdersArray.Add(profitTargetOrder);
    }

    ensuring the Target is only moved to the downside, by manipulating the currentPtPrice variable.
    For example:
    The Target is set to EntryPrice + 10 Ticks initially.
    Then Price must move below EntryPrice to lower currentPrice as much.
    Then Price must move below Price at the time/level of previous currentPrice change for currentPrice to change again.

    How did you arrive at this algorithm? What principles did you use? it seems obvious but it's not for the uninitiated. it dizzies the forehead.
    ProfitTargetDistance
    currentPrice
    profitTargetOrder

    I see you keep ProfitTargetDistance constant, and use the Close[0] down ticks in reference to itself to move down exclusively the profitTargetOrder order. That I understand.

    I'm thinking it is some sort of cyclical algorithm/reasoning you use. How do you see the cyclical part of if before you code it? I'm struggling a lot with that part, so much so that I have to commit to memory the form of it to keep a hint/prompt of it as arbitrary figure to recall when needing that sort of "cyclical" algorithm, but I cannot "see it work" first and then code it myself.
    How do you yourself "see it work" first and then code it?

    I mean what training specifically made you able to derive that cyclical multiple layers processes operations condensed into one? Is there a specific Computer Science domain that trains that multiple / condensed operations "reasoning"? You condensed things that aren't seeming to go "well" together. And it's not just about algebra, nor just about rote experience/reading many scripts.

    I know the close is the key, i.e. that's the variable that will be used to move the Target (that's the basic idea that will need to be used anyway you turn the problem).
    I know currentPrice is the Target's order limitPrice variable so that will also need to be used to move the Target.
    What I don't know/I can't foresee is


    How do you/what do you do to see the cycle before coding it? What do you "train" to "think/see" the cycle in code. Is there a computer science domain that can train that cyclical reasoning? How do you personally approach the problem? Do you draw coordinates on some graph? Do you use some sort of flow chart? Do you use the number/numerical computation to derive the right formula? Do you use an app? Anything else?

    I managed to reproduce the steps for 2 down moves in a formula in cyclicalalgo attached picture but it's not enough to get the cyclical concept out of it.

    Thanks!


    Comment


      #32
      Hello PaulMohn,

      "How did you arrive at this algorithm? What principles did you use?"

      This seems like a simple question.. but I'm finding myself unable to answer.

      Its like asking someone how they drive a car. Its looking at the road seeing where you want to be and adjusting the steering wheel to point in that direction.

      To start, I write down explicitly the behavior I want to achieve. Like submit entry if flat, when entry fills submit stop and limit at preset distance, then after x many ticks of loss or gain set limit or stop to n distance.
      I didn't really start with anything else, just the rules of how C# works, order of operations which always needs to be in mind, and the documentation for working with NinjaScript properties as defined in the help guide.

      Unfortunately, our NinjaScript Engineering Support team does not get a lot guidance from development unless there is a glaring issue that needs to be resolved. Most of our examples come from seeing a need for an example to exist and conjuring one up.

      Thinking cyclically, OnBarUpdate() is the cycle. Its what's revolving that we run our code on each pass. So the next data is coming in, we check those numbers and see if the distance has been traveled since the last cycle.

      "Is there a specific Computer Science domain that trains that multiple / condensed operations "reasoning"? You condensed things that aren't seeming to go "well" together"

      What specifically doesn't seem to go together?

      I'm not actually sure what you are asking here. But I think in terms of explicit steps. To make my bed, i have to move my body to the foot of the bed, then extend right arm forward 1 foot, right 2 feet, and down 2 feet, then close hand to grasp sheet, the raise arm to pull corner of sheet up.... and it goes on until each step is completed in order removing the old sheet first, taking a new, and pulling the corners down. Just a sequence of explicit steps.

      Possibly the most difficult part is explicitly knowing the behavior you want to see.


      Close is the current price (either at the time a bar closes if Calculate.OnBarClose, or intra-bar with Calculate.OnEachTick or OnPriceChange). I'm working with the current price as I don't need the specific ask or bid from OnMarketData since I'm not working with volume or buy sell pressure or anything.
      Chelsea B.NinjaTrader Customer Service

      Comment


        #33
        Thanks for the illustrations and tips! It still seems there's more to it than sheer unconscious competence, though it must be a semi conscious steps outline after some point in the reduction.

        I suspect you must know some things I don't know about cycling the algorithm in your foresight before committing that vision to script formulation.

        Do you still have your notes about the script? How specifically did you "see work" the transition from
        currentPtPrice = AverageFillPrice + ProfitTargetDistance (1st cycle in Close[0] < currentPtPrice - ProfitTargetDistance * TickSize) to
        currentPtPrice = Close[0] + ProfitTargetDistance (2nd cycle in Close[0] < currentPtPrice - ProfitTargetDistance * TickSize) to then
        currentPtPrice = Close[0] + ProfitTargetDistance (for all subsequent cycles)?

        What doesn't seem to go "well together" is all the subsequent cycles after the 2nd one to derive that the Close[0] values required for it to work must be less than the previous "stored" ones. I had to draw the coordinates on a paper graph to "see it work" (currentPtPrice doesn't change when Close[0] upticks back above its prior values after the 2nd cycle).

        The fact that you can derive all subsequent cycles is the foresight escaping part, and how it links to the first 2 cycles is also dizzying the forehead (cycles interrelations vs linear/parallels extrapolation). That is, how do you usually derive it will work for all up and down tick of the Close[0]? Do you "see work" cycle 1, then 2, then 3, then 4 etc. before generalizing the formula? Or do you use a known cyclical algorithm you refer to to "know" it does work for all cases?

        I would have thought (much lesser experienced that I am, but then I don't have that cyclical algorithm training I suspect you must have been made familiar to at some point, maybe some special algorithmic design training?) of storing the Close[0] since entry values and checking for new min/low/down ticks values to move the Target in reference to. But your way to do it seems a lot shorter/less efforts prone (but the downside with it is you can't easily see/outline the steps and their relations, a bit like with complex loops), provided you know how to "see work" the cyclical algorithm, not just the linear one (if you don't, you have to memorize the working figure without "seeing it work/understanding it yourself", knowing that it works and you can use it as arbitrary sign with no meaning, just known function), also the principle of reusability of already used variables we can't do without is better at work with your approach/less variables used (I think you couldn't reduce their number any further than with your approach).
        I'll try and look for resources to cyclical programming concepts if I can find some. Thanks!
        Last edited by PaulMohn; 05-11-2022, 03:59 PM.

        Comment


          #34
          Hello PaulMohn,

          When the entry fills, the average fill price is the entry point. This is used for the initial distance for the order. Then for the trailing action this is based on how far the current price has travelled.

          On each new bar update, if the current price is more ticks in distance, then the order price is moved toward the current price by the number of ticks.

          Check if close is greater than the current stop price plus number of ticks.
          Close[0] > currentSlPrice + StopLossDistance * TickSize

          If it is, set stop price to current price minus number of ticks
          currentSlPrice = Close[0] - StopLossDistance * TickSize;

          I don't see this as a cyclical algorithm.. the conditions are simply checked each time the bar updates.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #35
            Hello Chelsea, and thanks for the tips! I'll check it out later.
            I've tried several modifications to the indicator.
            I've added the following KeyDown trigger event that works and submit the entryBuyMar****rder.
            PHP Code:
                  else if (State == State.DataLoaded)
                  {
                    
            submissionAccount Account.All.FirstOrDefault(=> a.Name == "Sim101");

                    if (
            submissionAccount != null)
                      
            submissionAccount.OrderUpdate += Account_OrderUpdate;

                    if (
            ChartControl != null)
                    {
                      
            ChartControl.PreviewKeyDown += ChartControl_PreviewKeyDown;    
                    }
                  }
                  else if (
            State == State.Terminated)
                  {
                    if (
            submissionAccount != null)
                      
            submissionAccount.OrderUpdate -= Account_OrderUpdate;

                    if (
            ChartControl != null)
                    {
                      
            ChartControl.PreviewKeyDown -= ChartControl_PreviewKeyDown;    
                    }
                  }


                protected 
            void ChartControl_PreviewKeyDown(object senderKeyEventArgs e)
                {
                  
            TriggerCustomEvent(=>
                  {
                    
            Order entryBuyMar****rder null;

                    if (
            Keyboard.IsKeyDown(Key.NumPad1))
                    {
                      
            entryBuyMar****rder submissionAccount.CreateOrder(
                          
            Instrument,
                          
            OrderAction.Buy,
                          
            OrderType.Market,
                          
            OrderEntry.Manual,
                          
            TimeInForce.Day,
                          
            1,
                          
            0,
                          
            0,
                          
            string.Empty,
                          
            "Entry",
                          
            Core.Globals.MaxDate,
                          
            null);
                    }

                    
            submissionAccount.Submit(new[] { entryBuyMar****rder });

                  }, 
            null);
                  
            e.Handled true;
                } 


            Trying to check why the KeyDown Event is not picked up by either the Account_OrderUpdate() method or/and the OnBarUpdate() method,
            I've added prints to the Account_OrderUpdate() (highlighted in blue)
            private void Account_OrderUpdate(object sender, OrderEventArgs orderUpdateArgs)
            {
            Print("orderUpdateArgs.AverageFillPrice : " + orderUpdateArgs.AverageFillPrice);
            Print("profitTargetOrder : " + profitTargetOrder);
            Print("currentPtPrice : " + currentPtPrice);
            Print("stopLossOrder : " + stopLossOrder);


            Print("entryBuyMar****rder : " + entryBuyMar****rder);

            if (entryBuyMar****rder != null && entryBuyMar****rder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Filled)
            {
            string oco = Guid.NewGuid().ToString("N");
            submitOrdersArray = new List<Order>();

            if (UseProfitTarget)
            {
            currentPtPrice = orderUpdateArgs.AverageFillPrice + ProfitTargetDistance * TickSize;

            if (PrintDetails)
            Print(string.Format("{0} | Account_OrderUpdate | placing profit target | currentPtPrice: {1}", orderUpdateArgs.Time, currentPtPrice));

            profitTargetOrder = submissionAccount.CreateOrder(orderUpdateArgs.Orde r.Instrument, OrderAction.Sell, OrderType.Limit, OrderEntry.Automated, TimeInForce.Day, orderUpdateArgs.Quantity, currentPtPrice, 0, oco, "Profit Target", Core.Globals.MaxDate, null);
            submitOrdersArray.Add(profitTargetOrder);
            }

            if (UseStopLoss)
            {
            currentSlPrice = orderUpdateArgs.AverageFillPrice - StopLossDistance * TickSize;

            if (PrintDetails)
            Print(string.Format("{0} | Account_OrderUpdate | placing stop loss | currentSlPrice: {1}", orderUpdateArgs.Time, currentSlPrice));

            stopLossOrder = submissionAccount.CreateOrder(orderUpdateArgs.Orde r.Instrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, orderUpdateArgs.Quantity, 0, currentSlPrice, oco, "Stop Loss", Core.Globals.MaxDate, null);
            submitOrdersArray.Add(stopLossOrder);
            }

            submissionAccount.Submit(submitOrdersArray);
            }

            // once the exit orders are closed, reset for a new entry.
            else if ((profitTargetOrder != null && (profitTargetOrder.OrderState == OrderState.Filled || profitTargetOrder.OrderState == OrderState.Rejected || profitTargetOrder.OrderState == OrderState.Cancelled)) || (stopLossOrder != null && (stopLossOrder.OrderState == OrderState.Filled || stopLossOrder.OrderState == OrderState.Rejected || stopLossOrder.OrderState == OrderState.Cancelled)))
            {
            entryBuyMar****rder = null;
            profitTargetOrder = null;
            stopLossOrder = null;
            }
            }

            with Prints results as
            orderUpdateArgs.AverageFillPrice : 0
            profitTargetOrder :
            currentPtPrice : 0
            stopLossOrder :
            entryBuyMar****rder :
            orderUpdateArgs.AverageFillPrice : 0
            profitTargetOrder :
            currentPtPrice : 0
            stopLossOrder :
            entryBuyMar****rder :
            orderUpdateArgs.AverageFillPrice : 0
            profitTargetOrder :
            currentPtPrice : 0
            stopLossOrder :
            entryBuyMar****rder :
            orderUpdateArgs.AverageFillPrice : 0
            profitTargetOrder :
            currentPtPrice : 0
            stopLossOrder :
            entryBuyMar****rder :
            orderUpdateArgs.AverageFillPrice : 106.54
            profitTargetOrder :
            currentPtPrice : 0
            stopLossOrder :
            entryBuyMar****rder :


            and made the following reductions in the OnBarUpdate() method (highlighted in red)
            protected override void OnBarUpdate()
            {
            if (State != State.Realtime)
            return;

            // check if the account position for this instrument is flat, if so submit entry

            if (submissionAccount != null && submissionAccount.Positions.Where(o => o.Instrument == Instrument).Count() > 0)
            accountPosition = submissionAccount.Positions.Where(o => o.Instrument == Instrument).Last();
            else
            accountPosition = null;

            if (accountPosition == null || accountPosition.MarketPosition == MarketPosition.Flat)
            // if (entryBuyMar****rder != null && entryBuyMar****rder.OrderState == OrderState.Filled)

            {
            changeOrdersArray = new List<Order>();

            if (profitTargetOrder != null &&
            (profitTargetOrder.OrderState == OrderState.Accepted || profitTargetOrder.OrderState == OrderState.Working)
            )
            {
            currentPtPrice = Close[0] + ProfitTargetDistance * TickSize;
            profitTargetOrder.LimitPriceChanged = currentPtPrice;
            changeOrdersArray.Add(profitTargetOrder);

            if (PrintDetails)
            Print(string.Format("{0} | OOU | chasing target, currentPtPrice: {1}", Time[0], currentPtPrice));
            }

            if (stopLossOrder != null &&
            (stopLossOrder.OrderState == OrderState.Accepted || stopLossOrder.OrderState == OrderState.Working)
            )
            {
            currentSlPrice = Close[0] - StopLossDistance * TickSize;
            stopLossOrder.StopPriceChanged = currentSlPrice;
            changeOrdersArray.Add(stopLossOrder);

            if (PrintDetails)
            Print(string.Format("{0} | OOU | trailing stop, currentPtPrice: {1}", Time[0], currentSlPrice));
            }

            if (changeOrdersArray.Count() > 0)
            submissionAccount.Change(changeOrdersArray);
            }
            }



            The prints show entryBuyMar****rder / orderUpdateArgs.AverageFillPrice : 106.54 value does get picked up by the Account_OrderUpdate() method, but that's the only value that does.
            And the profitTargetOrder and stopLossOrder orders don't get sumbited.

            Then the OnBarUpdate() doesn't get a chance to operations since the profitTargetOrder and stopLossOrder orders don't get sumbited.

            Any Idea why the profitTargetOrder and stopLossOrder orders don't get triggered?
            Please find attached the script MyOCOKeyEvent1.zip
            Thanks!


            I thought of adding a condition in the OnBarUpdate modified If statement to check if the KeyDown method is true but I don't know if that would help nor how I can check a Key event with a bool.









            Attached Files

            Comment


              #36
              Hello PaulMohn,

              What is the line code that is not being reached?

              Print all values used in the condition that triggers the action one line above the condition.

              Below is a link to a forum post that demonstrates how to use prints to understand behavior.


              Chelsea B.NinjaTrader Customer Service

              Comment


                #37
                I also got a 2nd version of the script more in line with my end use.
                My end use would be to add multiple KeyDown events to customize multiple Targets and Stops orders moves presets.

                I reduced the script down a lot. Please see MyOCOKeyEvent2.zip
                The script works and does sumbit correct OCO Target and Sopt orders for the 1st KeyDown Even with multiple actions separated by pauses. But not for the 2nd KeyDown Event separated snippet. And Also it seems that as is the script sometime crashes or misubmit the 1st trade sometimes (I suspect it's due to the potential not proper reset of the orders list).

                Here're both the KeyDown events snippet.
                protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                {
                // 1st KeyDown Event: NumPad key 1 Press = Sumbit MktBuyOrder

                TriggerCustomEvent(o =>
                {
                Order entryBuyMar****rder = null;

                if (Keyboard.IsKeyDown(Key.NumPad1))
                {
                entryBuyMar****rder = submissionAccount.CreateOrder(
                Instrument,
                OrderAction.Buy,
                OrderType.Market,
                OrderEntry.Manual,
                TimeInForce.Day,
                1,
                0,
                0,
                string.Empty,
                "Entry",
                Core.Globals.MaxDate,
                null);
                }

                submissionAccount.Submit(new[] { entryBuyMar****rder });

                Task.Delay(200).Wait(); // wait 300ms

                // Set The Target Order

                string oco = Guid.NewGuid().ToString("N");
                submitOrdersArray = new List<Order>();

                currentPtPrice = entryBuyMar****rder.AverageFillPrice + ProfitTargetDistance * TickSize;

                profitTargetOrder = submissionAccount.CreateOrder(Instrument, OrderAction.Sell, OrderType.Limit, OrderEntry.Manual,
                TimeInForce.Day, entryBuyMar****rder.Quantity, currentPtPrice, 0, oco, "Profit Target", Core.Globals.MaxDate, null);
                submitOrdersArray.Add(profitTargetOrder);

                submissionAccount.Submit(submitOrdersArray);


                Task.Delay(200).Wait(); // wait 300ms

                // Move The Target Order

                changeOrdersArray = new List<Order>();

                currentPtPrice = entryBuyMar****rder.AverageFillPrice + (ProfitTargetJump * TickSize);

                profitTargetOrder.LimitPriceChanged = currentPtPrice;

                changeOrdersArray.Add(profitTargetOrder);

                submissionAccount.Change(changeOrdersArray);


                Task.Delay(200).Wait(); // wait 300ms

                // Set the Stop Order

                currentSlPrice = entryBuyMar****rder.AverageFillPrice - StopLossDistance * TickSize;

                stopLossOrder = submissionAccount.CreateOrder(Instrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Manual,
                TimeInForce.Day, entryBuyMar****rder.Quantity, 0, currentSlPrice, oco, "Stop Loss", Core.Globals.MaxDate, null);
                submitOrdersArray.Add(stopLossOrder);

                submissionAccount.Submit(submitOrdersArray);

                }, null);
                e.Handled = true;

                Print("profitTargetOrder.LimitPrice : " + profitTargetOrder.LimitPrice);
                Print("profitTargetOrder.LimitPrice : " + (profitTargetOrder.LimitPrice + (2 * TickSize)));
                Print("currentPtPrice : " + currentPtPrice);
                Print("changeOrdersArray.Count() : " + changeOrdersArray.Count());


                // 2nd KeyDown Event: NumPad key 1 Press = Sumbit MktBuyOrder
                // Move the Target Order again (independantly of the 1st KeyDown Event
                //(problem is the
                TriggerCustomEvent(p =>
                {
                if (Keyboard.IsKeyDown(Key.NumPad4))
                {
                changeOrdersArray = new List<Order>();

                currentPtPrice = profitTargetOrder.LimitPrice + (2 * TickSize);

                profitTargetOrder.LimitPriceChanged = currentPtPrice;

                changeOrdersArray.Add(profitTargetOrder);

                submissionAccount.Change(changeOrdersArray);

                }
                }, null);
                e.Handled = true;


                }

                I focused on adding a 2nd KeyDown event snippet to trigger a move of +2 ticks higher than the current Target price, upon the Keypress (NumPad4) it throws this error

                Error on triggering custom event for NinjaScript 'MyOCOKeyEvent2' on bar 5307: Object reference not set to an instance of an object.
                I also added a 1st order move in the 1st KeyDown event to check that it worked and it does (no errors).

                I then tried calling an external method to see if it would work but it doesn't
                PHP Code:
                    private void MoveTPAway()
                    {
                      foreach (
                Account acct in Account.All)
                      {
                        if (
                acct.Positions != null)
                        {
                          foreach (
                Position pos in acct.Positions)
                          {
                            if (
                pos.MarketPosition == MarketPosition.Long)
                            {
                              
                lock (submissionAccount.Orders)
                              {
                                foreach (
                Order moveTPOrder1 in submissionAccount.Orders)
                                {
                                  
                moveTPOrder1.LimitPriceChanged moveTPOrder1.LimitPrice + (TickSize);
                                  
                submissionAccount.Change(new[] { moveTPOrder1 });
                                }
                              }
                            }
                            else if (
                pos.MarketPosition == MarketPosition.Short)
                            {
                              
                lock (submissionAccount.Orders)
                              {
                                foreach (
                Order moveTPOrder1 in submissionAccount.Orders)
                                {
                                  
                moveTPOrder1.LimitPriceChanged moveTPOrder1.LimitPrice - (TickSize);
                                  
                submissionAccount.Change(new[] { moveTPOrder1 });
                                }
                              }
                            }
                          }
                        }
                      }
                    }

                =======

                      
                TriggerCustomEvent(=>
                      {
                        if (
                Keyboard.IsKeyDown(Key.NumPad4))
                        {
                            
                MoveTPAway();
                        }
                      }, 
                null);
                      
                e.Handled true

                Any idea on how to get the 2nd KeyDown Event to pick up the Target order?
                And how to check why the script can be unstable (submit the 1st order incorrectly at times)? Thanks!
                Attached Files

                Comment


                  #38
                  Originally posted by NinjaTrader_ChelseaB View Post
                  Hello PaulMohn,

                  What is the line code that is not being reached?

                  Print all values used in the condition that triggers the action one line above the condition.

                  Below is a link to a forum post that demonstrates how to use prints to understand behavior.

                  I just tried printing the folowing in the OnBarUpdate()

                  Prints
                  PHP Code:
                  protected override void OnBarUpdate()
                  {
                  // Print("orderUpdateArgs.AverageFillPrice : " + orderUpdateArgs.AverageFillPrice);
                  Print("profitTargetOrder : " profitTargetOrder);
                  Print(
                  "currentPtPrice : " currentPtPrice);
                  Print(
                  "stopLossOrder : " stopLossOrder);

                  Print(
                  "entryBuyMar****rder : " entryBuyMar****rder);
                  Print(
                  "accountPosition : " accountPosition);
                  Print(
                  "submissionAccount : " submissionAccount);
                  Print(
                  "changeOrdersArray : " changeOrdersArray);
                  Print(
                  "currentSlPrice : " currentSlPrice);
                  Print(
                  "**** : "); 
                  Results
                  profitTargetOrder :
                  currentPtPrice : 0
                  stopLossOrder :
                  entryBuyMar****rder :
                  accountPosition :
                  submissionAccount : Sim101
                  changeOrdersArray : System.Collections.Generic.List`1[NinjaTrader.Cbi.Order]
                  currentSlPrice : 0
                  **** :

                  Here the Prints in the Account_OrderUpdate() method

                  PHP Code:
                  private void Account_OrderUpdate(object senderOrderEventArgs orderUpdateArgs)
                  {
                  // Print("orderUpdateArgs.AverageFillPrice : " + orderUpdateArgs.AverageFillPrice);
                  // Print("profitTargetOrder : " + profitTargetOrder);
                  // Print("currentPtPrice : " + currentPtPrice);
                  // Print("stopLossOrder : " + stopLossOrder);

                  // Print("entryBuyMar****rder : " + entryBuyMar****rder);


                  Print("orderUpdateArgs.AverageFillPrice : " orderUpdateArgs.AverageFillPrice);
                  Print(
                  "profitTargetOrder : " profitTargetOrder);
                  Print(
                  "currentPtPrice : " currentPtPrice);
                  Print(
                  "stopLossOrder : " stopLossOrder);

                  Print(
                  "entryBuyMar****rder : " entryBuyMar****rder);
                  Print(
                  "accountPosition : " accountPosition);
                  Print(
                  "submissionAccount : " submissionAccount);
                  Print(
                  "changeOrdersArray : " changeOrdersArray);
                  Print(
                  "currentSlPrice : " currentSlPrice);
                  Print(
                  "**** : "); 
                  **** :
                  orderUpdateArgs.AverageFillPrice : 105.81
                  profitTargetOrder :
                  currentPtPrice : 0
                  stopLossOrder :
                  entryBuyMar****rder :
                  accountPosition :
                  submissionAccount : Sim101
                  changeOrdersArray : System.Collections.Generic.List`1[NinjaTrader.Cbi.Order]
                  currentSlPrice : 0
                  **** :
                  The only value that get's printed
                  orderUpdateArgs.AverageFillPrice : 105.81


                  I think that's all the values I can print. Any another tip? Thanks!

                  Comment


                    #39
                    Hello PaulMohn,

                    What is the line of code not being reached?

                    You said a stop and target not being submitted. I'm guessing this is not in OnBarUpdate but is likely in the Account.OrderUpdate event handler. Is that line of code being reached?

                    What is the condition that triggers the stop and limit to be submitted?

                    Instead providing a lot of information, try and focus on one thing at a time. One line of code, one condition.
                    Last edited by NinjaTrader_ChelseaB; 05-29-2022, 06:38 PM.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #40
                      Ah ok thanks for the precision.

                      I just printed more just above the Account.OrderUpdate event handler method

                      The results:

                      **** :
                      orderUpdateArgs.Order.OrderState : Working
                      submitOrdersArray :
                      orderUpdateArgs.AverageFillPrice : 106.07
                      profitTargetOrder :
                      currentPtPrice : 0
                      stopLossOrder :
                      entryBuyMar****rder :
                      accountPosition :
                      submissionAccount : Sim101
                      changeOrdersArray : System.Collections.Generic.List`1[NinjaTrader.Cbi.Order]
                      currentSlPrice : 0
                      **** :
                      orderUpdateArgs.Order.OrderState : Filled
                      submitOrdersArray :
                      ### :
                      UseProfitTarget : True
                      UseStopLoss : True


                      I think this time those are all the variables I can print.
                      There's only the orderUpdateArgs.AverageFillPrice : 106.07 that return a value.
                      And the orderUpdateArgs.Order.OrderState : Filled that tells the order got filled.
                      And the UseProfitTarget and UseStopLoss that show up as true (I did check the checkboxes).


                      The prints I used
                      PHP Code:
                      private void Account_OrderUpdate(object senderOrderEventArgs orderUpdateArgs)
                      {
                      Print(
                      "orderUpdateArgs.AverageFillPrice : " orderUpdateArgs.AverageFillPrice);
                      Print(
                      "profitTargetOrder : " profitTargetOrder);
                      Print(
                      "currentPtPrice : " currentPtPrice);
                      Print(
                      "stopLossOrder : " stopLossOrder);

                      Print(
                      "entryBuyMar****rder : " entryBuyMar****rder);
                      Print(
                      "accountPosition : " accountPosition);
                      Print(
                      "submissionAccount : " submissionAccount);
                      Print(
                      "changeOrdersArray : " changeOrdersArray);
                      Print(
                      "currentSlPrice : " currentSlPrice);
                      Print(
                      "**** : ");
                      Print(
                      "orderUpdateArgs.Order.OrderState : " orderUpdateArgs.Order.OrderState);
                      Print(
                      "submitOrdersArray : " submitOrdersArray);
                      // Print("oco : " + oco);

                      Print("### : ");
                      Print(
                      "UseProfitTarget : " UseProfitTarget);
                      Print(
                      "UseStopLoss : " UseStopLoss); 

                      I'm still not sure what is preventing the Target and the Stop from being triggered. Any mode suggestion? Thanks!

                      Comment


                        #41
                        Ah i think I found something.
                        orderUpdateArgs.Order.OrderState : Working
                        it says working but the condition requires filled
                        if (entryBuyMar****rder != null && entryBuyMar****rder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Filled)
                        {

                        Also I'm not sure if I can Print this orderUpdateArgs.Order. I'll test and see if it returns entryBuyMar****rder. Thanks!

                        It returns
                        orderUpdateArgs.Order : orderId='9ee34f7d61a740b290c0ea349bd4f313' account='Sim101' name='Entry' orderState=Filled instrument='CL 06-22' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Day oco='' filled=1 averageFillPrice=106.33 onBehalfOf='' id=389 time='2022-05-12 20:33:40' gtd='2099-12-01' statementDate='2022-05-12'

                        I'm not sure if it satisfies this condition entryBuyMar****rder == orderUpdateArgs.Order. How do I check? Thanks!

                        It does show
                        limitPrice=0 stopPrice=0
                        Is it normal? Since the prints occur before the Target and Stop action snippets? Thanks!
                        Last edited by PaulMohn; 05-12-2022, 12:37 PM.

                        Comment


                          #42
                          I tested using orderUpdateArgs.Order.OrderState == OrderState.Working (Working instead of Filled)
                          PHP Code:
                          private void Account_OrderUpdate(object senderOrderEventArgs orderUpdateArgs)
                          {
                          Print(
                          "orderUpdateArgs.AverageFillPrice : " orderUpdateArgs.AverageFillPrice);
                          Print(
                          "profitTargetOrder : " profitTargetOrder);
                          Print(
                          "currentPtPrice : " currentPtPrice);
                          Print(
                          "stopLossOrder : " stopLossOrder);

                          Print(
                          "entryBuyMar****rder : " entryBuyMar****rder);
                          Print(
                          "accountPosition : " accountPosition);
                          Print(
                          "submissionAccount : " submissionAccount);
                          Print(
                          "changeOrdersArray : " changeOrdersArray);
                          Print(
                          "currentSlPrice : " currentSlPrice);
                          Print(
                          "**** : ");
                          Print(
                          "orderUpdateArgs.Order.OrderState : " orderUpdateArgs.Order.OrderState);
                          Print(
                          "submitOrdersArray : " submitOrdersArray);
                          // Print("oco : " + oco);

                          Print("### : ");
                          Print(
                          "UseProfitTarget : " UseProfitTarget);
                          Print(
                          "UseStopLoss : " UseStopLoss);
                          Print(
                          "orderUpdateArgs.Order : " orderUpdateArgs.Order);

                          if (
                          entryBuyMar****rder != null && entryBuyMar****rder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Working)


                          ### :
                          UseProfitTarget : True
                          UseStopLoss : True
                          orderUpdateArgs.Order : orderId='845e020fc5b3424c8aace5cec770673d' account='Sim101' name='Entry' orderState=Working instrument='CL 06-22' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Day oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=399 time='2022-05-12 21:08:41' gtd='2099-12-01' statementDate='2022-05-12'
                          orderUpdateArgs.AverageFillPrice : 106.26
                          profitTargetOrder :
                          currentPtPrice : 0
                          stopLossOrder :
                          entryBuyMar****rder :
                          accountPosition :
                          submissionAccount : Sim101
                          changeOrdersArray : System.Collections.Generic.List`1[NinjaTrader.Cbi.Order]
                          currentSlPrice : 0
                          **** :
                          orderUpdateArgs.Order.OrderState : Filled
                          submitOrdersArray :
                          ### :
                          UseProfitTarget : True
                          UseStopLoss : True
                          orderUpdateArgs.Order : orderId='845e020fc5b3424c8aace5cec770673d' account='Sim101' name='Entry' orderState=Filled instrument='CL 06-22' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Day oco='' filled=1 averageFillPrice=106.26 onBehalfOf='' id=399 time='2022-05-12 21:08:41' gtd='2099-12-01' statementDate='2022-05-12'
                          but it's not submitting the Target and Stop orders. What would be next to try? Thanks!
                          Have a good evening! I'll be back tomorrow.

                          Comment


                            #43
                            Hello PaulMohn,

                            What is the condition that triggers the stop and limit to be submitted?

                            Please only reply with just the condition and nothing else.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #44
                              if (entryBuyMar****rder != null && entryBuyMar****rder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Filled)
                              {
                              if (UseProfitTarget)
                              {
                              //Trigger the limit order action
                              }

                              if (UseStopLoss)
                              {
                              //Trigger the stop order action
                              }
                              }
                              Last edited by PaulMohn; 05-13-2022, 01:12 AM.

                              Comment


                                #45
                                Chelsea I just discovered you can check if an equation or inequation (I guess an inequality also) result is true with the prints (I thought previously you could only get numerical values from prints).

                                I printed the condition's 4 element equations:

                                Results:
                                True
                                2 : False
                                3 : True
                                4 : False
                                Prints:

                                PHP Code:
                                Print("1 : " entryBuyMar****rder != null);

                                Print(
                                "2 : " + (entryBuyMar****rder == orderUpdateArgs.Order));

                                Print(
                                "3 : " + (orderUpdateArgs.Order.OrderState == OrderState.Filled));

                                Print(
                                "4 : " + (orderUpdateArgs.Order.OrderState == OrderState.Working));


                                if (
                                entryBuyMar****rder != null && entryBuyMar****rder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Filled)


                                For some reason entryBuyMar****rder == orderUpdateArgs.Order and orderUpdateArgs.Order.OrderState == OrderState.Working return false.

                                So I tested only as
                                if (entryBuyMar****rder != null && orderUpdateArgs.Order.OrderState == OrderState.Filled)
                                {

                                but it still doesn't trigger the Target and StopLoss.

                                I also tested with only
                                if (entryBuyMar****rder != null)
                                {

                                Still not Target and StopLoss.


                                I guess entryBuyMar****rder == orderUpdateArgs.Order must be used and TRUE for the Target and StopLoss to trigger. Is that so? If so, could you please explain what it means as I'm not sure I understand it correctly.

                                I suspect my ChartControl_PreviewKeyDown(object sender, KeyEventArgs e) method KeyDown event doesn't get picked up by your Event handler method private void Account_OrderUpdate(object sender, OrderEventArgs orderUpdateArgs). If so, why? I can't see why since your Event Handler method does pick up the BuyMKrt order from the OnBarUpdate() method in you original script. So it should also work for my KeyDown method.

                                Also, line 123-4 of your script you say
                                // the name of the order must be Entry or the order will get stuck in the intialize state
                                entryBuyMar****rder = submissionAccount.CreateOrder(Instrument, OrderAction.Buy, OrderType.Market, OrderEntry.Automated, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", Core.Globals.MaxDate, null);


                                I did name the order "Entry" in my Created order as
                                PHP Code:
                                    protected void ChartControl_PreviewKeyDown(object senderKeyEventArgs e)
                                    {
                                      
                                TriggerCustomEvent(=>
                                      {
                                        
                                Order entryBuyMar****rder null;

                                        if (
                                Keyboard.IsKeyDown(Key.NumPad1))
                                        {
                                          
                                entryBuyMar****rder submissionAccount.CreateOrder(
                                              
                                Instrument,
                                              
                                OrderAction.Buy,
                                              
                                OrderType.Market,
                                              
                                OrderEntry.Manual,
                                              
                                TimeInForce.Day,
                                              
                                1,
                                              
                                0,
                                              
                                0,
                                              
                                string.Empty,
                                              
                                "Entry",
                                              
                                Core.Globals.MaxDate,
                                              
                                null);
                                        }

                                        
                                submissionAccount.Submit(new[] { entryBuyMar****rder });

                                      }, 
                                null);
                                      
                                e.Handled true;
                                    } 

                                So I can't see where the issue lies. Please shed some light on what the issue is. Thanks!

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Segwin, 05-07-2018, 02:15 PM
                                14 responses
                                1,789 views
                                0 likes
                                Last Post aligator  
                                Started by Jimmyk, 01-26-2018, 05:19 AM
                                6 responses
                                837 views
                                0 likes
                                Last Post emuns
                                by emuns
                                 
                                Started by jxs_xrj, 01-12-2020, 09:49 AM
                                6 responses
                                3,293 views
                                1 like
                                Last Post jgualdronc  
                                Started by Touch-Ups, Today, 10:36 AM
                                0 responses
                                13 views
                                0 likes
                                Last Post Touch-Ups  
                                Started by geddyisodin, 04-25-2024, 05:20 AM
                                11 responses
                                63 views
                                0 likes
                                Last Post halgo_boulder  
                                Working...
                                X