Need to place multiple orders for stocks

Question:

I need to code in python for placing orders for stocks. Each order cannot exceed a certain quantity, say 600. If the required quantity is 1900, I would need to place three orders, 3 of 600 each and 1 of the remaining. I tried a for loop:

max_qty=600
req_qty=1900
for qty in range(max_qty, req_qty, max_qty):
   print(qty) 

This does not seem to be the right method. Pls help.

Asked By: Thomas Amal

||

Answers:

Try the following, where I have put in a function place_order to represent what ever the code for placing the actual order is.

  1. Loop while we still have a remaining number of stocks to order
  2. Get a quantity for the next sub-order which is the smaller of the requested quantity or the max limit
  3. Place the order for the largest possible amount at once.
  4. Update the outstanding requested amount by subtracting the ordered amount
def place_order(qty):
    # Do the actual ordering
    ...
    

max_qty=600
req_qty=1900

while req_qty:
    order_qty = min(req_qty, max_qty)
    place_order(order_qty)   # Place the order
    req_qty -= order_qty

Some things I didn’t include as they are beyond the scope of the original question:

  1. You could have place_order return a True or False of whether it was actually successful and only update req_qty on success
  2. In an actual application you might use something like async/await on the ordering function so that you can place multiple orders without waiting for the previous order to complete.
Answered By: nigh_anxiety

Here is a piece of code making use of divmod:

max_qty=600
req_qty=1900
full_orders, remainder = divmod(req_qty, max_qty)
for i in range(full_orders):
    place_order(max_qty)
if remainder:
    place_order(remainder)
Answered By: Swifty
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.