-1

I have data that looks as follows

{'exchange1': [{'price': 9656.04, 'side': 'bid', 'size': 0.16, 'timestamp': 1589504786}, 
               {'price': 9653.97, 'side': 'ask', 'size': 0.021, 'timestamp': 1589504786}], 
'exchange2': [{'price': 9755.3, 'side': 'bid', 'size': 27.0, 'timestamp': 1589504799},
              {'price': 9728.0, 'side': 'bid', 'size': 1.0, 'timestamp': 1589504799}]}

I want to iterate over each exchange and then for all prices and change them depending on the side key. If side : bid I want to multiply that price by a number (ex: 0.99) and if side : ask I want to multiply the price by a different number (ex: 1.01).

I am not sure how to iterate on the list of dictionaries that contain the side and price data.

Thank you for your help.

finstats
  • 1,349
  • 4
  • 19
  • 31

3 Answers3

2

You could use a dict here to hold the price multipliers, and iterate through all orders with nested for loops.

exchanges = {
    'exchange1': [{'price': 9656.04, 'side': 'bid', 'size': 0.16, 'timestamp': 1589504786},
                  {'price': 9653.97, 'side': 'ask', 'size': 0.021, 'timestamp': 1589504786}],
    'exchange2': [{'price': 9755.3, 'side': 'bid', 'size': 27.0, 'timestamp': 1589504799},
                  {'price': 9728.0, 'side': 'bid', 'size': 1.0, 'timestamp': 1589504799}]
}

price_multipliers = {
    'bid': 0.99,
    'ask': 1.01
}

for orders in exchanges.values():
    for order in orders:
        order["price"] *= price_multipliers[order["side"]]
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
0

The way to do this as a comprehension would be:

{k: [
    {**order, 'price': (
        order['price'] * 0.99 
        if order['side'] == 'ask' 
        else order['price'] * 1.01
    )}
    for order in exchange
] for k, exchange in exchanges.items()}
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

I am quite new to python so forgive me if I am doing this wrong:

def iterFunc(dic,bidf=0.99,askf=1.01):
    for exchange in dic:
        for part in dic[exchange]:
            ty = part['side']
            if ty == "bid":
                part['price'] *= bidf
            elif ty == "ask":
                part['price'] *= askf

I made a function instead in which "dic" is the dictionary with the nested dictionaries.