I want to get my balance using the FTX api.
Refer to the Python sample code in the api docs and change it as follows.
But it returns an error message.
{"success":false,"error":"Not logged in: Invalid signature"}
I don't know why the signature is wrong.
Can someone please help?
import json
import hmac
import time
import requests
# API Keys
with open('../json/api.json', 'r') as f:
api = json.load(f)
accessKey = api['FTX']['ACCESS']
secretKey = api['FTX']['SECRET']
endpoint = 'https://ftx.com/api'
url = '/wallet/balances'
method = 'GET'
ts = int(time.time() * 1000)
signature_payload = f'{ts}{method}{url}'.encode()
signature = hmac.new(secretKey.encode(), signature_payload, 'sha256').hexdigest()
headers = {
'FTX-KEY': accessKey,
'FTX-SIGN': signature,
'FTX-TS': str(ts)
}
res = requests.request(method, endpoint+url, headers=headers)
print(res.text)
Reference
FTX API Authentication
FTX API Get Balance
Try changing the url to ftx.us
and the headers to
'FTXUS-KEY': accessKey,
'FTXUS-SIGN': signature,
'FTXUS-TS': str(ts)
signature_payload = f'{ts}{method}{url}'.encode()
Where the URL would look like => /api/wallet/balances
You need to include /api in your URL.
Related
I would like to know how to scrape data (position, name of the trader, symbol,..)from the Binance leaderboard with Python and Binance API.
Thanks for your answers !
This is my actual code wiche doesn't work.
from binance.client import Client, AsyncClient
api_key = 'xxx'
api_secret = 'xxx'
client = Client(api_key, api_secret)
leaderboard = client.futures_leaderboard()['positions']
I tried the code juste above, but there is no results.
You can use this third party API. Remember to check its documentation.
Here is an example of code to achieve what I think you want:
Getting traders:
import requests
# API URL with its endpoint to use
url = "https://binance-futures-leaderboard1.p.rapidapi.com/v2/searchLeaderboard"
# Parameters to use
querystring = {
"isShared": True, # Set to true if you want to get traders sharing their positions
"limit": 10 # Total traders to get
}
# Headers to use
headers = {
"X-RapidAPI-Key": "YOUR-API-KEY",
"X-RapidAPI-Host": "binance-futures-leaderboard1.p.rapidapi.com"
}
# Get response
response = requests.get(url, headers=headers, params=querystring)
# Print response to JSON
print(response.json())
Getting trader positions:
import requests
# Now we use the endpoint to get the positions shared by a trader
url = "https://binance-futures-leaderboard1.p.rapidapi.com/v2/getTraderPositions"
# Parameters to use
querystring = {
"encryptedUid": "<REQUIRED>", # Trader UUID
"tradeType": "PERPETUAL" # Set to PERPETUAL to get USDⓈ-M positions
}
# Parameters to use
headers = {
"X-RapidAPI-Key": "YOUR-API-KEY",
"X-RapidAPI-Host": "binance-futures-leaderboard1.p.rapidapi.com"
}
# Get response
response = requests.get(url, headers=headers, params=querystring)
# Print response to JSON
print(response.json())
You have to fill in the api key and secret
How to Create API
Creating an API allows you to connect to Binance’s servers via several
programming languages.
I'm trying to use the sandbox from https://fhir.epic.com/ for Backend Services.
I am following this tutorial : https://fhir.epic.com/Documentation?docId=oauth2§ion=BackendOAuth2Guide :
I already register a new app, created a JWT (using SSL keys) tested the JWT on https://jwt.io/ : works fine! When I POST the JWT to the endpoint (https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token) I get an access token.
Using this access token, I can access a single patient Appointment ressource but that's it. I don't understand how to access other Resources like DiagnosticReport, Observations, etc. I added them in the scope of my App of course but still doesn't seems to work.
What am I missing here ?
This is my code where I can access the Appointment resource:
import json
from datetime import datetime, timedelta, timezone
import requests
from requests.structures import CaseInsensitiveDict
from jwt import (
JWT,
jwk_from_dict,
jwk_from_pem,
)
from jwt.utils import get_int_from_datetime
import random
import xmltodict
def main():
instance = JWT()
message = {
# Client ID for non-production
'iss': 'my_iss_here',
'sub': 'my_sub_here',
'aud': 'https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token',
'jti': f'7777-7777-7777-7777-7777{random.randint(100,1000)}',
'iat': get_int_from_datetime(datetime.now(timezone.utc)),
'exp': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(minutes=2)),
}
# Load a RSA key from a PEM file.
with open('./privatekey.pem', 'rb') as fh:
signing_key = jwk_from_pem(fh.read())
compact_jws = instance.encode(message, signing_key, alg='RS384')
headers = {}
headers['Content-Type'] = 'application/x-www-form-urlencoded'
data = {
'grant_type': 'client_credentials',
'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion': compact_jws
}
x = requests.post('https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token', headers=headers, data=data)
access_token = x.json()['access_token']
headers = {}
headers['Authorization'] = f'Bearer {access_token}'
x = requests.get('https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/STU3/Appointment/eWLhfjXHp4RUczv2om.1Ii2uiHcDc6rMEjO0xHBA3', headers=headers)
print(x.content)
When I change the request for one of these two (of the online tutorial), it doesn't work:
x = requests.get('https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4/Observation/erXuFYUfucBZaryVksYEcMg3', headers=headers)
I'm using the FHIR ID of Camilia Lopez (test patient). She supposed to have a Observation Ressource but I get an error :
<OperationOutcome xmlns="http://hl7.org/fhir"><issue><severity value="fatal" /><code value="not-found" /><details><coding><system value="urn:oid:1.2.840.114350.1.13.0.1.7.2.657369" /><code value="59008" /><display value="The FHIR ID provided was not found." /></coding><text value="The FHIR ID provided was not found." /></details><diagnostics value="Invalid FHIR ID provided" /><location value="/f:id" /><expression value="id" /></issue></OperationOutcome>
Neither of those appear to be valid FHIR IDs for the resources requested in the Epic on FHIR sandbox. The IDs in the tutorial are just examples. You should use the test data reference here for identifying Patient and other resources that are available to test with. You should also ensure you are including all the necessary headers in your calls.
I am trying to fetch data from API from a tool called Paylocity.
I have managed to generate the access token and trying to connect to their API as below
client_id = client_id
client_secret = client_secret
company_id = company_id
prod_auth_url = 'https://apisandbox.paylocity.com/IdentityServer/connect/token'
body_params = urllib.parse.urlencode({'grant_type': 'client_credentials','scope':'WebLinkAPI'})
# Requests can use auth= for basic authentication
auth_response = requests.post(prod_auth_url,auth=(client_id, client_secret), data=urllib.parse.urlencode(body_params))
response = json.loads(auth_response.content)
api_call_headers = {'Authorization': 'Bearer ' + response['access']}
This however returns an error
TypeError: not a valid non-string sequence or mapping object
Figured out by changing the ** auth_response** variable as below
auth_response = requests.post(prod_auth_url,auth=(client_id, client_secret), data=body_params)
response = json.loads(auth_response.text)
auth_response.content gives you a byte string. Which likely causes the error. Use auth_response.text.
Better even: You don't need json.loads() here.
Just do:
response = auth_response.json()
I try to acess data from an Exchange Platform with API.
I have my API_Key and my SECRET_KEY, and I have the documentation of that Platform here:
https://apidocs.exir.io/
I generate the "signature-key" just as described in the documentation under "Authentication" chapter and then try to test it with a sample GET request with only one parameter.
Now if I run the Code I get "message": "Access Denied: Invalid API Signature"
Can you please help me to find the wrong thing in this code?
I think I do something wrong with params because if I use other GET orders without parameters it works!
Thank you in advance!
import time
import json
import hmac
import hashlib
import requests
API_KEY = '*****'
SECRET_KEY = '*****'
BASE_URL = 'https://api.exir.io'
timestamp = str(int(time.time()+10))
headers = {
'api-key': API_KEY,
'api-expires': timestamp} # see documentation under "Authentication"
PATH = '/v1/user/orders' # This ist just a simple example, which uses "params". See Exir documentation under "Get All Orders"
params = {"symbol":"btc-irt"}
string = 'GET'+timestamp+str(params) # see Exir API doumentation under "Authentication"
headers['api-signature'] = hmac.new(SECRET_KEY.encode('utf-8'), string.encode('utf-8'), hashlib.sha256).hexdigest()
url = 'https://api.exir.io/v1/user/orders?symbol=btc-irt'
r = requests.get(url, headers=headers)
data = r.json()
print(json.dumps(data, indent=2))
A lot of what you are doing is unnecessary, actually. The requests library handles most of what you are trying to do.
import requests
API_KEY = '*****'
SECRET_KEY = '*****'
BASE_URL = 'https://api.exir.io'
timestamp = str(int(time.time()+10))
headers = {
'api-key': API_KEY,
'api-expires': timestamp
}
url = 'https://api.exir.io/v1/user/orders?symbol=btc-irt'
r = requests.get(url, headers=headers)
The library will do the encoding for you.
You mixed the post and get request parameters. For the get request, you only need to include the params in the URL to sign. In your case it will be:
PATH = '/v1/user/orders?symbol=btc-irt'
string = 'GET/' + PATH + timestamp
and thank you for you useful help already.
I am trying to make an API call using python. Sadly, the only documentation of the API is an implementation already existing in C#.
My problem is, that after i acquire an Azure AADTokenCredential object - i simply do not know how to use it in my HTTPS request.
def get_data_from_api(credentials):
serialNumber = "123456789"
fromDate = "01/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS
untilDate = "09/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS
PARAMS = {
serialNumber: serialNumber,
fromDate: fromDate,
untilDate: untilDate
}
url = "https://myapi.azurewebsites.net/api/sensordata/GetBySerialNumber"
r = requests.get(url = url, header={"Authorization": credentials}, params=PARAMS)
print(r)
#data = r.json()
return data
The credentials is an msrestazure.azure_active_directory.AADTokenCredentials retrieved using the adal package.
The above code results in an error as the header object can only be strings.
My question is - How do i pass the authorization object in the correct way?
The C# implementation looks like this:
// Make a request to get the token from AAD
AuthenticationResult result = Task.Run(async () => await authContext.AcquireTokenAsync(resource, cc)).Result;
// Get the auth header which includes the token from the result
string authHeader = result.CreateAuthorizationHeader();
// ...
// Prepare a HTTP request for getting data.
// First create a client
HttpClient client = new HttpClient();
// Create the actual request. It is a GET request so pass the arguments in the url is enough
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, $"https://api.azurewebsites.net/api/sensordata/GetBySerialNumber?serialNumber={serialNumber}&from={fromDate}&until={untilDate}");
// Add the required authorization header that includes the token. Without it the request will fail as unauthorized
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
// Prepare the response object
HttpResponseMessage response = Task.Run(async () => await client.SendAsync(request)).Result;
So yes! I finally solved it.
My problem was that i was passing on the ADAL object to the requests phase, however what I needed to do was pass on the actual token that is retrieved using: 'credentials = context.acquire_token_with_client_credentials(resource_uri,client_id,client_secret)'.
Here credentials is a dictionary and what the requests needs in the header for authentication was:
header = {
"Authorization": "Bearer "+credentials["accessToken"]
}
r = requests.get(url=url, headers=header, params=PARAMS)
passing this on to the requests.get method worked!