FM2020
FM2020

Reputation: 293

What is wrong with my while loop (Python)?

I am quite new to programming and I face a strange issue with the below while-loop in Python. When I manually run the code below the loop (i.e. starting with "time now..." to "t += 1"), I get the output I want:

The time is now: 13:31:01
Your current position is -1
This is iteration: 1
The time is now: 13:32:01
Your current position is -1
This is iteration: 2

However, when I run the full loop, I get double, triple or multiple prints of the same minute (see output below the while-loop code). Do you see the issue with this loop? Its as if the "t += 1" increment is running several times per loop (i.e. for each minute several prints). I dont get it.

Thanks for your help!

Blockquote

t=1
while t < 2000:

  time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))              
  if time_now[6:8] == str('00'):
    sleep(1)
  elif time_now[6:8] == str('01'):
    sleep(0)
  else:    
    x = 61 - int(time_now[6:8])
    sleep(x)
  time_now = (time.strftime('%H:%M:%S', time.localtime(int(time.time()))))
  print("The time is now: " + time_now)

  #+1 is the middle bar
  totalBars = leftBars + rightBars + 1
  swing_candles = client.Trade.Trade_getBucketed(symbol=symbol, binSize="1m", count=totalBars, reverse=True).result()[0]

  last_highs = []
  last_lows = []

  i=0
  while i <= (len(swing_candles)-1):
    last_highs.append(swing_candles[i]["high"])
    last_lows.append(swing_candles[i]["low"])
    i += 1

  #get the highest high and the lowest low
  highest_high = max(last_highs)
  lowest_low = min(last_lows)

  #check if there are existing positions & orders
  positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]

  #check existing orders
  buy_orders_quantity = []
  sell_orders_quantity = []
  orders_quantity = client.Order.Order_getOrders(filter=json.dumps({"open": True})).result()[0]   

  h=0
  while h <= len(orders_quantity)-1:
    if orders_quantity[h]["side"] == "Sell":
        sell_orders_quantity.append(orders_quantity[h])
    elif orders_quantity[h]["side"] == "Buy":
        buy_orders_quantity.append(orders_quantity[h])            
    h += 1 



  if highest_high == last_highs[rightBars] and positions_quantity == 0:
    if buy_orders_quantity == []:
        client.Order.Order_new(symbol = symbol, orderQty = orderQty*1, side = "Buy", ordType = 'Stop', stopPx = highest_high, execInst ='LastPrice' ).result()

    elif buy_orders_quantity != []:
        orderID = buy_orders_quantity[0]["orderID"]
        client.Order.Order_amend(orderID=orderID, orderQty=orderQty*1, stopPx = highest_high).result()
    else:
        pass


  elif highest_high == last_highs[rightBars] and positions_quantity > 0:
        #dont place any additional long
        pass


  elif highest_high == last_highs[rightBars] and positions_quantity < 0:
    if buy_orders_quantity != []:
        orderID = buy_orders_quantity[0]["orderID"]
        client.Order.Order_amend(orderID=orderID, orderQty=orderQty*2, stopPx = highest_high).result()    
    else:
        client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*2, side = "Buy", ordType = 'Stop', stopPx = highest_high, execInst ='LastPrice' ).result()


  elif lowest_low == last_lows[rightBars] and positions_quantity == 0:
    if sell_orders_quantity == []:
        client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-1, side = "Sell", ordType = 'Stop', stopPx = lowest_low, execInst ='LastPrice' ).result()
    elif sell_orders_quantity != []:
        orderID = sell_orders_quantity[0]["orderID"]
        client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-1, stopPx = lowest_low ).result()
    else:
        pass        

  elif lowest_low == last_lows[rightBars] and positions_quantity < 0:
        #dont place any additional shorts
        pass       

  elif lowest_low == last_lows[rightBars] and positions_quantity > 0:
    if sell_orders_quantity != []:
        orderID = sell_orders_quantity[0]["orderID"]
        client.Order.Order_amend(orderID=orderID, orderQty=orderQty*-2, stopPx = lowest_low).result()    
    else:
        #if there is no order, place new order with double amount   
        client.Order.Order_new(symbol = symbol, orderQty = (orderQty)*-2, side = "Sell", ordType = 'Stop', stopPx = lowest_low, execInst ='LastPrice' ).result()

  positions_quantity = client.Position.Position_get().result()[0][0]["currentQty"]
  print("Your current position is " + str(positions_quantity))
  print("This is iteration: " + str(t))
  t += 1

This is the output when I run the while-loop above (however each minute there should be just one print, but starting with iteration two there are several prints for the same minute (loop)):

The time is now: 13:39:01
Your current position is -1
This is iteration: 1
The time is now: 13:39:01
Your current position is -1
This is iteration: 2
The time is now: 13:40:01
Your current position is -1
This is iteration: 3
The time is now: 13:40:01
Your current position is -1
This is iteration: 4
The time is now: 13:40:01
Your current position is -1
This is iteration: 5
The time is now: 13:40:01
Your current position is -1
This is iteration: 6
The time is now: 13:40:01
Your current position is -1
This is iteration: 7
The time is now: 13:41:01
Your current position is -1
This is iteration: 8
The time is now: 13:41:01
Your current position is -1
This is iteration: 9
The time is now: 13:41:01
Your current position is -1
This is iteration: 10
The time is now: 13:41:01
Your current position is -1
This is iteration: 11
The time is now: 13:41:01
Your current position is -1
This is iteration: 12

Upvotes: 0

Views: 63

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

Assuming that "running the full loop" (scenario A) is faster than when you "manually runtime code" (scenario B), what appears to be happening is that, when the # of seconds in time_now is "01", the scenario A is fast enough to complete a few iterations with the # of seconds in time_now staying at "01", while scenario B is not.

If you slept for at least 1 second when the # of seconds in time_now was "01", that should prevent this, as it would change the # of seconds in time_now.

Upvotes: 1

Related Questions