Unable to send authenticated OKEx API POST requests with body (in python). 401 Signature invalid. Authenticated GET requests work

Viewed 1129

As the title suggests I am able to send the authenticated GET requests for the OKEx API without any issues. However as soon as I make a POST request by adding in the extra parameters in the signature as well as in the request's body I get the 401 response {'msg': 'Invalid Sign', 'code': '50113'}.


def signature(timestamp, method, request_path, body,secret_key):
    if str(body) == '{}' or str(body) == 'None':
        message = str(timestamp) + str.upper(method) + request_path + ''
    else:

        message = str(timestamp) + str.upper(method) + request_path +body
    
    mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)


def get_header(endpoint,request,body={}):

    header = dict()
    header['CONTENT-TYPE'] = 'application/json'
    header['OK-ACCESS-KEY'] = okex_key
    current_time=get_time()
    header['OK-ACCESS-SIGN'] = signature(current_time, request, endpoint , body, okex_secret)
    header['OK-ACCESS-TIMESTAMP'] = str(current_time)
    header['OK-ACCESS-PASSPHRASE'] = okex_pass
    return header


def place_market_order(url,pair,side,amount,tdMode='cash'):

    endpoint='/api/v5/trade/order' 
    request='POST'

    body={
            "instId":pair,
            "tdMode":tdMode, #cash, cross, isolated
            "side":side,
            "ordType":"market",
            "sz":str(Decimal(str(amount)))
        }

    body = json.dumps(body)
    header = get_header(endpoint,request,body)
    response= requests.post(url+endpoint, headers=header,data=body)
    

    return response

#
url = 'http://www.okex.com'

place_market_order(url,pair="BTC-USDT",side="buy",amount=0.001)

The signature logic should be ok since authenticated GET requests work.

But what's wrong with how I handle the body? I'm using v5 of the OKEx API.

Thanks in advance!

2 Answers

You need send POST request as JSON formate.

Good example:

{"instId":"BTC-USDT","tdMode":"cash","side":"buy","ordType":"limit","sz":"0.00001","px":"30000"}

Bad example:

instId=BTC-USDT&tdMode=cash&side=buy&ordType=limit&sz=0.00001&px=30000

Under place_market_order function: response= requests.post(url+endpoint, headers=header,data=body) should be as follows response= requests.post(url=url+endpoint, headers=header,data=body)

Related