how do I check the complete array? - python

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

Related

How to Transform data in a nested json?

I have the following data, and when I used json_flatten i was able to extract most of the data except for deliveryMethod.items and languages.items.
I also tried to use pd.json_normalize(a, record_path= 'deliveryMethod.items') but it doesn't seem to be working.
a = {'ID': '1', 'Name': 'ABC', 'Center': 'Center For Education', 'providerNameAr': 'ABC', 'city': {'id': 1, 'cityEn': 'LA', 'regionId': 0, 'region': None}, 'cityName': None, 'LevelNumber': 'ABCD', 'activityStartDate': '09/01/2020', 'activityEndDate': '09/02/2020', 'activityType': {'lookUpId': 2, 'lookUpEn': 'Course', 'code': None, 'parent': None, 'hasParent': False}, 'deliveryMethod': {'items': [{'lookUpId': 2, 'lookUpEn': 'online' 'code': None, 'parent': None, 'hasParent': False}]}, 'languages': {'items': [{'lookUpId': 1, 'lookUpEn': 'English', 'code': None, 'parent': None, 'hasParent': False}]}, 'activityCategory': {'lookUpId': 1, 'lookUpEn': 'Regular', 'code': None, 'parent': None, 'hasParent': False}, 'address': 'LA', 'phoneNumber': '-11111', 'emailAddress': 'ABCS#Gmail.com', 'isAllSpeciality': True, 'requestId': 23, 'parentActivityId': None, 'sppData': None}

ccxt OKEx placing orders

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.

How to access element in nested list with condition in python

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.

Python-solidity-parser failed to handle throw keyword

I tried to parse the following code using python-solidity-parser (https://github.com/ConsenSys/python-solidity-parser)
pragma solidity ^0.4.13;
contract someContract {
mapping(address => uint) balances;
function deposit() payable {
balances[msg.sender] += msg.value;
}
function withdrawOkayish(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount; if(!msg.sender.send(amount)) { throw; }
}
}
function withdrawBad2(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount;
if(!msg.sender.call.gas(2500000).value(amount)()) { throw; }
}
}
}
It produces the following output
{'children': [{'name': 'solidity',
'type': 'PragmaDirective',
'value': '^0.4.13'},
{'baseContracts': [],
'kind': 'contract',
'name': 'someContract',
'subNodes': [{'initialValue': None,
'type': 'StateVariableDeclaration',
'variables': [{'expression': None,
'isDeclaredConst': False,
'isIndexed': False,
'isStateVar': True,
'name': 'balances',
'type': 'VariableDeclaration',
'typeName': {'keyType': {'name': 'address',
'type': 'ElementaryTypeName'},
'type': 'Mapping',
'valueType': {'name': 'uint',
'type': 'ElementaryTypeName'}},
'visibility': 'default'}]},
{'body': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '+=',
'right': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'value',
'type': 'MemberAccess'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'deposit',
'parameters': {'parameters': [],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': 'payable',
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [';'],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'send',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawOkayish',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [';'],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [],
'expression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'arguments': [{'number': '2500000',
'subdenomination': None,
'type': 'NumberLiteral'}],
'expression': {'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'call',
'type': 'MemberAccess'},
'memberName': 'gas',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'memberName': 'value',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawBad2',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'}],
'type': 'ContractDefinition'}],
'type': 'SourceUnit'}
I have found that it does not handle the throw keyword. Both if case block contains only ';'.
I am not able to find a way to resolve this issue. Is there any way to resolve this issue.
Created issue here: https://github.com/ConsenSys/python-solidity-parser/issues/11
(Still... not a Python programmer)
This took quite a bit of hacking around on my part just to pick up modifications. (For example, on my system, scripts/antlr4.sh (BTW, docs say script/antlr4, so... off to a great start.) doesn't execute properly)
That said, in the solidity_antlr4 directory is a parser.py source file.
It is missing a visitThrowStatement method.
I added:
def visitThrowStatement(self,ctx):
return Node(ctx=ctx,
type='ThrowStatement')
amongst the other visits* defs.
After moving my code to the site-packages (told ya... not a Python program, and definitely hacking around here, so not the right way to accomplish effecting this change I'm sure)
My output from running python3 -m solidity_parser parse ./samples/so_example.sol > testParse.txt (where ./samples/so_example.sol is your sample input) is:
{'children': [{'name': 'solidity',
'type': 'PragmaDirective',
'value': '^0.4.13'},
{'baseContracts': [],
'kind': 'contract',
'name': 'someContract',
'subNodes': [{'initialValue': None,
'type': 'StateVariableDeclaration',
'variables': [{'expression': None,
'isDeclaredConst': False,
'isIndexed': False,
'isStateVar': True,
'name': 'balances',
'type': 'VariableDeclaration',
'typeName': {'keyType': {'name': 'address',
'type': 'ElementaryTypeName'},
'type': 'Mapping',
'valueType': {'name': 'uint',
'type': 'ElementaryTypeName'}},
'visibility': 'default'}]},
{'body': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '+=',
'right': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'value',
'type': 'MemberAccess'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'deposit',
'parameters': {'parameters': [],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': 'payable',
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'send',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawOkayish',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [],
'expression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'arguments': [{'number': '2500000',
'subdenomination': None,
'type': 'NumberLiteral'}],
'expression': {'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'call',
'type': 'MemberAccess'},
'memberName': 'gas',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'memberName': 'value',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawBad2',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'}],
'type': 'ContractDefinition'}],
'type': 'SourceUnit'}
relevant excerpt example:
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
I don't even know if this is the right content, but it does demonstrate that the solution will be to rebuild with a visitThrowStatement implemented.
(It's absence, would make me suspect other visitor methods may also be missing.)

doing a 'group by', 'sum' and 'count' at one time using panda

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()

Categories

Resources