Coibase API v2, get fill_price from a transaction - python

i'm using the coinbase python lib and i want to save all the transactions i made in a json file. But i'm struggling with the "fill_price"(the price for the currency pair at the time of the Fill) info.
Currently I have this:
data = json.load(f)
for i in data:
api_key = i['api_key']
secret_api = i['secret_api']
client = Client(api_key, secret_api)
user = client.get_account("token")
print(user.get_transaction("token")
I'm not listing transaction yet because i can't figure out how to get the info written here
I even tried params, but still nothing

Related

Python - save multiple responses from multiple requests

I am pulling JSON data from an api and I am looking to pass in a different parameter for each request and save each response
My current code
# create an empty list to store each account id
accounts = []
##store in accounts list every id
for each in allAccounts['data']:
accounts.append((each['id']))
#for each account , call a new account id for the url
for id in accounts:
urlAccounts = 'https://example.somewebsite.ie:000/v12345/accounts/'+id+'/users'
I save a response and print out the values.
accountReq = requests.get(urlAccounts, headers=headers)
allUsers = accountReq.json()
for each in allUsers['data']:
print(each['username']," " +each['first_name'])
This is fine and it works but I only store the first ID's response.
How do I store the responses from all of the requests?
So I'm looking to send multiple requests where the ID changes every time and save each response essentially.
I'm using python version 3.10.4 .
My code for this in case anyone stumbles across this.
# list of each api url to use
link =[]
#for every id in the accounts , create a new url link into the link list
for i in accounts:
link.append('https://example.somewebsite.ie:000/v12345/accounts/'+i+'/users')
#create a list with all the different requests
accountReq = []
for i in link:
accountReq.append(requests.get(i, headers=headers).json())
# write to a txt file
with open('masterSheet.txt', 'x') as f:
#for every request
for each in accountReq:
#get each accounts data
account = each['data']
#for each accounts data
#get each users email and names
for data in account:
sheet=(data['username']+" "+" ",data['first_name'],data['last_name'])
f.write(str(sheet)+"\n")

How to read data from Azure's CosmosDB in python

I have a trial account with Azure and have uploaded some JSON files into CosmosDB. I am creating a python program to review the data but I am having trouble doing so. This is the code I have so far:
import pydocumentdb.documents as documents
import pydocumentdb.document_client as document_client
import pydocumentdb.errors as errors
url = 'https://ronyazrak.documents.azure.com:443/'
key = '' # primary key
# Initialize the Python DocumentDB client
client = document_client.DocumentClient(url, {'masterKey': key})
collection_link = '/dbs/test1/colls/test1'
collection = client.ReadCollection(collection_link)
result_iterable = client.QueryDocuments(collection)
query = { 'query': 'SELECT * FROM server s' }
I read somewhere that the key would be my primary key that I can find in my Azure account Keys. I have filled the key string with my primary key shown in the image but key here is empty just for privacy purposes.
I also read somewhere that the collection_link should be '/dbs/test1/colls/test1' if my data is in collection 'test1' Collections.
My code gets an error at the function client.ReadCollection().
That's the error I have "pydocumentdb.errors.HTTPFailure: Status code: 401
{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ncolls\ndbs/test1/colls/test1\nmon, 29 may 2017 19:47:28 gmt\n\n'\r\nActivityId: 03e13e74-8db4-4661-837a-f8d81a2804cc"}"
Once this error is fixed, what is there left to do? I want to get the JSON files as a big dictionary so that I can review the data.
Am I in the right path? Am I approaching this the wrong way? How can I read documents that are in my database? Thanks.
According to your error information, it seems to be caused by the authentication failed with your key as the offical explaination said below from here.
So please check your key, but I think the key point is using pydocumentdb incorrectly. These id of Database, Collection & Document are different from their links. These APIs ReadCollection, QueryDocuments need to be pass related link. You need to retrieve all resource in Azure CosmosDB via resource link, not resource id.
According to your description, I think you want to list all documents under the collection id path /dbs/test1/colls/test1. As reference, here is my sample code as below.
from pydocumentdb import document_client
uri = 'https://ronyazrak.documents.azure.com:443/'
key = '<your-primary-key>'
client = document_client.DocumentClient(uri, {'masterKey': key})
db_id = 'test1'
db_query = "select * from r where r.id = '{0}'".format(db_id)
db = list(client.QueryDatabases(db_query))[0]
db_link = db['_self']
coll_id = 'test1'
coll_query = "select * from r where r.id = '{0}'".format(coll_id)
coll = list(client.QueryCollections(db_link, coll_query))[0]
coll_link = coll['_self']
docs = client.ReadDocuments(coll_link)
print list(docs)
Please see the details of DocumentDB Python SDK from here.
For those using azure-cosmos, the current library (2019) I opened a doc bug and provided a sample in GitHub
Sample
from azure.cosmos import cosmos_client
import json
CONFIG = {
"ENDPOINT": "ENDPOINT_FROM_YOUR_COSMOS_ACCOUNT",
"PRIMARYKEY": "KEY_FROM_YOUR_COSMOS_ACCOUNT",
"DATABASE": "DATABASE_ID", # Prolly looks more like a name to you
"CONTAINER": "YOUR_CONTAINER_ID" # Prolly looks more like a name to you
}
CONTAINER_LINK = f"dbs/{CONFIG['DATABASE']}/colls/{CONFIG['CONTAINER']}"
FEEDOPTIONS = {}
FEEDOPTIONS["enableCrossPartitionQuery"] = True
# There is also a partitionKey Feed Option, but I was unable to figure out how to us it.
QUERY = {
"query": f"SELECT * from c"
}
# Initialize the Cosmos client
client = cosmos_client.CosmosClient(
url_connection=CONFIG["ENDPOINT"], auth={"masterKey": CONFIG["PRIMARYKEY"]}
)
# Query for some data
results = client.QueryItems(CONTAINER_LINK, QUERY, FEEDOPTIONS)
# Look at your data
print(list(results))
# You can also use the list as JSON
json.dumps(list(results), indent=4)

How to get information about groups liked by a user using Facebook Graph API

I am very new to the Graph API and a basically trying to write a python (v2.7) script which takes as input the userID of a Facebook user and returns names/IDs of all groups/pages that have been liked by the user.
I have managed to acquire an Access Token that uses the following permissions: user_likes and user_groups. Do I need anything else?
I have used the following code so far to get a JSON dump of all the output from this access token:
import urllib
import json
import sys
import os
accessToken = 'ACCESS_ToKEN_HERE' #INSERT YOUR ACCESS TOKEN
userId = sys.argv[1]
limit=100
# Read my likes as a json object
url='https://graph.facebook.com/'+userId+'/feed?access_token='+accessToken +'&limit='+str(limit)
data = json.load(urllib.urlopen(url))
id=0
print str(data)
I did get some JSON data but I couldn't find any page/group related info in it neither did it seem to be the most recently updated data! Why is this?
Also, what are the field names that must be tracked to detect a page or a group in the likes data? Please help!
You are using the wrong API- /feed - this will fetch the feeds/posts of the user, not the pages/groups.
To get the groups he has joined:
API: /{user-id}/groups
Permissions req: user_groups
To get the pages he has liked:
API: /{user-id}/likes
Permissions req: user_likes

How can I use the Shopify python api adapter to pull assets?

Shopify Python API on Github
I am able to get this far and pull in a list of all of the assets, but can't figure out how to actually pull them down from here. Any ideas?
SHOP_NAME = "SHOP-NAME"
API_PASSWORD = "API-PASSWORD"
session = shopify.Session(SHOP_NAME)
session.token = API_PASSWORD
shopify.ShopifyResource.activate_session(session)
assets = shopify.Asset.find()
shopify.Asset.find() is using the list endpoint which doesn't include the asset value, and it sounds like that is what you are after.
If you use the receive a single Asset endpoint, then you can also get the assets value.
asset = shopify.Asset.find(assets[0].key, theme_id=assets[0].theme_id)
print asset.value

get logged in user data using facebook api in python and store in mongo database

i have already developed a FB app.now,i am trying to harvest the user data and store it into the database.But, one thing i am not understanding is how to store the data of the logged in user in mongo db using graph api? prior to that how to fetch data in python?
I know this is repetitive but,i am not able to clear my concept of how to use the api in python.
i have tried this:
#!/usr/bin/env python
# encoding: utf-8
import json
import urllib2
import re
def getdata(id):
'''Queries the Facebook API for the specific group ID, and populates the
results dictionary with the Group ID, User Name, and User ID'''
#An access token is now required for quering the group messages.
a_token='access_token=<access token>'
urlquery='https://graph.facebook.com/'+id+'/feed&limit=20?access_token='+ a_token +''
print urlquery
data=json.load(urllib2.urlopen(urlquery))
harvest = []
results = {}
for item in data['data']:
try:
results = {}
results['grpid'] = id
user = item['from']
results['uname'] = user['name']
results['uid'] = user['id']
harvest.append(results)
except:
pass
print len(harvest)
def getgrpids():
urlquery='https://graph.facebook.com/<any username>'#can i put my app name?
#not clear from examples given on facebook graph api page.
data=json.load(urllib2.urlopen(urlquery))
ids=[]
for item in data['data']:
try:
ids.append(item['id'])
except:
pass
return ids
def main():
idres=getgrpids()
for id in idres:
#Loops through all of the group ids returned by getgrpids()
print 'Group ID:', id
getdata(id)
if __name__ == '__main__':
main()
Now the problem goes like this.When i change the username to some other the error report says that the user should be logged in or the app cannot get the user details.I am not understanding this since my friend was online at that time still the error?
Am i missing something?secondly i am not able to put my APP NAME IN THE QUERY (see the comment). Somebody please help.
thanks,
Assuming that you have access token of the user:
import facebook as fb
graph = fb.GraphAPI(access_token)
profile = graph.get_object("me")
# if you want to get the user's profile picture (you need to have the session UID)
profile.update({"picture": "http://graph.facebook.com/%s/picture?type=large" % uid})

Categories