As mentioned in the "General Information" section, Websocket is divided into Public and Private data. No authentication is required to receive Public data. To receive Private data, authentication must be successful when establishing a Websocket connection.
- Authentication is carried out through the
Authorization
header, just like in the REST API. - Please refer to "Generate an Authorization Token (JWT)" in Creating an Authorized Request.
(Example) Including Authentication token in the Header for Websocket Connection.
const jwt = require("jsonwebtoken");
const {v4: uuidv4} = require('uuid');
const WebSocket = require("ws");
const payload = {
access_key: "Your Access key",
nonce: uuidv4(),
};
const jwtToken = jwt.sign(payload, "Your Secret key");
const ws = new WebSocket("wss://{region}-api.upbit.com/websocket/v1", {
headers: {
authorization: `Bearer ${jwtToken}`
}
});
ws.on("open", () => {
console.log("connected!");
// Request after connection
ws.send('[{"ticket":"test example"},{"type":"myTrade"}]');
});
ws.on("error", console.error);
ws.on("message", (data) => console.log(data.toString()));
ws.on("close", () => console.log("closed!"));
import jwt # PyJWT
import uuid
import websocket # websocket-client
def on_message(ws, message):
# do something
data = message.decode('utf-8')
print(data)
def on_connect(ws):
print("connected!")
# Request after connection
ws.send('[{"ticket":"test example"},{"type":"myTrade"}]')
def on_error(ws, err):
print(err)
def on_close(ws, status_code, msg):
print("closed!")
payload = {
'access_key': "발급받은 Access key",
'nonce': str(uuid.uuid4()),
}
jwt_token = jwt.encode(payload, "발급받은 Secret key");
authorization_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorization_token}
ws_app = websocket.WebSocketApp("wss://api.upbit.com/websocket/v1",
header=headers,
on_message=on_message,
on_open=on_connect,
on_error=on_error,
on_close=on_close)
ws_app.run_forever()