I have a dataframe that I created from a Data Dictionary format in the following way:
df = pd.DataFrame( info_closed, columns = [ 'type', 'origQty', 'executedQty' ] )
The result is as follows:
type origQty executedQty
0 LIMIT 0.00362000 0.00362000
1 MARKET 0.00200000 0.00200000
2 MARKET 0.00150000 0.00150000
3 MARKET 0.00150000 0.00150000
4 LIMIT 0.00150000 0.00150000
5 LIMIT 0.00150000 0.00150000
6 MARKET 0.00199500 0.00199500
7 LIMIT 0.00150000 0.00150000
8 MARKET 0.00149800 0.00149800
9 LIMIT 0.00150000 0.00150000
10 LIMIT 0.00149900 0.00149900
11 LIMIT 0.00150000 0.00150000
12 MARKET 0.00149800 0.00149800
[... snip ...]
I am trying to create a result in the following manner:
type origQty executedQty Count
0 LIMIT 13.03 15.01 23
1 MARKET 122.0l 40.00 54
[.. snip ...]
Basically, this would be a group_by (type) and a sum( origQty ) and sum ( origQty ) within each 'type' and a count of records that were use to calculate the values of sum( origQty ) and sum (origQty)
I tried:
g = df.groupby(['type'])['origQty', 'executedQty'].sum().reset_index()
but the results come out as follows:
type origQty executedQty
0 LIMIT 0.003620000.001500000.001500000.001500000.0015... 0.003620000.001500000.001500000.001500000.0015...
1 LIMIT_MAKER 0.001499000.001500000.001500000.001500000.0014... 0.001499000.001500000.001500000.001500000.0014...
2 MARKET 0.002000000.001500000.001500000.001995000.0014... 0.002000000.001500000.001500000.001995000.0014...
3 STOP_LOSS_LIMIT 0.00150000 0.00150000
Question: what am I doing wrong?
TIA
ETA:
Thanks all for the provided solutions!
I ran some but I was still getting this type of output:
origQty
executedQty
type
LIMIT_MAKER 0.001499000.001500000.001500000.001500000.0014... 0.001499000.001500000.001500000.001500000.0014...
The original data was like this (it is a combination of data from the Binance exchange and the ccxt wrapper code. I was attempting to isolate the Binance data ~only~ (whichi is associated with ['info'])
[{'info': {'symbol': 'BTCUSDT', 'orderId': 2538903025, 'orderListId':
-1, 'clientOrderId': 'ENDsgXoqtv2ct5jizrfeQe', 'price': '9638.00000000', 'origQty': '0.00150000', 'executedQty': '0.00150000',
'cummulativeQuoteQty': '14.45700000', 'status': 'FILLED',
'timeInForce': 'GTC', 'type': 'LIMIT_MAKER', 'side': 'BUY',
'stopPrice': '0.00000000', 'icebergQty': '0.00000000', 'time':
1592879158045, 'updateTime': 1592879162299, 'isWorking': True,
'origQuoteOrderQty': '0.00000000'}, 'id': '2538903025',
'clientOrderId': 'ENDsgXoqtv2ct5jizrfeQe', 'timestamp': 1592879158045,
'datetime': '2020-06-23T02:25:58.045Z', 'lastTradeTimestamp': None,
'symbol': 'BTC/USDT', 'type': 'limit', 'side': 'buy', 'price': 9638.0,
'amount': 0.0015, 'cost': 14.457, 'average': 9638.0, 'filled': 0.0015,
'remaining': 0.0, 'status': 'closed', 'fee': None, 'trades': None},
{'info': {'symbol': 'BTCUSDT', 'orderId': 2539250884, 'orderListId':
-1, 'clientOrderId': '5UFBYwDF6b9qJ1UWNsvOYU', 'price': '9653.00000000', 'origQty': '0.00299700', 'executedQty': '0.00299700',
'cummulativeQuoteQty': '28.93004100', 'status': 'FILLED',
'timeInForce': 'GTC', 'type': 'LIMIT_MAKER', 'side': 'SELL',
'stopPrice': '0.00000000', 'icebergQty': '0.00000000', 'time':
1592883883927, 'updateTime': 1592884056113, 'isWorking': True,
'origQuoteOrderQty': '0.00000000'}, 'id': '2539250884',
'clientOrderId': '5UFBYwDF6b9qJ1UWNsvOYU', 'timestamp': 1592883883927,
'datetime': '2020-06-23T03:44:43.927Z', 'lastTradeTimestamp': None,
'symbol': 'BTC/USDT', 'type': 'limit', 'side': 'sell', 'price':
9653.0, 'amount': 0.002997, 'cost': 28.930041, 'average': 9653.0, 'filled': 0.002997, 'remaining': 0.0, 'status': 'closed', 'fee': None,
'trades': None}, {'info': {'symbol': 'BTCUSDT', 'orderId': 2539601261,
'orderListId': -1, 'clientOrderId': 'testme-15928890617592764',
'price': '9633.00000000', 'origQty': '0.00150000', 'executedQty':
'0.00150000', 'cummulativeQuoteQty': '14.44950000', 'status':
'FILLED', 'timeInForce': 'GTC', 'type': 'LIMIT_MAKER', 'side': 'BUY',
'stopPrice': '0.00000000', 'icebergQty': '0.00000000', 'time':
1592889061852, 'updateTime': 1592889136305, 'isWorking': True,
'origQuoteOrderQty': '0.00000000'}, 'id': '2539601261',
'clientOrderId': 'testme-15928890617592764', 'timestamp':
1592889061852, 'datetime': '2020-06-23T05:11:01.852Z',
'lastTradeTimestamp': None, 'symbol': 'BTC/USDT', 'type': 'limit',
'side': 'buy', 'price': 9633.0, 'amount': 0.0015, 'cost': 14.4495,
'average': 9633.0, 'filled': 0.0015, 'remaining': 0.0, 'status':
'closed', 'fee': None, 'trades': None}]
I paired it back by executing the following :
info_closed = []
for index,item in enumerate( orders_closed ):
info_closed.append( item['info'] )
The results of what I had is listed above in the first post.
I then ran:
df = pd.DataFrame( final_output, columns = [ 'type', 'origQty', 'executedQty' ] )
I am starting to wonder if there is something amiss with the dataframe ... will start looking at this area ...
try this, before groupby cast the values to float.
df[['origQty', 'executedQty']] = df[['origQty', 'executedQty']].astype(float)
(
df.groupby(['type'])
.agg({"origQty": sum, "executedQty": sum, "type": len})
.rename(columns={'type': 'count'})
.reset_index()
)
I am 99% sure you get the result you want by just doing this:
df.groupby(['type'])[['origQty', 'executedQty']].sum()
Related
I'm accessing an API and retrieving some data from the API as a dictionary where the keys are all the same. Code below.
order_book = session.orderbook(symbol="ETHUSDT")
print(order_book)
This returns the below dictionary. A Range of prices, the symbol name (which is always the same), how many contracts are available at the price and the side available as buy or sell.
{'ret_code': 0, 'ret_msg': 'OK', 'ext_code': '', 'ext_info': '', 'result': [{'symbol': 'ETHUSDT', 'price': '1125.55', 'size': 99.62, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.5', 'size': 4.93, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.45', 'size': 6.45, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.4', 'size': 6.39, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.35', 'size': 32.81, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.3', 'size': 17.89, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.25', 'size': 4.41, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.2', 'size': 26.39, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.15', 'size': 15.35, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.1', 'size': 23.01, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.05', 'size': 37.36, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125', 'size': 62.45, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.95', 'size': 0.01, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.9', 'size': 6.25, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.85', 'size': 12.03, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.8', 'size': 48.02, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.75', 'size': 10, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.7', 'size': 0.01, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.65', 'size': 4.6, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.6', 'size': 4.17, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.55', 'size': 24.44, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.5', 'size': 16.72, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.45', 'size': 2.68, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.4', 'size': 8.87, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1124.35', 'size': 135.25, 'side': 'Buy'}, {'symbol': 'ETHUSDT', 'price': '1125.6', 'size': 21.38, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.7', 'size': 0.02, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.75', 'size': 9.46, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.8', 'size': 0.01, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.85', 'size': 29.1, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.9', 'size': 4.26, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1125.95', 'size': 14.53, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126', 'size': 13.9, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.05', 'size': 21.66, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.1', 'size': 39.36, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.15', 'size': 24.7, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.2', 'size': 9.07, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.25', 'size': 4.08, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.3', 'size': 49.79, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.35', 'size': 9.66, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.4', 'size': 17.13, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.45', 'size': 11.72, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.5', 'size': 4.55, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.55', 'size': 4.58, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.6', 'size': 124.11, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.65', 'size': 1.86, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.75', 'size': 18.47, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.8', 'size': 3.42, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.85', 'size': 18.46, 'side': 'Sell'}, {'symbol': 'ETHUSDT', 'price': '1126.9', 'size': 27.71, 'side': 'Sell'}], 'time_now': '1655855941.823052'}
So I am trying to figure out how I can access specific contract size for specific prices when the keys are the same? For example, the first 5 buy side and the first 5 sell side contract size, or even individual contract sizes based on specific prices.
I have tried googling this but I'm not even sure what to google to be honest.
Any help would be vey much appreciated. Even some idea on what I could search to figure it out myself?
Thanks in advance for any help.
Edit:
okay so I'm trying to use the code posted below to find the largest value contract size of the buy side
transactions = [trans for trans in order_book['result'] if trans['size'] == max and trans['side'] == 'Sell']print(transactions)
I'm receiving the following error
TypeError Traceback (most recent call last)~\AppData\Local\Temp/ipykernel_15204/2875214528.py in <module>
12 order_book = [session.orderbook(symbol="ETHUSDT")]
13 ---> 14 transactions = [trans for trans in order_book['result'] if trans['size'] == max and trans['side'] == 'Sell']
15 print(transactions)TypeError: list indices must be integers or slices, not str
again any help is very much appreciated :)
UPDATED (Based on OP's comment that order_book is a list of dict, not just a dict.)
def find_largest_contract(order_side, order_book):
largest_contract = float('-inf')
for order in order_book:
for result in order['result']:
if result['side'] == order_side:
largest_contract = max(largest_contract, result['size'])
return largest_contract
OLD VERSION
def find_largest_contract(order_side, order_book):
largest_contract = float('-inf')
for result in order_book['result']:
if result['side'] == order_side:
largest_contract = max(largest_contract, result['size'])
return largest_contract
Output:
>>> print(find_largest_contract('Buy', order_book))
>>> 135.25
>>> print(find_largest_contract('Sell', order_book))
>>> 124.11
I assume you mean result, which is a list of dictionaries, rather than a dictionary.
The lazy way would be with a list comprehension
transactions = [trans for trans in order_book['result'] if trans['size'] > 30]
transactions = [trans for trans in order_book['result'] if trans['side'] == 'Buy']
transactions = [trans for trans in order_book['result'] if float(trans['price']) < 1125.4 and trans['side'] == 'Sell']
I placed DEMO order on OKEx with amount 246 and price 0.46. When I looked on site, order amount was more than 11k:
I fetched info about order:
{'info': {'accFillSz': '0', 'avgPx': '', 'cTime': '1652262833825', 'category': 'normal', 'ccy': '', 'clOrdId': 'e847386590ce4dBCc812b22b16d7807c', 'fee': '0', 'feeCcy': 'USDT', 'fillPx': '', 'fillSz': '0', 'fillTime': '', 'instId': 'XRP-USDT-SWAP', 'instType': 'SWAP', 'lever': '1', 'ordId': '444557778278035458', 'ordType': 'limit', 'pnl': '0', 'posSide': 'long', 'px': '0.45693', 'rebate': '0', 'rebateCcy': 'USDT', 'side': 'buy', 'slOrdPx': '-1', 'slTriggerPx': '0.44779', 'slTriggerPxType': 'mark', 'source': '', 'state': 'live', 'sz': '246', 'tag': '', 'tdMode': 'isolated', 'tgtCcy': '', 'tpOrdPx': '-1', 'tpTriggerPx': '0.46606', 'tpTriggerPxType': 'mark', 'tradeId': '', 'uTime': '1652262833825'}, 'id': '444557778278035458', 'clientOrderId': 'e847386590ce4dBCc812b22b16d7807c', 'timestamp': 1652262833825, 'datetime': '2022-05-11T09:53:53.825Z', 'lastTradeTimestamp': None, 'symbol': 'XRP/USDT:USDT', 'type': 'limit', 'timeInForce': None, 'postOnly': None, 'side': 'buy', 'price': 0.45693, 'stopPrice': 0.44779, 'average': None, 'cost': 0.0, 'amount': 246.0, 'filled': 0.0, 'remaining': 246.0, 'status': 'open', 'fee': {'cost': 0.0, 'currency': 'USDT'}, 'trades': [], 'fees': [{'cost': 0.0, 'currency': 'USDT'}]}
and amount is 246.
Here is my code:
exchange = ccxt.okx(
{
'apiKey': API_KEY,
'secret': API_SECRET,
'password': API_PASSPHRASE,
'options': {
'defaultType': 'swap'
},
'headers': {
'x-simulated-trading': '1'
}
}
exchange.load_markets()
market = exchange.market(PAIR)
params = {
'tdMode': 'isolated',
'posSide': 'long',
'instId': market['id'],
'side': 'buy',
'sz': 246,
'tpOrdPx': '-1',
'slOrdPx': '-1',
'tpTriggerPx': str(take_profit),
'slTriggerPx': str(stop_loss),
'tpTriggerPxType': 'mark',
'slTriggerPxType': 'mark',
}
order = exchange.create_order(
f"{PAIR}", ORDER_TYPE, 'buy', summa, price, params=params)
info = exchange.fetch_order(order['id'], PAIR)
print(info)
What I'm doing wrong?
For starters you can only buy multiples of 100 of XRP as you can see in the screenshot below so you can only buy 200 or 300 and not 246.
Secondly, it looks like there's a multiplier of 100 being applied in the api where 1 = 100 XRP. I was able to deduce this by entering 24,600 XRP which gives you around $11k that you mentioned.
In your case, if you were to buy 200 or 300 XRP, you would need to enter 2 or 3 as an amount in the api request.
I am trying to check for the data-id is equal or not from the given list array
how do I check the complete array to know where the id is found or not?
order_id= 121553197332
inf = {data of array given below}
if inf[n]["id"] == order_id:
info = inf[n]["info"]
elif
do someting here
return (info)
the array in need to check?
[{'amount': 0.3,
'id': '121553197332',
'info': {'avgFillPrice': None,
'id': '121553197332',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.0',
'reduceOnly': False,
'remainingSize': '0.3',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit'},
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit'},
{'amount': 0.3,
'id': '121553197726',
'info': {'avgFillPrice': None,
'future': None,
'id': '121553197726',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.062',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit'},
'postOnly': True,
'price': 40.062,
'remaining': 0.3,
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit'}]
I need to return the info of the array at last.
You Can try use a for loop
like this:
inf = [{ 'amount': 0.3,
'id': '121553197332',
'info': { 'avgFillPrice': None,
'id': '121553197332',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.0',
'reduceOnly': False,
'remainingSize': '0.3',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit' },
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit' },
{ 'amount': 0.3,
'id': '121553197726',
'info': { 'avgFillPrice': None,
'future': None,
'id': '121553197726',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.062',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit' },
'postOnly': True,
'price': 40.062,
'remaining': 0.3,
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit' }]
order_id= 121553197332
for inner_data in inf:
if inner_data['id'] == order_id:
print(inner_data)
info = inner_data["info"]
Use next:
# Sample data (reduced)
orders = [{
'id': '121553197332',
'info': { 'id': '121553197332' },
}, {
'id': '121553197726',
'info': { 'id': '121553197726' },
}]
# The order to find
order_id = 121553197332
# Find it
found = next((d for d in orders if int(d["id"]) == order_id), None)
Here is the snippet that is ready to run. target variable is the one you are searching for in the records.
data = [{'amount': 0.3,
'id': '121553197332',
'info': {'avgFillPrice': None,
'id': '121553197332',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.0',
'reduceOnly': False,
'remainingSize': '0.3',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit'},
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit'},
{'amount': 0.3,
'id': '121553197726',
'info': {'avgFillPrice': None,
'future': None,
'id': '121553197726',
'ioc': False,
'liquidation': False,
'market': 'FTT/USD',
'postOnly': True,
'price': '40.062',
'side': 'buy',
'size': '0.3',
'status': 'open',
'type': 'limit'},
'postOnly': True,
'price': 40.062,
'remaining': 0.3,
'side': 'buy',
'status': 'open',
'stopPrice': None,
'symbol': 'FTT/USD',
'trades': [],
'type': 'limit'}]
target= '121553197726'
for d in data:
if d['id']==target:
info = d["info"]
print(info)
else:
pass
I have a nested list and I need to filter out a key / value based on a condition.
the list:
[{'buyer': False,
'commission': '0.01333920',
'commissionAsset': 'USDT',
'id': 52549382,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2448678953,
'positionSide': 'BOTH',
'price': '3334.80',
'qty': '0.010',
'quoteQty': '33.34800',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628311810877},
{'buyer': True,
'commission': '0.01334440',
'commissionAsset': 'USDT',
'id': 52544760,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909783,
'positionSide': 'BOTH',
'price': '3336.10',
'qty': '0.010',
'quoteQty': '33.36100',
'realizedPnl': '-0.29400000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628309268672},
{'buyer': False,
'commission': '0.01322680',
'commissionAsset': 'USDT',
'id': 52532126,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909485,
'positionSide': 'BOTH',
'price': '3306.70',
'qty': '0.010',
'quoteQty': '33.06700',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628301912771},
{'buyer': True,
'commission': '0.01319760',
'commissionAsset': 'USDT',
'id': 52525468,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447502727,
'positionSide': 'BOTH',
'price': '3299.40',
'qty': '0.010',
'quoteQty': '32.99400',
'realizedPnl': '-0.29700000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628297857042},
Now, how can I get the 'time' value of the nested block where the 'id' is equal to 52532126 ? Although I prefer vectorization I tried to iterate through the list but I had no success.
for item in response_tradelist:
if item == '52532126':
print('ok')
Even If it would work how do I get the 'time' value in the corresponding block?
That's a list of dictionaries, you must compare with id in each item and then print the time if id is a match.
Also id value is not a string, so don't use quotes around id.
Try this:
for item in response_tradelist:
if item['id'] == 52532126:
print(item['time'])
if you want to print the dictionary with id 52532126:
for dic in response_tradelist:
if dic['id'] == 52532126:
print(dic)
if you want time specifically, replace print(dic) with:
print(dic['time'])
Since the value of your id is in integer in that block of dictionary, thus you cannot check with string value,
you need to check value like item['id']== 52532126
l=[{'buyer': False,
'commission': '0.01333920',
'commissionAsset': 'USDT',
'id': 52549382,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2448678953,
'positionSide': 'BOTH',
'price': '3334.80',
'qty': '0.010',
'quoteQty': '33.34800',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628311810877},
{'buyer': True,
'commission': '0.01334440',
'commissionAsset': 'USDT',
'id': 52544760,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909783,
'positionSide': 'BOTH',
'price': '3336.10',
'qty': '0.010',
'quoteQty': '33.36100',
'realizedPnl': '-0.29400000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628309268672},
{'buyer': False,
'commission': '0.01322680',
'commissionAsset': 'USDT',
'id': 52532126,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909485,
'positionSide': 'BOTH',
'price': '3306.70',
'qty': '0.010',
'quoteQty': '33.06700',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628301912771},
{'buyer': True,
'commission': '0.01319760',
'commissionAsset': 'USDT',
'id': 52525468,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447502727,
'positionSide': 'BOTH',
'price': '3299.40',
'qty': '0.010',
'quoteQty': '32.99400',
'realizedPnl': '-0.29700000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628297857042}]
for d in l:
if d["id"]==52532126:
print(d["time"])
and if you want to print the whole dictionary then ,
for d in l:
if d["id"]==52532126:
print(d)
You are halfway there. You only need to access the right element instead of just item and the ID value is an int not an str
Fixing those two things gives you the result:
for item in response_tradelist:
if item['id'] == 52532126:
print('ok')
you can filter using a filter function in case you have multiple values and want to retrieve a list.
filtered_list = list(filter(lambda x: x['id'] == 52525468, response_tradelist))
reference: Filtering a list of strings based on contents
Since it's a dict
for item in response_tradelist:
if item['id] == '52532126':
print(item['time'])
You need to iterate thru the list of dictionaries and check the i["time"] index for each one.
dictList = [{
'buyer': False,
'commission': '0.01333920',
'commissionAsset': 'USDT',
'id': 52549382,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2448678953,
'positionSide': 'BOTH',
'price': '3334.80',
'qty': '0.010',
'quoteQty': '33.34800',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628311810877
},
{
'buyer': True,
'commission': '0.01334440',
'commissionAsset': 'USDT',
'id': 52544760,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909783,
'positionSide': 'BOTH',
'price': '3336.10',
'qty': '0.010',
'quoteQty': '33.36100',
'realizedPnl': '-0.29400000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628309268672
},
{
'buyer': False,
'commission': '0.01322680',
'commissionAsset': 'USDT',
'id': 52532126,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447909485,
'positionSide': 'BOTH',
'price': '3306.70',
'qty': '0.010',
'quoteQty': '33.06700',
'realizedPnl': '0',
'side': 'SELL',
'symbol': 'MKRUSDT',
'time': 1628301912771},
{
'buyer': True,
'commission': '0.01319760',
'commissionAsset': 'USDT',
'id': 52525468,
'maker': False,
'marginAsset': 'USDT',
'orderId': 2447502727,
'positionSide': 'BOTH',
'price': '3299.40',
'qty': '0.010',
'quoteQty': '32.99400',
'realizedPnl': '-0.29700000',
'side': 'BUY',
'symbol': 'MKRUSDT',
'time': 1628297857042
}]
searchValue = 1628297857042
for i in dictList:
if i["time"] == searchValue:
print(f"Found: {i["time"]}")
Alternatively if you were looking to do some "fun" python magic -
value = [True for item in dictList if item["time"] == searchValue]
print(value)
You could use list comprehension, unfortunately it does return an array, but that could be fixed pretty easily.
I have a list of dictionaries like so:
[{'asset': 'Discovery Fund', 'amount': 100000, 'rating': 'High'},
{'asset': 'Ethical Fund', 'amount': 200000, 'rating': 'High'},
{'asset': 'Foreign Stocks', 'amount': 9350000, 'rating': 'Very High'},
{'asset': 'Local Stocks', 'amount': 550000, 'rating': 'Very High'}]
I'm trying to merge any duplicate values for the rating key and sum up the amounts.
For example, the list above has ratings value as "High", "High", "Very High", "Very High"
Expected result:
[
{'amount': 300000, 'rating': 'High'},
{'amount': 900000, 'rating': 'Very High'}
]
Please how can I go about this?
Any help would be appreciated.
Thanks
You can achieve this quite easily using pandas.
import pandas as pd
data = [{'asset': 'Discovery Fund', 'amount': 100000, 'rating': 'High'},
{'asset': 'Ethical Fund', 'amount': 200000, 'rating': 'High'},
{'asset': 'Foreign Stocks', 'amount': 9350000, 'rating': 'Very High'},
{'asset': 'Local Stocks', 'amount': 550000, 'rating': 'Very High'}]
df = pd.DataFrame(data)
output = df.groupby('rating', as_index=False).sum().to_dict('records')
print(output)
#[{'rating': 'High', 'amount': 300000}, {'rating': 'Very High', 'amount': 9900000}]
To do this without pandas we can use a loop over our list and dict.get() to grab the value, or 0 for key rating.
output = {}
for _dict in data:
output[_dict['rating']] = output.get(_dict['rating'], 0) + _dict['amount']
output
#{'High': 300000, 'Very High': 9900000}