Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

2 entry orders help!

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

  • NinjaTrader_Jim
    replied
    Hello PaulMohn,

    How can I make the script execute the full size defined by the QuantitySelector field and not the default 1 contract size?
    You need to make sure your code is capturing the value from the QuantitySelector. (Use prints to verify.) After you confirm you are fetching the correct value, consider saving that value to a class level variable. Then use that variable for the order submission quantity. I have attached an example that can be helpful for capturing controls from ChartTrader.

    How can I fix the Log tab error? I don't understand why the method works and does execute but for the size part. Thanks for your tips!
    When you add prints to the script to identify the last line of code reached, what line is that?

    After identifying this line of code, are there any objects that are referenced that are null? Use additional prints like Print((someObject1 == null)); Print((someObject2 == null)); to confirm which specific object is null when the error is reached.
    Attached Files

    Leave a comment:


  • PaulMohn
    replied
    Hello Chelsea, I'm getting back to post #25 and bitdavid's split order method applied to my new OCO Hotkeys Order script shared on the User Apps Share.
    I need to use that handy method for the order to execute split sizes instead of the full size at once, for my next user Apps Share release. So I thought of using bitdavid's method to try and see how it works. If it doesn't work as needed I would resort to more complex code with separated orders (but the Target and StopLoss handling for multiple separated orders would seem more difficult so I'd privilege bitdavid's method if working as well).

    Here's my application of bitdavid's method
    PHP Code:
        private static Random MyRand = new Random(DateTime.Now.Millisecond);
    
        private const int SHORT = -1;
        private const int NONE = 0;
        private const int LONG = 1;
    
        private void EnterOrder(int Direction, int totalQuantity)
        {
          int orderNum = 1;
          while (totalQuantity > 0)
          {
            int quantity = Math.Min(MyRand.Next(1, 4), totalQuantity);
            if (Direction > 0)
            {
              entryBuyMar****rder = myAccount.CreateOrder(
                  Instrument,
                  OrderAction.Buy,
                  OrderType.Market,
                  OrderEntry.Manual,
                  TimeInForce.Day,
                  quantity,
                  0,
                  0,
                  string.Empty,
                  "Entry"+"L"+orderNum,
                  Core.Globals.MaxDate,
                  null);
            }
            else if (Direction < 0)
            {
              entrySellMar****rder = myAccount.CreateOrder(
                  Instrument,
                  OrderAction.Sell,
                  OrderType.Market,
                  OrderEntry.Manual,
                  TimeInForce.Day,
                  quantity,
                  0,
                  0,
                  string.Empty,
                  "Entry"+"S"+orderNum,
                  Core.Globals.MaxDate,
                  null);
            }
            totalQuantity = totalQuantity - quantity;
            ++orderNum;
          } 
    

    Here's my Hotkeys method
    PHP Code:
          protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
      {
            // LONG Orders
            TriggerCustomEvent(o =>
            {
              if (Keyboard.IsKeyDown(Key.NumPad1))
              {
                EnterOrder(LONG, quantitySelector.Value);
              }
    
              myAccount.Submit(new[] { entryBuyMar****rder });
    
            }, null);
            e.Handled = true;
    
    
            // SHORT Orders
            TriggerCustomEvent(p =>
            {
              if (Keyboard.IsKeyDown(Key.NumPad2))
              {
    
                EnterOrder(SHORT, quantitySelector.Value);
              }
    
              myAccount.Submit(new[] { entrySellMar****rder });
    
            }, null);
            e.Handled = true;
          } 
    

    Now, the script executes but only 1 contract instead of the given Quantity Selector value (when I set 10 for example in the QuantitySelector field).

    There's also a Log Tab error
    Time Category Message
    25/05/2022 13:07:53 Order Failed to submit orders: System.NullReferenceException: Object reference not set to an instance of an object. at NinjaTrader.Cbi.Account.Submit(IEnumerable`1 orders)
    I see Kate and Patrick request for the script or Log and Trace files.
    Here's attached the latest version of the script ProfitSniperSplitOrders.zip (the previous is on the User Apps Share page above link).

    How can I make the script execute the full size defined by the QuantitySelector field and not the default 1 contract size?
    How can I fix the Log tab error? I don't understand why the method works and does execute but for the size part. Thanks for your tips!
    Attached Files

    Leave a comment:


  • PaulMohn
    replied
    Hello Chelsea, I got a new indicator in the User Apps Share for OCO Orders movable with Hotkeys, mainly thanks to your recent help! Thanks!

    Leave a comment:


  • PaulMohn
    replied
    Hi Chels, I think I got it right now. The issue was a a2nd local assignment/local variable in the TriggerCustomEvent() Event Handler within my ChartControl_PreviewKeyDown() method.


    protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
    TriggerCustomEvent(p =>
    {
    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;
    }






    I removed it as


    protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
    TriggerCustomEvent(p =>
    {
    //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;
    }






    Now it seems to work and submit and move the Target and StopLoss.

    I think the reason it didn't work before is because the 2nd assignment of //Order entryBuyMar****rder = null; "conflicted" with the class level 1st assignment of
    entryBuyMar****rder

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class MyOCOKeyEvent1 : Indicator
    {
    private Order entryBuyMar****rder, profitTargetOrder, stopLossOrder;

    If I understand it right, the 2nd assignment was setting the entryBuyMar****rder order to null? Before and after the order was placed? So it couldn't be picked up by the OnOrderUpdate() method? If that's so, why? I mean my 2nd assignment appears before the if (Keyboard.IsKeyDown(Key.NumPad1)) statement, so shouldn't entryBuyMar****rder "stay" ¬null once it is triggered? Thanks!
    Last edited by PaulMohn; 05-16-2022, 03:10 AM.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello PaulMohn,

    Where you have stated:
    "I can see your Event handler method cannot pick up the entryBuyMar****rder KeyDown event"

    I don't understand what this means. Which event handler?
    Order objects do not have a keydown event. This makes no sense. entryBuyMar****rder does not have a KeyDown event.

    Your output possibly is showing entryBuyMar****rder is null. Have you assigned entryBuyMar****rder the order object from OnOrderUpdate()?

    accountPosition also appears null. Are you assigning accountPosition from the <Account>.Positions collection?

    Leave a comment:


  • PaulMohn
    replied
    Here a Prints video.
    I can see your Event handler method cannot pick up the entryBuyMar****rder KeyDown event (please see entryBuyMar****rder != null : False in the Prints below).
    Why can't it pick it up while it can pick it up when the entryBuyMar****rder is autotriggered from the OnbarUpdate as in your script? Thanks!

    ### 1A. OnBarUpdate() with !KEYDOWN 13/05/2022 19:02:00
    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    ### 1A. OnBarUpdate() with !KEYDOWN 13/05/2022 19:02:00
    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    2A. Account_OrderUpdate() with KEYDOWN 13/05/2022 19:02:00
    entryBuyMar****rder != null : False
    entryBuyMar****rder == orderUpdateArgs.Order : False
    orderUpdateArgs.Order.OrderState == OrderState.Filled : False
    orderUpdateArgs.Order.OrderState == OrderState.Working : False

    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    2A. Account_OrderUpdate() with KEYDOWN 13/05/2022 19:02:00
    entryBuyMar****rder != null : False
    entryBuyMar****rder == orderUpdateArgs.Order : False
    orderUpdateArgs.Order.OrderState == OrderState.Filled : False
    orderUpdateArgs.Order.OrderState == OrderState.Working : False

    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    ### 1A. OnBarUpdate() with !KEYDOWN 13/05/2022 19:02:00
    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    2A. Account_OrderUpdate() with KEYDOWN 13/05/2022 19:02:00
    entryBuyMar****rder != null : False
    entryBuyMar****rder == orderUpdateArgs.Order : False
    orderUpdateArgs.Order.OrderState == OrderState.Filled : False
    orderUpdateArgs.Order.OrderState == OrderState.Working : False

    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    2A. Account_OrderUpdate() with KEYDOWN 13/05/2022 19:02:00
    entryBuyMar****rder != null : False
    entryBuyMar****rder == orderUpdateArgs.Order : False
    orderUpdateArgs.Order.OrderState == OrderState.Filled : False
    orderUpdateArgs.Order.OrderState == OrderState.Working : True

    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    2A. Account_OrderUpdate() with KEYDOWN 13/05/2022 19:02:00
    entryBuyMar****rder != null : False
    entryBuyMar****rder == orderUpdateArgs.Order : False
    orderUpdateArgs.Order.OrderState == OrderState.Filled : True
    orderUpdateArgs.Order.OrderState == OrderState.Working : False

    accountPosition == null : True
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    1B. OnBarUpdate() with KEYDOWN 13/05/2022 19:02:00
    accountPosition == null : False
    profitTargetOrder == nul : True
    sstopLossOrder == nul : True

    *
    Last edited by PaulMohn; 05-13-2022, 11:21 AM.

    Leave a comment:


  • PaulMohn
    replied
    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 sender, KeyEventArgs e)
        {
          TriggerCustomEvent(p =>
          {
            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!

    Leave a comment:


  • PaulMohn
    replied
    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.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    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.

    Leave a comment:


  • PaulMohn
    replied
    I tested using orderUpdateArgs.Order.OrderState == OrderState.Working (Working instead of Filled)
    PHP Code:
    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);
    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.

    Leave a comment:


  • PaulMohn
    replied
    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.

    Leave a comment:


  • PaulMohn
    replied
    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 sender, OrderEventArgs 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!

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    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.

    Leave a comment:


  • PaulMohn
    replied
    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 sender, OrderEventArgs 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!

    Leave a comment:


  • PaulMohn
    replied
    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 + (2 * TickSize);
                      submissionAccount.Change(new[] { moveTPOrder1 });
                    }
                  }
                }
                else if (pos.MarketPosition == MarketPosition.Short)
                {
                  lock (submissionAccount.Orders)
                  {
                    foreach (Order moveTPOrder1 in submissionAccount.Orders)
                    {
                      moveTPOrder1.LimitPriceChanged = moveTPOrder1.LimitPrice - (2 * TickSize);
                      submissionAccount.Change(new[] { moveTPOrder1 });
                    }
                  }
                }
              }
            }
          }
        }
    
    =======
    
          TriggerCustomEvent(p =>
          {
            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

    Leave a comment:

Latest Posts

Collapse

Topics Statistics Last Post
Started by CarlTrading, 05-11-2026, 05:56 AM
0 responses
56 views
0 likes
Last Post CarlTrading  
Started by CarlTrading, 05-10-2026, 08:12 PM
0 responses
33 views
0 likes
Last Post CarlTrading  
Started by Hwop38, 05-04-2026, 07:02 PM
0 responses
195 views
0 likes
Last Post Hwop38
by Hwop38
 
Started by CaptainJack, 04-24-2026, 11:07 PM
0 responses
359 views
0 likes
Last Post CaptainJack  
Started by Mindset, 04-21-2026, 06:46 AM
0 responses
280 views
0 likes
Last Post Mindset
by Mindset
 
Working...
X