Type/to search
Built-in Functions
Global
Log
Market
Trade
Account
Futures
Exchange
exchange.GetName
exchange.GetLabel
exchange.GetCurrency
exchange.SetCurrency
exchange.GetQuoteCurrency
exchange.GetPeriod
exchange.SetMaxBarLen
exchange.SetPrecision
exchange.GetRate
exchange.SetRate
exchange.SetBase
exchange.GetBase
exchange.SetProxy
exchange.SetTimeout
exchange.Encode
IO
Network
Storage
Threads
TA
Talib
OS
Structures
Built-in Variables and Constants
Conventions
Exchanges

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.

    javascript
    function main() { var query = "symbol=BTCUSDT&timestamp=" + Date.now() var signature = exchange.Encode("sha256", "raw", "hex", query, "raw", "{{secretkey}}") Log(signature) // Output: a 64-character hex signature }
    python
    import time def main(): query = "symbol=BTCUSDT&timestamp=" + str(int(time.time() * 1000)) signature = exchange.Encode("sha256", "raw", "hex", query, "raw", "{{secretkey}}") Log(signature) # Output: a 64-character hex signature
    rust
    fn main() { let query = format!("symbol=BTCUSDT&timestamp={}", 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 key is passed the calculation is an HMAC, and the signature is the hex encoding of HMAC_SHA256(secretKey, "GET/realtime" + expires), where expires is a millisecond timestamp. "{{secretkey}}" refers to the secretKey configured in the exchange object (used as a string, so keyFormat is string), so the secret key never appears in plain text in the strategy code.

    javascript
    function 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 } }) } } }
    python
    import 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] = now
    rust
    use 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

TypeDescription

string

Computed hash value encoding.

Arguments

NameTypeRequiredDescription

algo

string

Yes

The signing or hashing algorithm, for example sha256 or ed25519; see the remarks for all values.

inputFormat

string

Yes

Used to specify the data format of the data parameter. The inputFormat parameter supports being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

outputFormat

string

Yes

Used to specify the output data format. The outputFormat parameter supports being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

data

string

Yes

Data to be processed.

keyFormat

string

No

Used to specify the data format of the key parameter. The keyFormat parameter supports being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

key

string

No

Key used in the signature computation. You can use a plaintext string, or you can use "{{accesskey}}" and "{{secretkey}}" to refer respectively to the accessKey and secretKey configured in the exchange object.

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:

CategoryValues
No algorithmraw
Signingsign, 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 decodingtext.encoder.utf8, text.decoder.utf8, text.encoder.gbk, text.decoder.gbk
Ed25519ed25519, ed25519.seed; a hash algorithm can be given, for example ed25519.md5, ed25519.sha512