Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

average fill price

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

    #31
    Hello,

    Which example in particular? These are just references for educational purposes to learn how dictionaries work in C#.

    Please note our support team is generally for NinjaScript Support, and not general C# education. A basic understanding of C# programming is prerequisite to writing NinjaScript code.

    As in the site linked below, there are several different ways you can query a dictionary (for loops, by index, for each loop, etc:

    Comment


      #32
      Hey yeah that's the example i meant. It only writes to console but doesn't show how to assign the dict values to a variable for further use.

      I coded a lot in Supercollider at Uni which i believe is C# but never had any actual training in it sorry. So your help is much appreciated.

      So do i need to use 2 separate Linq queries, one for string and one for double to access the dict values? Sorry but I'm a bit stuck on that part and couldn't see the solution in the examples or from googling

      Comment


        #33
        Why are you looking to assign the values to a variable, if they are already stored in the dictionary?

        What values in particular are you trying to access from the dictonary? What wring and what double? I'm not clear on what exactly you're trying to do.

        Comment


          #34
          Haha sorry, i just want to loop through the existing orders in the dict and calculate the average price. Right now I'm just seeing the separate fill prices of each order. I got confused with the "x" inside the Print structures that i wasn't able to use for further calculation. So how do i use the values from the dict other than for printing?

          Comment


            #35
            Hello,

            You could use a for loop to loop through the dictionary and get the AveragePrice of each order in the dictionary.

            Code:
            for(int x=0; x < positionOrders.Count; x++)
            {
            Print(positionOrders.ElementAt(x).Value.AverageFillPrice);
            }

            Comment


              #36
              That was the line of code that I needed, thank you, Gaby!!

              While I thought it would all work flawlessly now, it still doesn't, and I can't quite pinpoint the error at this time.

              //onorderupdate block checking for new buy and sell orders
              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity,int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {

              if (order.OrderAction == OrderAction.Buy && order.OrderState == OrderState.Filled && !positionOrdersLong.ContainsKey(order.Name))
              {positionOrdersLong.Add(order.Name, order);}
              else if (order.OrderAction == OrderAction.Sell && order.OrderState == OrderState.Filled && order.FromEntrySignal != null && positionOrdersLong.ContainsKey(order.FromEntrySign al))
              [positionOrdersLong.Remove(order.FromEntrySignal);}
              if (order.OrderAction == OrderAction.Sell && order.OrderState == OrderState.Filled && !positionOrdersShort.ContainsKey(order.Name))
              {positionOrdersShort.Add(order.Name, order);}
              else if (order.OrderAction == OrderAction.Buy && order.OrderState == OrderState.Filled && order.FromEntrySignal != null && positionOrdersShort.ContainsKey(order.FromEntrySig nal))
              {positionOrdersShort.Remove(order.FromEntrySignal) ;}

              }

              This is the basic setup for having a dictionary for each side. Perhaps it would be better to just have one for both sides? Could the issue be here?

              I then have the for loop which at first I put after the above block and now have tried putting inside each of the blocks (i.e. to update whenever an order gets opened or closed)

              double addPos=0;
              for(int x=0; x< positionOrdersShort.Count; x++)
              {​
              addPos+=positionOrdersShort.ElementAt(x).Value.Ave rageFillPrice;//sum up all the entry prices
              if(x==positionOrdersShort.Count-1){//when loop is finished, calculate the average
              double tempPrice=addPos/positionOrdersShort.Count;
              entryPriceShort=Math.Round(tempPrice/TickSize)*TickSize;///round price
              Print("entryPriceShort = "+entryPriceShort+" - Count = "+positionOrdersShort.Count);//Printing my calculated average and orders inside dict
              Print(string.Format( "{0} | entries contributing to Short position: {1}", Time[0], string.Join(", ", positionOrdersShort.Select(x => String.Format("{0}: {1}", x.Key, x.Value.AverageFillPrice))) ));//the original print from the example to show how many orders are actually in the dict
              }​


              This is what the prints look like:

              entryPriceLong = 19937.5 - Count = 1
              26/06/2024 16:10:57 | entries contributing to Long position: LongPos0: 19937.5
              entryPriceShort = 19936.75 - Count = 1
              26/06/2024 16:10:58 | entries contributing to Short position: ShortPos1: 19936.75
              entryPriceShort = 19937 - Count = 2
              26/06/2024 16:10:58 | entries contributing to Short position: ShortPos1: 19936.75, ShortPos0: 19937.25
              entryPriceLong = 19936.5 - Count = 2
              26/06/2024 16:11:00 | entries contributing to Long position: LongPos0: 19937.5, LongPos1: 19935.25
              entryPriceLong = 19935.5 - Count = 3
              26/06/2024 16:11:10 | entries contributing to Long position: LongPos0: 19937.5, LongPos1: 19935.25, LongPos2: 19933.5
              entryPriceShort = 19932.5 - Count = 3
              26/06/2024 16:11:30 | entries contributing to Short position: ShortPos1: 19936.75, ShortPos0: 19937.25, ShortPos2: 19923.5
              entryPriceShort = 19931 - Count = 4
              26/06/2024 16:11:33 | entries contributing to Short position: ShortPos1: 19936.75, ShortPos0: 19937.25, ShortPos2: 19923.5, ShortPos4: 19926.5
              entryPriceLong = 19932.75 - Count = 4
              26/06/2024 16:11:38 | entries contributing to Long position: LongPos0: 19937.5, LongPos1: 19935.25, LongPos2: 19933.5, LongPos3: 19924.75​

              While the count and average is correct, it doesn't reflect on the actual orders and average I am seeing on the chart with ChartTrader.
              It also doesn't always print when an order is filled, so I'm thinking the issue is with the initial block and the keys in regards to the dict.

              I label my orders as "LongPos"+i (within a for loop). and in the code it checks for the key;
              !positionOrdersLong.ContainsKey(order.Name)
              //and
              order.FromEntrySignal != null && positionOrdersLong.ContainsKey(order.FromEntrySign al)

              I played around with taking it out, but I'm not a hundred percent sure on what it does, and also what FromEntrySignal does here. Could it be a discrepancy between my orders having changing labels and in the example there were only 3 labels (that had specific strings)?




              ​​

              Comment


                #37
                Hello,

                Can you clarify, you're saying that on the chart you are not seeing the same average price and/or quantity of open positions?

                That line is checking the dictionary to see if a corresponding order with the same fromEntrySignal already exists in the dictionary.

                Comment


                  #38
                  oh so fromentrysignal is ust there to doublecheck for doublicates but doesn't do much more in this context?

                  yes, the average calculations from what is in the dict are correct, however they do not correspond to the trades on the chart

                  Comment


                    #39
                    Hello kalli44100,

                    Can you clarify, is it the quantity of trades that doesn't correspond to what you see on the chart? i.e. the chart is showing 3 positions open, but the output is showing your dictionary only contains 2.

                    In this case, you would need to double-check the logic for adding and removing the orders from the dictionary when the order is filled. Take a look at the PositionEntryOrdersExampleScript for an idea of how this works. If you have any questions about what anything in the script is doing, please let us know.

                    If the quantity of trades is the same, but your calculated average price of the open positions is not, then you'll need to double-check your logic for calculating the average price.

                    While we don't have visibility on how the average price that is reported in the chart is calculated internally, there is an existing sample script that demonstrates manually calculating the Position.AveragePrice:

                    Comment


                      #40
                      from the dict i will e.g. get: dict.count = 5 and the resulting average of those orders in the dict. on the chart at the same time i might see 8 contracts filled and a completely different average price.

                      I think the issue is in onorderupdate:
                      if (order.OrderAction == OrderAction.Buy && order.OrderState == OrderState.Filled && !positionOrdersLong.ContainsKey(order.Name))
                      {positionOrdersLong.Add(order.Name, order);}
                      else if (order.OrderAction == OrderAction.Sell && order.OrderState == OrderState.Filled && order.FromEntrySignal != null && positionOrdersLong.ContainsKey(order.FromEntrySign al))
                      [positionOrdersLong.Remove(order.FromEntrySignal);}
                      if (order.OrderAction == OrderAction.Sell && order.OrderState == OrderState.Filled && !positionOrdersShort.ContainsKey(order.Name))
                      {positionOrdersShort.Add(order.Name, order);}
                      else if (order.OrderAction == OrderAction.Buy && order.OrderState == OrderState.Filled && order.FromEntrySignal != null && positionOrdersShort.ContainsKey(order.FromEntrySig nal))
                      {positionOrdersShort.Remove(order.FromEntrySignal) ;}

                      but i don't know.

                      Any ideas? Alternatively are there other ways to check the number of filled orders (as well as open unfilled limit orders)? I saw that there is an addon account thingy.. or account in general but i couldn't get it to work. would that be better than the dictionary approach?​

                      Comment


                        #41
                        your above example uses the specific order labels again i..e.. order1, order2, ,order3. i don't know how many orders and specifically with what labels i'll have.. Isn't there an easier way to get the label of the latest execution? that way i can then get the average fill price etc.

                        Comment


                          #42
                          Hello,

                          Can you clarify, are you trying to get the average fill price for all orders the strategy has executed (i.e. all closed trades)?

                          The example Chelsea provided is for the example is specifically for tracking entry orders that make up an open position. Once exited, the entries are removed from the dictionary so if you're printing out the average price that way it's not going to include previously closed trades.

                          Additionally, it doesn't matter what the entry order names are- the example uses longEntry1, longEntry2, etc for simplicity but the order names could be anything, and there can be as many orders added as you like. The logic for adding/removing the orders doesn't depend on the order names or even the number of orders. ​​

                          Comment


                            #43
                            Hi Gaby,

                            So I want to know on an ongoing basis:
                            - active position and size (e.g. 12 contracts short)
                            - existing Limit Orders both buy and sell (e.g. 10 sell and 5 buy limit orders)

                            And any changes to the above

                            For example:

                            I have 10 sell Limit orders above at different prices
                            my position is 12 contracts short at the moment
                            I have 5 Limit Buy orders below at different prices

                            1. Should a new buy level emerge, I want to check that it is below my current short average fill price and only then place a new Limit buy order
                            2. I want the 12 short contracts to be filled by the 5 Limit buy orders so will split them into 2, 2, 2, 3 and 3 contracts per level
                            3. Now if the top buy level gets hit that means 2 contracts are bought and my short position is now 10 contracts (2 less than before)
                            4. Let's say a few sell orders get hit above, my short position is now 18 but I still only have 4 Limit buy orders below, ,I want to now change the quantities of the Limit orders below to be 4, 4, 5 and 5 (i.e. (18-(18%4))/4 .... and the remainder somehow gets spread over the lower levels,, I havent quite thought that through yet
                            6. And as risk management, if the current unrealised P&L exceeds e.g.. $1K then close all active and limit orders, or only active orders (will have to test what works)

                            Anyway, I hope you get the concept and my need to constantly monitor averagefillprice and amount of limit and active orders and adjust those accordingly

                            Let me know your thoughts

                            Thank you

                            K

                            Comment


                              #44
                              Hello,

                              I want to know on an ongoing basis: existing Limit Orders both buy and sell (e.g. 10 sell and 5 buy limit orders)
                              As in working limit orders that have not been filled, both entry and exit orders?

                              ​active position and size (e.g. 12 contracts short)
                              These can be tracked using Position.MarketPosition, Position.AveragePrice, and Position.Quantity.








                              If you want a collection of accepted or working orders, you can add these to a list or dictionary in OnOrderUpdate when the OrderState is OrderState.Accepted. Then, remove them from the list or dictionary with the order is filled, canceled, or rejected.

                              PositionEntryOrders is adding entry orders when they fill and removing them when the exit fills. Your logic would instead add the order when it becomes Accepted or Working, then remove them when it is Filled or Canceled.

                              It's also possible to check the order.OrderAction to be Buy or SellShort to check if it's an entry, without having to check for the signalName if you don't want to do it that way. ​

                              Comment


                                #45
                                "As in working limit orders that have not been filled, both entry and exit orders?"
                                Yep that's right

                                Thank you for your suggestions, the logic sounds good, i will try those tomorrow.

                                And how can i check unrealised profit? Do i need the add-on to use Account or did i misunderstood that part?

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                                0 responses
                                558 views
                                0 likes
                                Last Post Geovanny Suaza  
                                Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                                0 responses
                                324 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by Mindset, 02-09-2026, 11:44 AM
                                0 responses
                                101 views
                                0 likes
                                Last Post Mindset
                                by Mindset
                                 
                                Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                                0 responses
                                545 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by RFrosty, 01-28-2026, 06:49 PM
                                0 responses
                                547 views
                                1 like
                                Last Post RFrosty
                                by RFrosty
                                 
                                Working...
                                X