Binance API Python - How to use a specific output - python

When i let my bot place an order, it gives me something like the following output:
[{
"symbol": "BNBBTC",
"orderId": 3301945,
"clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
"transactTime": 1507725176595,
"price": "0.00000000",
"origQty": "10.00000000",
"executedQty": "10.00000000",
"status": "FILLED",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL"
}]
I want my bot to automatically be able to fetch the orderId so that it is able to continue working with that by itself without me manually typing in the Id.
For example, if i want to cancel that order:
result = client.cancel_order(
symbol='BNBBTC',
orderId='orderId')
I'd need to ask for the Id first, replace that 'orderId' and run again to be able to cancel the order. There has to be a way to automate this, right?

I suggest looking at some basic tutorials on dictionaries. Getting values of keys is and should be the first thing you learn.
In your case with a dictionary as provided, the structure is very plain. So to get the value of orderId you can just use your_dictionary.get("orderId").
Note I use .get instead of dict[key], this way if there is no orderId in your dictionary the console will only output None. Whereas if I use dict[key] and there is no such key, we will get a KeyError.

Related

Preventing script-exiting exceptions when finding JSON values that might not exist?

How would I prevent KeyError when grabbing a value from an API query JSON?
Explanation: I am calling an API for a user one at a time. Each user returns a JSON with a set of information. I am creating a dictionary from a few specific pieces of information in that JSON. However, sometimes users don't have a specific value (such as Role or Username). How can I write my program so it doesn't throw an exception and end the program when it can't find this value? And instead of throwing an exception it just enters a blank for that specific dictionary value? I have looked into .get but I cannot seem to get it to work with my specific use case.
Code:
APResponse = requests.request('POST', APurl, headers=headers, json={'offset': str(AssetPandaCurrentUser), 'limit': '1'})
APResponseJSON = APResponse.json()
AssetPandaUserDict = {
"Username": [APResponseJSON['objects'][0]['data']['field_52']],
"Role": [APResponseJSON['objects'][0]['data']['field_49']['value']],
"User Status": [APResponseJSON['objects'][0]['data']['field_6']['value']],
"Laptop Status": [],
"Laptop Serial": []
}
So if "Role" is blank or missing in the JSON, it will just set "Role" to a blank instead of throwing a KeyError exception.
I have tried this:
"Username": [APResponseJSON.get(['objects'][0]['data']['field_52'])]
But I get an error
TypeError: string indices must be integers
Any ideas?
You can use get() method.
For example:
"Role": [APResponseJSON.get(['objects'][0].get("data", {}).get("field_49"{}).get("value")]
of course if you are sure that APResponseJSON.get(['objects'][0] exists.
You can also prepare pydantic model to easily parse your response.

Listing the Document ID from TinyDB

I am trying to list out the content of db.json from this github (https://github.com/syntaxsmurf/todo/blob/main/main.py) on line 40 in main.py
Specifically this line
for item in db:
table.add_row( item["task"], item["completed_by"], item["status"]) #need to find the right command for pulling data out of tinyDB into these example strings
as you can see I can pull out and list the items just fine that I defined the names on Fx with item["task]
here is an example entry from db.json if you don't wanna take a look at github.
{
"_default": {
"1": {
"completed_by": "Today",
"status": "Pending",
"task": "Shopping"
}
}
Now what I am missing is how do I pull out the default generated ID "1" and list that? I wanna use that to for the user being able to remove it later.
Thank you I hope the question makes sense!
From reddit user azzal07: item.doc_id would be the correct implementation of this.
for item in db:
table.add_row(str(item.doc_id), item["task"], item["completed_by"], item["status"])
Str() is for Rich table function it does not work if it's an int it would seem.

Validate object values against yaml configuration

I have an application where a nested Python dictionary is created based on a JSON document that I get as a response from an API. Example:
colleagues = [
{ "name": "John",
"skills": ["python", "java", "scala"],
"job": "developer"
},
{ "name": "George",
"skills": ["c", "go", "nodejs"],
"job": "developer"
}]
This dictionary can have many more nested levels.
What I want to do is let the user define their own arbitrary conditions (e.g. in order to find colleagues that have "python" among their skills, or whose name is "John") in a YAML configuration file, which I will use to check against the Python dictionary.
I thought about letting them configure that in the following manner in the YAML file, but this would require using exec(), which I want to avoid for security reasons:
constraints:
- "python" in colleagues[x]["skills"]
- colleagues[x]["name"] == "John"
What other options are there for such a problem, so that the user can specify their own constraints for the dictionary values? Again, the dictionary above is just an example. The actual one is much larger in size and nesting levels.
You could use a Lucene query parser to convert queries like "skill:python" and "name:John" to executable predicate functions, and then filter your list of colleagues using those predicates. Googling for "python lucene parser" will turn up several parsing options.

Trying to convert a CSV into JSON in python for posting to REST API

I've got the following data in a CSV file (a few hundred lines) that I'm trying to massage into sensible JSON to post into a rest api
I've gone with the bare minimum fields required, but here's what I've got:
dateAsked,author,title,body,answers.author,answers.body,topics.name,answers.accepted
13-Jan-16,Ben,Cant set a channel ,"Has anyone had any issues setting channels. it stays at �0�. It actually tells me there are �0� files.",Silvio,"I�m not sure. I think you can leave the cable out, because the control works. But you could try and switch two port and see if problem follows the serial port. maybe �extended� clip names over 32 characters.
Please let me know if you find out!
Best regards.",club_k,TRUE
Here's a sample of JSON that is roughly like where I need to get to:
json_test = """{
"title": "Can I answer a question?",
"body": "Some text for the question",
"author": "Silvio",
"topics": [
{
"name": "club_k"
}
],
"answers": [
{
"author": "john",
"body": "I\'m not sure. I think you can leave the cable out. Please let me know if you find out! Best regards.",
"accepted": "true"
}
]
}"""
Pandas seems to import it into a dataframe okay (ish) but keeps telling me I can't serialize it to json - also need to clean it and sanitise, but that should be fairly easy to achieve within the script.
There must also be a way to do this in Pandas, but I'm beating my head against a wall here - as the columns for both answers and topics can't easily be merged together into a dict or a list in python.
You can use a csv.DictReader to process the CSV file as a dictionary for each row. Using the field names as keys, a new dictionary can be constructed that groups common keys into a nested dictionary keyed by the part of the field name after the .. The nested dictionary is held within a list, although it is unclear whether that is really necessary - the nested dictionary could probably be placed immediately under the top-level without requiring a list. Here's the code to do it:
import csv
import json
json_data = []
for row in csv.DictReader(open('/tmp/data.csv')):
data = {}
for field in row:
key, _, sub_key = field.partition('.')
if not sub_key:
data[key] = row[field]
else:
if key not in data:
data[key] = [{}]
data[key][0][sub_key] = row[field]
# print(json.dumps(data, indent=True))
# print('---------------------------')
json_data.append(json.dumps(data))
For your data, with the print() statements enabled, the output would be:
{
"body": "Has anyone had any issues setting channels. it stays at '0'. It actually tells me there are '0' files.",
"author": "Ben",
"topics": [
{
"name": "club_k"
}
],
"title": "Cant set a channel ",
"answers": [
{
"body": "I'm not sure. I think you can leave the cable out, because the control works. But you could try and switch two port and see if problem follows the serial port. maybe 'extended' clip names over 32 characters. \nPlease let me know if you find out!\n Best regards.",
"accepted ": "TRUE",
"author": "Silvio"
}
],
"dateAsked": "13-Jan-16"
}
---------------------------

Parsing Json data sent by android clinet using "post" request in django view

I am trying to loop around a json data sent by my android client. I used the code below but its not working for me. Any possible error that I am doing...????
def api_json(request):
try:
x101=json.loads(request.body)
print x101
for data in x101:
print data+"xp"
asset_code=data['asset_code']
credential=data['credential']
d1=data['d1']
d2=data['d2']
d3=data['d3']
angle=data['angle']
status=data['status']
operator=data['operator']
location=data['location']
print asset_code,credential,d1,d2,d3,angle,status,operator,location
v=Verification(asset_code=asset_code,
scan_time=datetime.datetime.now(),
credential=credential,
d1=d1,
d2=d2,
d3=d3,
angle=angle,
status=status,
operator=operator,
location=location,
image='')
v.save()
except:
print 'nope'
return HttpResponse('success')
error trace:
TypeError: string indices must be integers
Assuming your JSON decodes to a dictionary, for data in x101 iterates through the keys of that dictionary. So data['d1'] will give the TypeError that you see, "string indices must be integers".
Since you have given absolutely no details about what the data structure actually looks like, we can only guess, but you perhaps want to iterate through the dict's values with for data in x101.values().
In any case, you should definitely remove that try/except that does nothing except print "nope". Errors are there for a reason, and silencing them will only prevent you from debugging properly, as we see here.
Edit
x101 is just a single dict. You say that there will frequently be more than one dict, but it can't possibly work like that: the only way to have multiple dicts is to have them inside a list (ie a JSON array). And if so, they would have to always be in a list, even when there is just one. So your structure should be:
[
{
"angle": "10",
"asset_code": "XPS1020",
"credential": "wqw2323ds2",
"d1": "1",
"d2": "2",
"d3": "3",
"location": "Bangalore",
"operator": "pradeep",
"status": "1"
}
]
and then your code will work as is, whether there is a single dict or many.

Categories

Resources