For-If loop in python not working as intended

68 Views Asked by At

I've pasted in a snippet of my code - I am struggling with the loop below. The total_entered_qty_buy keeps showing 4x (The total tranches are 4 as you can see in the initialization of the variables) the quantity even if only 1,2 or 3 tranches have been executed and this of course affects other calcs in the code. I've tried playing around with the positioning of the variable inside and outside the loop as well initializing it inside or outside. Can someone please help point out how I am not handling the loop correctly. Please let me know if I am missing any info I should be providing here.

total_tranches = 4
tranche_portfolio_value = initial_portfolio_value / total_tranches
buy_qty_tranches = [0, 0, 0, 0]
entry_price_buy = [0, 0, 0, 0]
position_profit = 0
entry_tranches = [False, False, False, False]

while True:
    try:
        time.sleep(2)
        total_entered_qty_buy = 0
        total_entered_qty_sell = 0
        # Request market data
        app.reqMktData(app.req_id, contract_buy, '', False, False, [])
        app.reqMktData(app.req_id + 1, contract_sell, '', False, False, [])
        time.sleep(0.5)

        # Cancel market data subscription
        app.cancelMktData(app.req_id)
        app.cancelMktData(app.req_id + 1)

        if all([app.bid_price1, app.ask_price1]):
            log_message(f"Updated Prices: {stock_to_buy} - Bid: {app.bid_price1}, Ask: {app.ask_price1}")
           
            for tranche in range(total_tranches):
                if not entry_tranches[tranche]:
                    if tranche == 0 or (tranche > 0 and position_profit > 500 * tranche):
                        entry_tranches[tranche] = True
                        entry_price_buy[tranche] = app.ask_price1
                        buy_qty_tranches[tranche] = round(tranche_portfolio_value / app.ask_price1)
                        app.handle_tiered_entry(stock_to_buy, contract_buy, 'BUY', tranche + 1, total_tranches, tranche_portfolio_value)

                # Only update the total quantities if a new tranche was entered
                if entry_tranches[tranche]:
                    total_entered_qty_buy += buy_qty_tranches[tranche]
                   

            
            # Log the total entered quantities for buy and sell
            log_message(f"Total Entered Quantity Buy: {total_entered_qty_buy}")
0

There are 0 best solutions below