exchange.Encode
Performs signature and encryption computations.
exchange.Encode(algo, inputFormat, outputFormat, data)
exchange.Encode(algo, inputFormat, outputFormat, data, keyFormat, key)Examples
-
Sign request parameters with HMAC-SHA256 using the secretKey configured on the exchange object.
javascriptfunction main() { var query = "symbol=BTCUSDT×tamp=" + Date.now() var signature = exchange.Encode("sha256", "raw", "hex", query, "raw", "{{secretkey}}") Log(signature) // Output: a 64-character hex signature }pythonimport time def main(): query = "symbol=BTCUSDT×tamp=" + str(int(time.time() * 1000)) signature = exchange.Encode("sha256", "raw", "hex", query, "raw", "{{secretkey}}") Log(signature) # Output: a 64-character hex signaturerustfn main() { let query = format!("symbol=BTCUSDT×tamp={}", Unix() * 1000); let signature = exchange.Encode("sha256", "raw", "hex", &query, "raw", "{{secretkey}}"); Log!(signature); // Output: a 64-character hex signature } -
Example of Bybit v5 private WebSocket authentication and position push subscription (wss protocol): when
keyis passed the calculation is an HMAC, and the signature is the hex encoding ofHMAC_SHA256(secretKey, "GET/realtime" + expires), whereexpiresis a millisecond timestamp."{{secretkey}}"refers to thesecretKeyconfigured in the exchange object (used as a string, sokeyFormatisstring), so the secret key never appears in plain text in the strategy code.javascriptfunction main() { var APIKEY = "your Bybit API Key" // expires is a millisecond timestamp; signature = HMAC_SHA256(secretKey, "GET/realtime" + // expires), hex encoded var expires = Date.now() + 10000 var signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + expires, "string", "{{secretkey}}") var client = Dial("wss://stream.bybit.com/v5/private", 60) if (!client) { Log("connection failed") return } client.write(JSON.stringify({op: "auth", args: [APIKEY, expires, signature]})) client.write(JSON.stringify({op: "subscribe", args: ["position"]})) var positions = {} var lastPing = Date.now() while (true) { // Bybit recommends sending a heartbeat every 20 seconds if (Date.now() - lastPing >= 20000) { client.write(JSON.stringify({op: "ping"})) lastPing = Date.now() } var buf = client.read(1000) if (buf === "") { break // connection closed } if (!buf) { continue } var msg = JSON.parse(buf) if (msg.op == "auth" && !msg.success) { Log("auth failed", msg.ret_msg) break } if (msg.topic == "position") { msg.data.forEach(function(p) { var key = p.symbol + "/" + p.positionIdx var now = p.side + " " + p.size if (positions[key] !== now) { Log("position change", key, positions[key], "->", now, "@") positions[key] = now } }) } } }pythonimport time import json def main(): APIKEY = "your Bybit API Key" # expires is a millisecond timestamp; signature = HMAC_SHA256(secretKey, "GET/realtime" + # expires), hex encoded expires = int(time.time() * 1000) + 10000 signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + str(expires), "string", "{{secretkey}}") client = Dial("wss://stream.bybit.com/v5/private", 60) if not client: Log("connection failed") return client.write(json.dumps({"op": "auth", "args": [APIKEY, expires, signature]})) client.write(json.dumps({"op": "subscribe", "args": ["position"]})) positions = {} lastPing = time.time() while True: # Bybit recommends sending a heartbeat every 20 seconds if time.time() - lastPing >= 20: client.write(json.dumps({"op": "ping"})) lastPing = time.time() buf = client.read(1000) if buf == "": break # connection closed if not buf: continue msg = json.loads(buf) if msg.get("op") == "auth" and not msg.get("success"): Log("auth failed", msg.get("ret_msg")) break if msg.get("topic") == "position": for p in msg["data"]: key = "%s/%s" % (p["symbol"], p["positionIdx"]) now = p["side"] + " " + p["size"] if positions.get(key) != now: Log("position change", key, positions.get(key), "->", now, "@") positions[key] = nowrustuse std::collections::HashMap; fn main() { let apikey = "your Bybit API Key"; // expires is a millisecond timestamp; signature = HMAC_SHA256(secretKey, "GET/realtime" + // expires), hex encoded let expires = Unix() * 1000 + 10000; let signature = exchange.Encode("sha256", "string", "hex", &format!("GET/realtime{}", expires), "string", "{{secretkey}}"); let mut client = Dial::new("wss://stream.bybit.com/v5/private", 60); if !client.Valid() { Log!("connection failed"); return; } // the Rust SDK has no JSON serializer, so build the requests with string formatting client.write(&format!(r#"{{"op":"auth","args":["{}",{},"{}"]}}"#, apikey, expires, signature), 0); client.write(r#"{"op":"subscribe","args":["position"]}"#, 0); let mut positions: HashMap<String, String> = HashMap::new(); let mut last_ping = Unix(); while !client.IsClosed() { // Bybit recommends sending a heartbeat every 20 seconds if Unix() - last_ping >= 20 { client.write(r#"{"op":"ping"}"#, 0); last_ping = Unix(); } let buf = client.read(1000); if buf == "" { continue; } let msg = match JSONParse(&buf) { Some(v) => v, None => continue, }; if msg["op"].as_str() == Some("auth") && msg["success"].as_bool() != Some(true) { Log!("auth failed", msg["ret_msg"].as_str().unwrap_or("")); break; } if msg["topic"].as_str() == Some("position") { if let Some(arr) = msg["data"].as_array() { for p in arr { let key = format!("{}/{}", p["symbol"].as_str().unwrap_or(""), p["positionIdx"].as_i64().unwrap_or(0)); let now = format!("{} {}", p["side"].as_str().unwrap_or(""), p["size"].as_str().unwrap_or("0")); if positions.get(&key) != Some(&now) { Log!("position change", &key, &now, "@"); positions.insert(key, now); } } } } } }
Returns
| Type | Description |
string | Computed hash value encoding. |
Arguments
| Name | Type | Required | Description |
algo | string | Yes | The signing or hashing algorithm, for example |
inputFormat | string | Yes | Used to specify the data format of the |
outputFormat | string | Yes | Used to specify the output data format. The |
data | string | Yes | Data to be processed. |
keyFormat | string | No | Used to specify the data format of the |
key | string | No | Key used in the signature computation. You can use a plaintext string, or you can use |
See Also
Remarks
Only live trading supports calling the exchange.Encode() function. The reference methods "{{accesskey}}" and "{{secretkey}}" are only valid when calling the exchange.Encode() function.
Values of algo:
| Category | Values |
|---|---|
| No algorithm | raw |
| Signing | sign, signTx |
| Hash (MD, SHA-1, SHA-2) | md4, md5, sha1, sha256, sha512, sha512.384, sha512.256, sha512.224 |
| Hash (SHA-3, Keccak) | keccak256, sha3.224, sha3.256, sha3.384, sha3.512, sha3.keccak256, sha3.keccak512 |
| Hash (others) | ripemd160, blake2b.256, blake2b.512, blake2s.128, blake2s.256 |
| String encoding and decoding | text.encoder.utf8, text.decoder.utf8, text.encoder.gbk, text.decoder.gbk |
| Ed25519 | ed25519, ed25519.seed; a hash algorithm can be given, for example ed25519.md5, ed25519.sha512 |