I'm trying to get some parameters of my orders from Python-Binance API.
In this case, I would like to get only the 'status' of an order and save it into a variable.
I used this to get my last order :
orders = client.get_all_orders(symbol=symbol, limit=1)
And I get this result:
[{'clientOrderId': 'HzHxjogJf5rXrzD2uFnTyMn',
'cummulativeQuoteQty': '12.06757100',
'executedQty': '0.00030000',
'icebergQty': '0.00000000',
'isWorking': True,
'orderId': 88978639302,
'orderListId': -1,
'origQty': '0.00030000',
'origQuoteOrderQty': '0.00000000',
'price': '31558.57000000',
'side': 'BUY',
'status': 'FILLED',
'stopPrice': '31592.06000000',
'symbol': 'BTCUSDT',
'time': 1612653434918,
'timeInForce': 'GTC',
'type': 'STOP_LOSS_LIMIT',
'updateTime': 1612109872451}]
Tried to print just the status:
pprint.pprint(orders['status'])
But it returns an error:
TypeError: list indices must be integers or slices, not str
Try this:
pprint.pprint(orders[0]['status'])
order variable is a list that contains dictionary. To get access to first element of the list use [0]. Now you only get value from dictionary. You can do this using [dictionary_key] in this example ['status']. Combining this you can print status.
If you are not sure which type is your variable use simply print(type(variable_name))
Related
In the following code I'm creating a function intended to return the order ID of a trade from Binance. I am receiving all of the trade data in JSON form but when I try use json.loads to access the data using python I get the following two errors...
list indices must be integers or slices, not str
the JSON object must be str, bytes or bytearray, not list
The code follows...
def fetch_order_ID(symbol):
open_stop_loss = client.get_open_orders(symbol = symbol)
json_message = json.loads(open_stop_loss)
order_ID = json_message['orderId']
print(order_ID)
fetch_order_ID(TRADE_SYMBOL)
the JSON message...
[{'clientOrderId': 'web_f90baa98950a471485d5f4ab387d495d',
'cummulativeQuoteQty': '0.00000000',
'executedQty': '0.00000000',
'icebergQty': '0.00000000',
'isWorking': True,
'orderId': 1623049977,
'orderListId': -1,
'origQty': '0.01400000',
'origQuoteOrderQty': '0.00000000',
'price': '1800.00000000',
'side': 'BUY',
'status': 'NEW',
'stopPrice': '0.00000000',
'symbol': 'ETHBUSD',
'time': 1617387578966,
'timeInForce': 'GTC',
'type': 'LIMIT',
'updateTime': 1617387578966}]
json_message appears to be a list with one element (the dictionary), hence the error when trying to index a list with a string. Try json_message = json.loads(open_stop_loss)[0] or use a for loop.
Working on a little project and I may be in over my head. Using the CoinMarketCap API, I am trying to understand how to parse through their results to pull out just specific pieces of the returned value.
As an example:
result = {'status': {'timestamp': '2021-02-22T00:04:51.978Z', 'error_code': 0, 'error_message': None, 'elapsed': 46, 'credit_count': 1, 'notice': None}, 'data': {'1INCH': {'id': 8104, 'name': '1inch', 'symbol': '1INCH', 'slug': '1inch', 'cmc_rank': 83, 'last_updated': '2021-02-22T00:03:09.000Z', 'quote': {'BTC': {'price': 8.793673178965842e-05, 'volume_24h': 4010.9008604493424, 'percent_change_1h': 1.77689058, 'percent_change_24h': -3.76351861, 'percent_change_7d': -19.9798068, 'percent_change_30d': 66.4333541, 'market_cap': 12615.667000751586, 'last_updated': '2021-02-22T00:03:02.000Z'}}}}}
I am unable to figure out how to extract the 'symbol', 'cmc_rank', and 'market_cap' values from this variable. What is the proper approach to doing so?
Thank you
Try this solution, it should give you what you're looking for:
symbol = result['data']['1INCH']['symbol']
cmc_rank = result['data']['1INCH']['cmc_rank']
market_cap = result['data']['1INCH']['quote']['BTC']['market_cap']
Did you try this?
print(result["data"]["1INCH"]["symbol"])
print(result["data"]["1INCH"]["cmc_rank"])
print(result["data"]["1INCH"]["quote"]["BTC"]["market_cap"])
The "{}" indicate a python dict (dictionary) -- (square brackets [] would be a list, and parentheses () would be a tuple). Dicts can also be nested (same with lists and tuples)
In this case, you have a nested dictionar(ies). It's helpful to do some indentation...
result = {
'status': {
'timestamp': '2021-02-22T00:04:51.978Z',
'error_code': 0,
'error_message': None, 'elapsed': 46, 'credit_count': 1, 'notice': None},
'data': {
'1INCH': {
'id': 8104, 'name': '1inch', 'symbol': '1INCH', 'slug': '1inch', 'cmc_rank': 83, 'last_updated': '2021-02-22T00:03:09.000Z',
'quote': {
'BTC': {
'price': 8.793673178965842e-05, 'volume_24h': 4010.9008604493424, 'percent_change_1h': 1.77689058, 'percent_change_24h': -3.76351861, 'percent_change_7d': -19.9798068, 'percent_change_30d': 66.4333541, 'market_cap': 12615.667000751586, 'last_updated': '2021-02-22T00:03:02.000Z'}}}}}
The part to the left of the colon (:) in a dict is the key and the part to the right is the value.
So in the example you gave: result['data']['1INCH']['symbol'] would give you the value of symbol and result['data']['1INCH']['quote']['BTC']['market_cap'] would give you the value of market cap.
HOWEVER, this will only work if the keys don't change. In this case, it looks like the result is coming back with the symbol ('1INCH') as the key. Same with the currency ('BTC'). If you are always expecting '1INCH' and 'BTC' then you can hard code it. On the other hand, if the symbol and/or currency changes you would want to (a) store variables and use those instead (e.g. symbol='1INCH' .... result = x.query(symbol).... result['data'][symbol].....) OR (2) get the keys or (3) loop.
To get a list of the keys of any dictionary -- in this example, the keys of the dictionary 'data' : dkeys = list(result['data'].keys()) ... you can then check the length with len(dkeys) and/or access the key with numbers (since it's a list) dkeys[0]. So, something like result['data'][dkeys[0]]...
Or you could loop - which would be great if you have multiple results:
#the .items() method will return 2 values - the key and value for each entry
for k, v in result['data'].items():
#k would be the symbol in this case and v is the dictionary represented by that key
market_cap = v['quote']['BTC']['market_cap']
#note if there are multiple symbols here, it would overwrite market_cap...
I am trying to figure out how to do an assertion to see if a number exists in a list.
So my list looks like:
data = [{'value': Decimal('4.21'), 'Type': 'sale'},
{'value': Decimal('84.73'), 'Type': 'sale'},
{'value': Decimal('70.62'), 'Type': 'sale'},
{'value': Decimal('15.00'), 'Type': 'credit'},
{'value': Decimal('2.21'), 'Type': 'credit'},
{'value': Decimal('4.21'), 'Type': 'sale'},
{'value': Decimal('84.73'), 'Type': 'sale'},
{'value': Decimal('70.62'), 'Type': 'sale'},
{'value': Decimal('15.00'), 'Type': 'credit'},
{'value': Decimal('2.21'), 'Type': 'credit'}]
Now I am trying to iterate through the list like:
for i in data:
s = i['value']
print(s)
assert 2.21 in i['value'], "Value should be there"
I am somehow only getting the first number returned for "value" i.e. 4.21
You have two problems as other commenters pointed out. You compare the wrong data types (str against Decimal, or after your edit, float against Decimal) and you also terminate on first failure. You probably wanted to write:
assert Decimal('2.21') in (d["value"] for d in data)
This will extract the value of the "value" key from each sub-dictionary inside the list and search for Decimal('2.21') in them.
I am working in Django and I am saving the below variable as a list:
manifestData = form.cleaned_data
so if I print this it returns:
[{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}]
I need to pull the ProductCode values out of this and save them to variables. Really I need the values APPLES-1 and ORANGES-1 pulled from the list. What would my best approach be for this?
Thanks!
so you need to use map function:-
map(lambda x: x['ProductCode'], manifestData)
Can you share your Product model? Assuming, the model has a field as name you could try
codes = map(lambda x: x['ProductCode'].name, manifestData)
I am trying to extract a specific column or layer, not sure what you want to call it.. that is inside a json object of which I have converted to what I think is a layered list but I have two problems, my check to see if "return" is in the list is not finding anything even though when printing jsonb I can see it is in the list, my second problem is how do I extract a certain column from a layer.. in this case I need the number "43343243" out the second layer and put into a variable I tried referencing it with jsonb["return"][0] and I got a key error..
My code:
def worker(pairtxt):
while (1 < 2):
balanceobject = requests.post(urlauth, headers=headers, data=paybytes)
json_stringb = str(balanceobject.content, 'utf8')
jsonb = json.loads(json_stringb)
print(jsonb)
if "return" in jsonb: #fails
print(jsonb["return"]["0"]) # key error
print(jsonb["return"]) # prints everything even layers under the number
My jsonb print output
{'success': 1, 'return': {'43343243': {'status': 0, 'pair': 'rgeg',
'type': 'sell', 'amount': 0.01000002, 'rate': 1.0,
'timestamp_created': 1502642258}}}
Because 43343243 is a key not a value, you need to get the keys of return :
jsonb = {'success': 1, 'return': {'43343243': {'status': 0, 'pair': 'rgeg', 'type': 'sell', 'amount': 0.01000002, 'rate': 1.0, 'timestamp_created': 1502642258}}}
numberWanted = list(jsonb['return'].keys())[0]
print(numberWanted) # => 43343243
I think you are looking at the output jsonb as a list (which is not true). jsonb is a dictionary. To verify that you can do this:
print(type(jsonb))
A dictionary has key-value pairs.
success is a key and 1 is the value.
return is a key and the value is another dictionary.
{
'43343243': {
'status': 0,
'pair': 'rgeg',
'type': 'sell',
'amount': 0.01000002,
'rate': 1.0,
'timestamp_created': 1502642258
}
}
If you want to access 43343243, then you can do jsonb['return']['43343243']