Search code examples
c#.netpostwebrequest

HitBTC api POST request, C#


I know how to do a GET request, but POST does not work:

public string Order()
    {
        var client = new RestClient("http://api.hitbtc.com");
        var request = new RestRequest("/api/2/order", Method.POST);
        request.AddQueryParameter("nonce", GetNonce().ToString());
        request.AddQueryParameter("apikey", HapiKey);

       // request.AddParameter("clientOrderId", "");
        request.AddParameter("symbol", "BCNUSD");
        request.AddParameter("side", "sell");
        request.AddParameter("quantity", "10");
        request.AddParameter("type", "market");

        var body = string.Join("&", request.Parameters.Where(x => x.Type == ParameterType.GetOrPost));

        string sign = CalculateSignature(client.BuildUri(request).PathAndQuery + body, HapiSecret);
        request.AddHeader("X-Signature", sign);

        var response = client.Execute(request);
        return response.Content;
    }
    private static long GetNonce()
    {
        return DateTime.Now.Ticks * 10;
    }

    public static string CalculateSignature(string text, string secretKey)
    {
        using (var hmacsha512 = new HMACSHA512(Encoding.UTF8.GetBytes(secretKey)))
        {
            hmacsha512.ComputeHash(Encoding.UTF8.GetBytes(text));
            return string.Concat(hmacsha512.Hash.Select(b => b.ToString("x2")).ToArray());
        }
    }

Error: code: 1001, "Authorization required".

Where is my failure? Is "apikey" and "X-Signature" not correct for v2 anymore?

Thank you very much for helping me!


Solution

  • Please review authentication documentation.

    You need to use Basic authentication using public and private key.

    Example for RestSharp:

    var client = new RestClient("https://api.hitbtc.com")
    {
        Authenticator = new HttpBasicAuthenticator(<PublicKey>, <SecretKey>)
    };
    

    For creating API keys you need to visit Setting page.

    Also for your API action you need to set "Place/cancel orders" permission to true.

    Details on the screenshot: enter image description here

    Also here is full code which works for me well:

    var client = new RestClient("https://api.hitbtc.com")
    {
        Authenticator = new HttpBasicAuthenticator(PublicKey, SecretKey)
    };
    
    var request = new RestRequest("/api/2/order", Method.POST)
    {
        RequestFormat = DataFormat.Json
    };
    
    request.AddParameter("symbol", "BCNUSD");
    request.AddParameter("side", "sell");
    request.AddParameter("quantity", "10");
    request.AddParameter("type", "market");
    request.AddParameter("timeInForce", "IOC");
    
    var response = client.Execute(request);
    if (!response.IsSuccessful)
    {
        var message = $"REQUEST ERROR (Status Code: {response.StatusCode}; Content: {response.Content})";
        throw new Exception(message);
    }