I am trying to view my open orders through the Bittrex API but all I get is an INVALID_SIGNATURE response.
I'm using Python 3.6. Here is my code:
import time
import hmac
import hashlib
import requests
apikey = '12345'
apisecret = '56789'
nonce = str(time.time())
url = 'https://bittrex.com/api/v1.1/market/getopenorders?&apikey=' + apikey + '&nonce=' + nonce
signature = hmac.new(apisecret.encode(), url.encode(), hashlib.sha512).hexdigest()
hdrs = {'apisign' : signature}
r = requests.get(url, headers = hdrs)
print(r.json())
I'm expecting a response like:
{
"success" : true,
"message" : "",
"result" : [{
"Uuid" : null,
"OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
"Exchange" : "BTC-LTC",
"OrderType" : "LIMIT_SELL",
"Quantity" : 5.00000000,
…
}
]
}
But instead I get:
{'success': False, 'message': 'INVALID_SIGNATURE', 'result': None}
I know my keys are correct, and using purposely incorrect keys changes the INVALID_SIGNATURE response to
APIKEY_INVALID. I've tried to pull other information such as "getbalance", "getorderhistory", etc., but they all give the same result.
I've found many variations of the code above, but each one I try ends with the same result. I'm sure I'm just missing something simple but after a week of searching, I still don't know why it isn't working.
Any insight is appreciated.
Thanks.
Related
Is there a way to validate a sting in Flask to check for the following. I am looking for it to not only show up in the Swagger documentation but to also catch it as a string validation error if possible
Min length 10
Max length 1,024
Starts with [a-zA-Z]
Contains [a-zA-Z0-9=!##$%^&*()-]
Ends with [a-zA-z0-9]
Here is how I have my endpoint set up so far
from flask import Flask
from flask_restplus import Api, Resource, fields
flask_app= Flask (__name__)
app = Api(app = flask_app,
version = "1.0",
title = "Test API",
description = "Example endpoint to test validation of POST body parameter using Flaskplus")
model = app.model (
'username model',
{
'username': fields.String (
required = True,
description = "Username of the user",
help = "Username cannot be blank, must be of length 10, can start with an upper or lower case letter, can contain upper/lower case, numbers, and the following special characters [=!##$%^&*()-], and must end with an upper/lower case letter or a number",
example = "john.smith123"
)
}
)
name_space = app.namespace ('', 'Main API')
#name_space.route ("/test")
class test (Resource)
#app.doc(
responses = {
200: 'OK',
400: 'Invalid Argument',
500: 'Mapping Key Error'
}
)
#app.expect (model)
def post (self):
try:
username = request.json.get('username')
return {
'status': 'Username valid',
'status_code': 200
}
except KeyError as e:
name_space.abort (
500,
e.__doc__,
status = "Key error",
statusCode = "500"
)
You can use the flask-parameter-validation project in order to do this. You'll be able to implement it with something similar to the following:
from flask_parameter_validation import ValidateParameters, Json
#name_space.route("/test", methods=["POST"])
#ValidateParameters()
def hello(
username: str = Json(
min_str_length=10,
max_str_length=1024,
pattern=r"REGEX"
)
):
return f"Hello, {username}"
You'll need to replace REGEX with a regex pattern that fulfills your start, middle and end criteria.
Hope that this helps!
Trying to authenticate to crypto.com but cant seem to get it to work... Been trying few days now and getting really frustrated, any help? Their api docs # https://exchange-docs.crypto.com/?python#digital-signature
Heres how to do it + sample code, Im stuck..
The authentication is based on the pairing of the API Key, along with the HMAC-SHA256 hash of the request parameters using the API Secret as the cryptographic key.
The algorithm for generating the HMAC-SHA256 signature is as follows:
If "params" exist in the request, sort the request parameter keys in ascending order.
Combine all the ordered parameter keys as key + value (no spaces, no delimiters). Let's call this the parameter string
Next, do the following: method + id + api_key + parameter string + nonce
Use HMAC-SHA256 to hash the above using the API Secret as the cryptographic key
Encode the output as a hex string -- this is your Digital Signature
import hmac
import hashlib
import json
import requests
import time
API_KEY = "API_KEY"
SECRET_KEY = "SECRET_KEY"
req = {
"id": 11,
"method": "private/get-order-detail",
"api_key": API_KEY,
"params": {
"order_id": "337843775021233500",
},
"nonce": int(time.time() * 1000)
};
# First ensure the params are alphabetically sorted by key
paramString = ""
if "params" in req:
for key in req['params']:
paramString += key
paramString += str(req['params'][key])
sigPayload = req['method'] + str(req['id']) + req['api_key'] + paramString + str(req['nonce'])
request['sig'] = hmac.new(
bytes(str(SECRET_KEY), 'utf-8'),
msg=bytes(sigPayload, 'utf-8'),
digestmod=hashlib.sha256
).hexdigest()
I ran into the same issue today. Overall I found the API doc from crypto.com very poor.
Change the last bit of your code so that you add a field to the "req" dictionnary:
req['sig'] = hmac.new(
bytes(str(SECRET_KEY), 'utf-8'),
msg=bytes(sigPayload, 'utf-8'),
digestmod=hashlib.sha256
).hexdigest()
To get your order detail (as is written in your example), you can make the API call with a POST request like so:
api_url = f"https://api.crypto.com/v2/{req["method"]}"
response = requests.post(api_url, json=req)
order_detail = response.json()
I tried to create Meter using HTTP POST olscmeter and mxapimeter.
My python code is
postReq = mxURL + "/maximo/oslc/os/oslcmeter"
headers = {'Content-type': 'application/json', 'maxauth' : maxAuth}
body = {'METERNAME' : meterName, 'METERTYPE' : meterType, 'DESCRIPTION' : description, 'READINGTYPE' : 'ACTUAL', 'MEASUREUNITID' : ''}
print(postReq, headers, body)
r = requests.post(url = postReq, headers = headers, json = body)
print(r.status_code, r.text)
And I kept encountering the under-mentioned error.
400
{"oslc:Error":
{"oslc:statusCode":"400",
"errorattrname":"metername",
"spi:reasonCode":"BMXAA4195E",
"errorobjpath":"meter",
"correlationid":null,
"oslc:message":"BMXAA4195E - A value is required for the Meter field on the METER object.",
"oslc:extendedError":{"oslc:moreInfo":{"rdf:resource":"http:\/\/mx7vm\/maximo\/oslc\/error\/messages\/BMXAA4195E"}
}
}
}
Any advice on what I have missed?
Thank you.
BMXAA4195E is just a generic error that means a required field is missing.
I have never generated MBOs this way, but I think the issue is that JSON keys are case sensitive. In all the examples I've seen online, the attributes in the body are always lowercase. This also makes sense with the error message.
Try using all lowercase keys in your body.
I'm trying to recreate a scenario with the postman and there is a _csrf value in the previous GET request response body to be passed with the next POST request.
I Can't find a way to extract the value from POSTMAN.
NOTE: What I want is something similar to Regular Expression Extractor in Jmeter.If you have any Idea about extracting a value form the response body and setting it to a variable. Please let me know.
Cheers,
Muditha
This might help you https://media.readthedocs.org/pdf/postman-quick-reference-guide/latest/postman-quick-reference-guide.pdf
They use Cheerio
2.2.5 How to parse a HTML response to extract a specific value?
Presumed you want to get the _csrf hidden field value for assertions or later use from the response below:
To parse and retrive the value, we will use the cherrio JavaScript library:
responseHTML = cheerio(pm.response.text());
console.log(responseHTML.find('[name="_csrf"]').val());
Cheerio is designed for non-browser use and implements a subset of the jQuery functionality. Read more about it at
https://github.com/cheeriojs/cheerio
responseHTML = cheerio(pm.response.text());
var po= responseHTML.find('[name="_csrf"]').val();
console.log(po);
pm.environment.set("token", po);
/* You need to set the environment in Postman and capture the CSRF token in variable "here po" using a get request. Next in post request the environment variable token can be used */
Just made this JS in post man to parse Without a REGEx. Hope it will help people in the futur
Text to parse : Json : Extract data-id :
{
"code": "OK",
"response": {
"append": {
"html": {
"< .folders": "<a class=\"folder\" href=\"/foobarfoo\" data-id=\"ToExtract\"><div><i class=\"far fa-fw fa-folder\"></i></div><div class=\"folder-name\">blabla</div><div><div class=\"badge\">0</div></div></a>"
}
}
}
}
console.log(responseBody.response);
var jsonData = JSON.parse(responseBody);
var iStart = responseBody.indexOf("response\":")+10;
var scenarioId = responseBody.substr(iStart,10);
var iEnd = scenarioId.indexOf("}");
var scenarioId = scenarioId.substr(0,iEnd);
console.log("scenarioId:" + scenarioId + "iStart: "+ iStart + " scenarioId : " + scenarioId);
pm.environment.set("scenario", scenarioId);
I am trying to do this curl post in Titanium but I keep getting a 400 error.
I have tried passing the data as a Javascript object. I tried also changing the header.
Maybe I haven't hit the right combination of things.
Please help.
curl 'https://ortc-mobilepush.realtime.co/mp/publish' --data-binary '{"applicationKey": "[INSERT_YOUR_APP_KEY]","privateKey": "[INSERT_YOUR_PRIVATE_KEY]",
"channel" : "NewArticles",
"message" : "We have new articles for you",
"payload" : "{ \"sound\" : \"default\", \"badge\" : \"2\" }" }'
var url = 'https://ortc-mobilepush.realtime.co/mp/publish';
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e);
//alert('error');
},
timeout : 5000 // in milliseconds
});
client.open("POST", url);
client.setRequestHeader('Content-Type', 'multipart/form-data');
// Send the request.
var text = '{"applicationKey": "[App Key]","privateKey": "[Private key]", "channel" : "GlobalChanell", "message" : "test", "payload" : "{ \"sound\" : \"default\", \"badge\" : \"32\" }" }';
client.send(text);
recently I also faced same problem in one of my client application...
so i should give solution for that..
may be there is a problem of server url...so you can try to change that url and replace it with something below...
https://exampleserver.com/mp/publish
then set Content-Type to application/json
and create json object like below....
var text = {
applicationKey : [key],
privateKey : [p_key],
etc....
}
then pass it like....
client.send(JSON.stringify(text));