Crypto Exchange Authentication Errors in Getting data via C#

I am working to get my account data from Deribit Exchange Websocket using C#.

When i tried to get my account data with Python, it worked well.

But i did the same thing on C#, it makes unauthorized error to get response.

What is the problem? How to get the Authorized Data from server?

Here is My Code details.

First of all, Written in Python. (It works well)

import asyncio
import websockets
import json

CL_ID = "CLIENT ID IS HERE"
CL_SECRET = 'SECRET KEY IS HERE'
REQ_URL = 'wss://test.deribit.com/ws/api/v2'

acc_token = ''

msg = {
    "jsonrpc": "2.0",
    "id": 1,
    "params": {}
}

async def auth_api():

    global msg
    global acc_token 
    msg["method"] = "public/auth"
    msg["params"] = {
        "grant_type": "client_credentials",
        "client_id": CL_ID,
        "client_secret": CL_SECRET,
        "scope": "session:test"
    }

    async with websockets.connect(REQ_URL) as websocket:
        await websocket.send(json.dumps(msg))
        while websocket.open:
            response = await websocket.recv()
            response_json = json.loads(response)
            acc_token = response_json["result"]["access_token"]
            return

async def get_position(websocket, instrument):
    global msg
    global acc_token
    msg["id"] = 12
    msg["method"] = "private/get_position"
    msg["params"] = {
        "access_token": acc_token,
        #"currency":"BTC",
        #"kind":"future",
        "instrument_name": instrument
    }
    
 
    
    await websocket.send(json.dumps(msg))
    while websocket.open:
        response = await websocket.recv()
        return response

async def main():
    global msg
    await auth_api()
    async with websockets.connect(REQ_URL) as websocket:
        response = await get_position(websocket, "BTC-PERPETUAL")
        print(response)
        
asyncio.get_event_loop().run_until_complete(main())

Then Response is

{“jsonrpc”:”2.0″,”id”:12,”result”:[{“total_profit_loss”:-0.000245296,”size_currency”:0.005049217,”size”:200.0,”settlement_price”:40612.43,”realized_profit_loss”:4e-9,”realized_funding”:0.0,”open_orders_margin”:0.0,”mark_price”:39610.1,”maintenance_margin”:0.00003787,”leverage”:50,”kind”:”future”,”instrument_name”:”BTC-PERPETUAL”,”initial_margin”:0.000100986,”index_price”:39603.84,”floating_profit_loss”:-0.000124616,”estimated_liquidation_price”:10.08,”direction”:”buy”,”delta”:0.005049217,”average_price”:41632.66}]”,”usIn”:1650982776157472,”usOut”:1650982776158382,”usDiff”:910,”testnet”:true}

But when i try with C# at below, it makes error.

using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using WebSocketSharp;

public class DeribitRest
{
    private string atoken = "";
    private enum SslProtocolsHack
    {
        Tls = 192,
        Tls11 = 768,
        Tls12 = 3072
    }
    public void DeribitAuth()
    {
        JObject obj1 = new JObject();
        JObject paramObj = new JObject();
        JArray paramO = new JArray();

        obj1["method"] = "public/auth";
        paramObj["grant_type"] = "client_credentials";
        paramObj["client_id"] = "CLIENT ID IS HERE";
        paramObj["client_secret"] = "SECRET KEY IS HERE";
        obj1["params"] = paramObj;
        obj1["scope"] = "session:test";
        obj1["jsonrpc"] = "2.0";
        obj1["id"] = 0;

        string sendMessage = JsonConvert.SerializeObject(obj1, Formatting.None);

        Console.WriteLine(sendMessage);

        WebSocket deribitWebsocket = new WebSocket("wss://test.deribit.com/ws/api/v2");
        deribitWebsocket.OnMessage += DeribitMessage;

        var sslProtocolHack = (System.Security.Authentication.SslProtocols)(SslProtocolsHack.Tls12 | SslProtocolsHack.Tls11 | SslProtocolsHack.Tls);

        if (deribitWebsocket.SslConfiguration.EnabledSslProtocols != sslProtocolHack)
        {
            deribitWebsocket.SslConfiguration.EnabledSslProtocols = sslProtocolHack;
            deribitWebsocket.Connect();
        }

        deribitWebsocket.Send(sendMessage);
    }

    private void DeribitMessage(object sender, MessageEventArgs e)
    {

        string requestMsg = Encoding.UTF8.GetString(e.RawData);
        JsonDocument marketData = JsonDocument.Parse(requestMsg);

        GetAccessToken(marketData);

        Thread.Sleep(2000);

        RequestPosition();
    }

    private void GetAccessToken(JsonDocument document)
    {
        if (document != null && document.RootElement.TryGetProperty("result", out var element))
        {
            var marketData = document.RootElement.GetProperty("result");
            if (marketData.TryGetProperty("access_token", out var quoteData))
            {
                atoken = quoteData.GetString();
                Console.WriteLine(atoken);
            }
        }
    }
    public void RequestPosition()
    {

        JObject obj1 = new JObject();
        JObject paramObj = new JObject();
        JArray paramO = new JArray();

        obj1["method"] = "private/get_positions";

        obj1["jsonrpc"] = "2.0";
        obj1["id"] = 2;
        paramObj["access_token"] = atoken;
        paramObj["currency"] = "BTC";
        paramObj["kind"] = "future";

        obj1["params"] = paramObj;



        string sendMessage = JsonConvert.SerializeObject(obj1, Formatting.None);

        Console.WriteLine(sendMessage);


        WebSocket deribitWebsocket = new WebSocket("wss://test.deribit.com/ws/api/v2");

        deribitWebsocket.OnMessage += OrderResult;


        var sslProtocolHack = (System.Security.Authentication.SslProtocols)(SslProtocolsHack.Tls12 | SslProtocolsHack.Tls11 | SslProtocolsHack.Tls);

        if (deribitWebsocket.SslConfiguration.EnabledSslProtocols != sslProtocolHack)
        {
            deribitWebsocket.SslConfiguration.EnabledSslProtocols = sslProtocolHack;
            deribitWebsocket.Connect();
        }


        if (deribitWebsocket.ReadyState == WebSocketState.Open)
        {
            deribitWebsocket.Send(sendMessage);
        }
    }

    private void OrderResult(object sender, MessageEventArgs e)
    {

        string requestMsg = Encoding.UTF8.GetString(e.RawData);
        JObject marketData = JObject.Parse(requestMsg);

        Console.WriteLine(marketData);
    }
}

the response from it is:

{“jsonrpc”:”2.0″,”id”:2,”error”:{“message”:”unauthorized”,”data”:{“reason”:”invalid_token”},”code:13009},” usIn:1650981338773781,”usOut”:1650981338773850,”usDiff”:69,”testnet”:true}

Leave a Comment