Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Positions sizing not as expected

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

    Positions sizing not as expected

    Hi,

    I implemented a strategy that reverses the amount of open contracts and there is always a part of the position wrongly closed.

    The growth of the contracts shall be 1, 2, 4, 8, 16 etc.
    But the logic reverses somehow the existing amount of contracts in the other direction, results in.
    1, 3, 6, 8, 20 etc.


    The implementation starts with opening the first order:

    EnterLong(DefaultQuantity,"buyOrder");

    followed by (On execution update)
    if (execution.Order.OrderAction == OrderAction.Buy)
    {
    // Set stop loss
    double stopOrderPrice = execution.Order.AverageFillPrice - BoxSize * TickSize * 4;
    ExitLongStopMarket(0, true, execution.Order.Quantity, stopOrderPrice, "Stop loss", execution.Order.FromEntrySignal);

    // Set profit target 1
    double profitTarget = execution.Order.AverageFillPrice + ProfitFactor * BoxSize * TickSize * 4; ;
    ExitLongLimit(0, true, execution.Order.Quantity, profitTarget, "Profit target", execution.Order.FromEntrySignal);
    }

    When the reverse shall happen, the Stop Loss of the first position is hit, the following code is called:

    if (order.OrderAction == OrderAction.Sell) // long position
    {
    order.Account.CancelAllOrders(order.Instrument);
    //SetProfitTarget("sellOrder", CalculationMode.Pips, BoxSize * ProfitFactor);
    //SetStopLoss("sellOrder", CalculationMode.Pips, BoxSize, false);
    EnterShort(DefaultQuantity * (int)Math.Pow(2, reversesCount), "sellOrder");
    reversesCount++;
    }​

    with respective stop loss setting

    if (execution.Order.OrderAction == OrderAction.SellShort)
    {
    // Set stop loss
    double stopOrderPrice = execution.Order.AverageFillPrice + BoxSize * TickSize * 4;
    ExitShortStopMarket(0, true, execution.Order.Quantity, stopOrderPrice, "Stop loss", execution.Order.FromEntrySignal);

    // Set profit target 1
    double profitTarget = execution.Order.AverageFillPrice - ProfitFactor * BoxSize * TickSize * 4; ;
    ExitShortLimit(0, true, execution.Order.Quantity, profitTarget, "Profit target", execution.Order.FromEntrySignal);
    }​

    The first reverse returns instead of 2 contracts a position with 3 contracts:


    Click image for larger version

Name:	image.png
Views:	49
Size:	18.2 KB
ID:	1334275

    The log delivers an opening of 2 contracts

    SellStopLimit order is no longer active.
    10.02.2025 22:23:51 Strategy 'SzymonTC24DSv2/340536621': Entered internal SubmitOrderManaged() method at 10.02.2025 22:23:51: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=21834.50 SignalName='Stop loss' FromEntrySignal=''
    10.02.2025 22:23:51 Strategy 'SzymonTC24DSv2/340536621': Entered internal SubmitOrderManaged() method at 10.02.2025 22:23:51: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=21828.50 StopPrice=0 SignalName='Profit target' FromEntrySignal=''
    Stop loss was triggered at: 10.02.2025 22:28:53
    10.02.2025 22:28:53 Strategy 'SzymonTC24DSv2/340536621': Entered internal SubmitOrderManaged() method at 10.02.2025 22:28:53: BarsInProgress=0 Action=Buy OrderType=Market Quantity=2 LimitPrice=0 StopPrice=0 SignalName='buyOrder' FromEntrySignal=''
    buy order updated: Submitted
    Buy Limit = 21835.75 Sell Limit = 21833.25
    buy order updated: Accepted
    buy order updated: Working
    buy order updated: Filled
    BuyStopLimit order is no longer active.
    10.02.2025 22:28:53 Strategy 'SzymonTC24DSv2/340536621': Entered internal SubmitOrderManaged() method at 10.02.2025 22:28:53: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=2 LimitPrice=0 StopPrice=21832.50 SignalName='Stop loss' FromEntrySignal=''
    10.02.2025 22:28:53 Strategy 'SzymonTC24DSv2/340536621': Entered internal SubmitOrderManaged() method at 10.02.2025 22:28:53: BarsInProgress=0 Action=Sell OrderType=Limit Quantity=2 LimitPrice=21838.50 StopPrice=0 SignalName='Profit target' FromEntrySignal=''
    Stop loss was triggered at: 10.02.2025 22:30:26​


    I can't get the reason of the missing of the full closing of the previous position. Does anyone have good ideas for that?
    Last edited by moneymaster; 02-10-2025, 03:32 PM.

    #2
    Hello moneymaster,

    From the given information its hard to tell how your logic equated but it sounds like you may have conflicting orders working. When you call the opposite entry method that automatically closes the associated position and reverses it so if you have other exits working or exit with a market order at the same time that could result in a double exit for that position.

    Are you currently entering separate entries with unique signal names that are tied to each exit? To scale in the managed approach you need multiple entries with different names to avoid closing the whole position.



    JesseNinjaTrader Customer Service

    Comment


      #3
      Hi Jesse,
      thanks for your answer!
      I have renamed all orders, so they have now unique names.
      The problem still persists.
      Can you tell me please in which cases a double order occurs in Ninjatrader, that creates an additional order in the other direction that desired?
      Maybe then it will become clear to me and I can solve the issue.

      Is the problem the usage of the EnterLong and EnterShort methods or rather the usage of the stop losses?
      I also removed all methods manually closing orders and positions, but there is no improvement.

      In the log I see no change, except the order names with a number value.

      Enabling NinjaScript strategy 'BoxTradingStrategyDSV2/340536622' : On starting a real-time strategy - StartBehavior=ImmediatelySubmitSynchronizeAccount EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Ignore all errors ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On price change IsUnmanaged=False MaxRestarts=4 in 5 minutes
      Buy Limit = 21045 Sell Limit = 21043.25
      03.02.2025 06:48:47 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:47: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='sellOrder0' FromEntrySignal=''
      03.02.2025 06:48:47 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:47: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=21044.00 SignalName='Stop loss0' FromEntrySignal=''
      03.02.2025 06:48:47 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:47: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=21041.00 StopPrice=0 SignalName='Profit target0' FromEntrySignal=''
      Stop loss was triggered at: 03.02.2025 06:48:52
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:52: BarsInProgress=0 Action=Buy OrderType=Market Quantity=2 LimitPrice=0 StopPrice=0 SignalName='buyOrder1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy '340536622/SzymonTC24DSv2: Cancelled pending exit order, since associated position is closed, orderId='ddd54813bd554ae99fcf246bfe116aea' account='Playback101' name='Profit target0' orderState=Working instrument='NQ MAR25' orderAction=BuyToCover orderType='Limit' limitPrice=21041 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=67103 time='2025-02-03 06:48:47' gtd='2099-12-01' statementDate='2025-02-03'
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=2 LimitPrice=0 StopPrice=21043.25 SignalName='Stop loss1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=Limit Quantity=2 LimitPrice=21046.25 StopPrice=0 SignalName='Profit target1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=2 LimitPrice=0 StopPrice=21043.50 SignalName='Stop loss1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Amended matching order at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=2 LimitPrice=0 StopPrice=21043.50 SignalName='Stop loss1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Entered internal SubmitOrderManaged() method at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=Limit Quantity=2 LimitPrice=21046.50 StopPrice=0 SignalName='Profit target1' FromEntrySignal=''
      03.02.2025 06:48:52 Strategy 'SzymonTC24DSv2/340536622': Amended matching order at 03.02.2025 06:48:52: BarsInProgress=0 Action=Sell OrderType=Limit Quantity=2 LimitPrice=21046.50 StopPrice=0 SignalName='Profit target1' FromEntrySignal=''
      03.02.2025 06:49:02 Strategy 'SzymonTC24DSv2/340536622: Amended pending exit order, since associated position is closed, orderId='d94587b2d40d496da90f696c6fb49d30' account='Playback101' name='Profit target1' orderState=Working instrument='NQ MAR25' orderAction=Sell orderType='Limit' limitPrice=21046.5 stopPrice=0 quantity=2 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=67107 time='2025-02-03 06:48:52' gtd='2099-12-01' statementDate='2025-02-03'
      Stop loss was triggered at: 03.02.2025 06:49:02​

      Thanks and best regards
      Last edited by moneymaster; 02-10-2025, 05:01 PM.

      Comment


        #4
        Hello moneymaster,

        I cant tell from the output what your logic may be doing. I will ask again, are you currently entering separate entries with unique signal names that are tied to each exit?
        JesseNinjaTrader Customer Service

        Comment


          #5
          Hi Jesse,
          I worked out the problem.
          What I am doing is opening positions with unique names in opposite direction one after another. E.g.

          1 long contract runs to SL then
          2 short contracts are opened, if they run to SL then
          4 long contracts are opened. if they run to SL then
          8 short contracts are opened

          I figured out that the EnterLong and EnterShort method have a special feature.
          When you run them during stop loss handling in OnOrderUpdate, than the position that is being closed, will be additionally reversed adding an amount of contracts to the value of the respective EnterLong call.
          When you run them during stop loss handling in OnExecutionUpdate, than this method is called multiple times during position closing when more than 1 contract is affected.
          In that case it is needed to wait until the last call proceeded otherwise the position being closed will be additionally reversed and if there are multiple contracts being closed all of them will be reversed.

          The problem is, that I don't want to have the reversed position and that the stop loss and take profit positions are not set up for handling the additional reversed contract.

          Do you have any place where the reversing of a position during EnterLong or EnterShort is documented, so I can read a bit more about it?

          Thanks for your help.
          BR
          Last edited by moneymaster; 02-12-2025, 01:22 AM.

          Comment


            #6
            Hello moneymaster,

            There is only a small note in the help guide about reversing, there is not really anything additional to know about that. If you call the opposite entry method while in a position you will get a reversal, if you want to avoid that you need to make sure to not call the opposite entry method while in a position.

            To find out an execution was the last in this context would require your own custom logic as multiple orders are being used. You would need to monitor the execution events and accumulate the filled quantities to a variable to know when the last execution happens the total quantity has been met and then do an action.

            JesseNinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by Pointtoni, Yesterday, 11:41 PM
            2 responses
            19 views
            0 likes
            Last Post Pointtoni  
            Started by DayTradingDEMON, Yesterday, 02:10 PM
            5 responses
            28 views
            0 likes
            Last Post DayTradingDEMON  
            Started by Nate G, 03-17-2025, 02:53 PM
            4 responses
            54 views
            0 likes
            Last Post timko
            by timko
             
            Started by several, 03-18-2025, 03:53 AM
            11 responses
            173 views
            1 like
            Last Post timko
            by timko
             
            Started by Amelie4262, Today, 10:45 AM
            0 responses
            6 views
            0 likes
            Last Post Amelie4262  
            Working...
            X