Search code examples
pythonbybit

Return list from API response across multiple symbols


I need to return a list of symbols only if they have 'position_value' > 0. From there I want to get more data corresponding to the symbol like side, unrealised_pnl etc, possibly into some easily readable format like a pandas dataframe.

So far I use this to get the whole JSON response, but the moment I move beyond 'result' by adding ['data'], I encounter the error "TypeError: list indices must be integers or slices, not str"

def get_positions():
    res = session_auth_unlocked.my_position()['result']
    return res
    

print(get_positions())

I understand I must use a for loop and have tried like so but I am getting stuck.

def get_positions():
    res = session_auth_unlocked.my_position()

    for item in res['result']['data']:
        if value > 0:
            positions[item['symbol']] = value

    return positions
    
print(get_positions())

This is the JSON API response for just one symbol but there are many more in the whole response.

{
"ret_code": 0,
"ret_msg": "OK",
"ext_code": "",
"ext_info": "",
"result": [
    {
        "data": {
            "user_id": 533285,
            "symbol": "10000NFTUSDT",
            "side": "Sell",
            "size": 0,
            "position_value": 0,
            "entry_price": 0,
            "liq_price": 0,
            "bust_price": 0,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": false,
            "position_margin": 0,
            "occ_closing_fee": 0,
            "realised_pnl": 0,
            "cum_realised_pnl": 0,
            "free_qty": 0,
            "tp_sl_mode": "Full",
            "unrealised_pnl": 0,
            "deleverage_indicator": 0,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 2,
            "mode": "BothSide"
        },
        "is_valid": true
    },
    ...
    {
        "data": {
            "user_id": 533285,
            "symbol": "10000NFTUSDT",
            "side": "Buy",
            "size": 0,
            "position_value": 0,
            "entry_price": 0,
            "liq_price": 0,
            "bust_price": 0,
            "leverage": 10,
            "auto_add_margin": 0,
            "is_isolated": false,
            "position_margin": 0,
            "occ_closing_fee": 0,
            "realised_pnl": 0,
            "cum_realised_pnl": 0,
            "free_qty": 0,
            "tp_sl_mode": "Full",
            "unrealised_pnl": 0,
            "deleverage_indicator": 0,
            "risk_id": 1,
            "stop_loss": 0,
            "take_profit": 0,
            "trailing_stop": 0,
            "position_idx": 1,
            "mode": "BothSide"
        },
        "is_valid": true
    }
],
"time_now": "1604302080.356538",
"rate_limit_status": 119,
"rate_limit_reset_ms": 1604302080353,
"rate_limit": 120}

Solution

  • After being JSON-loaded, the result is a list of dictionaries. You can't directly access the keys of each dict in that list until you have the whole dict first. So you'd iterate over it like this:

    for item in res['result']:
        data = item['data']  # to get the value stored in the 'data' key
    

    What do you expect if value > 0: to do? You've not set value to anything so that's going to be a NameError. If you wanted to use position_value, then do it like this:

    if data["position_value"] > 0:
        ...
    

    Depending on what you want in your final list of dictionaries or dataframe, add the other keys or just filter them out when loading your dataframe.

    final_result = []
    for item in res['result']:
        data = item['data']  # to get the value stored in the 'data' key
        if data["position_value"] > 0:
            final_dict = {
                "side": data["side"],
                "unrealised_pnl": data["unrealised_pnl"],
                ... # add the others which you want, or put the keys in a list
            }
            final_result.append(final_dict)
    
    return final_result  # assuming you put this in a function
    

    That can also be done with list & dict comprehensions but will leave it for you to research.

    To load your final list of dicts to a dataframe, see these answers.