I trying work with Poloniex API. And I try get balances via Trading API methods. And I try do it with requests library like this:
import requests
import hmac
import hashlib
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
With this code I always get error with message: "Request: {'error': 'Invalid command.'}". What I do wrong?
From other side code below returns data without any problem! Look at this, please:
import requests
import hmac
import hashlib
import json
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
res = urllib.request.urlopen(req, timeout=20)
Ret_data = json.loads(res.read().decode('utf-8'))
print('Request: {0}'.format(Ret_data))
return Ret_data
I using Python 3.6
It's best to let requests handle post data because it creates the appropriate headers. Other than that i don't see anything wrong with your code.
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(
str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post(
'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
Or you could specify the 'Content-Type' in headers if you want to have a string in data, example,
headers = {
'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'],
'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)
Related
I wanted to make a program where I can check the order details of my order at Bithumb Exchange.
So I looked at the docs(https://api.bithumb.com/info/orders) and made it, but the same error code kept coming out, so I don't know what to do.
import time
import math
import base64
import hmac, hashlib
import urllib.parse
import requests
class XCoinAPI:
api_url = "https://api.bithumb.com";
api_key = "";
api_secret = "";
def __init__(self, api_key, api_secret):
self.api_key = api_key;
self.api_secret = api_secret;
def body_callback(self, buf):
self.contents = buf;
def microtime(self, get_as_float = False):
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
def usecTime(self) :
mt = self.microtime(False)
mt_array = mt.split(" ")[:2];
return mt_array[1] + mt_array[0][2:5];
def xcoinApiCall(self, endpoint, rgParams):
# 1. Api-Sign and Api-Nonce information generation.
# 2. Request related information from the Bithumb API server.
#
# - nonce: it is an arbitrary number that may only be used once.
# - api_sign: API signature information created in various combinations values.
endpoint_item_array = {
"endpoint" : endpoint
}
uri_array = dict(endpoint_item_array, **rgParams) # Concatenate the two arrays.
str_data = urllib.parse.urlencode(uri_array)
nonce = self.usecTime()
data = endpoint + chr(1) + str_data + chr(1) + nonce
utf8_data = data.encode('utf-8')
key = self.api_secret
utf8_key = key.encode('utf-8')
h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
hex_output = h.hexdigest()
utf8_hex_output = hex_output.encode('utf-8')
api_sign = base64.b64encode(utf8_hex_output)
utf8_api_sign = api_sign.decode('utf-8')
headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Api-Key": self.api_key,
"Api-Nonce": nonce,
"Api-Sign": utf8_api_sign
}
url = self.api_url + endpoint
r = requests.post(url, headers=headers, data=uri_array)
return r.json()
a = XCoinAPI(api_key="MYKEY1c", api_secret="MYKEY2")
aa= a.xcoinApiCall("/info/orders",{"order_currency":"LN","payment_currency":"BTC"})
print(aa)
{'status': '5100', 'message': 'Bad Request.(Auth Data)'}
Process finished with exit code 0
The error code 5100, bad request keeps coming up(https://apidocs.bithumb.com/docs/api-%EC%A3%BC%EC%9A%94-%EC%97%90%EB%9F%AC-%EC%BD%94%EB%93%9C)
I really don't know which code to modify.
I think it's a parameter problem with XcoinApiCall, but I don't know.
I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.
The code I have for the query is as follows:
import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse
def create_checksum(http_method, raw_url, headers, request_body):
string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
return base64_string
def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
iat=time.time(), algorithm='HS256', version='V1'):
payload = {'appid': appication_id,
'iat': iat,
'version': version,
'checksum': create_checksum(http_method, raw_url, headers, request_body)}
token = jwt.encode(payload, api_key, algorithm=algorithm)
return token
# Use this region to setup the call info of the Apex Central server (server url, application id, api key)
# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'
productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''
payload = {
'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'
}
useRequestBody = json.dumps(payload)
jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
productAgentAPIPath + useQueryString,
canonicalRequestHeaders, useRequestBody, iat=time.time())
headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)
print(r.status_code)
if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
print(json.dumps(r.json(), indent=4))
else:
print(r.text)
I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post
the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2
I wanted to trade on Wootrade with some bots but I have a hard time getting the authentification right..
Here is my code:
import time
import hmac
from urllib.parse import urlencode
import requests
import hashlib, json, pprint
YOUR_API_SECRET = "SECRET"
YOUR_API_KEY = "KEY"
api_endpoint = "https://api.staging.woo.network/v1/client/info"
ts = int(time.time() * 1000)
hashedsig = hashlib.sha256(YOUR_API_SECRET.encode('utf-8'))
params = urlencode({
"signature" : hashedsig,
"timestamp" : ts,
})
hashedsig = hmac.new(YOUR_API_SECRET.encode(), params.encode('utf-8'), hashlib.sha256).hexdigest()
userdata = requests.get(api_endpoint,
params = {
"x-api-signature": hashedsig,
"x-api-timestamp": ts,
"x-api-key": YOUR_API_KEY
},
headers = {
"x-api-signature": hashedsig,
"x-api-timestamp": str(ts),
"x-api-key": YOUR_API_KEY
}
)
print(userdata.json())
and that's the error message:
{'success': False, 'code': -1002, 'message': 'invalid api key.'}
But I am pretty sure, that my api-key is right, I tried a new one and that didnt work either.
I tried to follow the instructions on the website: https://kronosresearch.github.io/wootrade-documents/#example
But I am not that familiar with hashing my authentication, because the exchanges I used before had either some examples in python or a package to download, so I am not sure, what I did wrong.
I am thankful for any help I can get!
Cheers!
You should also send your params in requests, the following code is how I make it work to get account orders:
import requests
import datetime
import time
import hmac
import hashlib
from collections import OrderedDict
class Client():
def __init__(self, api_key=None, api_secret=None):
self.api_key = api_key
self.api_secret = api_secret
self.base_api = "https://api.woo.network/v1/"
def get_signature(self, params, timestamp):
query_string = '&'.join(["{}={}".format(k, v) for k, v in params.items()]) + f"|{timestamp}"
signature = hmac.new(
self.api_secret.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
def get_orders(self, symbol):
url = self.base_api + "orders/"
params = {
"symbol": symbol
}
params = OrderedDict(sorted(params.items()))
timestamp = str(int(time.time() * 1000))
signature = self.get_signature(params, timestamp)
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'x-api-key': self.api_key,
'x-api-signature': signature,
'x-api-timestamp': timestamp,
'cache-control': 'no-cache'
}
resp = requests.get(url=url, params=params, headers=headers).json()
print(resp)
If you have any further questions, please join the WOOTRADE official telegram group and ask the admins~
(Please don't do any transfer if anyone ask you to do so in the group!)
Telegram: T.me/wootrade
Or you can try this python library for wootrade API
https://github.com/wanth1997/python-wootrade?fbclid=IwAR15onh2IX4KX85ahG-hJjXspFwhrTLHSNWGyW7n8c5kAw_8U4cQocbZEEc
Trying to get information with post request but it returns RESPONSE [500]. I have tried to use the get response and it returns response 200 code. I copied the form_data from the website and included in my code.
import requests, json
from bs4 import BeautifulSoup as bs
from requests.utils import quote
url = 'https://mpcr.cbar.az/service/mpcr.publicSearchApplication'
tax_ids = [
'1000276532',
]
data = {
'searchFilter': {"fields":"{\"orgTin\":\"%s\"}"},
'compId': 'frontend',
'access_token': '123',
'refresh_token': '123',
'token': '123',
'requestNumber': '1p5i9m5s9T9W8',
'_token': 'MQ2cZyD092qFKknKpZMV0w2ksNhqWj17PSl6iaCG',
}
with requests.Session() as s:
for i in tax_ids:
data["searchFilter"] = quote(json.dumps(data["searchFilter"]["fields"] % i))
print(data)
print("--" * 10)
r = s.post(url, data=data)
print(r)
so i want to read some sms received in my huawei modem.
For that i m tryin to first get the token and session id from the 'http://192.168.8.1/api/webserver/SesTokInfo page
then try to reuse this token in the page http://192.168.8.1/api/sms/sms-list
but i got this error
<error>
<code>125002</code>
<message></message>
</error>
which mean that i don t have the right token value, what i m wondering about.
so this is how my code looks
import hashlib
import base64
import binascii
import xml.etree.ElementTree as ET
from datetime import datetime
import requests
from bs4 import BeautifulSoup
BASEURL = 'http://192.168.8.1'
session = requests.Session()
reqresponse = session.get(BASEURL + '/api/webserver/SesTokInfo')
if reqresponse.status_code == 200:
root = ET.fromstring(reqresponse.text)
for results in root.iter('SesInfo'):
sessionid = results.text
print("the sessionId is", sessionid)
for results in root.iter('TokInfo'):
token = results.text
print("The token is", token)
sessioncookies = reqresponse.cookies
post_data = '<?xml version = "1.0" encoding = "UTF-8"?>\n'
post_data += '<request><PageIndex>1</PageIndex><ReadCount>3</ReadCount><BoxType>1</BoxType><SortTyp$
headers = {'Content-Type': 'text/xml; charset=UTF-8',
'__RequestVerificationToken': token
}
api_url = BASEURL + '/api/sms/sms-list'
logonresponse = session.post( api_url, data=post_data, headers=headers, cookies=sessioncookies)
logonresponse2 = session.get( api_url, data=post_data, headers=headers, cookies=sessioncookies)
result = BeautifulSoup(logonresponse.text, 'html.parser')
for r in result:
print(r)
can someone helo me with the troubleshooting please?