Search code examples
python-3.xdataframeccxt

How to return only the most recent value that meets a certain criteria in pandas dataframe


I'm building a trading bot using CCXT and Bybit as my exchange.

I have a function that fetches closed orders; the problem is bybit.fetch_closed_orders fetches trades that are both cancelled and closed/filled trades.

I need the function to only return orders with a closed status and, more specifically, only the most recent one.

Below is my function.

def closed_positions(symbol=symbol):
    
    index_pos = -1 
    
    closed_pos = bybit.fetch_closed_orders(symbol)
    
    closedpos_side = closed_pos[index_pos]['side']
    closedpos_size = closed_pos[index_pos]['amount']
    
    if closedpos_side == ('buy'):
        closedpos_bool = True
        long = True
    elif closedpos_side == ('sell'):
        closedpos_bool = True
        long = False
    else:
        closedpos_bool = False
        long = None
        
    print(f'closed possitions... | closedpos_bool {closedpos_bool} | closedpos_size {closedpos_size} | long {long}')
        
    return closed_pos, closedpos_bool, closedpos_size, long

The index_pos variable must return the index number for the most recent trade where closed_pos[index_pos]['status' == 'closed'].

The df consists of 20 dictionaries.

I've been struggling all afternoon with this; assistance is greatly appreciated!


Solution

  • After many hours of searching and trial and error, I got the answer.

    Here is for if anyone has the same problem.

    closed_pos = bybit.fetch_closed_orders(symbol)
    
    filtered = []
    
    for order in closed_pos:
        if order['status'] == 'closed':
            filtered.append(order)