WebSocket Authentication

1) HMAC Authentication

  • Endpoint: wss://ws-feed-pro.btcturk.com
  • The WebSocket feed provides real-time market data updates for orders and trades.
  • The WebSocket feed uses a bidirectional protocol, which encodes all messages as JSON objects. All messages have a type attribute that can be used to handle the message appropriately.
  • Please note that new message types can be added at any point in time. Clients are expected to ignore messages they do not support.
HMAC login mechanism for WebSocket:
From BtcTurk | PRO go to ACCOUNT>API Access
In the form select WebSocket, enter you are IP address and submit. This action will create public key and private key to achieve WebSocket login.
Code Example
C#
Python
1
// You can download ApiClient .net core complete library from github https://github.com/BTCTrader/broker-api-csharp-v2
2
3
private static async Task HmacTest()
4
{
5
Uri _uri = new Uri("wss://ws-feed-pro.btcturk.com");
6
ClientWebSocket client = new ClientWebSocket();
7
await client.ConnectAsync(_uri, CancellationToken.None);
8
9
string publicKey = "YOUR_PUBLIC_KEY";
10
string privateKey = "YOUR_PRIVATE_KEY";
11
long nonce = 3000;
12
string baseString = quot;{publicKey}{nonce}";
13
string signature = ComputeHash(privateKey, baseString);
14
long timestamp = ToUnixTime(DateTime.UtcNow);
15
object[] hmacMessageObject = { 114, new { type = 114, publicKey = publicKey, timestamp = timestamp, nonce = nonce, signature = signature } };
16
string message = JsonSerializer.Serialize(hmacMessageObject);
17
18
await client.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.UTF8.GetBytes(message),
19
offset: 0,
20
count: message.Length),
21
messageType: WebSocketMessageType.Text,
22
endOfMessage: true,
23
cancellationToken: CancellationToken.None);
24
}
25
26
private static string ComputeHash(string privateKey, string baseString)
27
{
28
var key = Convert.FromBase64String(privateKey);
29
string hashString;
30
31
using (var hmac = new HMACSHA256(key))
32
{
33
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(baseString));
34
hashString = Convert.ToBase64String(hash);
35
}
36
37
return hashString;
38
}
39
40
private static long ToUnixTime(DateTime date)
41
{
42
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
43
return Convert.ToInt64((date - epoch).TotalMilliseconds);
44
}
Copied!
1
import asyncio
2
import base64
3
import hashlib
4
import hmac
5
import json
6
import time
7
import websockets
8
class InterfaceWS:
9
def __init__(self, exchange_name: str = None) -> None:
10
self.exchange_name = "BTC Turk"
11
self.uri = "wss://ws-feed-pro.btcturk.com/"
12
13
async def authenticate_ws(self) -> bool:
14
self.ws = await websockets.connect(self.uri)
15
publicKey = "PUBLIC_KEY_HERE";
16
privateKey = "PRIVATE_KEY_HERE";
17
nonce = 3000
18
print("\nnonce", nonce)
19
baseString = "{}{}".format(publicKey, nonce).encode("utf-8")
20
print("\nbaseString", baseString)
21
signature = hmac.new(
22
base64.b64decode(privateKey), baseString, hashlib.sha256
23
).digest()
24
print("\nsignature", signature)
25
signature = base64.b64encode(signature)
26
print("\nsignature", signature)
27
timestamp = round(time.time() * 1000)
28
print("\ntimestamp", timestamp)
29
hmacMessageObject = [
30
114,
31
{
32
"nonce": nonce,
33
"publicKey": publicKey,
34
"signature": signature.decode("utf-8"),
35
"timestamp": timestamp,
36
"type": 114,
37
},
38
]
39
print("hmacMessageObject", hmacMessageObject)
40
await self.ws.send(json.dumps(hmacMessageObject))
41
while True:
42
try:
43
response = await asyncio.wait_for(self.ws.recv(), timeout=0.5)
44
print("response after auth: ", response)
45
except Exception as e:
46
print(e)
47
48
async def main():
49
w = InterfaceWS()
50
await w.authenticate_ws()
51
52
if __name__ == "__main__":
53
asyncio.run(main())
Copied!

2) Token Authentication

To access token information, press F12 after logging into our SSO site.
You can get token information by following the steps Storage > Local Storage > btcUser
  • You can use https://api.btcturk.com/api/v2/token/refresh endpoint to renew the token.
  • After sending a user login message to channel 111, p-coded messages are automatically received
You can use HMAC authentication instead of Token to establish WebSocket connection.
Python
1
import json
2
import pprint
3
import time
4
import websocket
5
6
try:
7
import thread
8
except ImportError:
9
import _thread as thread
10
11
def on_message(ws, message):
12
data = json.loads(message)
13
pprint.pprint(data)
14
def on_error(ws, error):
15
print(error)
16
def on_close(ws):
17
print("### closed ###")
18
def on_open(ws):
19
def run(*args):
20
time.sleep(1)
21
message = [
22
111,
23
{
24
"type": 111,
25
"id": USER_ID_HERE, #number
26
"token": "ACCESS_TOKEN_INFORMATION_HERE",
27
"username": "YOUR_MAIL_HERE"
28
}
29
]
30
ws.send(json.dumps(message))
31
thread.start_new_thread(run, ())
32
33
if __name__ == "__main__":
34
websocket.enableTrace(True)
35
ws = websocket.WebSocketApp(
36
"wss://ws-feed-pro.btcturk.com/",
37
on_message=on_message,
38
on_error=on_error,
39
on_close=on_close)
40
ws.on_open = on_open
41
ws.run_forever()
Copied!